From 461fcf20e55bc1eded9bc2920b1cec25dc22d434 Mon Sep 17 00:00:00 2001 From: maziggy Date: Sun, 15 Feb 2026 14:54:03 +0100 Subject: [PATCH 1/7] Sync --- .../{index-BpibLMBb.js => index-DLlMitUB.js} | 848 +++++++++--------- static/assets/index-OqmBOPoC.css | 1 - static/assets/index-VlqasY_r.css | 1 + static/index.html | 4 +- 4 files changed, 427 insertions(+), 427 deletions(-) rename static/assets/{index-BpibLMBb.js => index-DLlMitUB.js} (56%) delete mode 100644 static/assets/index-OqmBOPoC.css create mode 100644 static/assets/index-VlqasY_r.css diff --git a/static/assets/index-BpibLMBb.js b/static/assets/index-DLlMitUB.js similarity index 56% rename from static/assets/index-BpibLMBb.js rename to static/assets/index-DLlMitUB.js index ac5f7d56d..23f3fce63 100644 --- a/static/assets/index-BpibLMBb.js +++ b/static/assets/index-DLlMitUB.js @@ -1,18 +1,18 @@ -function Aoe(t,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var i_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function tc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var jT={exports:{}},Qx={};var zU;function Toe(){if(zU)return Qx;zU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,i,s){var o=null;if(s!==void 0&&(o=""+s),i.key!==void 0&&(o=""+i.key),"key"in i){s={};for(var l in i)l!=="key"&&(s[l]=i[l])}else s=i;return i=s.ref,{$$typeof:t,type:r,key:o,ref:i!==void 0?i:null,props:s}}return Qx.Fragment=e,Qx.jsx=n,Qx.jsxs=n,Qx}var UU;function Eoe(){return UU||(UU=1,jT.exports=Toe()),jT.exports}var a=Eoe(),DT={exports:{}},Cn={};var BU;function Poe(){if(BU)return Cn;BU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),f=Symbol.iterator;function p(V){return V===null||typeof V!="object"?null:(V=f&&V[f]||V["@@iterator"],typeof V=="function"?V:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,b={};function y(V,X,re){this.props=V,this.context=X,this.refs=b,this.updater=re||x}y.prototype.isReactComponent={},y.prototype.setState=function(V,X){if(typeof V!="object"&&typeof V!="function"&&V!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,V,X,"setState")},y.prototype.forceUpdate=function(V){this.updater.enqueueForceUpdate(this,V,"forceUpdate")};function S(){}S.prototype=y.prototype;function N(V,X,re){this.props=V,this.context=X,this.refs=b,this.updater=re||x}var M=N.prototype=new S;M.constructor=N,v(M,y.prototype),M.isPureReactComponent=!0;var C=Array.isArray;function T(){}var k={H:null,A:null,T:null,S:null},j=Object.prototype.hasOwnProperty;function E(V,X,re){var te=re.ref;return{$$typeof:t,type:V,key:X,ref:te!==void 0?te:null,props:re}}function P(V,X){return E(V.type,X,V.props)}function U(V){return typeof V=="object"&&V!==null&&V.$$typeof===t}function L(V){var X={"=":"=0",":":"=2"};return"$"+V.replace(/[=:]/g,function(re){return X[re]})}var B=/\/+/g;function D(V,X){return typeof V=="object"&&V!==null&&V.key!=null?L(""+V.key):X.toString(36)}function H(V){switch(V.status){case"fulfilled":return V.value;case"rejected":throw V.reason;default:switch(typeof V.status=="string"?V.then(T,T):(V.status="pending",V.then(function(X){V.status==="pending"&&(V.status="fulfilled",V.value=X)},function(X){V.status==="pending"&&(V.status="rejected",V.reason=X)})),V.status){case"fulfilled":return V.value;case"rejected":throw V.reason}}throw V}function G(V,X,re,te,_e){var pe=typeof V;(pe==="undefined"||pe==="boolean")&&(V=null);var me=!1;if(V===null)me=!0;else switch(pe){case"bigint":case"string":case"number":me=!0;break;case"object":switch(V.$$typeof){case t:case e:me=!0;break;case d:return me=V._init,G(me(V._payload),X,re,te,_e)}}if(me)return _e=_e(V),me=te===""?"."+D(V,0):te,C(_e)?(re="",me!=null&&(re=me.replace(B,"$&/")+"/"),G(_e,X,re,"",function(ce){return ce})):_e!=null&&(U(_e)&&(_e=P(_e,re+(_e.key==null||V&&V.key===_e.key?"":(""+_e.key).replace(B,"$&/")+"/")+me)),X.push(_e)),1;me=0;var De=te===""?".":te+":";if(C(V))for(var de=0;de>>1,ae=G[Z];if(0>>1;Zi(re,W))tei(_e,re)?(G[Z]=_e,G[te]=W,Z=te):(G[Z]=re,G[X]=W,Z=X);else if(tei(_e,W))G[Z]=_e,G[te]=W,Z=te;else break e}}return I}function i(G,I){var W=G.sortIndex-I.sortIndex;return W!==0?W:G.id-I.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var c=[],u=[],d=1,h=null,f=3,p=!1,x=!1,v=!1,b=!1,y=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function M(G){for(var I=n(u);I!==null;){if(I.callback===null)r(u);else if(I.startTime<=G)r(u),I.sortIndex=I.expirationTime,e(c,I);else break;I=n(u)}}function C(G){if(v=!1,M(G),!x)if(n(c)!==null)x=!0,T||(T=!0,L());else{var I=n(u);I!==null&&H(C,I.startTime-G)}}var T=!1,k=-1,j=5,E=-1;function P(){return b?!0:!(t.unstable_now()-EG&&P());){var Z=h.callback;if(typeof Z=="function"){h.callback=null,f=h.priorityLevel;var ae=Z(h.expirationTime<=G);if(G=t.unstable_now(),typeof ae=="function"){h.callback=ae,M(G),I=!0;break t}h===n(c)&&r(c),M(G)}else r(c);h=n(c)}if(h!==null)I=!0;else{var V=n(u);V!==null&&H(C,V.startTime-G),I=!1}}break e}finally{h=null,f=W,p=!1}I=void 0}}finally{I?L():T=!1}}}var L;if(typeof N=="function")L=function(){N(U)};else if(typeof MessageChannel<"u"){var B=new MessageChannel,D=B.port2;B.port1.onmessage=U,L=function(){D.postMessage(null)}}else L=function(){y(U,0)};function H(G,I){k=y(function(){G(t.unstable_now())},I)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(G){G.callback=null},t.unstable_forceFrameRate=function(G){0>G||125Z?(G.sortIndex=W,e(u,G),n(c)===null&&G===n(u)&&(v?(S(k),k=-1):v=!0,H(C,W-Z))):(G.sortIndex=ae,e(c,G),x||p||(x=!0,T||(T=!0,L()))),G},t.unstable_shouldYield=P,t.unstable_wrapCallback=function(G){var I=f;return function(){var W=f;f=I;try{return G.apply(this,arguments)}finally{f=W}}}})(LT)),LT}var VU;function Roe(){return VU||(VU=1,FT.exports=Doe()),FT.exports}var OT={exports:{}},ls={};var GU;function Foe(){if(GU)return ls;GU=1;var t=zb();function e(c){var u="https://react.dev/errors/"+c;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),OT.exports=Foe(),OT.exports}var WU;function Loe(){if(WU)return Zx;WU=1;var t=Roe(),e=zb(),n=lK();function r(m){var g="https://react.dev/errors/"+m;if(1ae||(m.current=Z[ae],Z[ae]=null,ae--)}function re(m,g){ae++,Z[ae]=m.current,m.current=g}var te=V(null),_e=V(null),pe=V(null),me=V(null);function De(m,g){switch(re(pe,g),re(_e,m),re(te,null),g.nodeType){case 9:case 11:m=(m=g.documentElement)&&(m=m.namespaceURI)?lU(m):0;break;default:if(m=g.tagName,g=g.namespaceURI)g=lU(g),m=cU(g,m);else switch(m){case"svg":m=1;break;case"math":m=2;break;default:m=0}}X(te),re(te,m)}function de(){X(te),X(_e),X(pe)}function ce(m){m.memoizedState!==null&&re(me,m);var g=te.current,_=cU(g,m.type);g!==_&&(re(_e,m),re(te,_))}function ke(m){_e.current===m&&(X(te),X(_e)),me.current===m&&(X(me),Wx._currentValue=W)}var ee,Le;function $(m){if(ee===void 0)try{throw Error()}catch(_){var g=_.stack.trim().match(/\n( *(at )?)/);ee=g&&g[1]||"",Le=-1<_.stack.indexOf(` +function Poe(t,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var l_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var IT={exports:{}},ry={};var VU;function joe(){if(VU)return ry;VU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,i,s){var o=null;if(s!==void 0&&(o=""+s),i.key!==void 0&&(o=""+i.key),"key"in i){s={};for(var l in i)l!=="key"&&(s[l]=i[l])}else s=i;return i=s.ref,{$$typeof:t,type:r,key:o,ref:i!==void 0?i:null,props:s}}return ry.Fragment=e,ry.jsx=n,ry.jsxs=n,ry}var GU;function Doe(){return GU||(GU=1,IT.exports=joe()),IT.exports}var a=Doe(),zT={exports:{}},Nn={};var qU;function Roe(){if(qU)return Nn;qU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),f=Symbol.iterator;function p(V){return V===null||typeof V!="object"?null:(V=f&&V[f]||V["@@iterator"],typeof V=="function"?V:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,b={};function y(V,X,ne){this.props=V,this.context=X,this.refs=b,this.updater=ne||x}y.prototype.isReactComponent={},y.prototype.setState=function(V,X){if(typeof V!="object"&&typeof V!="function"&&V!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,V,X,"setState")},y.prototype.forceUpdate=function(V){this.updater.enqueueForceUpdate(this,V,"forceUpdate")};function S(){}S.prototype=y.prototype;function N(V,X,ne){this.props=V,this.context=X,this.refs=b,this.updater=ne||x}var A=N.prototype=new S;A.constructor=N,v(A,y.prototype),A.isPureReactComponent=!0;var M=Array.isArray;function T(){}var k={H:null,A:null,T:null,S:null},j=Object.prototype.hasOwnProperty;function E(V,X,ne){var te=ne.ref;return{$$typeof:t,type:V,key:X,ref:te!==void 0?te:null,props:ne}}function P(V,X){return E(V.type,X,V.props)}function U(V){return typeof V=="object"&&V!==null&&V.$$typeof===t}function L(V){var X={"=":"=0",":":"=2"};return"$"+V.replace(/[=:]/g,function(ne){return X[ne]})}var B=/\/+/g;function D(V,X){return typeof V=="object"&&V!==null&&V.key!=null?L(""+V.key):X.toString(36)}function H(V){switch(V.status){case"fulfilled":return V.value;case"rejected":throw V.reason;default:switch(typeof V.status=="string"?V.then(T,T):(V.status="pending",V.then(function(X){V.status==="pending"&&(V.status="fulfilled",V.value=X)},function(X){V.status==="pending"&&(V.status="rejected",V.reason=X)})),V.status){case"fulfilled":return V.value;case"rejected":throw V.reason}}throw V}function G(V,X,ne,te,we){var pe=typeof V;(pe==="undefined"||pe==="boolean")&&(V=null);var me=!1;if(V===null)me=!0;else switch(pe){case"bigint":case"string":case"number":me=!0;break;case"object":switch(V.$$typeof){case t:case e:me=!0;break;case d:return me=V._init,G(me(V._payload),X,ne,te,we)}}if(me)return we=we(V),me=te===""?"."+D(V,0):te,M(we)?(ne="",me!=null&&(ne=me.replace(B,"$&/")+"/"),G(we,X,ne,"",function(ce){return ce})):we!=null&&(U(we)&&(we=P(we,ne+(we.key==null||V&&V.key===we.key?"":(""+we.key).replace(B,"$&/")+"/")+me)),X.push(we)),1;me=0;var De=te===""?".":te+":";if(M(V))for(var de=0;de>>1,oe=G[Z];if(0>>1;Zi(ne,W))tei(we,ne)?(G[Z]=we,G[te]=W,Z=te):(G[Z]=ne,G[X]=W,Z=X);else if(tei(we,W))G[Z]=we,G[te]=W,Z=te;else break e}}return I}function i(G,I){var W=G.sortIndex-I.sortIndex;return W!==0?W:G.id-I.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var c=[],u=[],d=1,h=null,f=3,p=!1,x=!1,v=!1,b=!1,y=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function A(G){for(var I=n(u);I!==null;){if(I.callback===null)r(u);else if(I.startTime<=G)r(u),I.sortIndex=I.expirationTime,e(c,I);else break;I=n(u)}}function M(G){if(v=!1,A(G),!x)if(n(c)!==null)x=!0,T||(T=!0,L());else{var I=n(u);I!==null&&H(M,I.startTime-G)}}var T=!1,k=-1,j=5,E=-1;function P(){return b?!0:!(t.unstable_now()-EG&&P());){var Z=h.callback;if(typeof Z=="function"){h.callback=null,f=h.priorityLevel;var oe=Z(h.expirationTime<=G);if(G=t.unstable_now(),typeof oe=="function"){h.callback=oe,A(G),I=!0;break t}h===n(c)&&r(c),A(G)}else r(c);h=n(c)}if(h!==null)I=!0;else{var V=n(u);V!==null&&H(M,V.startTime-G),I=!1}}break e}finally{h=null,f=W,p=!1}I=void 0}}finally{I?L():T=!1}}}var L;if(typeof N=="function")L=function(){N(U)};else if(typeof MessageChannel<"u"){var B=new MessageChannel,D=B.port2;B.port1.onmessage=U,L=function(){D.postMessage(null)}}else L=function(){y(U,0)};function H(G,I){k=y(function(){G(t.unstable_now())},I)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(G){G.callback=null},t.unstable_forceFrameRate=function(G){0>G||125Z?(G.sortIndex=W,e(u,G),n(c)===null&&G===n(u)&&(v?(S(k),k=-1):v=!0,H(M,W-Z))):(G.sortIndex=oe,e(c,G),x||p||(x=!0,T||(T=!0,L()))),G},t.unstable_shouldYield=P,t.unstable_wrapCallback=function(G){var I=f;return function(){var W=f;f=I;try{return G.apply(this,arguments)}finally{f=W}}}})(HT)),HT}var XU;function Ooe(){return XU||(XU=1,BT.exports=Loe()),BT.exports}var $T={exports:{}},ss={};var YU;function Ioe(){if(YU)return ss;YU=1;var t=Bb();function e(c){var u="https://react.dev/errors/"+c;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),$T.exports=Ioe(),$T.exports}var ZU;function zoe(){if(ZU)return iy;ZU=1;var t=Ooe(),e=Bb(),n=gK();function r(m){var g="https://react.dev/errors/"+m;if(1oe||(m.current=Z[oe],Z[oe]=null,oe--)}function ne(m,g){oe++,Z[oe]=m.current,m.current=g}var te=V(null),we=V(null),pe=V(null),me=V(null);function De(m,g){switch(ne(pe,g),ne(we,m),ne(te,null),g.nodeType){case 9:case 11:m=(m=g.documentElement)&&(m=m.namespaceURI)?mU(m):0;break;default:if(m=g.tagName,g=g.namespaceURI)g=mU(g),m=fU(g,m);else switch(m){case"svg":m=1;break;case"math":m=2;break;default:m=0}}X(te),ne(te,m)}function de(){X(te),X(we),X(pe)}function ce(m){m.memoizedState!==null&&ne(me,m);var g=te.current,_=fU(g,m.type);g!==_&&(ne(we,m),ne(te,_))}function Ne(m){we.current===m&&(X(te),X(we)),me.current===m&&(X(me),Jx._currentValue=W)}var ee,Fe;function $(m){if(ee===void 0)try{throw Error()}catch(_){var g=_.stack.trim().match(/\n( *(at )?)/);ee=g&&g[1]||"",Fe=-1<_.stack.indexOf(` at`)?" ()":-1<_.stack.indexOf("@")?"@unknown:0:0":""}return` -`+ee+m+Le}var K=!1;function ue(m,g){if(!m||K)return"";K=!0;var _=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var A={DetermineComponentFrameRoot:function(){try{if(g){var Ct=function(){throw Error()};if(Object.defineProperty(Ct.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ct,[])}catch(xt){var mt=xt}Reflect.construct(m,[],Ct)}else{try{Ct.call()}catch(xt){mt=xt}m.call(Ct.prototype)}}else{try{throw Error()}catch(xt){mt=xt}(Ct=m())&&typeof Ct.catch=="function"&&Ct.catch(function(){})}}catch(xt){if(xt&&mt&&typeof xt.stack=="string")return[xt.stack,mt.stack]}return[null,null]}};A.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var F=Object.getOwnPropertyDescriptor(A.DetermineComponentFrameRoot,"name");F&&F.configurable&&Object.defineProperty(A.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var O=A.DetermineComponentFrameRoot(),ie=O[0],Me=O[1];if(ie&&Me){var Be=ie.split(` -`),dt=Me.split(` -`);for(F=A=0;AF||Be[A]!==dt[F]){var vt=` -`+Be[A].replace(" at new "," at ");return m.displayName&&vt.includes("")&&(vt=vt.replace("",m.displayName)),vt}while(1<=A&&0<=F);break}}}finally{K=!1,Error.prepareStackTrace=_}return(_=m?m.displayName||m.name:"")?$(_):""}function Q(m,g){switch(m.tag){case 26:case 27:case 5:return $(m.type);case 16:return $("Lazy");case 13:return m.child!==g&&g!==null?$("Suspense Fallback"):$("Suspense");case 19:return $("SuspenseList");case 0:case 15:return ue(m.type,!1);case 11:return ue(m.type.render,!1);case 1:return ue(m.type,!0);case 31:return $("Activity");default:return""}}function oe(m){try{var g="",_=null;do g+=Q(m,_),_=m,m=m.return;while(m);return g}catch(A){return` -Error generating stack: `+A.message+` -`+A.stack}}var Y=Object.prototype.hasOwnProperty,he=t.unstable_scheduleCallback,be=t.unstable_cancelCallback,J=t.unstable_shouldYield,z=t.unstable_requestPaint,R=t.unstable_now,q=t.unstable_getCurrentPriorityLevel,fe=t.unstable_ImmediatePriority,we=t.unstable_UserBlockingPriority,xe=t.unstable_NormalPriority,ze=t.unstable_LowPriority,Ne=t.unstable_IdlePriority,He=t.log,Ze=t.unstable_setDisableYieldValue,Se=null,ve=null;function Ce(m){if(typeof He=="function"&&Ze(m),ve&&typeof ve.setStrictMode=="function")try{ve.setStrictMode(Se,m)}catch{}}var Ue=Math.clz32?Math.clz32:Te,je=Math.log,Ve=Math.LN2;function Te(m){return m>>>=0,m===0?32:31-(je(m)/Ve|0)|0}var Je=256,Pe=262144,Ye=4194304;function Re(m){var g=m&42;if(g!==0)return g;switch(m&-m){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return m&261888;case 262144:case 524288:case 1048576:case 2097152:return m&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return m&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return m}}function Oe(m,g,_){var A=m.pendingLanes;if(A===0)return 0;var F=0,O=m.suspendedLanes,ie=m.pingedLanes;m=m.warmLanes;var Me=A&134217727;return Me!==0?(A=Me&~O,A!==0?F=Re(A):(ie&=Me,ie!==0?F=Re(ie):_||(_=Me&~m,_!==0&&(F=Re(_))))):(Me=A&~O,Me!==0?F=Re(Me):ie!==0?F=Re(ie):_||(_=A&~m,_!==0&&(F=Re(_)))),F===0?0:g!==0&&g!==F&&(g&O)===0&&(O=F&-F,_=g&-g,O>=_||O===32&&(_&4194048)!==0)?g:F}function qe(m,g){return(m.pendingLanes&~(m.suspendedLanes&~m.pingedLanes)&g)===0}function pt(m,g){switch(m){case 1:case 2:case 4:case 8:case 64:return g+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return g+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function kt(){var m=Ye;return Ye<<=1,(Ye&62914560)===0&&(Ye=4194304),m}function Dt(m){for(var g=[],_=0;31>_;_++)g.push(m);return g}function nn(m,g){m.pendingLanes|=g,g!==268435456&&(m.suspendedLanes=0,m.pingedLanes=0,m.warmLanes=0)}function Tt(m,g,_,A,F,O){var ie=m.pendingLanes;m.pendingLanes=_,m.suspendedLanes=0,m.pingedLanes=0,m.warmLanes=0,m.expiredLanes&=_,m.entangledLanes&=_,m.errorRecoveryDisabledLanes&=_,m.shellSuspendCounter=0;var Me=m.entanglements,Be=m.expirationTimes,dt=m.hiddenUpdates;for(_=ie&~_;0<_;){var vt=31-Ue(_),Ct=1<"u")return null;try{return m.activeElement||m.body}catch{return m.body}}var qr=/[\n"\\]/g;function Dn(m){return m.replace(qr,function(g){return"\\"+g.charCodeAt(0).toString(16)+" "})}function _n(m,g,_,A,F,O,ie,Me){m.name="",ie!=null&&typeof ie!="function"&&typeof ie!="symbol"&&typeof ie!="boolean"?m.type=ie:m.removeAttribute("type"),g!=null?ie==="number"?(g===0&&m.value===""||m.value!=g)&&(m.value=""+En(g)):m.value!==""+En(g)&&(m.value=""+En(g)):ie!=="submit"&&ie!=="reset"||m.removeAttribute("value"),g!=null?mi(m,ie,En(g)):_!=null?mi(m,ie,En(_)):A!=null&&m.removeAttribute("value"),F==null&&O!=null&&(m.defaultChecked=!!O),F!=null&&(m.checked=F&&typeof F!="function"&&typeof F!="symbol"),Me!=null&&typeof Me!="function"&&typeof Me!="symbol"&&typeof Me!="boolean"?m.name=""+En(Me):m.removeAttribute("name")}function Gn(m,g,_,A,F,O,ie,Me){if(O!=null&&typeof O!="function"&&typeof O!="symbol"&&typeof O!="boolean"&&(m.type=O),g!=null||_!=null){if(!(O!=="submit"&&O!=="reset"||g!=null)){fn(m);return}_=_!=null?""+En(_):"",g=g!=null?""+En(g):_,Me||g===m.value||(m.value=g),m.defaultValue=g}A=A??F,A=typeof A!="function"&&typeof A!="symbol"&&!!A,m.checked=Me?m.checked:!!A,m.defaultChecked=!!A,ie!=null&&typeof ie!="function"&&typeof ie!="symbol"&&typeof ie!="boolean"&&(m.name=ie),fn(m)}function mi(m,g,_){g==="number"&&Gr(m.ownerDocument)===m||m.defaultValue===""+_||(m.defaultValue=""+_)}function mr(m,g,_,A){if(m=m.options,g){g={};for(var F=0;F<_.length;F++)g["$"+_[F]]=!0;for(_=0;_"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ir=!1;if(Oi)try{var kl={};Object.defineProperty(kl,"passive",{get:function(){Ir=!0}}),window.addEventListener("test",kl,kl),window.removeEventListener("test",kl,kl)}catch{Ir=!1}var Ba=null,wi=null,ac=null;function Wr(){if(ac)return ac;var m,g=wi,_=g.length,A,F="value"in Ba?Ba.value:Ba.textContent,O=F.length;for(m=0;m<_&&g[m]===F[m];m++);var ie=_-m;for(A=1;A<=ie&&g[_-A]===F[O-A];A++);return ac=F.slice(m,1=fx),pI=" ",gI=!1;function bI(m,g){switch(m){case"keyup":return Yae.indexOf(g.keyCode)!==-1;case"keydown":return g.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function xI(m){return m=m.detail,typeof m=="object"&&"data"in m?m.data:null}var dp=!1;function Zae(m,g){switch(m){case"compositionend":return xI(g);case"keypress":return g.which!==32?null:(gI=!0,pI);case"textInput":return m=g.data,m===pI&&gI?null:m;default:return null}}function Jae(m,g){if(dp)return m==="compositionend"||!IM&&bI(m,g)?(m=Wr(),ac=wi=Ba=null,dp=!1,m):null;switch(m){case"paste":return null;case"keypress":if(!(g.ctrlKey||g.altKey||g.metaKey)||g.ctrlKey&&g.altKey){if(g.char&&1=g)return{node:_,offset:g-m};m=A}e:{for(;_;){if(_.nextSibling){_=_.nextSibling;break e}_=_.parentNode}_=void 0}_=CI(_)}}function AI(m,g){return m&&g?m===g?!0:m&&m.nodeType===3?!1:g&&g.nodeType===3?AI(m,g.parentNode):"contains"in m?m.contains(g):m.compareDocumentPosition?!!(m.compareDocumentPosition(g)&16):!1:!1}function TI(m){m=m!=null&&m.ownerDocument!=null&&m.ownerDocument.defaultView!=null?m.ownerDocument.defaultView:window;for(var g=Gr(m.document);g instanceof m.HTMLIFrameElement;){try{var _=typeof g.contentWindow.location.href=="string"}catch{_=!1}if(_)m=g.contentWindow;else break;g=Gr(m.document)}return g}function BM(m){var g=m&&m.nodeName&&m.nodeName.toLowerCase();return g&&(g==="input"&&(m.type==="text"||m.type==="search"||m.type==="tel"||m.type==="url"||m.type==="password")||g==="textarea"||m.contentEditable==="true")}var ose=Oi&&"documentMode"in document&&11>=document.documentMode,hp=null,HM=null,xx=null,$M=!1;function EI(m,g,_){var A=_.window===_?_.document:_.nodeType===9?_:_.ownerDocument;$M||hp==null||hp!==Gr(A)||(A=hp,"selectionStart"in A&&BM(A)?A={start:A.selectionStart,end:A.selectionEnd}:(A=(A.ownerDocument&&A.ownerDocument.defaultView||window).getSelection(),A={anchorNode:A.anchorNode,anchorOffset:A.anchorOffset,focusNode:A.focusNode,focusOffset:A.focusOffset}),xx&&bx(xx,A)||(xx=A,A=$w(HM,"onSelect"),0>=ie,F-=ie,oc=1<<32-Ue(g)+F|_<jn?(Zn=Xt,Xt=null):Zn=Xt.sibling;var cr=mt(nt,Xt,ut[jn],_t);if(cr===null){Xt===null&&(Xt=Zn);break}m&&Xt&&cr.alternate===null&&g(nt,Xt),Ke=O(cr,Ke,jn),lr===null?an=cr:lr.sibling=cr,lr=cr,Xt=Zn}if(jn===ut.length)return _(nt,Xt),nr&&Zc(nt,jn),an;if(Xt===null){for(;jnjn?(Zn=Xt,Xt=null):Zn=Xt.sibling;var Vd=mt(nt,Xt,cr.value,_t);if(Vd===null){Xt===null&&(Xt=Zn);break}m&&Xt&&Vd.alternate===null&&g(nt,Xt),Ke=O(Vd,Ke,jn),lr===null?an=Vd:lr.sibling=Vd,lr=Vd,Xt=Zn}if(cr.done)return _(nt,Xt),nr&&Zc(nt,jn),an;if(Xt===null){for(;!cr.done;jn++,cr=ut.next())cr=Ct(nt,cr.value,_t),cr!==null&&(Ke=O(cr,Ke,jn),lr===null?an=cr:lr.sibling=cr,lr=cr);return nr&&Zc(nt,jn),an}for(Xt=A(Xt);!cr.done;jn++,cr=ut.next())cr=xt(Xt,nt,jn,cr.value,_t),cr!==null&&(m&&cr.alternate!==null&&Xt.delete(cr.key===null?jn:cr.key),Ke=O(cr,Ke,jn),lr===null?an=cr:lr.sibling=cr,lr=cr);return m&&Xt.forEach(function(Moe){return g(nt,Moe)}),nr&&Zc(nt,jn),an}function Ar(nt,Ke,ut,_t){if(typeof ut=="object"&&ut!==null&&ut.type===v&&ut.key===null&&(ut=ut.props.children),typeof ut=="object"&&ut!==null){switch(ut.$$typeof){case p:e:{for(var an=ut.key;Ke!==null;){if(Ke.key===an){if(an=ut.type,an===v){if(Ke.tag===7){_(nt,Ke.sibling),_t=F(Ke,ut.props.children),_t.return=nt,nt=_t;break e}}else if(Ke.elementType===an||typeof an=="object"&&an!==null&&an.$$typeof===j&&Nm(an)===Ke.type){_(nt,Ke.sibling),_t=F(Ke,ut.props),Nx(_t,ut),_t.return=nt,nt=_t;break e}_(nt,Ke);break}else g(nt,Ke);Ke=Ke.sibling}ut.type===v?(_t=ym(ut.props.children,nt.mode,_t,ut.key),_t.return=nt,nt=_t):(_t=sw(ut.type,ut.key,ut.props,null,nt.mode,_t),Nx(_t,ut),_t.return=nt,nt=_t)}return ie(nt);case x:e:{for(an=ut.key;Ke!==null;){if(Ke.key===an)if(Ke.tag===4&&Ke.stateNode.containerInfo===ut.containerInfo&&Ke.stateNode.implementation===ut.implementation){_(nt,Ke.sibling),_t=F(Ke,ut.children||[]),_t.return=nt,nt=_t;break e}else{_(nt,Ke);break}else g(nt,Ke);Ke=Ke.sibling}_t=YM(ut,nt.mode,_t),_t.return=nt,nt=_t}return ie(nt);case j:return ut=Nm(ut),Ar(nt,Ke,ut,_t)}if(H(ut))return Wt(nt,Ke,ut,_t);if(L(ut)){if(an=L(ut),typeof an!="function")throw Error(r(150));return ut=an.call(ut),dn(nt,Ke,ut,_t)}if(typeof ut.then=="function")return Ar(nt,Ke,mw(ut),_t);if(ut.$$typeof===N)return Ar(nt,Ke,cw(nt,ut),_t);fw(nt,ut)}return typeof ut=="string"&&ut!==""||typeof ut=="number"||typeof ut=="bigint"?(ut=""+ut,Ke!==null&&Ke.tag===6?(_(nt,Ke.sibling),_t=F(Ke,ut),_t.return=nt,nt=_t):(_(nt,Ke),_t=XM(ut,nt.mode,_t),_t.return=nt,nt=_t),ie(nt)):_(nt,Ke)}return function(nt,Ke,ut,_t){try{Sx=0;var an=Ar(nt,Ke,ut,_t);return Sp=null,an}catch(Xt){if(Xt===_p||Xt===dw)throw Xt;var lr=ho(29,Xt,null,nt.mode);return lr.lanes=_t,lr.return=nt,lr}}}var Cm=JI(!0),e5=JI(!1),Md=!1;function lA(m){m.updateQueue={baseState:m.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function cA(m,g){m=m.updateQueue,g.updateQueue===m&&(g.updateQueue={baseState:m.baseState,firstBaseUpdate:m.firstBaseUpdate,lastBaseUpdate:m.lastBaseUpdate,shared:m.shared,callbacks:null})}function Ad(m){return{lane:m,tag:0,payload:null,callback:null,next:null}}function Td(m,g,_){var A=m.updateQueue;if(A===null)return null;if(A=A.shared,(pr&2)!==0){var F=A.pending;return F===null?g.next=g:(g.next=F.next,F.next=g),A.pending=g,g=aw(m),OI(m,null,_),g}return iw(m,A,g,_),aw(m)}function kx(m,g,_){if(g=g.updateQueue,g!==null&&(g=g.shared,(_&4194048)!==0)){var A=g.lanes;A&=m.pendingLanes,_|=A,g.lanes=_,gt(m,_)}}function uA(m,g){var _=m.updateQueue,A=m.alternate;if(A!==null&&(A=A.updateQueue,_===A)){var F=null,O=null;if(_=_.firstBaseUpdate,_!==null){do{var ie={lane:_.lane,tag:_.tag,payload:_.payload,callback:null,next:null};O===null?F=O=ie:O=O.next=ie,_=_.next}while(_!==null);O===null?F=O=g:O=O.next=g}else F=O=g;_={baseState:A.baseState,firstBaseUpdate:F,lastBaseUpdate:O,shared:A.shared,callbacks:A.callbacks},m.updateQueue=_;return}m=_.lastBaseUpdate,m===null?_.firstBaseUpdate=g:m.next=g,_.lastBaseUpdate=g}var dA=!1;function Cx(){if(dA){var m=wp;if(m!==null)throw m}}function Mx(m,g,_,A){dA=!1;var F=m.updateQueue;Md=!1;var O=F.firstBaseUpdate,ie=F.lastBaseUpdate,Me=F.shared.pending;if(Me!==null){F.shared.pending=null;var Be=Me,dt=Be.next;Be.next=null,ie===null?O=dt:ie.next=dt,ie=Be;var vt=m.alternate;vt!==null&&(vt=vt.updateQueue,Me=vt.lastBaseUpdate,Me!==ie&&(Me===null?vt.firstBaseUpdate=dt:Me.next=dt,vt.lastBaseUpdate=Be))}if(O!==null){var Ct=F.baseState;ie=0,vt=dt=Be=null,Me=O;do{var mt=Me.lane&-536870913,xt=mt!==Me.lane;if(xt?(Qn&mt)===mt:(A&mt)===mt){mt!==0&&mt===vp&&(dA=!0),vt!==null&&(vt=vt.next={lane:0,tag:Me.tag,payload:Me.payload,callback:null,next:null});e:{var Wt=m,dn=Me;mt=g;var Ar=_;switch(dn.tag){case 1:if(Wt=dn.payload,typeof Wt=="function"){Ct=Wt.call(Ar,Ct,mt);break e}Ct=Wt;break e;case 3:Wt.flags=Wt.flags&-65537|128;case 0:if(Wt=dn.payload,mt=typeof Wt=="function"?Wt.call(Ar,Ct,mt):Wt,mt==null)break e;Ct=h({},Ct,mt);break e;case 2:Md=!0}}mt=Me.callback,mt!==null&&(m.flags|=64,xt&&(m.flags|=8192),xt=F.callbacks,xt===null?F.callbacks=[mt]:xt.push(mt))}else xt={lane:mt,tag:Me.tag,payload:Me.payload,callback:Me.callback,next:null},vt===null?(dt=vt=xt,Be=Ct):vt=vt.next=xt,ie|=mt;if(Me=Me.next,Me===null){if(Me=F.shared.pending,Me===null)break;xt=Me,Me=xt.next,xt.next=null,F.lastBaseUpdate=xt,F.shared.pending=null}}while(!0);vt===null&&(Be=Ct),F.baseState=Be,F.firstBaseUpdate=dt,F.lastBaseUpdate=vt,O===null&&(F.shared.lanes=0),Rd|=ie,m.lanes=ie,m.memoizedState=Ct}}function t5(m,g){if(typeof m!="function")throw Error(r(191,m));m.call(g)}function n5(m,g){var _=m.callbacks;if(_!==null)for(m.callbacks=null,m=0;m<_.length;m++)t5(_[m],g)}var Np=V(null),pw=V(0);function r5(m,g){m=cu,re(pw,m),re(Np,g),cu=m|g.baseLanes}function hA(){re(pw,cu),re(Np,Np.current)}function mA(){cu=pw.current,X(Np),X(pw)}var mo=V(null),$o=null;function Ed(m){var g=m.alternate;re(Ii,Ii.current&1),re(mo,m),$o===null&&(g===null||Np.current!==null||g.memoizedState!==null)&&($o=m)}function fA(m){re(Ii,Ii.current),re(mo,m),$o===null&&($o=m)}function i5(m){m.tag===22?(re(Ii,Ii.current),re(mo,m),$o===null&&($o=m)):Pd()}function Pd(){re(Ii,Ii.current),re(mo,mo.current)}function fo(m){X(mo),$o===m&&($o=null),X(Ii)}var Ii=V(0);function gw(m){for(var g=m;g!==null;){if(g.tag===13){var _=g.memoizedState;if(_!==null&&(_=_.dehydrated,_===null||vT(_)||wT(_)))return g}else if(g.tag===19&&(g.memoizedProps.revealOrder==="forwards"||g.memoizedProps.revealOrder==="backwards"||g.memoizedProps.revealOrder==="unstable_legacy-backwards"||g.memoizedProps.revealOrder==="together")){if((g.flags&128)!==0)return g}else if(g.child!==null){g.child.return=g,g=g.child;continue}if(g===m)break;for(;g.sibling===null;){if(g.return===null||g.return===m)return null;g=g.return}g.sibling.return=g.return,g=g.sibling}return null}var tu=0,Pn=null,Cr=null,Ki=null,bw=!1,kp=!1,Mm=!1,xw=0,Ax=0,Cp=null,bse=0;function Si(){throw Error(r(321))}function pA(m,g){if(g===null)return!1;for(var _=0;_O?O:8;var ie=G.T,Me={};G.T=Me,EA(m,!1,g,_);try{var Be=F(),dt=G.S;if(dt!==null&&dt(Me,Be),Be!==null&&typeof Be=="object"&&typeof Be.then=="function"){var vt=gse(Be,A);Ex(m,g,vt,bo(m))}else Ex(m,g,A,bo(m))}catch(Ct){Ex(m,g,{then:function(){},status:"rejected",reason:Ct},bo())}finally{I.p=O,ie!==null&&Me.types!==null&&(ie.types=Me.types),G.T=ie}}function _se(){}function AA(m,g,_,A){if(m.tag!==5)throw Error(r(476));var F=R5(m).queue;D5(m,F,g,W,_===null?_se:function(){return F5(m),_(A)})}function R5(m){var g=m.memoizedState;if(g!==null)return g;g={memoizedState:W,baseState:W,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:nu,lastRenderedState:W},next:null};var _={};return g.next={memoizedState:_,baseState:_,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:nu,lastRenderedState:_},next:null},m.memoizedState=g,m=m.alternate,m!==null&&(m.memoizedState=g),g}function F5(m){var g=R5(m);g.next===null&&(g=m.alternate.memoizedState),Ex(m,g.next.queue,{},bo())}function TA(){return $a(Wx)}function L5(){return zi().memoizedState}function O5(){return zi().memoizedState}function Sse(m){for(var g=m.return;g!==null;){switch(g.tag){case 24:case 3:var _=bo();m=Ad(_);var A=Td(g,m,_);A!==null&&(qs(A,g,_),kx(A,g,_)),g={cache:iA()},m.payload=g;return}g=g.return}}function Nse(m,g,_){var A=bo();_={lane:A,revertLane:0,gesture:null,action:_,hasEagerState:!1,eagerState:null,next:null},Nw(m)?z5(g,_):(_=WM(m,g,_,A),_!==null&&(qs(_,m,A),U5(_,g,A)))}function I5(m,g,_){var A=bo();Ex(m,g,_,A)}function Ex(m,g,_,A){var F={lane:A,revertLane:0,gesture:null,action:_,hasEagerState:!1,eagerState:null,next:null};if(Nw(m))z5(g,F);else{var O=m.alternate;if(m.lanes===0&&(O===null||O.lanes===0)&&(O=g.lastRenderedReducer,O!==null))try{var ie=g.lastRenderedState,Me=O(ie,_);if(F.hasEagerState=!0,F.eagerState=Me,uo(Me,ie))return iw(m,g,F,0),zr===null&&rw(),!1}catch{}if(_=WM(m,g,F,A),_!==null)return qs(_,m,A),U5(_,g,A),!0}return!1}function EA(m,g,_,A){if(A={lane:2,revertLane:lT(),gesture:null,action:A,hasEagerState:!1,eagerState:null,next:null},Nw(m)){if(g)throw Error(r(479))}else g=WM(m,_,A,2),g!==null&&qs(g,m,2)}function Nw(m){var g=m.alternate;return m===Pn||g!==null&&g===Pn}function z5(m,g){kp=bw=!0;var _=m.pending;_===null?g.next=g:(g.next=_.next,_.next=g),m.pending=g}function U5(m,g,_){if((_&4194048)!==0){var A=g.lanes;A&=m.pendingLanes,_|=A,g.lanes=_,gt(m,_)}}var Px={readContext:$a,use:vw,useCallback:Si,useContext:Si,useEffect:Si,useImperativeHandle:Si,useLayoutEffect:Si,useInsertionEffect:Si,useMemo:Si,useReducer:Si,useRef:Si,useState:Si,useDebugValue:Si,useDeferredValue:Si,useTransition:Si,useSyncExternalStore:Si,useId:Si,useHostTransitionStatus:Si,useFormState:Si,useActionState:Si,useOptimistic:Si,useMemoCache:Si,useCacheRefresh:Si};Px.useEffectEvent=Si;var B5={readContext:$a,use:vw,useCallback:function(m,g){return Cs().memoizedState=[m,g===void 0?null:g],m},useContext:$a,useEffect:N5,useImperativeHandle:function(m,g,_){_=_!=null?_.concat([m]):null,_w(4194308,4,A5.bind(null,g,m),_)},useLayoutEffect:function(m,g){return _w(4194308,4,m,g)},useInsertionEffect:function(m,g){_w(4,2,m,g)},useMemo:function(m,g){var _=Cs();g=g===void 0?null:g;var A=m();if(Mm){Ce(!0);try{m()}finally{Ce(!1)}}return _.memoizedState=[A,g],A},useReducer:function(m,g,_){var A=Cs();if(_!==void 0){var F=_(g);if(Mm){Ce(!0);try{_(g)}finally{Ce(!1)}}}else F=g;return A.memoizedState=A.baseState=F,m={pending:null,lanes:0,dispatch:null,lastRenderedReducer:m,lastRenderedState:F},A.queue=m,m=m.dispatch=Nse.bind(null,Pn,m),[A.memoizedState,m]},useRef:function(m){var g=Cs();return m={current:m},g.memoizedState=m},useState:function(m){m=SA(m);var g=m.queue,_=I5.bind(null,Pn,g);return g.dispatch=_,[m.memoizedState,_]},useDebugValue:CA,useDeferredValue:function(m,g){var _=Cs();return MA(_,m,g)},useTransition:function(){var m=SA(!1);return m=D5.bind(null,Pn,m.queue,!0,!1),Cs().memoizedState=m,[!1,m]},useSyncExternalStore:function(m,g,_){var A=Pn,F=Cs();if(nr){if(_===void 0)throw Error(r(407));_=_()}else{if(_=g(),zr===null)throw Error(r(349));(Qn&127)!==0||l5(A,g,_)}F.memoizedState=_;var O={value:_,getSnapshot:g};return F.queue=O,N5(u5.bind(null,A,O,m),[m]),A.flags|=2048,Mp(9,{destroy:void 0},c5.bind(null,A,O,_,g),null),_},useId:function(){var m=Cs(),g=zr.identifierPrefix;if(nr){var _=lc,A=oc;_=(A&~(1<<32-Ue(A)-1)).toString(32)+_,g="_"+g+"R_"+_,_=xw++,0<_&&(g+="H"+_.toString(32)),g+="_"}else _=bse++,g="_"+g+"r_"+_.toString(32)+"_";return m.memoizedState=g},useHostTransitionStatus:TA,useFormState:y5,useActionState:y5,useOptimistic:function(m){var g=Cs();g.memoizedState=g.baseState=m;var _={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return g.queue=_,g=EA.bind(null,Pn,!0,_),_.dispatch=g,[m,g]},useMemoCache:vA,useCacheRefresh:function(){return Cs().memoizedState=Sse.bind(null,Pn)},useEffectEvent:function(m){var g=Cs(),_={impl:m};return g.memoizedState=_,function(){if((pr&2)!==0)throw Error(r(440));return _.impl.apply(void 0,arguments)}}},PA={readContext:$a,use:vw,useCallback:E5,useContext:$a,useEffect:kA,useImperativeHandle:T5,useInsertionEffect:C5,useLayoutEffect:M5,useMemo:P5,useReducer:ww,useRef:S5,useState:function(){return ww(nu)},useDebugValue:CA,useDeferredValue:function(m,g){var _=zi();return j5(_,Cr.memoizedState,m,g)},useTransition:function(){var m=ww(nu)[0],g=zi().memoizedState;return[typeof m=="boolean"?m:Tx(m),g]},useSyncExternalStore:o5,useId:L5,useHostTransitionStatus:TA,useFormState:v5,useActionState:v5,useOptimistic:function(m,g){var _=zi();return m5(_,Cr,m,g)},useMemoCache:vA,useCacheRefresh:O5};PA.useEffectEvent=k5;var H5={readContext:$a,use:vw,useCallback:E5,useContext:$a,useEffect:kA,useImperativeHandle:T5,useInsertionEffect:C5,useLayoutEffect:M5,useMemo:P5,useReducer:_A,useRef:S5,useState:function(){return _A(nu)},useDebugValue:CA,useDeferredValue:function(m,g){var _=zi();return Cr===null?MA(_,m,g):j5(_,Cr.memoizedState,m,g)},useTransition:function(){var m=_A(nu)[0],g=zi().memoizedState;return[typeof m=="boolean"?m:Tx(m),g]},useSyncExternalStore:o5,useId:L5,useHostTransitionStatus:TA,useFormState:_5,useActionState:_5,useOptimistic:function(m,g){var _=zi();return Cr!==null?m5(_,Cr,m,g):(_.baseState=m,[m,_.queue.dispatch])},useMemoCache:vA,useCacheRefresh:O5};H5.useEffectEvent=k5;function jA(m,g,_,A){g=m.memoizedState,_=_(A,g),_=_==null?g:h({},g,_),m.memoizedState=_,m.lanes===0&&(m.updateQueue.baseState=_)}var DA={enqueueSetState:function(m,g,_){m=m._reactInternals;var A=bo(),F=Ad(A);F.payload=g,_!=null&&(F.callback=_),g=Td(m,F,A),g!==null&&(qs(g,m,A),kx(g,m,A))},enqueueReplaceState:function(m,g,_){m=m._reactInternals;var A=bo(),F=Ad(A);F.tag=1,F.payload=g,_!=null&&(F.callback=_),g=Td(m,F,A),g!==null&&(qs(g,m,A),kx(g,m,A))},enqueueForceUpdate:function(m,g){m=m._reactInternals;var _=bo(),A=Ad(_);A.tag=2,g!=null&&(A.callback=g),g=Td(m,A,_),g!==null&&(qs(g,m,_),kx(g,m,_))}};function $5(m,g,_,A,F,O,ie){return m=m.stateNode,typeof m.shouldComponentUpdate=="function"?m.shouldComponentUpdate(A,O,ie):g.prototype&&g.prototype.isPureReactComponent?!bx(_,A)||!bx(F,O):!0}function V5(m,g,_,A){m=g.state,typeof g.componentWillReceiveProps=="function"&&g.componentWillReceiveProps(_,A),typeof g.UNSAFE_componentWillReceiveProps=="function"&&g.UNSAFE_componentWillReceiveProps(_,A),g.state!==m&&DA.enqueueReplaceState(g,g.state,null)}function Am(m,g){var _=g;if("ref"in g){_={};for(var A in g)A!=="ref"&&(_[A]=g[A])}if(m=m.defaultProps){_===g&&(_=h({},_));for(var F in m)_[F]===void 0&&(_[F]=m[F])}return _}function G5(m){nw(m)}function q5(m){console.error(m)}function W5(m){nw(m)}function kw(m,g){try{var _=m.onUncaughtError;_(g.value,{componentStack:g.stack})}catch(A){setTimeout(function(){throw A})}}function K5(m,g,_){try{var A=m.onCaughtError;A(_.value,{componentStack:_.stack,errorBoundary:g.tag===1?g.stateNode:null})}catch(F){setTimeout(function(){throw F})}}function RA(m,g,_){return _=Ad(_),_.tag=3,_.payload={element:null},_.callback=function(){kw(m,g)},_}function X5(m){return m=Ad(m),m.tag=3,m}function Y5(m,g,_,A){var F=_.type.getDerivedStateFromError;if(typeof F=="function"){var O=A.value;m.payload=function(){return F(O)},m.callback=function(){K5(g,_,A)}}var ie=_.stateNode;ie!==null&&typeof ie.componentDidCatch=="function"&&(m.callback=function(){K5(g,_,A),typeof F!="function"&&(Fd===null?Fd=new Set([this]):Fd.add(this));var Me=A.stack;this.componentDidCatch(A.value,{componentStack:Me!==null?Me:""})})}function kse(m,g,_,A,F){if(_.flags|=32768,A!==null&&typeof A=="object"&&typeof A.then=="function"){if(g=_.alternate,g!==null&&yp(g,_,F,!0),_=mo.current,_!==null){switch(_.tag){case 31:case 13:return $o===null?Ow():_.alternate===null&&Ni===0&&(Ni=3),_.flags&=-257,_.flags|=65536,_.lanes=F,A===hw?_.flags|=16384:(g=_.updateQueue,g===null?_.updateQueue=new Set([A]):g.add(A),aT(m,A,F)),!1;case 22:return _.flags|=65536,A===hw?_.flags|=16384:(g=_.updateQueue,g===null?(g={transitions:null,markerInstances:null,retryQueue:new Set([A])},_.updateQueue=g):(_=g.retryQueue,_===null?g.retryQueue=new Set([A]):_.add(A)),aT(m,A,F)),!1}throw Error(r(435,_.tag))}return aT(m,A,F),Ow(),!1}if(nr)return g=mo.current,g!==null?((g.flags&65536)===0&&(g.flags|=256),g.flags|=65536,g.lanes=F,A!==JM&&(m=Error(r(422),{cause:A}),vx(zo(m,_)))):(A!==JM&&(g=Error(r(423),{cause:A}),vx(zo(g,_))),m=m.current.alternate,m.flags|=65536,F&=-F,m.lanes|=F,A=zo(A,_),F=RA(m.stateNode,A,F),uA(m,F),Ni!==4&&(Ni=2)),!1;var O=Error(r(520),{cause:A});if(O=zo(O,_),zx===null?zx=[O]:zx.push(O),Ni!==4&&(Ni=2),g===null)return!0;A=zo(A,_),_=g;do{switch(_.tag){case 3:return _.flags|=65536,m=F&-F,_.lanes|=m,m=RA(_.stateNode,A,m),uA(_,m),!1;case 1:if(g=_.type,O=_.stateNode,(_.flags&128)===0&&(typeof g.getDerivedStateFromError=="function"||O!==null&&typeof O.componentDidCatch=="function"&&(Fd===null||!Fd.has(O))))return _.flags|=65536,F&=-F,_.lanes|=F,F=X5(F),Y5(F,m,_,A),uA(_,F),!1}_=_.return}while(_!==null);return!1}var FA=Error(r(461)),Xi=!1;function Va(m,g,_,A){g.child=m===null?e5(g,null,_,A):Cm(g,m.child,_,A)}function Q5(m,g,_,A,F){_=_.render;var O=g.ref;if("ref"in A){var ie={};for(var Me in A)Me!=="ref"&&(ie[Me]=A[Me])}else ie=A;return _m(g),A=gA(m,g,_,ie,O,F),Me=bA(),m!==null&&!Xi?(xA(m,g,F),ru(m,g,F)):(nr&&Me&&QM(g),g.flags|=1,Va(m,g,A,F),g.child)}function Z5(m,g,_,A,F){if(m===null){var O=_.type;return typeof O=="function"&&!KM(O)&&O.defaultProps===void 0&&_.compare===null?(g.tag=15,g.type=O,J5(m,g,O,A,F)):(m=sw(_.type,null,A,g,g.mode,F),m.ref=g.ref,m.return=g,g.child=m)}if(O=m.child,!$A(m,F)){var ie=O.memoizedProps;if(_=_.compare,_=_!==null?_:bx,_(ie,A)&&m.ref===g.ref)return ru(m,g,F)}return g.flags|=1,m=Qc(O,A),m.ref=g.ref,m.return=g,g.child=m}function J5(m,g,_,A,F){if(m!==null){var O=m.memoizedProps;if(bx(O,A)&&m.ref===g.ref)if(Xi=!1,g.pendingProps=A=O,$A(m,F))(m.flags&131072)!==0&&(Xi=!0);else return g.lanes=m.lanes,ru(m,g,F)}return LA(m,g,_,A,F)}function ez(m,g,_,A){var F=A.children,O=m!==null?m.memoizedState:null;if(m===null&&g.stateNode===null&&(g.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),A.mode==="hidden"){if((g.flags&128)!==0){if(O=O!==null?O.baseLanes|_:_,m!==null){for(A=g.child=m.child,F=0;A!==null;)F=F|A.lanes|A.childLanes,A=A.sibling;A=F&~O}else A=0,g.child=null;return tz(m,g,O,_,A)}if((_&536870912)!==0)g.memoizedState={baseLanes:0,cachePool:null},m!==null&&uw(g,O!==null?O.cachePool:null),O!==null?r5(g,O):hA(),i5(g);else return A=g.lanes=536870912,tz(m,g,O!==null?O.baseLanes|_:_,_,A)}else O!==null?(uw(g,O.cachePool),r5(g,O),Pd(),g.memoizedState=null):(m!==null&&uw(g,null),hA(),Pd());return Va(m,g,F,_),g.child}function jx(m,g){return m!==null&&m.tag===22||g.stateNode!==null||(g.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),g.sibling}function tz(m,g,_,A,F){var O=sA();return O=O===null?null:{parent:Wi._currentValue,pool:O},g.memoizedState={baseLanes:_,cachePool:O},m!==null&&uw(g,null),hA(),i5(g),m!==null&&yp(m,g,A,!0),g.childLanes=F,null}function Cw(m,g){return g=Aw({mode:g.mode,children:g.children},m.mode),g.ref=m.ref,m.child=g,g.return=m,g}function nz(m,g,_){return Cm(g,m.child,null,_),m=Cw(g,g.pendingProps),m.flags|=2,fo(g),g.memoizedState=null,m}function Cse(m,g,_){var A=g.pendingProps,F=(g.flags&128)!==0;if(g.flags&=-129,m===null){if(nr){if(A.mode==="hidden")return m=Cw(g,A),g.lanes=536870912,jx(null,m);if(fA(g),(m=ei)?(m=fU(m,Ho),m=m!==null&&m.data==="&"?m:null,m!==null&&(g.memoizedState={dehydrated:m,treeContext:Sd!==null?{id:oc,overflow:lc}:null,retryLane:536870912,hydrationErrors:null},_=zI(m),_.return=g,g.child=_,Ha=g,ei=null)):m=null,m===null)throw kd(g);return g.lanes=536870912,null}return Cw(g,A)}var O=m.memoizedState;if(O!==null){var ie=O.dehydrated;if(fA(g),F)if(g.flags&256)g.flags&=-257,g=nz(m,g,_);else if(g.memoizedState!==null)g.child=m.child,g.flags|=128,g=null;else throw Error(r(558));else if(Xi||yp(m,g,_,!1),F=(_&m.childLanes)!==0,Xi||F){if(A=zr,A!==null&&(ie=Yt(A,_),ie!==0&&ie!==O.retryLane))throw O.retryLane=ie,xm(m,ie),qs(A,m,ie),FA;Ow(),g=nz(m,g,_)}else m=O.treeContext,ei=Vo(ie.nextSibling),Ha=g,nr=!0,Nd=null,Ho=!1,m!==null&&HI(g,m),g=Cw(g,A),g.flags|=4096;return g}return m=Qc(m.child,{mode:A.mode,children:A.children}),m.ref=g.ref,g.child=m,m.return=g,m}function Mw(m,g){var _=g.ref;if(_===null)m!==null&&m.ref!==null&&(g.flags|=4194816);else{if(typeof _!="function"&&typeof _!="object")throw Error(r(284));(m===null||m.ref!==_)&&(g.flags|=4194816)}}function LA(m,g,_,A,F){return _m(g),_=gA(m,g,_,A,void 0,F),A=bA(),m!==null&&!Xi?(xA(m,g,F),ru(m,g,F)):(nr&&A&&QM(g),g.flags|=1,Va(m,g,_,F),g.child)}function rz(m,g,_,A,F,O){return _m(g),g.updateQueue=null,_=s5(g,A,_,F),a5(m),A=bA(),m!==null&&!Xi?(xA(m,g,O),ru(m,g,O)):(nr&&A&&QM(g),g.flags|=1,Va(m,g,_,O),g.child)}function iz(m,g,_,A,F){if(_m(g),g.stateNode===null){var O=pp,ie=_.contextType;typeof ie=="object"&&ie!==null&&(O=$a(ie)),O=new _(A,O),g.memoizedState=O.state!==null&&O.state!==void 0?O.state:null,O.updater=DA,g.stateNode=O,O._reactInternals=g,O=g.stateNode,O.props=A,O.state=g.memoizedState,O.refs={},lA(g),ie=_.contextType,O.context=typeof ie=="object"&&ie!==null?$a(ie):pp,O.state=g.memoizedState,ie=_.getDerivedStateFromProps,typeof ie=="function"&&(jA(g,_,ie,A),O.state=g.memoizedState),typeof _.getDerivedStateFromProps=="function"||typeof O.getSnapshotBeforeUpdate=="function"||typeof O.UNSAFE_componentWillMount!="function"&&typeof O.componentWillMount!="function"||(ie=O.state,typeof O.componentWillMount=="function"&&O.componentWillMount(),typeof O.UNSAFE_componentWillMount=="function"&&O.UNSAFE_componentWillMount(),ie!==O.state&&DA.enqueueReplaceState(O,O.state,null),Mx(g,A,O,F),Cx(),O.state=g.memoizedState),typeof O.componentDidMount=="function"&&(g.flags|=4194308),A=!0}else if(m===null){O=g.stateNode;var Me=g.memoizedProps,Be=Am(_,Me);O.props=Be;var dt=O.context,vt=_.contextType;ie=pp,typeof vt=="object"&&vt!==null&&(ie=$a(vt));var Ct=_.getDerivedStateFromProps;vt=typeof Ct=="function"||typeof O.getSnapshotBeforeUpdate=="function",Me=g.pendingProps!==Me,vt||typeof O.UNSAFE_componentWillReceiveProps!="function"&&typeof O.componentWillReceiveProps!="function"||(Me||dt!==ie)&&V5(g,O,A,ie),Md=!1;var mt=g.memoizedState;O.state=mt,Mx(g,A,O,F),Cx(),dt=g.memoizedState,Me||mt!==dt||Md?(typeof Ct=="function"&&(jA(g,_,Ct,A),dt=g.memoizedState),(Be=Md||$5(g,_,Be,A,mt,dt,ie))?(vt||typeof O.UNSAFE_componentWillMount!="function"&&typeof O.componentWillMount!="function"||(typeof O.componentWillMount=="function"&&O.componentWillMount(),typeof O.UNSAFE_componentWillMount=="function"&&O.UNSAFE_componentWillMount()),typeof O.componentDidMount=="function"&&(g.flags|=4194308)):(typeof O.componentDidMount=="function"&&(g.flags|=4194308),g.memoizedProps=A,g.memoizedState=dt),O.props=A,O.state=dt,O.context=ie,A=Be):(typeof O.componentDidMount=="function"&&(g.flags|=4194308),A=!1)}else{O=g.stateNode,cA(m,g),ie=g.memoizedProps,vt=Am(_,ie),O.props=vt,Ct=g.pendingProps,mt=O.context,dt=_.contextType,Be=pp,typeof dt=="object"&&dt!==null&&(Be=$a(dt)),Me=_.getDerivedStateFromProps,(dt=typeof Me=="function"||typeof O.getSnapshotBeforeUpdate=="function")||typeof O.UNSAFE_componentWillReceiveProps!="function"&&typeof O.componentWillReceiveProps!="function"||(ie!==Ct||mt!==Be)&&V5(g,O,A,Be),Md=!1,mt=g.memoizedState,O.state=mt,Mx(g,A,O,F),Cx();var xt=g.memoizedState;ie!==Ct||mt!==xt||Md||m!==null&&m.dependencies!==null&&lw(m.dependencies)?(typeof Me=="function"&&(jA(g,_,Me,A),xt=g.memoizedState),(vt=Md||$5(g,_,vt,A,mt,xt,Be)||m!==null&&m.dependencies!==null&&lw(m.dependencies))?(dt||typeof O.UNSAFE_componentWillUpdate!="function"&&typeof O.componentWillUpdate!="function"||(typeof O.componentWillUpdate=="function"&&O.componentWillUpdate(A,xt,Be),typeof O.UNSAFE_componentWillUpdate=="function"&&O.UNSAFE_componentWillUpdate(A,xt,Be)),typeof O.componentDidUpdate=="function"&&(g.flags|=4),typeof O.getSnapshotBeforeUpdate=="function"&&(g.flags|=1024)):(typeof O.componentDidUpdate!="function"||ie===m.memoizedProps&&mt===m.memoizedState||(g.flags|=4),typeof O.getSnapshotBeforeUpdate!="function"||ie===m.memoizedProps&&mt===m.memoizedState||(g.flags|=1024),g.memoizedProps=A,g.memoizedState=xt),O.props=A,O.state=xt,O.context=Be,A=vt):(typeof O.componentDidUpdate!="function"||ie===m.memoizedProps&&mt===m.memoizedState||(g.flags|=4),typeof O.getSnapshotBeforeUpdate!="function"||ie===m.memoizedProps&&mt===m.memoizedState||(g.flags|=1024),A=!1)}return O=A,Mw(m,g),A=(g.flags&128)!==0,O||A?(O=g.stateNode,_=A&&typeof _.getDerivedStateFromError!="function"?null:O.render(),g.flags|=1,m!==null&&A?(g.child=Cm(g,m.child,null,F),g.child=Cm(g,null,_,F)):Va(m,g,_,F),g.memoizedState=O.state,m=g.child):m=ru(m,g,F),m}function az(m,g,_,A){return vm(),g.flags|=256,Va(m,g,_,A),g.child}var OA={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function IA(m){return{baseLanes:m,cachePool:KI()}}function zA(m,g,_){return m=m!==null?m.childLanes&~_:0,g&&(m|=go),m}function sz(m,g,_){var A=g.pendingProps,F=!1,O=(g.flags&128)!==0,ie;if((ie=O)||(ie=m!==null&&m.memoizedState===null?!1:(Ii.current&2)!==0),ie&&(F=!0,g.flags&=-129),ie=(g.flags&32)!==0,g.flags&=-33,m===null){if(nr){if(F?Ed(g):Pd(),(m=ei)?(m=fU(m,Ho),m=m!==null&&m.data!=="&"?m:null,m!==null&&(g.memoizedState={dehydrated:m,treeContext:Sd!==null?{id:oc,overflow:lc}:null,retryLane:536870912,hydrationErrors:null},_=zI(m),_.return=g,g.child=_,Ha=g,ei=null)):m=null,m===null)throw kd(g);return wT(m)?g.lanes=32:g.lanes=536870912,null}var Me=A.children;return A=A.fallback,F?(Pd(),F=g.mode,Me=Aw({mode:"hidden",children:Me},F),A=ym(A,F,_,null),Me.return=g,A.return=g,Me.sibling=A,g.child=Me,A=g.child,A.memoizedState=IA(_),A.childLanes=zA(m,ie,_),g.memoizedState=OA,jx(null,A)):(Ed(g),UA(g,Me))}var Be=m.memoizedState;if(Be!==null&&(Me=Be.dehydrated,Me!==null)){if(O)g.flags&256?(Ed(g),g.flags&=-257,g=BA(m,g,_)):g.memoizedState!==null?(Pd(),g.child=m.child,g.flags|=128,g=null):(Pd(),Me=A.fallback,F=g.mode,A=Aw({mode:"visible",children:A.children},F),Me=ym(Me,F,_,null),Me.flags|=2,A.return=g,Me.return=g,A.sibling=Me,g.child=A,Cm(g,m.child,null,_),A=g.child,A.memoizedState=IA(_),A.childLanes=zA(m,ie,_),g.memoizedState=OA,g=jx(null,A));else if(Ed(g),wT(Me)){if(ie=Me.nextSibling&&Me.nextSibling.dataset,ie)var dt=ie.dgst;ie=dt,A=Error(r(419)),A.stack="",A.digest=ie,vx({value:A,source:null,stack:null}),g=BA(m,g,_)}else if(Xi||yp(m,g,_,!1),ie=(_&m.childLanes)!==0,Xi||ie){if(ie=zr,ie!==null&&(A=Yt(ie,_),A!==0&&A!==Be.retryLane))throw Be.retryLane=A,xm(m,A),qs(ie,m,A),FA;vT(Me)||Ow(),g=BA(m,g,_)}else vT(Me)?(g.flags|=192,g.child=m.child,g=null):(m=Be.treeContext,ei=Vo(Me.nextSibling),Ha=g,nr=!0,Nd=null,Ho=!1,m!==null&&HI(g,m),g=UA(g,A.children),g.flags|=4096);return g}return F?(Pd(),Me=A.fallback,F=g.mode,Be=m.child,dt=Be.sibling,A=Qc(Be,{mode:"hidden",children:A.children}),A.subtreeFlags=Be.subtreeFlags&65011712,dt!==null?Me=Qc(dt,Me):(Me=ym(Me,F,_,null),Me.flags|=2),Me.return=g,A.return=g,A.sibling=Me,g.child=A,jx(null,A),A=g.child,Me=m.child.memoizedState,Me===null?Me=IA(_):(F=Me.cachePool,F!==null?(Be=Wi._currentValue,F=F.parent!==Be?{parent:Be,pool:Be}:F):F=KI(),Me={baseLanes:Me.baseLanes|_,cachePool:F}),A.memoizedState=Me,A.childLanes=zA(m,ie,_),g.memoizedState=OA,jx(m.child,A)):(Ed(g),_=m.child,m=_.sibling,_=Qc(_,{mode:"visible",children:A.children}),_.return=g,_.sibling=null,m!==null&&(ie=g.deletions,ie===null?(g.deletions=[m],g.flags|=16):ie.push(m)),g.child=_,g.memoizedState=null,_)}function UA(m,g){return g=Aw({mode:"visible",children:g},m.mode),g.return=m,m.child=g}function Aw(m,g){return m=ho(22,m,null,g),m.lanes=0,m}function BA(m,g,_){return Cm(g,m.child,null,_),m=UA(g,g.pendingProps.children),m.flags|=2,g.memoizedState=null,m}function oz(m,g,_){m.lanes|=g;var A=m.alternate;A!==null&&(A.lanes|=g),nA(m.return,g,_)}function HA(m,g,_,A,F,O){var ie=m.memoizedState;ie===null?m.memoizedState={isBackwards:g,rendering:null,renderingStartTime:0,last:A,tail:_,tailMode:F,treeForkCount:O}:(ie.isBackwards=g,ie.rendering=null,ie.renderingStartTime=0,ie.last=A,ie.tail=_,ie.tailMode=F,ie.treeForkCount=O)}function lz(m,g,_){var A=g.pendingProps,F=A.revealOrder,O=A.tail;A=A.children;var ie=Ii.current,Me=(ie&2)!==0;if(Me?(ie=ie&1|2,g.flags|=128):ie&=1,re(Ii,ie),Va(m,g,A,_),A=nr?yx:0,!Me&&m!==null&&(m.flags&128)!==0)e:for(m=g.child;m!==null;){if(m.tag===13)m.memoizedState!==null&&oz(m,_,g);else if(m.tag===19)oz(m,_,g);else if(m.child!==null){m.child.return=m,m=m.child;continue}if(m===g)break e;for(;m.sibling===null;){if(m.return===null||m.return===g)break e;m=m.return}m.sibling.return=m.return,m=m.sibling}switch(F){case"forwards":for(_=g.child,F=null;_!==null;)m=_.alternate,m!==null&&gw(m)===null&&(F=_),_=_.sibling;_=F,_===null?(F=g.child,g.child=null):(F=_.sibling,_.sibling=null),HA(g,!1,F,_,O,A);break;case"backwards":case"unstable_legacy-backwards":for(_=null,F=g.child,g.child=null;F!==null;){if(m=F.alternate,m!==null&&gw(m)===null){g.child=F;break}m=F.sibling,F.sibling=_,_=F,F=m}HA(g,!0,_,null,O,A);break;case"together":HA(g,!1,null,null,void 0,A);break;default:g.memoizedState=null}return g.child}function ru(m,g,_){if(m!==null&&(g.dependencies=m.dependencies),Rd|=g.lanes,(_&g.childLanes)===0)if(m!==null){if(yp(m,g,_,!1),(_&g.childLanes)===0)return null}else return null;if(m!==null&&g.child!==m.child)throw Error(r(153));if(g.child!==null){for(m=g.child,_=Qc(m,m.pendingProps),g.child=_,_.return=g;m.sibling!==null;)m=m.sibling,_=_.sibling=Qc(m,m.pendingProps),_.return=g;_.sibling=null}return g.child}function $A(m,g){return(m.lanes&g)!==0?!0:(m=m.dependencies,!!(m!==null&&lw(m)))}function Mse(m,g,_){switch(g.tag){case 3:De(g,g.stateNode.containerInfo),Cd(g,Wi,m.memoizedState.cache),vm();break;case 27:case 5:ce(g);break;case 4:De(g,g.stateNode.containerInfo);break;case 10:Cd(g,g.type,g.memoizedProps.value);break;case 31:if(g.memoizedState!==null)return g.flags|=128,fA(g),null;break;case 13:var A=g.memoizedState;if(A!==null)return A.dehydrated!==null?(Ed(g),g.flags|=128,null):(_&g.child.childLanes)!==0?sz(m,g,_):(Ed(g),m=ru(m,g,_),m!==null?m.sibling:null);Ed(g);break;case 19:var F=(m.flags&128)!==0;if(A=(_&g.childLanes)!==0,A||(yp(m,g,_,!1),A=(_&g.childLanes)!==0),F){if(A)return lz(m,g,_);g.flags|=128}if(F=g.memoizedState,F!==null&&(F.rendering=null,F.tail=null,F.lastEffect=null),re(Ii,Ii.current),A)break;return null;case 22:return g.lanes=0,ez(m,g,_,g.pendingProps);case 24:Cd(g,Wi,m.memoizedState.cache)}return ru(m,g,_)}function cz(m,g,_){if(m!==null)if(m.memoizedProps!==g.pendingProps)Xi=!0;else{if(!$A(m,_)&&(g.flags&128)===0)return Xi=!1,Mse(m,g,_);Xi=(m.flags&131072)!==0}else Xi=!1,nr&&(g.flags&1048576)!==0&&BI(g,yx,g.index);switch(g.lanes=0,g.tag){case 16:e:{var A=g.pendingProps;if(m=Nm(g.elementType),g.type=m,typeof m=="function")KM(m)?(A=Am(m,A),g.tag=1,g=iz(null,g,m,A,_)):(g.tag=0,g=LA(null,g,m,A,_));else{if(m!=null){var F=m.$$typeof;if(F===M){g.tag=11,g=Q5(null,g,m,A,_);break e}else if(F===k){g.tag=14,g=Z5(null,g,m,A,_);break e}}throw g=D(m)||m,Error(r(306,g,""))}}return g;case 0:return LA(m,g,g.type,g.pendingProps,_);case 1:return A=g.type,F=Am(A,g.pendingProps),iz(m,g,A,F,_);case 3:e:{if(De(g,g.stateNode.containerInfo),m===null)throw Error(r(387));A=g.pendingProps;var O=g.memoizedState;F=O.element,cA(m,g),Mx(g,A,null,_);var ie=g.memoizedState;if(A=ie.cache,Cd(g,Wi,A),A!==O.cache&&rA(g,[Wi],_,!0),Cx(),A=ie.element,O.isDehydrated)if(O={element:A,isDehydrated:!1,cache:ie.cache},g.updateQueue.baseState=O,g.memoizedState=O,g.flags&256){g=az(m,g,A,_);break e}else if(A!==F){F=zo(Error(r(424)),g),vx(F),g=az(m,g,A,_);break e}else for(m=g.stateNode.containerInfo,m.nodeType===9?m=m.body:m=m.nodeName==="HTML"?m.ownerDocument.body:m,ei=Vo(m.firstChild),Ha=g,nr=!0,Nd=null,Ho=!0,_=e5(g,null,A,_),g.child=_;_;)_.flags=_.flags&-3|4096,_=_.sibling;else{if(vm(),A===F){g=ru(m,g,_);break e}Va(m,g,A,_)}g=g.child}return g;case 26:return Mw(m,g),m===null?(_=vU(g.type,null,g.pendingProps,null))?g.memoizedState=_:nr||(_=g.type,m=g.pendingProps,A=Vw(pe.current).createElement(_),A[Jt]=g,A[er]=m,Ga(A,_,m),Ge(A),g.stateNode=A):g.memoizedState=vU(g.type,m.memoizedProps,g.pendingProps,m.memoizedState),null;case 27:return ce(g),m===null&&nr&&(A=g.stateNode=bU(g.type,g.pendingProps,pe.current),Ha=g,Ho=!0,F=ei,zd(g.type)?(_T=F,ei=Vo(A.firstChild)):ei=F),Va(m,g,g.pendingProps.children,_),Mw(m,g),m===null&&(g.flags|=4194304),g.child;case 5:return m===null&&nr&&((F=A=ei)&&(A=roe(A,g.type,g.pendingProps,Ho),A!==null?(g.stateNode=A,Ha=g,ei=Vo(A.firstChild),Ho=!1,F=!0):F=!1),F||kd(g)),ce(g),F=g.type,O=g.pendingProps,ie=m!==null?m.memoizedProps:null,A=O.children,bT(F,O)?A=null:ie!==null&&bT(F,ie)&&(g.flags|=32),g.memoizedState!==null&&(F=gA(m,g,xse,null,null,_),Wx._currentValue=F),Mw(m,g),Va(m,g,A,_),g.child;case 6:return m===null&&nr&&((m=_=ei)&&(_=ioe(_,g.pendingProps,Ho),_!==null?(g.stateNode=_,Ha=g,ei=null,m=!0):m=!1),m||kd(g)),null;case 13:return sz(m,g,_);case 4:return De(g,g.stateNode.containerInfo),A=g.pendingProps,m===null?g.child=Cm(g,null,A,_):Va(m,g,A,_),g.child;case 11:return Q5(m,g,g.type,g.pendingProps,_);case 7:return Va(m,g,g.pendingProps,_),g.child;case 8:return Va(m,g,g.pendingProps.children,_),g.child;case 12:return Va(m,g,g.pendingProps.children,_),g.child;case 10:return A=g.pendingProps,Cd(g,g.type,A.value),Va(m,g,A.children,_),g.child;case 9:return F=g.type._context,A=g.pendingProps.children,_m(g),F=$a(F),A=A(F),g.flags|=1,Va(m,g,A,_),g.child;case 14:return Z5(m,g,g.type,g.pendingProps,_);case 15:return J5(m,g,g.type,g.pendingProps,_);case 19:return lz(m,g,_);case 31:return Cse(m,g,_);case 22:return ez(m,g,_,g.pendingProps);case 24:return _m(g),A=$a(Wi),m===null?(F=sA(),F===null&&(F=zr,O=iA(),F.pooledCache=O,O.refCount++,O!==null&&(F.pooledCacheLanes|=_),F=O),g.memoizedState={parent:A,cache:F},lA(g),Cd(g,Wi,F)):((m.lanes&_)!==0&&(cA(m,g),Mx(g,null,null,_),Cx()),F=m.memoizedState,O=g.memoizedState,F.parent!==A?(F={parent:A,cache:A},g.memoizedState=F,g.lanes===0&&(g.memoizedState=g.updateQueue.baseState=F),Cd(g,Wi,A)):(A=O.cache,Cd(g,Wi,A),A!==F.cache&&rA(g,[Wi],_,!0))),Va(m,g,g.pendingProps.children,_),g.child;case 29:throw g.pendingProps}throw Error(r(156,g.tag))}function iu(m){m.flags|=4}function VA(m,g,_,A,F){if((g=(m.mode&32)!==0)&&(g=!1),g){if(m.flags|=16777216,(F&335544128)===F)if(m.stateNode.complete)m.flags|=8192;else if(Lz())m.flags|=8192;else throw km=hw,oA}else m.flags&=-16777217}function uz(m,g){if(g.type!=="stylesheet"||(g.state.loading&4)!==0)m.flags&=-16777217;else if(m.flags|=16777216,!kU(g))if(Lz())m.flags|=8192;else throw km=hw,oA}function Tw(m,g){g!==null&&(m.flags|=4),m.flags&16384&&(g=m.tag!==22?kt():536870912,m.lanes|=g,Pp|=g)}function Dx(m,g){if(!nr)switch(m.tailMode){case"hidden":g=m.tail;for(var _=null;g!==null;)g.alternate!==null&&(_=g),g=g.sibling;_===null?m.tail=null:_.sibling=null;break;case"collapsed":_=m.tail;for(var A=null;_!==null;)_.alternate!==null&&(A=_),_=_.sibling;A===null?g||m.tail===null?m.tail=null:m.tail.sibling=null:A.sibling=null}}function ti(m){var g=m.alternate!==null&&m.alternate.child===m.child,_=0,A=0;if(g)for(var F=m.child;F!==null;)_|=F.lanes|F.childLanes,A|=F.subtreeFlags&65011712,A|=F.flags&65011712,F.return=m,F=F.sibling;else for(F=m.child;F!==null;)_|=F.lanes|F.childLanes,A|=F.subtreeFlags,A|=F.flags,F.return=m,F=F.sibling;return m.subtreeFlags|=A,m.childLanes=_,g}function Ase(m,g,_){var A=g.pendingProps;switch(ZM(g),g.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return ti(g),null;case 1:return ti(g),null;case 3:return _=g.stateNode,A=null,m!==null&&(A=m.memoizedState.cache),g.memoizedState.cache!==A&&(g.flags|=2048),eu(Wi),de(),_.pendingContext&&(_.context=_.pendingContext,_.pendingContext=null),(m===null||m.child===null)&&(xp(g)?iu(g):m===null||m.memoizedState.isDehydrated&&(g.flags&256)===0||(g.flags|=1024,eA())),ti(g),null;case 26:var F=g.type,O=g.memoizedState;return m===null?(iu(g),O!==null?(ti(g),uz(g,O)):(ti(g),VA(g,F,null,A,_))):O?O!==m.memoizedState?(iu(g),ti(g),uz(g,O)):(ti(g),g.flags&=-16777217):(m=m.memoizedProps,m!==A&&iu(g),ti(g),VA(g,F,m,A,_)),null;case 27:if(ke(g),_=pe.current,F=g.type,m!==null&&g.stateNode!=null)m.memoizedProps!==A&&iu(g);else{if(!A){if(g.stateNode===null)throw Error(r(166));return ti(g),null}m=te.current,xp(g)?$I(g):(m=bU(F,A,_),g.stateNode=m,iu(g))}return ti(g),null;case 5:if(ke(g),F=g.type,m!==null&&g.stateNode!=null)m.memoizedProps!==A&&iu(g);else{if(!A){if(g.stateNode===null)throw Error(r(166));return ti(g),null}if(O=te.current,xp(g))$I(g);else{var ie=Vw(pe.current);switch(O){case 1:O=ie.createElementNS("http://www.w3.org/2000/svg",F);break;case 2:O=ie.createElementNS("http://www.w3.org/1998/Math/MathML",F);break;default:switch(F){case"svg":O=ie.createElementNS("http://www.w3.org/2000/svg",F);break;case"math":O=ie.createElementNS("http://www.w3.org/1998/Math/MathML",F);break;case"script":O=ie.createElement("div"),O.innerHTML=" - + +
From 9babf5d345c1b32ef97fe542d0d936589d796238 Mon Sep 17 00:00:00 2001 From: maziggy Date: Sun, 15 Feb 2026 15:18:52 +0100 Subject: [PATCH 2/7] fix: spool edit form overwrites usage-tracked weight When editing a spool (changing note, color, etc.), the form always sent weight_used back to the server. If the React Query cache held a stale pre-print value, saving would silently reset remaining weight to full. Track whether the user explicitly touched the weight field and only include weight_used in the PATCH request when creating a new spool or when the weight was intentionally changed. --- CHANGELOG.md | 1 + frontend/src/components/SpoolFormModal.tsx | 10 +- .../{index-DLlMitUB.js => index-DDGLa0P-.js} | 94 +++++++++---------- static/index.html | 2 +- 4 files changed, 58 insertions(+), 49 deletions(-) rename static/assets/{index-DLlMitUB.js => index-DDGLa0P-.js} (54%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d64672a1..683f0c9f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ All notable changes to Bambuddy will be documented in this file. - **Archive List View Not Labeling Failed Prints** ([#365](https://github.com/maziggy/bambuddy/issues/365)) — The archive grid view displayed a red "Failed" / "Cancelled" badge on failed and aborted prints, but the list view had no equivalent indicator. Now shows an inline status badge next to the print name in list view. - **Reprint Fails with SD Card Error for Archives Without 3MF File** ([#376](https://github.com/maziggy/bambuddy/issues/376)) — When a print was sent from an external slicer and Bambuddy couldn't download the 3MF from the printer during auto-archiving, the fallback archive had no file. Attempting to reprint such an archive tried to upload the data directory as a file, causing a confusing "SD card error." The backend now returns a clear error for file-less archives, and the frontend disables Print/Schedule/Open in Slicer buttons with a tooltip explaining that the 3MF file is unavailable. - **Inventory Spool Weight Resets After Print Completes** — After a print, the usage tracker correctly updated `weight_used` (e.g., +1.6g), but periodic AMS status updates recalculated `weight_used` from the AMS remain% sensor and overwrote the precise value. For small prints on large spools (e.g., 1.6g on 1000g), the AMS remain% stays at 100% (integer resolution = 10g steps), resetting `weight_used` back to 0. The AMS weight sync now only increases `weight_used`, never decreases it, preserving precise values from the usage tracker. +- **Spool Edit Form Overwrites Usage-Tracked Weight** — Editing any spool field (note, color, material, etc.) sent the full form data back to the server, including `weight_used`. If the frontend cache was stale (e.g., loaded before the last print completed), saving the form would silently reset `weight_used` to the pre-print value, reverting the remaining weight to full. The form now only includes `weight_used` in the update request when the user explicitly changes the weight field. - **Loose Archive Name Matching Could Cause Wrong Archive Reuse** ([#374](https://github.com/maziggy/bambuddy/issues/374)) — The `on_print_start` callback used `ilike('%{name}%')` to find existing "printing" archives, which meant a print named "Clip" could incorrectly match "Cable Clip" or "Clip Stand". This could cause a new print to reuse the wrong archive or skip creating one. Tightened to exact `print_name` match or exact filename variants (`.3mf`, `.gcode.3mf`). - **Archive Duplicate Badge Misses Name-Based Duplicates** ([#315](https://github.com/maziggy/bambuddy/issues/315)) — The duplicate badge on archive cards only matched by file content hash, so re-sliced prints of the same model (different GCODE, same print name) were not flagged as duplicates. Now also matches by print name (case-insensitive), consistent with the detail view's duplicate detection. diff --git a/frontend/src/components/SpoolFormModal.tsx b/frontend/src/components/SpoolFormModal.tsx index b2d5b9710..2fab4433a 100644 --- a/frontend/src/components/SpoolFormModal.tsx +++ b/frontend/src/components/SpoolFormModal.tsx @@ -35,6 +35,7 @@ export function SpoolFormModal({ isOpen, onClose, spool, printersWithCalibration const [formData, setFormData] = useState(defaultFormData); const [errors, setErrors] = useState>>({}); const [activeTab, setActiveTab] = useState('filament'); + const [weightTouched, setWeightTouched] = useState(false); // Cloud presets const [cloudAuthenticated, setCloudAuthenticated] = useState(false); @@ -195,6 +196,7 @@ export function SpoolFormModal({ isOpen, onClose, spool, printersWithCalibration } setErrors({}); setActiveTab('filament'); + setWeightTouched(false); } }, [isOpen, spool]); @@ -208,6 +210,7 @@ export function SpoolFormModal({ isOpen, onClose, spool, printersWithCalibration // Update field helper const updateField = (key: K, value: SpoolFormData[K]) => { setFormData(prev => ({ ...prev, [key]: value })); + if (key === 'weight_used') setWeightTouched(true); if (errors[key]) { setErrors(prev => ({ ...prev, [key]: undefined })); } @@ -333,7 +336,6 @@ export function SpoolFormModal({ isOpen, onClose, spool, printersWithCalibration rgba: formData.rgba || null, label_weight: formData.label_weight, core_weight: formData.core_weight, - weight_used: formData.weight_used, slicer_filament: formData.slicer_filament || null, slicer_filament_name: presetName, nozzle_temp_min: null, @@ -341,6 +343,12 @@ export function SpoolFormModal({ isOpen, onClose, spool, printersWithCalibration note: formData.note || null, }; + // Only send weight_used when creating or when explicitly changed by the user. + // This prevents stale cached values from overwriting usage-tracker data. + if (!isEditing || weightTouched) { + data.weight_used = formData.weight_used; + } + if (isEditing) { updateMutation.mutate(data); } else { diff --git a/static/assets/index-DLlMitUB.js b/static/assets/index-DDGLa0P-.js similarity index 54% rename from static/assets/index-DLlMitUB.js rename to static/assets/index-DDGLa0P-.js index 23f3fce63..078fd5592 100644 --- a/static/assets/index-DLlMitUB.js +++ b/static/assets/index-DDGLa0P-.js @@ -1,14 +1,14 @@ -function Poe(t,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var l_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var IT={exports:{}},ry={};var VU;function joe(){if(VU)return ry;VU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,i,s){var o=null;if(s!==void 0&&(o=""+s),i.key!==void 0&&(o=""+i.key),"key"in i){s={};for(var l in i)l!=="key"&&(s[l]=i[l])}else s=i;return i=s.ref,{$$typeof:t,type:r,key:o,ref:i!==void 0?i:null,props:s}}return ry.Fragment=e,ry.jsx=n,ry.jsxs=n,ry}var GU;function Doe(){return GU||(GU=1,IT.exports=joe()),IT.exports}var a=Doe(),zT={exports:{}},Nn={};var qU;function Roe(){if(qU)return Nn;qU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),f=Symbol.iterator;function p(V){return V===null||typeof V!="object"?null:(V=f&&V[f]||V["@@iterator"],typeof V=="function"?V:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,b={};function y(V,X,ne){this.props=V,this.context=X,this.refs=b,this.updater=ne||x}y.prototype.isReactComponent={},y.prototype.setState=function(V,X){if(typeof V!="object"&&typeof V!="function"&&V!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,V,X,"setState")},y.prototype.forceUpdate=function(V){this.updater.enqueueForceUpdate(this,V,"forceUpdate")};function S(){}S.prototype=y.prototype;function N(V,X,ne){this.props=V,this.context=X,this.refs=b,this.updater=ne||x}var A=N.prototype=new S;A.constructor=N,v(A,y.prototype),A.isPureReactComponent=!0;var M=Array.isArray;function T(){}var k={H:null,A:null,T:null,S:null},j=Object.prototype.hasOwnProperty;function E(V,X,ne){var te=ne.ref;return{$$typeof:t,type:V,key:X,ref:te!==void 0?te:null,props:ne}}function P(V,X){return E(V.type,X,V.props)}function U(V){return typeof V=="object"&&V!==null&&V.$$typeof===t}function L(V){var X={"=":"=0",":":"=2"};return"$"+V.replace(/[=:]/g,function(ne){return X[ne]})}var B=/\/+/g;function D(V,X){return typeof V=="object"&&V!==null&&V.key!=null?L(""+V.key):X.toString(36)}function H(V){switch(V.status){case"fulfilled":return V.value;case"rejected":throw V.reason;default:switch(typeof V.status=="string"?V.then(T,T):(V.status="pending",V.then(function(X){V.status==="pending"&&(V.status="fulfilled",V.value=X)},function(X){V.status==="pending"&&(V.status="rejected",V.reason=X)})),V.status){case"fulfilled":return V.value;case"rejected":throw V.reason}}throw V}function G(V,X,ne,te,we){var pe=typeof V;(pe==="undefined"||pe==="boolean")&&(V=null);var me=!1;if(V===null)me=!0;else switch(pe){case"bigint":case"string":case"number":me=!0;break;case"object":switch(V.$$typeof){case t:case e:me=!0;break;case d:return me=V._init,G(me(V._payload),X,ne,te,we)}}if(me)return we=we(V),me=te===""?"."+D(V,0):te,M(we)?(ne="",me!=null&&(ne=me.replace(B,"$&/")+"/"),G(we,X,ne,"",function(ce){return ce})):we!=null&&(U(we)&&(we=P(we,ne+(we.key==null||V&&V.key===we.key?"":(""+we.key).replace(B,"$&/")+"/")+me)),X.push(we)),1;me=0;var De=te===""?".":te+":";if(M(V))for(var de=0;de>>1,oe=G[Z];if(0>>1;Zi(ne,W))tei(we,ne)?(G[Z]=we,G[te]=W,Z=te):(G[Z]=ne,G[X]=W,Z=X);else if(tei(we,W))G[Z]=we,G[te]=W,Z=te;else break e}}return I}function i(G,I){var W=G.sortIndex-I.sortIndex;return W!==0?W:G.id-I.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var c=[],u=[],d=1,h=null,f=3,p=!1,x=!1,v=!1,b=!1,y=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function A(G){for(var I=n(u);I!==null;){if(I.callback===null)r(u);else if(I.startTime<=G)r(u),I.sortIndex=I.expirationTime,e(c,I);else break;I=n(u)}}function M(G){if(v=!1,A(G),!x)if(n(c)!==null)x=!0,T||(T=!0,L());else{var I=n(u);I!==null&&H(M,I.startTime-G)}}var T=!1,k=-1,j=5,E=-1;function P(){return b?!0:!(t.unstable_now()-EG&&P());){var Z=h.callback;if(typeof Z=="function"){h.callback=null,f=h.priorityLevel;var oe=Z(h.expirationTime<=G);if(G=t.unstable_now(),typeof oe=="function"){h.callback=oe,A(G),I=!0;break t}h===n(c)&&r(c),A(G)}else r(c);h=n(c)}if(h!==null)I=!0;else{var V=n(u);V!==null&&H(M,V.startTime-G),I=!1}}break e}finally{h=null,f=W,p=!1}I=void 0}}finally{I?L():T=!1}}}var L;if(typeof N=="function")L=function(){N(U)};else if(typeof MessageChannel<"u"){var B=new MessageChannel,D=B.port2;B.port1.onmessage=U,L=function(){D.postMessage(null)}}else L=function(){y(U,0)};function H(G,I){k=y(function(){G(t.unstable_now())},I)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(G){G.callback=null},t.unstable_forceFrameRate=function(G){0>G||125Z?(G.sortIndex=W,e(u,G),n(c)===null&&G===n(u)&&(v?(S(k),k=-1):v=!0,H(M,W-Z))):(G.sortIndex=oe,e(c,G),x||p||(x=!0,T||(T=!0,L()))),G},t.unstable_shouldYield=P,t.unstable_wrapCallback=function(G){var I=f;return function(){var W=f;f=I;try{return G.apply(this,arguments)}finally{f=W}}}})(HT)),HT}var XU;function Ooe(){return XU||(XU=1,BT.exports=Loe()),BT.exports}var $T={exports:{}},ss={};var YU;function Ioe(){if(YU)return ss;YU=1;var t=Bb();function e(c){var u="https://react.dev/errors/"+c;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),$T.exports=Ioe(),$T.exports}var ZU;function zoe(){if(ZU)return iy;ZU=1;var t=Ooe(),e=Bb(),n=gK();function r(m){var g="https://react.dev/errors/"+m;if(1oe||(m.current=Z[oe],Z[oe]=null,oe--)}function ne(m,g){oe++,Z[oe]=m.current,m.current=g}var te=V(null),we=V(null),pe=V(null),me=V(null);function De(m,g){switch(ne(pe,g),ne(we,m),ne(te,null),g.nodeType){case 9:case 11:m=(m=g.documentElement)&&(m=m.namespaceURI)?mU(m):0;break;default:if(m=g.tagName,g=g.namespaceURI)g=mU(g),m=fU(g,m);else switch(m){case"svg":m=1;break;case"math":m=2;break;default:m=0}}X(te),ne(te,m)}function de(){X(te),X(we),X(pe)}function ce(m){m.memoizedState!==null&&ne(me,m);var g=te.current,_=fU(g,m.type);g!==_&&(ne(we,m),ne(te,_))}function Ne(m){we.current===m&&(X(te),X(we)),me.current===m&&(X(me),Jx._currentValue=W)}var ee,Fe;function $(m){if(ee===void 0)try{throw Error()}catch(_){var g=_.stack.trim().match(/\n( *(at )?)/);ee=g&&g[1]||"",Fe=-1<_.stack.indexOf(` +function Poe(t,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var l_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var IT={exports:{}},ry={};var VU;function joe(){if(VU)return ry;VU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,i,s){var o=null;if(s!==void 0&&(o=""+s),i.key!==void 0&&(o=""+i.key),"key"in i){s={};for(var l in i)l!=="key"&&(s[l]=i[l])}else s=i;return i=s.ref,{$$typeof:t,type:r,key:o,ref:i!==void 0?i:null,props:s}}return ry.Fragment=e,ry.jsx=n,ry.jsxs=n,ry}var GU;function Doe(){return GU||(GU=1,IT.exports=joe()),IT.exports}var a=Doe(),zT={exports:{}},Nn={};var qU;function Roe(){if(qU)return Nn;qU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),f=Symbol.iterator;function p(V){return V===null||typeof V!="object"?null:(V=f&&V[f]||V["@@iterator"],typeof V=="function"?V:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,b={};function y(V,X,te){this.props=V,this.context=X,this.refs=b,this.updater=te||x}y.prototype.isReactComponent={},y.prototype.setState=function(V,X){if(typeof V!="object"&&typeof V!="function"&&V!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,V,X,"setState")},y.prototype.forceUpdate=function(V){this.updater.enqueueForceUpdate(this,V,"forceUpdate")};function S(){}S.prototype=y.prototype;function N(V,X,te){this.props=V,this.context=X,this.refs=b,this.updater=te||x}var A=N.prototype=new S;A.constructor=N,v(A,y.prototype),A.isPureReactComponent=!0;var M=Array.isArray;function T(){}var k={H:null,A:null,T:null,S:null},j=Object.prototype.hasOwnProperty;function E(V,X,te){var J=te.ref;return{$$typeof:t,type:V,key:X,ref:J!==void 0?J:null,props:te}}function P(V,X){return E(V.type,X,V.props)}function U(V){return typeof V=="object"&&V!==null&&V.$$typeof===t}function L(V){var X={"=":"=0",":":"=2"};return"$"+V.replace(/[=:]/g,function(te){return X[te]})}var B=/\/+/g;function R(V,X){return typeof V=="object"&&V!==null&&V.key!=null?L(""+V.key):X.toString(36)}function $(V){switch(V.status){case"fulfilled":return V.value;case"rejected":throw V.reason;default:switch(typeof V.status=="string"?V.then(T,T):(V.status="pending",V.then(function(X){V.status==="pending"&&(V.status="fulfilled",V.value=X)},function(X){V.status==="pending"&&(V.status="rejected",V.reason=X)})),V.status){case"fulfilled":return V.value;case"rejected":throw V.reason}}throw V}function G(V,X,te,J,Se){var fe=typeof V;(fe==="undefined"||fe==="boolean")&&(V=null);var me=!1;if(V===null)me=!0;else switch(fe){case"bigint":case"string":case"number":me=!0;break;case"object":switch(V.$$typeof){case t:case e:me=!0;break;case d:return me=V._init,G(me(V._payload),X,te,J,Se)}}if(me)return Se=Se(V),me=J===""?"."+R(V,0):J,M(Se)?(te="",me!=null&&(te=me.replace(B,"$&/")+"/"),G(Se,X,te,"",function(ce){return ce})):Se!=null&&(U(Se)&&(Se=P(Se,te+(Se.key==null||V&&V.key===Se.key?"":(""+Se.key).replace(B,"$&/")+"/")+me)),X.push(Se)),1;me=0;var De=J===""?".":J+":";if(M(V))for(var de=0;de>>1,le=G[Z];if(0>>1;Zi(te,K))Ji(Se,te)?(G[Z]=Se,G[J]=K,Z=J):(G[Z]=te,G[X]=K,Z=X);else if(Ji(Se,K))G[Z]=Se,G[J]=K,Z=J;else break e}}return z}function i(G,z){var K=G.sortIndex-z.sortIndex;return K!==0?K:G.id-z.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var c=[],u=[],d=1,h=null,f=3,p=!1,x=!1,v=!1,b=!1,y=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function A(G){for(var z=n(u);z!==null;){if(z.callback===null)r(u);else if(z.startTime<=G)r(u),z.sortIndex=z.expirationTime,e(c,z);else break;z=n(u)}}function M(G){if(v=!1,A(G),!x)if(n(c)!==null)x=!0,T||(T=!0,L());else{var z=n(u);z!==null&&$(M,z.startTime-G)}}var T=!1,k=-1,j=5,E=-1;function P(){return b?!0:!(t.unstable_now()-EG&&P());){var Z=h.callback;if(typeof Z=="function"){h.callback=null,f=h.priorityLevel;var le=Z(h.expirationTime<=G);if(G=t.unstable_now(),typeof le=="function"){h.callback=le,A(G),z=!0;break t}h===n(c)&&r(c),A(G)}else r(c);h=n(c)}if(h!==null)z=!0;else{var V=n(u);V!==null&&$(M,V.startTime-G),z=!1}}break e}finally{h=null,f=K,p=!1}z=void 0}}finally{z?L():T=!1}}}var L;if(typeof N=="function")L=function(){N(U)};else if(typeof MessageChannel<"u"){var B=new MessageChannel,R=B.port2;B.port1.onmessage=U,L=function(){R.postMessage(null)}}else L=function(){y(U,0)};function $(G,z){k=y(function(){G(t.unstable_now())},z)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(G){G.callback=null},t.unstable_forceFrameRate=function(G){0>G||125Z?(G.sortIndex=K,e(u,G),n(c)===null&&G===n(u)&&(v?(S(k),k=-1):v=!0,$(M,K-Z))):(G.sortIndex=le,e(c,G),x||p||(x=!0,T||(T=!0,L()))),G},t.unstable_shouldYield=P,t.unstable_wrapCallback=function(G){var z=f;return function(){var K=f;f=z;try{return G.apply(this,arguments)}finally{f=K}}}})(HT)),HT}var XU;function Ooe(){return XU||(XU=1,BT.exports=Loe()),BT.exports}var $T={exports:{}},ss={};var YU;function Ioe(){if(YU)return ss;YU=1;var t=Bb();function e(c){var u="https://react.dev/errors/"+c;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),$T.exports=Ioe(),$T.exports}var ZU;function zoe(){if(ZU)return iy;ZU=1;var t=Ooe(),e=Bb(),n=gK();function r(m){var g="https://react.dev/errors/"+m;if(1le||(m.current=Z[le],Z[le]=null,le--)}function te(m,g){le++,Z[le]=m.current,m.current=g}var J=V(null),Se=V(null),fe=V(null),me=V(null);function De(m,g){switch(te(fe,g),te(Se,m),te(J,null),g.nodeType){case 9:case 11:m=(m=g.documentElement)&&(m=m.namespaceURI)?mU(m):0;break;default:if(m=g.tagName,g=g.namespaceURI)g=mU(g),m=fU(g,m);else switch(m){case"svg":m=1;break;case"math":m=2;break;default:m=0}}X(J),te(J,m)}function de(){X(J),X(Se),X(fe)}function ce(m){m.memoizedState!==null&&te(me,m);var g=J.current,_=fU(g,m.type);g!==_&&(te(Se,m),te(J,_))}function Ne(m){Se.current===m&&(X(J),X(Se)),me.current===m&&(X(me),Jx._currentValue=K)}var ie,Le;function H(m){if(ie===void 0)try{throw Error()}catch(_){var g=_.stack.trim().match(/\n( *(at )?)/);ie=g&&g[1]||"",Le=-1<_.stack.indexOf(` at`)?" ()":-1<_.stack.indexOf("@")?"@unknown:0:0":""}return` -`+ee+m+Fe}var K=!1;function ue(m,g){if(!m||K)return"";K=!0;var _=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var C={DetermineComponentFrameRoot:function(){try{if(g){var Ct=function(){throw Error()};if(Object.defineProperty(Ct.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ct,[])}catch(gt){var mt=gt}Reflect.construct(m,[],Ct)}else{try{Ct.call()}catch(gt){mt=gt}m.call(Ct.prototype)}}else{try{throw Error()}catch(gt){mt=gt}(Ct=m())&&typeof Ct.catch=="function"&&Ct.catch(function(){})}}catch(gt){if(gt&&mt&&typeof gt.stack=="string")return[gt.stack,mt.stack]}return[null,null]}};C.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var F=Object.getOwnPropertyDescriptor(C.DetermineComponentFrameRoot,"name");F&&F.configurable&&Object.defineProperty(C.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var O=C.DetermineComponentFrameRoot(),re=O[0],Ce=O[1];if(re&&Ce){var Be=re.split(` +`+ie+m+Le}var W=!1;function ue(m,g){if(!m||W)return"";W=!0;var _=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var C={DetermineComponentFrameRoot:function(){try{if(g){var Ct=function(){throw Error()};if(Object.defineProperty(Ct.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ct,[])}catch(gt){var mt=gt}Reflect.construct(m,[],Ct)}else{try{Ct.call()}catch(gt){mt=gt}m.call(Ct.prototype)}}else{try{throw Error()}catch(gt){mt=gt}(Ct=m())&&typeof Ct.catch=="function"&&Ct.catch(function(){})}}catch(gt){if(gt&&mt&&typeof gt.stack=="string")return[gt.stack,mt.stack]}return[null,null]}};C.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var F=Object.getOwnPropertyDescriptor(C.DetermineComponentFrameRoot,"name");F&&F.configurable&&Object.defineProperty(C.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var O=C.DetermineComponentFrameRoot(),ne=O[0],Ce=O[1];if(ne&&Ce){var Be=ne.split(` `),ht=Ce.split(` `);for(F=C=0;CF||Be[C]!==ht[F]){var yt=` -`+Be[C].replace(" at new "," at ");return m.displayName&&yt.includes("")&&(yt=yt.replace("",m.displayName)),yt}while(1<=C&&0<=F);break}}}finally{K=!1,Error.prepareStackTrace=_}return(_=m?m.displayName||m.name:"")?$(_):""}function Q(m,g){switch(m.tag){case 26:case 27:case 5:return $(m.type);case 16:return $("Lazy");case 13:return m.child!==g&&g!==null?$("Suspense Fallback"):$("Suspense");case 19:return $("SuspenseList");case 0:case 15:return ue(m.type,!1);case 11:return ue(m.type.render,!1);case 1:return ue(m.type,!0);case 31:return $("Activity");default:return""}}function le(m){try{var g="",_=null;do g+=Q(m,_),_=m,m=m.return;while(m);return g}catch(C){return` +`+Be[C].replace(" at new "," at ");return m.displayName&&yt.includes("")&&(yt=yt.replace("",m.displayName)),yt}while(1<=C&&0<=F);break}}}finally{W=!1,Error.prepareStackTrace=_}return(_=m?m.displayName||m.name:"")?H(_):""}function Q(m,g){switch(m.tag){case 26:case 27:case 5:return H(m.type);case 16:return H("Lazy");case 13:return m.child!==g&&g!==null?H("Suspense Fallback"):H("Suspense");case 19:return H("SuspenseList");case 0:case 15:return ue(m.type,!1);case 11:return ue(m.type.render,!1);case 1:return ue(m.type,!0);case 31:return H("Activity");default:return""}}function oe(m){try{var g="",_=null;do g+=Q(m,_),_=m,m=m.return;while(m);return g}catch(C){return` Error generating stack: `+C.message+` -`+C.stack}}var Y=Object.prototype.hasOwnProperty,he=t.unstable_scheduleCallback,be=t.unstable_cancelCallback,J=t.unstable_shouldYield,z=t.unstable_requestPaint,R=t.unstable_now,q=t.unstable_getCurrentPriorityLevel,fe=t.unstable_ImmediatePriority,ve=t.unstable_UserBlockingPriority,xe=t.unstable_NormalPriority,ze=t.unstable_LowPriority,Se=t.unstable_IdlePriority,He=t.log,Ze=t.unstable_setDisableYieldValue,_e=null,ye=null;function ke(m){if(typeof He=="function"&&Ze(m),ye&&typeof ye.setStrictMode=="function")try{ye.setStrictMode(_e,m)}catch{}}var Ue=Math.clz32?Math.clz32:Ae,je=Math.log,Ve=Math.LN2;function Ae(m){return m>>>=0,m===0?32:31-(je(m)/Ve|0)|0}var Je=256,Pe=262144,Ye=4194304;function Re(m){var g=m&42;if(g!==0)return g;switch(m&-m){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return m&261888;case 262144:case 524288:case 1048576:case 2097152:return m&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return m&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return m}}function Le(m,g,_){var C=m.pendingLanes;if(C===0)return 0;var F=0,O=m.suspendedLanes,re=m.pingedLanes;m=m.warmLanes;var Ce=C&134217727;return Ce!==0?(C=Ce&~O,C!==0?F=Re(C):(re&=Ce,re!==0?F=Re(re):_||(_=Ce&~m,_!==0&&(F=Re(_))))):(Ce=C&~O,Ce!==0?F=Re(Ce):re!==0?F=Re(re):_||(_=C&~m,_!==0&&(F=Re(_)))),F===0?0:g!==0&&g!==F&&(g&O)===0&&(O=F&-F,_=g&-g,O>=_||O===32&&(_&4194048)!==0)?g:F}function We(m,g){return(m.pendingLanes&~(m.suspendedLanes&~m.pingedLanes)&g)===0}function pt(m,g){switch(m){case 1:case 2:case 4:case 8:case 64:return g+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return g+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function At(){var m=Ye;return Ye<<=1,(Ye&62914560)===0&&(Ye=4194304),m}function Rt(m){for(var g=[],_=0;31>_;_++)g.push(m);return g}function Wt(m,g){m.pendingLanes|=g,g!==268435456&&(m.suspendedLanes=0,m.pingedLanes=0,m.warmLanes=0)}function Tt(m,g,_,C,F,O){var re=m.pendingLanes;m.pendingLanes=_,m.suspendedLanes=0,m.pingedLanes=0,m.warmLanes=0,m.expiredLanes&=_,m.entangledLanes&=_,m.errorRecoveryDisabledLanes&=_,m.shellSuspendCounter=0;var Ce=m.entanglements,Be=m.expirationTimes,ht=m.hiddenUpdates;for(_=re&~_;0<_;){var yt=31-Ue(_),Ct=1<"u")return null;try{return m.activeElement||m.body}catch{return m.body}}var Qr=/[\n"\\]/g;function gn(m){return m.replace(Qr,function(g){return"\\"+g.charCodeAt(0).toString(16)+" "})}function Zr(m,g,_,C,F,O,re,Ce){m.name="",re!=null&&typeof re!="function"&&typeof re!="symbol"&&typeof re!="boolean"?m.type=re:m.removeAttribute("type"),g!=null?re==="number"?(g===0&&m.value===""||m.value!=g)&&(m.value=""+Cn(g)):m.value!==""+Cn(g)&&(m.value=""+Cn(g)):re!=="submit"&&re!=="reset"||m.removeAttribute("value"),g!=null?vi(m,re,Cn(g)):_!=null?vi(m,re,Cn(_)):C!=null&&m.removeAttribute("value"),F==null&&O!=null&&(m.defaultChecked=!!O),F!=null&&(m.checked=F&&typeof F!="function"&&typeof F!="symbol"),Ce!=null&&typeof Ce!="function"&&typeof Ce!="symbol"&&typeof Ce!="boolean"?m.name=""+Cn(Ce):m.removeAttribute("name")}function Wn(m,g,_,C,F,O,re,Ce){if(O!=null&&typeof O!="function"&&typeof O!="symbol"&&typeof O!="boolean"&&(m.type=O),g!=null||_!=null){if(!(O!=="submit"&&O!=="reset"||g!=null)){sn(m);return}_=_!=null?""+Cn(_):"",g=g!=null?""+Cn(g):_,Ce||g===m.value||(m.value=g),m.defaultValue=g}C=C??F,C=typeof C!="function"&&typeof C!="symbol"&&!!C,m.checked=Ce?m.checked:!!C,m.defaultChecked=!!C,re!=null&&typeof re!="function"&&typeof re!="symbol"&&typeof re!="boolean"&&(m.name=re),sn(m)}function vi(m,g,_){g==="number"&&Cr(m.ownerDocument)===m||m.defaultValue===""+_||(m.defaultValue=""+_)}function mi(m,g,_,C){if(m=m.options,g){g={};for(var F=0;F<_.length;F++)g["$"+_[F]]=!0;for(_=0;_"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),vr=!1;if(Ur)try{var kl={};Object.defineProperty(kl,"passive",{get:function(){vr=!0}}),window.addEventListener("test",kl,kl),window.removeEventListener("test",kl,kl)}catch{vr=!1}var Ca=null,oa=null,rc=null;function Br(){if(rc)return rc;var m,g=oa,_=g.length,C,F="value"in Ca?Ca.value:Ca.textContent,O=F.length;for(m=0;m<_&&g[m]===F[m];m++);var re=_-m;for(C=1;C<=re&&g[_-C]===F[O-C];C++);return rc=F.slice(m,1=vx),vI=" ",wI=!1;function _I(m,g){switch(m){case"keyup":return Jae.indexOf(g.keyCode)!==-1;case"keydown":return g.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function SI(m){return m=m.detail,typeof m=="object"&&"data"in m?m.data:null}var mp=!1;function tse(m,g){switch(m){case"compositionend":return SI(g);case"keypress":return g.which!==32?null:(wI=!0,vI);case"textInput":return m=g.data,m===vI&&wI?null:m;default:return null}}function nse(m,g){if(mp)return m==="compositionend"||!VM&&_I(m,g)?(m=Br(),rc=oa=Ca=null,mp=!1,m):null;switch(m){case"paste":return null;case"keypress":if(!(g.ctrlKey||g.altKey||g.metaKey)||g.ctrlKey&&g.altKey){if(g.char&&1=g)return{node:_,offset:g-m};m=C}e:{for(;_;){if(_.nextSibling){_=_.nextSibling;break e}_=_.parentNode}_=void 0}_=PI(_)}}function DI(m,g){return m&&g?m===g?!0:m&&m.nodeType===3?!1:g&&g.nodeType===3?DI(m,g.parentNode):"contains"in m?m.contains(g):m.compareDocumentPosition?!!(m.compareDocumentPosition(g)&16):!1:!1}function RI(m){m=m!=null&&m.ownerDocument!=null&&m.ownerDocument.defaultView!=null?m.ownerDocument.defaultView:window;for(var g=Cr(m.document);g instanceof m.HTMLIFrameElement;){try{var _=typeof g.contentWindow.location.href=="string"}catch{_=!1}if(_)m=g.contentWindow;else break;g=Cr(m.document)}return g}function WM(m){var g=m&&m.nodeName&&m.nodeName.toLowerCase();return g&&(g==="input"&&(m.type==="text"||m.type==="search"||m.type==="tel"||m.type==="url"||m.type==="password")||g==="textarea"||m.contentEditable==="true")}var use=Ur&&"documentMode"in document&&11>=document.documentMode,fp=null,KM=null,Nx=null,XM=!1;function FI(m,g,_){var C=_.window===_?_.document:_.nodeType===9?_:_.ownerDocument;XM||fp==null||fp!==Cr(C)||(C=fp,"selectionStart"in C&&WM(C)?C={start:C.selectionStart,end:C.selectionEnd}:(C=(C.ownerDocument&&C.ownerDocument.defaultView||window).getSelection(),C={anchorNode:C.anchorNode,anchorOffset:C.anchorOffset,focusNode:C.focusNode,focusOffset:C.focusOffset}),Nx&&Sx(Nx,C)||(Nx=C,C=Ww(KM,"onSelect"),0>=re,F-=re,ic=1<<32-Ue(g)+F|_<Rn?(tr=Jt,Jt=null):tr=Jt.sibling;var dr=mt(rt,Jt,ut[Rn],St);if(dr===null){Jt===null&&(Jt=tr);break}m&&Jt&&dr.alternate===null&&g(rt,Jt),Ke=O(dr,Ke,Rn),ur===null?an=dr:ur.sibling=dr,ur=dr,Jt=tr}if(Rn===ut.length)return _(rt,Jt),rr&&Qc(rt,Rn),an;if(Jt===null){for(;RnRn?(tr=Jt,Jt=null):tr=Jt.sibling;var $d=mt(rt,Jt,dr.value,St);if($d===null){Jt===null&&(Jt=tr);break}m&&Jt&&$d.alternate===null&&g(rt,Jt),Ke=O($d,Ke,Rn),ur===null?an=$d:ur.sibling=$d,ur=$d,Jt=tr}if(dr.done)return _(rt,Jt),rr&&Qc(rt,Rn),an;if(Jt===null){for(;!dr.done;Rn++,dr=ut.next())dr=Ct(rt,dr.value,St),dr!==null&&(Ke=O(dr,Ke,Rn),ur===null?an=dr:ur.sibling=dr,ur=dr);return rr&&Qc(rt,Rn),an}for(Jt=C(Jt);!dr.done;Rn++,dr=ut.next())dr=gt(Jt,rt,Rn,dr.value,St),dr!==null&&(m&&dr.alternate!==null&&Jt.delete(dr.key===null?Rn:dr.key),Ke=O(dr,Ke,Rn),ur===null?an=dr:ur.sibling=dr,ur=dr);return m&&Jt.forEach(function(Eoe){return g(rt,Eoe)}),rr&&Qc(rt,Rn),an}function Tr(rt,Ke,ut,St){if(typeof ut=="object"&&ut!==null&&ut.type===v&&ut.key===null&&(ut=ut.props.children),typeof ut=="object"&&ut!==null){switch(ut.$$typeof){case p:e:{for(var an=ut.key;Ke!==null;){if(Ke.key===an){if(an=ut.type,an===v){if(Ke.tag===7){_(rt,Ke.sibling),St=F(Ke,ut.props.children),St.return=rt,rt=St;break e}}else if(Ke.elementType===an||typeof an=="object"&&an!==null&&an.$$typeof===j&&_m(an)===Ke.type){_(rt,Ke.sibling),St=F(Ke,ut.props),Ex(St,ut),St.return=rt,rt=St;break e}_(rt,Ke);break}else g(rt,Ke);Ke=Ke.sibling}ut.type===v?(St=bm(ut.props.children,rt.mode,St,ut.key),St.return=rt,rt=St):(St=uw(ut.type,ut.key,ut.props,null,rt.mode,St),Ex(St,ut),St.return=rt,rt=St)}return re(rt);case x:e:{for(an=ut.key;Ke!==null;){if(Ke.key===an)if(Ke.tag===4&&Ke.stateNode.containerInfo===ut.containerInfo&&Ke.stateNode.implementation===ut.implementation){_(rt,Ke.sibling),St=F(Ke,ut.children||[]),St.return=rt,rt=St;break e}else{_(rt,Ke);break}else g(rt,Ke);Ke=Ke.sibling}St=nA(ut,rt.mode,St),St.return=rt,rt=St}return re(rt);case j:return ut=_m(ut),Tr(rt,Ke,ut,St)}if(H(ut))return Qt(rt,Ke,ut,St);if(L(ut)){if(an=L(ut),typeof an!="function")throw Error(r(150));return ut=an.call(ut),hn(rt,Ke,ut,St)}if(typeof ut.then=="function")return Tr(rt,Ke,bw(ut),St);if(ut.$$typeof===N)return Tr(rt,Ke,mw(rt,ut),St);xw(rt,ut)}return typeof ut=="string"&&ut!==""||typeof ut=="number"||typeof ut=="bigint"?(ut=""+ut,Ke!==null&&Ke.tag===6?(_(rt,Ke.sibling),St=F(Ke,ut),St.return=rt,rt=St):(_(rt,Ke),St=tA(ut,rt.mode,St),St.return=rt,rt=St),re(rt)):_(rt,Ke)}return function(rt,Ke,ut,St){try{Tx=0;var an=Tr(rt,Ke,ut,St);return kp=null,an}catch(Jt){if(Jt===Np||Jt===pw)throw Jt;var ur=ho(29,Jt,null,rt.mode);return ur.lanes=St,ur.return=rt,ur}}}var Nm=i5(!0),a5=i5(!1),Cd=!1;function fA(m){m.updateQueue={baseState:m.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function pA(m,g){m=m.updateQueue,g.updateQueue===m&&(g.updateQueue={baseState:m.baseState,firstBaseUpdate:m.firstBaseUpdate,lastBaseUpdate:m.lastBaseUpdate,shared:m.shared,callbacks:null})}function Md(m){return{lane:m,tag:0,payload:null,callback:null,next:null}}function Ad(m,g,_){var C=m.updateQueue;if(C===null)return null;if(C=C.shared,(pr&2)!==0){var F=C.pending;return F===null?g.next=g:(g.next=F.next,F.next=g),C.pending=g,g=cw(m),HI(m,null,_),g}return lw(m,C,g,_),cw(m)}function Px(m,g,_){if(g=g.updateQueue,g!==null&&(g=g.shared,(_&4194048)!==0)){var C=g.lanes;C&=m.pendingLanes,_|=C,g.lanes=_,xt(m,_)}}function gA(m,g){var _=m.updateQueue,C=m.alternate;if(C!==null&&(C=C.updateQueue,_===C)){var F=null,O=null;if(_=_.firstBaseUpdate,_!==null){do{var re={lane:_.lane,tag:_.tag,payload:_.payload,callback:null,next:null};O===null?F=O=re:O=O.next=re,_=_.next}while(_!==null);O===null?F=O=g:O=O.next=g}else F=O=g;_={baseState:C.baseState,firstBaseUpdate:F,lastBaseUpdate:O,shared:C.shared,callbacks:C.callbacks},m.updateQueue=_;return}m=_.lastBaseUpdate,m===null?_.firstBaseUpdate=g:m.next=g,_.lastBaseUpdate=g}var bA=!1;function jx(){if(bA){var m=Sp;if(m!==null)throw m}}function Dx(m,g,_,C){bA=!1;var F=m.updateQueue;Cd=!1;var O=F.firstBaseUpdate,re=F.lastBaseUpdate,Ce=F.shared.pending;if(Ce!==null){F.shared.pending=null;var Be=Ce,ht=Be.next;Be.next=null,re===null?O=ht:re.next=ht,re=Be;var yt=m.alternate;yt!==null&&(yt=yt.updateQueue,Ce=yt.lastBaseUpdate,Ce!==re&&(Ce===null?yt.firstBaseUpdate=ht:Ce.next=ht,yt.lastBaseUpdate=Be))}if(O!==null){var Ct=F.baseState;re=0,yt=ht=Be=null,Ce=O;do{var mt=Ce.lane&-536870913,gt=mt!==Ce.lane;if(gt?(er&mt)===mt:(C&mt)===mt){mt!==0&&mt===_p&&(bA=!0),yt!==null&&(yt=yt.next={lane:0,tag:Ce.tag,payload:Ce.payload,callback:null,next:null});e:{var Qt=m,hn=Ce;mt=g;var Tr=_;switch(hn.tag){case 1:if(Qt=hn.payload,typeof Qt=="function"){Ct=Qt.call(Tr,Ct,mt);break e}Ct=Qt;break e;case 3:Qt.flags=Qt.flags&-65537|128;case 0:if(Qt=hn.payload,mt=typeof Qt=="function"?Qt.call(Tr,Ct,mt):Qt,mt==null)break e;Ct=h({},Ct,mt);break e;case 2:Cd=!0}}mt=Ce.callback,mt!==null&&(m.flags|=64,gt&&(m.flags|=8192),gt=F.callbacks,gt===null?F.callbacks=[mt]:gt.push(mt))}else gt={lane:mt,tag:Ce.tag,payload:Ce.payload,callback:Ce.callback,next:null},yt===null?(ht=yt=gt,Be=Ct):yt=yt.next=gt,re|=mt;if(Ce=Ce.next,Ce===null){if(Ce=F.shared.pending,Ce===null)break;gt=Ce,Ce=gt.next,gt.next=null,F.lastBaseUpdate=gt,F.shared.pending=null}}while(!0);yt===null&&(Be=Ct),F.baseState=Be,F.firstBaseUpdate=ht,F.lastBaseUpdate=yt,O===null&&(F.shared.lanes=0),Dd|=re,m.lanes=re,m.memoizedState=Ct}}function s5(m,g){if(typeof m!="function")throw Error(r(191,m));m.call(g)}function o5(m,g){var _=m.callbacks;if(_!==null)for(m.callbacks=null,m=0;m<_.length;m++)s5(_[m],g)}var Cp=V(null),yw=V(0);function l5(m,g){m=lu,ne(yw,m),ne(Cp,g),lu=m|g.baseLanes}function xA(){ne(yw,lu),ne(Cp,Cp.current)}function yA(){lu=yw.current,X(Cp),X(yw)}var mo=V(null),$o=null;function Td(m){var g=m.alternate;ne(Oi,Oi.current&1),ne(mo,m),$o===null&&(g===null||Cp.current!==null||g.memoizedState!==null)&&($o=m)}function vA(m){ne(Oi,Oi.current),ne(mo,m),$o===null&&($o=m)}function c5(m){m.tag===22?(ne(Oi,Oi.current),ne(mo,m),$o===null&&($o=m)):Ed()}function Ed(){ne(Oi,Oi.current),ne(mo,mo.current)}function fo(m){X(mo),$o===m&&($o=null),X(Oi)}var Oi=V(0);function vw(m){for(var g=m;g!==null;){if(g.tag===13){var _=g.memoizedState;if(_!==null&&(_=_.dehydrated,_===null||CT(_)||MT(_)))return g}else if(g.tag===19&&(g.memoizedProps.revealOrder==="forwards"||g.memoizedProps.revealOrder==="backwards"||g.memoizedProps.revealOrder==="unstable_legacy-backwards"||g.memoizedProps.revealOrder==="together")){if((g.flags&128)!==0)return g}else if(g.child!==null){g.child.return=g,g=g.child;continue}if(g===m)break;for(;g.sibling===null;){if(g.return===null||g.return===m)return null;g=g.return}g.sibling.return=g.return,g=g.sibling}return null}var eu=0,En=null,Mr=null,qi=null,ww=!1,Mp=!1,km=!1,_w=0,Rx=0,Ap=null,vse=0;function Ni(){throw Error(r(321))}function wA(m,g){if(g===null)return!1;for(var _=0;_O?O:8;var re=G.T,Ce={};G.T=Ce,LA(m,!1,g,_);try{var Be=F(),ht=G.S;if(ht!==null&&ht(Ce,Be),Be!==null&&typeof Be=="object"&&typeof Be.then=="function"){var yt=yse(Be,C);Lx(m,g,yt,bo(m))}else Lx(m,g,C,bo(m))}catch(Ct){Lx(m,g,{then:function(){},status:"rejected",reason:Ct},bo())}finally{I.p=O,re!==null&&Ce.types!==null&&(re.types=Ce.types),G.T=re}}function kse(){}function RA(m,g,_,C){if(m.tag!==5)throw Error(r(476));var F=z5(m).queue;I5(m,F,g,W,_===null?kse:function(){return U5(m),_(C)})}function z5(m){var g=m.memoizedState;if(g!==null)return g;g={memoizedState:W,baseState:W,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:tu,lastRenderedState:W},next:null};var _={};return g.next={memoizedState:_,baseState:_,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:tu,lastRenderedState:_},next:null},m.memoizedState=g,m=m.alternate,m!==null&&(m.memoizedState=g),g}function U5(m){var g=z5(m);g.next===null&&(g=m.alternate.memoizedState),Lx(m,g.next.queue,{},bo())}function FA(){return Ha(Jx)}function B5(){return Ii().memoizedState}function H5(){return Ii().memoizedState}function Cse(m){for(var g=m.return;g!==null;){switch(g.tag){case 24:case 3:var _=bo();m=Md(_);var C=Ad(g,m,_);C!==null&&(qs(C,g,_),Px(C,g,_)),g={cache:uA()},m.payload=g;return}g=g.return}}function Mse(m,g,_){var C=bo();_={lane:C,revertLane:0,gesture:null,action:_,hasEagerState:!1,eagerState:null,next:null},Aw(m)?V5(g,_):(_=JM(m,g,_,C),_!==null&&(qs(_,m,C),G5(_,g,C)))}function $5(m,g,_){var C=bo();Lx(m,g,_,C)}function Lx(m,g,_,C){var F={lane:C,revertLane:0,gesture:null,action:_,hasEagerState:!1,eagerState:null,next:null};if(Aw(m))V5(g,F);else{var O=m.alternate;if(m.lanes===0&&(O===null||O.lanes===0)&&(O=g.lastRenderedReducer,O!==null))try{var re=g.lastRenderedState,Ce=O(re,_);if(F.hasEagerState=!0,F.eagerState=Ce,uo(Ce,re))return lw(m,g,F,0),Hr===null&&ow(),!1}catch{}if(_=JM(m,g,F,C),_!==null)return qs(_,m,C),G5(_,g,C),!0}return!1}function LA(m,g,_,C){if(C={lane:2,revertLane:fT(),gesture:null,action:C,hasEagerState:!1,eagerState:null,next:null},Aw(m)){if(g)throw Error(r(479))}else g=JM(m,_,C,2),g!==null&&qs(g,m,2)}function Aw(m){var g=m.alternate;return m===En||g!==null&&g===En}function V5(m,g){Mp=ww=!0;var _=m.pending;_===null?g.next=g:(g.next=_.next,_.next=g),m.pending=g}function G5(m,g,_){if((_&4194048)!==0){var C=g.lanes;C&=m.pendingLanes,_|=C,g.lanes=_,xt(m,_)}}var Ox={readContext:Ha,use:Nw,useCallback:Ni,useContext:Ni,useEffect:Ni,useImperativeHandle:Ni,useLayoutEffect:Ni,useInsertionEffect:Ni,useMemo:Ni,useReducer:Ni,useRef:Ni,useState:Ni,useDebugValue:Ni,useDeferredValue:Ni,useTransition:Ni,useSyncExternalStore:Ni,useId:Ni,useHostTransitionStatus:Ni,useFormState:Ni,useActionState:Ni,useOptimistic:Ni,useMemoCache:Ni,useCacheRefresh:Ni};Ox.useEffectEvent=Ni;var q5={readContext:Ha,use:Nw,useCallback:function(m,g){return Cs().memoizedState=[m,g===void 0?null:g],m},useContext:Ha,useEffect:T5,useImperativeHandle:function(m,g,_){_=_!=null?_.concat([m]):null,Cw(4194308,4,D5.bind(null,g,m),_)},useLayoutEffect:function(m,g){return Cw(4194308,4,m,g)},useInsertionEffect:function(m,g){Cw(4,2,m,g)},useMemo:function(m,g){var _=Cs();g=g===void 0?null:g;var C=m();if(km){ke(!0);try{m()}finally{ke(!1)}}return _.memoizedState=[C,g],C},useReducer:function(m,g,_){var C=Cs();if(_!==void 0){var F=_(g);if(km){ke(!0);try{_(g)}finally{ke(!1)}}}else F=g;return C.memoizedState=C.baseState=F,m={pending:null,lanes:0,dispatch:null,lastRenderedReducer:m,lastRenderedState:F},C.queue=m,m=m.dispatch=Mse.bind(null,En,m),[C.memoizedState,m]},useRef:function(m){var g=Cs();return m={current:m},g.memoizedState=m},useState:function(m){m=TA(m);var g=m.queue,_=$5.bind(null,En,g);return g.dispatch=_,[m.memoizedState,_]},useDebugValue:jA,useDeferredValue:function(m,g){var _=Cs();return DA(_,m,g)},useTransition:function(){var m=TA(!1);return m=I5.bind(null,En,m.queue,!0,!1),Cs().memoizedState=m,[!1,m]},useSyncExternalStore:function(m,g,_){var C=En,F=Cs();if(rr){if(_===void 0)throw Error(r(407));_=_()}else{if(_=g(),Hr===null)throw Error(r(349));(er&127)!==0||m5(C,g,_)}F.memoizedState=_;var O={value:_,getSnapshot:g};return F.queue=O,T5(p5.bind(null,C,O,m),[m]),C.flags|=2048,Tp(9,{destroy:void 0},f5.bind(null,C,O,_,g),null),_},useId:function(){var m=Cs(),g=Hr.identifierPrefix;if(rr){var _=ac,C=ic;_=(C&~(1<<32-Ue(C)-1)).toString(32)+_,g="_"+g+"R_"+_,_=_w++,0<_&&(g+="H"+_.toString(32)),g+="_"}else _=vse++,g="_"+g+"r_"+_.toString(32)+"_";return m.memoizedState=g},useHostTransitionStatus:FA,useFormState:N5,useActionState:N5,useOptimistic:function(m){var g=Cs();g.memoizedState=g.baseState=m;var _={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return g.queue=_,g=LA.bind(null,En,!0,_),_.dispatch=g,[m,g]},useMemoCache:CA,useCacheRefresh:function(){return Cs().memoizedState=Cse.bind(null,En)},useEffectEvent:function(m){var g=Cs(),_={impl:m};return g.memoizedState=_,function(){if((pr&2)!==0)throw Error(r(440));return _.impl.apply(void 0,arguments)}}},OA={readContext:Ha,use:Nw,useCallback:F5,useContext:Ha,useEffect:PA,useImperativeHandle:R5,useInsertionEffect:P5,useLayoutEffect:j5,useMemo:L5,useReducer:kw,useRef:A5,useState:function(){return kw(tu)},useDebugValue:jA,useDeferredValue:function(m,g){var _=Ii();return O5(_,Mr.memoizedState,m,g)},useTransition:function(){var m=kw(tu)[0],g=Ii().memoizedState;return[typeof m=="boolean"?m:Fx(m),g]},useSyncExternalStore:h5,useId:B5,useHostTransitionStatus:FA,useFormState:k5,useActionState:k5,useOptimistic:function(m,g){var _=Ii();return x5(_,Mr,m,g)},useMemoCache:CA,useCacheRefresh:H5};OA.useEffectEvent=E5;var W5={readContext:Ha,use:Nw,useCallback:F5,useContext:Ha,useEffect:PA,useImperativeHandle:R5,useInsertionEffect:P5,useLayoutEffect:j5,useMemo:L5,useReducer:AA,useRef:A5,useState:function(){return AA(tu)},useDebugValue:jA,useDeferredValue:function(m,g){var _=Ii();return Mr===null?DA(_,m,g):O5(_,Mr.memoizedState,m,g)},useTransition:function(){var m=AA(tu)[0],g=Ii().memoizedState;return[typeof m=="boolean"?m:Fx(m),g]},useSyncExternalStore:h5,useId:B5,useHostTransitionStatus:FA,useFormState:M5,useActionState:M5,useOptimistic:function(m,g){var _=Ii();return Mr!==null?x5(_,Mr,m,g):(_.baseState=m,[m,_.queue.dispatch])},useMemoCache:CA,useCacheRefresh:H5};W5.useEffectEvent=E5;function IA(m,g,_,C){g=m.memoizedState,_=_(C,g),_=_==null?g:h({},g,_),m.memoizedState=_,m.lanes===0&&(m.updateQueue.baseState=_)}var zA={enqueueSetState:function(m,g,_){m=m._reactInternals;var C=bo(),F=Md(C);F.payload=g,_!=null&&(F.callback=_),g=Ad(m,F,C),g!==null&&(qs(g,m,C),Px(g,m,C))},enqueueReplaceState:function(m,g,_){m=m._reactInternals;var C=bo(),F=Md(C);F.tag=1,F.payload=g,_!=null&&(F.callback=_),g=Ad(m,F,C),g!==null&&(qs(g,m,C),Px(g,m,C))},enqueueForceUpdate:function(m,g){m=m._reactInternals;var _=bo(),C=Md(_);C.tag=2,g!=null&&(C.callback=g),g=Ad(m,C,_),g!==null&&(qs(g,m,_),Px(g,m,_))}};function K5(m,g,_,C,F,O,re){return m=m.stateNode,typeof m.shouldComponentUpdate=="function"?m.shouldComponentUpdate(C,O,re):g.prototype&&g.prototype.isPureReactComponent?!Sx(_,C)||!Sx(F,O):!0}function X5(m,g,_,C){m=g.state,typeof g.componentWillReceiveProps=="function"&&g.componentWillReceiveProps(_,C),typeof g.UNSAFE_componentWillReceiveProps=="function"&&g.UNSAFE_componentWillReceiveProps(_,C),g.state!==m&&zA.enqueueReplaceState(g,g.state,null)}function Cm(m,g){var _=g;if("ref"in g){_={};for(var C in g)C!=="ref"&&(_[C]=g[C])}if(m=m.defaultProps){_===g&&(_=h({},_));for(var F in m)_[F]===void 0&&(_[F]=m[F])}return _}function Y5(m){sw(m)}function Q5(m){console.error(m)}function Z5(m){sw(m)}function Tw(m,g){try{var _=m.onUncaughtError;_(g.value,{componentStack:g.stack})}catch(C){setTimeout(function(){throw C})}}function J5(m,g,_){try{var C=m.onCaughtError;C(_.value,{componentStack:_.stack,errorBoundary:g.tag===1?g.stateNode:null})}catch(F){setTimeout(function(){throw F})}}function UA(m,g,_){return _=Md(_),_.tag=3,_.payload={element:null},_.callback=function(){Tw(m,g)},_}function ez(m){return m=Md(m),m.tag=3,m}function tz(m,g,_,C){var F=_.type.getDerivedStateFromError;if(typeof F=="function"){var O=C.value;m.payload=function(){return F(O)},m.callback=function(){J5(g,_,C)}}var re=_.stateNode;re!==null&&typeof re.componentDidCatch=="function"&&(m.callback=function(){J5(g,_,C),typeof F!="function"&&(Rd===null?Rd=new Set([this]):Rd.add(this));var Ce=C.stack;this.componentDidCatch(C.value,{componentStack:Ce!==null?Ce:""})})}function Ase(m,g,_,C,F){if(_.flags|=32768,C!==null&&typeof C=="object"&&typeof C.then=="function"){if(g=_.alternate,g!==null&&wp(g,_,F,!0),_=mo.current,_!==null){switch(_.tag){case 31:case 13:return $o===null?Bw():_.alternate===null&&ki===0&&(ki=3),_.flags&=-257,_.flags|=65536,_.lanes=F,C===gw?_.flags|=16384:(g=_.updateQueue,g===null?_.updateQueue=new Set([C]):g.add(C),dT(m,C,F)),!1;case 22:return _.flags|=65536,C===gw?_.flags|=16384:(g=_.updateQueue,g===null?(g={transitions:null,markerInstances:null,retryQueue:new Set([C])},_.updateQueue=g):(_=g.retryQueue,_===null?g.retryQueue=new Set([C]):_.add(C)),dT(m,C,F)),!1}throw Error(r(435,_.tag))}return dT(m,C,F),Bw(),!1}if(rr)return g=mo.current,g!==null?((g.flags&65536)===0&&(g.flags|=256),g.flags|=65536,g.lanes=F,C!==aA&&(m=Error(r(422),{cause:C}),Cx(zo(m,_)))):(C!==aA&&(g=Error(r(423),{cause:C}),Cx(zo(g,_))),m=m.current.alternate,m.flags|=65536,F&=-F,m.lanes|=F,C=zo(C,_),F=UA(m.stateNode,C,F),gA(m,F),ki!==4&&(ki=2)),!1;var O=Error(r(520),{cause:C});if(O=zo(O,_),Gx===null?Gx=[O]:Gx.push(O),ki!==4&&(ki=2),g===null)return!0;C=zo(C,_),_=g;do{switch(_.tag){case 3:return _.flags|=65536,m=F&-F,_.lanes|=m,m=UA(_.stateNode,C,m),gA(_,m),!1;case 1:if(g=_.type,O=_.stateNode,(_.flags&128)===0&&(typeof g.getDerivedStateFromError=="function"||O!==null&&typeof O.componentDidCatch=="function"&&(Rd===null||!Rd.has(O))))return _.flags|=65536,F&=-F,_.lanes|=F,F=ez(F),tz(F,m,_,C),gA(_,F),!1}_=_.return}while(_!==null);return!1}var BA=Error(r(461)),Wi=!1;function $a(m,g,_,C){g.child=m===null?a5(g,null,_,C):Nm(g,m.child,_,C)}function nz(m,g,_,C,F){_=_.render;var O=g.ref;if("ref"in C){var re={};for(var Ce in C)Ce!=="ref"&&(re[Ce]=C[Ce])}else re=C;return vm(g),C=_A(m,g,_,re,O,F),Ce=SA(),m!==null&&!Wi?(NA(m,g,F),nu(m,g,F)):(rr&&Ce&&rA(g),g.flags|=1,$a(m,g,C,F),g.child)}function rz(m,g,_,C,F){if(m===null){var O=_.type;return typeof O=="function"&&!eA(O)&&O.defaultProps===void 0&&_.compare===null?(g.tag=15,g.type=O,iz(m,g,O,C,F)):(m=uw(_.type,null,C,g,g.mode,F),m.ref=g.ref,m.return=g,g.child=m)}if(O=m.child,!XA(m,F)){var re=O.memoizedProps;if(_=_.compare,_=_!==null?_:Sx,_(re,C)&&m.ref===g.ref)return nu(m,g,F)}return g.flags|=1,m=Yc(O,C),m.ref=g.ref,m.return=g,g.child=m}function iz(m,g,_,C,F){if(m!==null){var O=m.memoizedProps;if(Sx(O,C)&&m.ref===g.ref)if(Wi=!1,g.pendingProps=C=O,XA(m,F))(m.flags&131072)!==0&&(Wi=!0);else return g.lanes=m.lanes,nu(m,g,F)}return HA(m,g,_,C,F)}function az(m,g,_,C){var F=C.children,O=m!==null?m.memoizedState:null;if(m===null&&g.stateNode===null&&(g.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),C.mode==="hidden"){if((g.flags&128)!==0){if(O=O!==null?O.baseLanes|_:_,m!==null){for(C=g.child=m.child,F=0;C!==null;)F=F|C.lanes|C.childLanes,C=C.sibling;C=F&~O}else C=0,g.child=null;return sz(m,g,O,_,C)}if((_&536870912)!==0)g.memoizedState={baseLanes:0,cachePool:null},m!==null&&fw(g,O!==null?O.cachePool:null),O!==null?l5(g,O):xA(),c5(g);else return C=g.lanes=536870912,sz(m,g,O!==null?O.baseLanes|_:_,_,C)}else O!==null?(fw(g,O.cachePool),l5(g,O),Ed(),g.memoizedState=null):(m!==null&&fw(g,null),xA(),Ed());return $a(m,g,F,_),g.child}function Ix(m,g){return m!==null&&m.tag===22||g.stateNode!==null||(g.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),g.sibling}function sz(m,g,_,C,F){var O=hA();return O=O===null?null:{parent:Gi._currentValue,pool:O},g.memoizedState={baseLanes:_,cachePool:O},m!==null&&fw(g,null),xA(),c5(g),m!==null&&wp(m,g,C,!0),g.childLanes=F,null}function Ew(m,g){return g=jw({mode:g.mode,children:g.children},m.mode),g.ref=m.ref,m.child=g,g.return=m,g}function oz(m,g,_){return Nm(g,m.child,null,_),m=Ew(g,g.pendingProps),m.flags|=2,fo(g),g.memoizedState=null,m}function Tse(m,g,_){var C=g.pendingProps,F=(g.flags&128)!==0;if(g.flags&=-129,m===null){if(rr){if(C.mode==="hidden")return m=Ew(g,C),g.lanes=536870912,Ix(null,m);if(vA(g),(m=Jr)?(m=yU(m,Ho),m=m!==null&&m.data==="&"?m:null,m!==null&&(g.memoizedState={dehydrated:m,treeContext:_d!==null?{id:ic,overflow:ac}:null,retryLane:536870912,hydrationErrors:null},_=VI(m),_.return=g,g.child=_,Ba=g,Jr=null)):m=null,m===null)throw Nd(g);return g.lanes=536870912,null}return Ew(g,C)}var O=m.memoizedState;if(O!==null){var re=O.dehydrated;if(vA(g),F)if(g.flags&256)g.flags&=-257,g=oz(m,g,_);else if(g.memoizedState!==null)g.child=m.child,g.flags|=128,g=null;else throw Error(r(558));else if(Wi||wp(m,g,_,!1),F=(_&m.childLanes)!==0,Wi||F){if(C=Hr,C!==null&&(re=vt(C,_),re!==0&&re!==O.retryLane))throw O.retryLane=re,gm(m,re),qs(C,m,re),BA;Bw(),g=oz(m,g,_)}else m=O.treeContext,Jr=Vo(re.nextSibling),Ba=g,rr=!0,Sd=null,Ho=!1,m!==null&&WI(g,m),g=Ew(g,C),g.flags|=4096;return g}return m=Yc(m.child,{mode:C.mode,children:C.children}),m.ref=g.ref,g.child=m,m.return=g,m}function Pw(m,g){var _=g.ref;if(_===null)m!==null&&m.ref!==null&&(g.flags|=4194816);else{if(typeof _!="function"&&typeof _!="object")throw Error(r(284));(m===null||m.ref!==_)&&(g.flags|=4194816)}}function HA(m,g,_,C,F){return vm(g),_=_A(m,g,_,C,void 0,F),C=SA(),m!==null&&!Wi?(NA(m,g,F),nu(m,g,F)):(rr&&C&&rA(g),g.flags|=1,$a(m,g,_,F),g.child)}function lz(m,g,_,C,F,O){return vm(g),g.updateQueue=null,_=d5(g,C,_,F),u5(m),C=SA(),m!==null&&!Wi?(NA(m,g,O),nu(m,g,O)):(rr&&C&&rA(g),g.flags|=1,$a(m,g,_,O),g.child)}function cz(m,g,_,C,F){if(vm(g),g.stateNode===null){var O=bp,re=_.contextType;typeof re=="object"&&re!==null&&(O=Ha(re)),O=new _(C,O),g.memoizedState=O.state!==null&&O.state!==void 0?O.state:null,O.updater=zA,g.stateNode=O,O._reactInternals=g,O=g.stateNode,O.props=C,O.state=g.memoizedState,O.refs={},fA(g),re=_.contextType,O.context=typeof re=="object"&&re!==null?Ha(re):bp,O.state=g.memoizedState,re=_.getDerivedStateFromProps,typeof re=="function"&&(IA(g,_,re,C),O.state=g.memoizedState),typeof _.getDerivedStateFromProps=="function"||typeof O.getSnapshotBeforeUpdate=="function"||typeof O.UNSAFE_componentWillMount!="function"&&typeof O.componentWillMount!="function"||(re=O.state,typeof O.componentWillMount=="function"&&O.componentWillMount(),typeof O.UNSAFE_componentWillMount=="function"&&O.UNSAFE_componentWillMount(),re!==O.state&&zA.enqueueReplaceState(O,O.state,null),Dx(g,C,O,F),jx(),O.state=g.memoizedState),typeof O.componentDidMount=="function"&&(g.flags|=4194308),C=!0}else if(m===null){O=g.stateNode;var Ce=g.memoizedProps,Be=Cm(_,Ce);O.props=Be;var ht=O.context,yt=_.contextType;re=bp,typeof yt=="object"&&yt!==null&&(re=Ha(yt));var Ct=_.getDerivedStateFromProps;yt=typeof Ct=="function"||typeof O.getSnapshotBeforeUpdate=="function",Ce=g.pendingProps!==Ce,yt||typeof O.UNSAFE_componentWillReceiveProps!="function"&&typeof O.componentWillReceiveProps!="function"||(Ce||ht!==re)&&X5(g,O,C,re),Cd=!1;var mt=g.memoizedState;O.state=mt,Dx(g,C,O,F),jx(),ht=g.memoizedState,Ce||mt!==ht||Cd?(typeof Ct=="function"&&(IA(g,_,Ct,C),ht=g.memoizedState),(Be=Cd||K5(g,_,Be,C,mt,ht,re))?(yt||typeof O.UNSAFE_componentWillMount!="function"&&typeof O.componentWillMount!="function"||(typeof O.componentWillMount=="function"&&O.componentWillMount(),typeof O.UNSAFE_componentWillMount=="function"&&O.UNSAFE_componentWillMount()),typeof O.componentDidMount=="function"&&(g.flags|=4194308)):(typeof O.componentDidMount=="function"&&(g.flags|=4194308),g.memoizedProps=C,g.memoizedState=ht),O.props=C,O.state=ht,O.context=re,C=Be):(typeof O.componentDidMount=="function"&&(g.flags|=4194308),C=!1)}else{O=g.stateNode,pA(m,g),re=g.memoizedProps,yt=Cm(_,re),O.props=yt,Ct=g.pendingProps,mt=O.context,ht=_.contextType,Be=bp,typeof ht=="object"&&ht!==null&&(Be=Ha(ht)),Ce=_.getDerivedStateFromProps,(ht=typeof Ce=="function"||typeof O.getSnapshotBeforeUpdate=="function")||typeof O.UNSAFE_componentWillReceiveProps!="function"&&typeof O.componentWillReceiveProps!="function"||(re!==Ct||mt!==Be)&&X5(g,O,C,Be),Cd=!1,mt=g.memoizedState,O.state=mt,Dx(g,C,O,F),jx();var gt=g.memoizedState;re!==Ct||mt!==gt||Cd||m!==null&&m.dependencies!==null&&hw(m.dependencies)?(typeof Ce=="function"&&(IA(g,_,Ce,C),gt=g.memoizedState),(yt=Cd||K5(g,_,yt,C,mt,gt,Be)||m!==null&&m.dependencies!==null&&hw(m.dependencies))?(ht||typeof O.UNSAFE_componentWillUpdate!="function"&&typeof O.componentWillUpdate!="function"||(typeof O.componentWillUpdate=="function"&&O.componentWillUpdate(C,gt,Be),typeof O.UNSAFE_componentWillUpdate=="function"&&O.UNSAFE_componentWillUpdate(C,gt,Be)),typeof O.componentDidUpdate=="function"&&(g.flags|=4),typeof O.getSnapshotBeforeUpdate=="function"&&(g.flags|=1024)):(typeof O.componentDidUpdate!="function"||re===m.memoizedProps&&mt===m.memoizedState||(g.flags|=4),typeof O.getSnapshotBeforeUpdate!="function"||re===m.memoizedProps&&mt===m.memoizedState||(g.flags|=1024),g.memoizedProps=C,g.memoizedState=gt),O.props=C,O.state=gt,O.context=Be,C=yt):(typeof O.componentDidUpdate!="function"||re===m.memoizedProps&&mt===m.memoizedState||(g.flags|=4),typeof O.getSnapshotBeforeUpdate!="function"||re===m.memoizedProps&&mt===m.memoizedState||(g.flags|=1024),C=!1)}return O=C,Pw(m,g),C=(g.flags&128)!==0,O||C?(O=g.stateNode,_=C&&typeof _.getDerivedStateFromError!="function"?null:O.render(),g.flags|=1,m!==null&&C?(g.child=Nm(g,m.child,null,F),g.child=Nm(g,null,_,F)):$a(m,g,_,F),g.memoizedState=O.state,m=g.child):m=nu(m,g,F),m}function uz(m,g,_,C){return xm(),g.flags|=256,$a(m,g,_,C),g.child}var $A={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function VA(m){return{baseLanes:m,cachePool:JI()}}function GA(m,g,_){return m=m!==null?m.childLanes&~_:0,g&&(m|=go),m}function dz(m,g,_){var C=g.pendingProps,F=!1,O=(g.flags&128)!==0,re;if((re=O)||(re=m!==null&&m.memoizedState===null?!1:(Oi.current&2)!==0),re&&(F=!0,g.flags&=-129),re=(g.flags&32)!==0,g.flags&=-33,m===null){if(rr){if(F?Td(g):Ed(),(m=Jr)?(m=yU(m,Ho),m=m!==null&&m.data!=="&"?m:null,m!==null&&(g.memoizedState={dehydrated:m,treeContext:_d!==null?{id:ic,overflow:ac}:null,retryLane:536870912,hydrationErrors:null},_=VI(m),_.return=g,g.child=_,Ba=g,Jr=null)):m=null,m===null)throw Nd(g);return MT(m)?g.lanes=32:g.lanes=536870912,null}var Ce=C.children;return C=C.fallback,F?(Ed(),F=g.mode,Ce=jw({mode:"hidden",children:Ce},F),C=bm(C,F,_,null),Ce.return=g,C.return=g,Ce.sibling=C,g.child=Ce,C=g.child,C.memoizedState=VA(_),C.childLanes=GA(m,re,_),g.memoizedState=$A,Ix(null,C)):(Td(g),qA(g,Ce))}var Be=m.memoizedState;if(Be!==null&&(Ce=Be.dehydrated,Ce!==null)){if(O)g.flags&256?(Td(g),g.flags&=-257,g=WA(m,g,_)):g.memoizedState!==null?(Ed(),g.child=m.child,g.flags|=128,g=null):(Ed(),Ce=C.fallback,F=g.mode,C=jw({mode:"visible",children:C.children},F),Ce=bm(Ce,F,_,null),Ce.flags|=2,C.return=g,Ce.return=g,C.sibling=Ce,g.child=C,Nm(g,m.child,null,_),C=g.child,C.memoizedState=VA(_),C.childLanes=GA(m,re,_),g.memoizedState=$A,g=Ix(null,C));else if(Td(g),MT(Ce)){if(re=Ce.nextSibling&&Ce.nextSibling.dataset,re)var ht=re.dgst;re=ht,C=Error(r(419)),C.stack="",C.digest=re,Cx({value:C,source:null,stack:null}),g=WA(m,g,_)}else if(Wi||wp(m,g,_,!1),re=(_&m.childLanes)!==0,Wi||re){if(re=Hr,re!==null&&(C=vt(re,_),C!==0&&C!==Be.retryLane))throw Be.retryLane=C,gm(m,C),qs(re,m,C),BA;CT(Ce)||Bw(),g=WA(m,g,_)}else CT(Ce)?(g.flags|=192,g.child=m.child,g=null):(m=Be.treeContext,Jr=Vo(Ce.nextSibling),Ba=g,rr=!0,Sd=null,Ho=!1,m!==null&&WI(g,m),g=qA(g,C.children),g.flags|=4096);return g}return F?(Ed(),Ce=C.fallback,F=g.mode,Be=m.child,ht=Be.sibling,C=Yc(Be,{mode:"hidden",children:C.children}),C.subtreeFlags=Be.subtreeFlags&65011712,ht!==null?Ce=Yc(ht,Ce):(Ce=bm(Ce,F,_,null),Ce.flags|=2),Ce.return=g,C.return=g,C.sibling=Ce,g.child=C,Ix(null,C),C=g.child,Ce=m.child.memoizedState,Ce===null?Ce=VA(_):(F=Ce.cachePool,F!==null?(Be=Gi._currentValue,F=F.parent!==Be?{parent:Be,pool:Be}:F):F=JI(),Ce={baseLanes:Ce.baseLanes|_,cachePool:F}),C.memoizedState=Ce,C.childLanes=GA(m,re,_),g.memoizedState=$A,Ix(m.child,C)):(Td(g),_=m.child,m=_.sibling,_=Yc(_,{mode:"visible",children:C.children}),_.return=g,_.sibling=null,m!==null&&(re=g.deletions,re===null?(g.deletions=[m],g.flags|=16):re.push(m)),g.child=_,g.memoizedState=null,_)}function qA(m,g){return g=jw({mode:"visible",children:g},m.mode),g.return=m,m.child=g}function jw(m,g){return m=ho(22,m,null,g),m.lanes=0,m}function WA(m,g,_){return Nm(g,m.child,null,_),m=qA(g,g.pendingProps.children),m.flags|=2,g.memoizedState=null,m}function hz(m,g,_){m.lanes|=g;var C=m.alternate;C!==null&&(C.lanes|=g),lA(m.return,g,_)}function KA(m,g,_,C,F,O){var re=m.memoizedState;re===null?m.memoizedState={isBackwards:g,rendering:null,renderingStartTime:0,last:C,tail:_,tailMode:F,treeForkCount:O}:(re.isBackwards=g,re.rendering=null,re.renderingStartTime=0,re.last=C,re.tail=_,re.tailMode=F,re.treeForkCount=O)}function mz(m,g,_){var C=g.pendingProps,F=C.revealOrder,O=C.tail;C=C.children;var re=Oi.current,Ce=(re&2)!==0;if(Ce?(re=re&1|2,g.flags|=128):re&=1,ne(Oi,re),$a(m,g,C,_),C=rr?kx:0,!Ce&&m!==null&&(m.flags&128)!==0)e:for(m=g.child;m!==null;){if(m.tag===13)m.memoizedState!==null&&hz(m,_,g);else if(m.tag===19)hz(m,_,g);else if(m.child!==null){m.child.return=m,m=m.child;continue}if(m===g)break e;for(;m.sibling===null;){if(m.return===null||m.return===g)break e;m=m.return}m.sibling.return=m.return,m=m.sibling}switch(F){case"forwards":for(_=g.child,F=null;_!==null;)m=_.alternate,m!==null&&vw(m)===null&&(F=_),_=_.sibling;_=F,_===null?(F=g.child,g.child=null):(F=_.sibling,_.sibling=null),KA(g,!1,F,_,O,C);break;case"backwards":case"unstable_legacy-backwards":for(_=null,F=g.child,g.child=null;F!==null;){if(m=F.alternate,m!==null&&vw(m)===null){g.child=F;break}m=F.sibling,F.sibling=_,_=F,F=m}KA(g,!0,_,null,O,C);break;case"together":KA(g,!1,null,null,void 0,C);break;default:g.memoizedState=null}return g.child}function nu(m,g,_){if(m!==null&&(g.dependencies=m.dependencies),Dd|=g.lanes,(_&g.childLanes)===0)if(m!==null){if(wp(m,g,_,!1),(_&g.childLanes)===0)return null}else return null;if(m!==null&&g.child!==m.child)throw Error(r(153));if(g.child!==null){for(m=g.child,_=Yc(m,m.pendingProps),g.child=_,_.return=g;m.sibling!==null;)m=m.sibling,_=_.sibling=Yc(m,m.pendingProps),_.return=g;_.sibling=null}return g.child}function XA(m,g){return(m.lanes&g)!==0?!0:(m=m.dependencies,!!(m!==null&&hw(m)))}function Ese(m,g,_){switch(g.tag){case 3:De(g,g.stateNode.containerInfo),kd(g,Gi,m.memoizedState.cache),xm();break;case 27:case 5:ce(g);break;case 4:De(g,g.stateNode.containerInfo);break;case 10:kd(g,g.type,g.memoizedProps.value);break;case 31:if(g.memoizedState!==null)return g.flags|=128,vA(g),null;break;case 13:var C=g.memoizedState;if(C!==null)return C.dehydrated!==null?(Td(g),g.flags|=128,null):(_&g.child.childLanes)!==0?dz(m,g,_):(Td(g),m=nu(m,g,_),m!==null?m.sibling:null);Td(g);break;case 19:var F=(m.flags&128)!==0;if(C=(_&g.childLanes)!==0,C||(wp(m,g,_,!1),C=(_&g.childLanes)!==0),F){if(C)return mz(m,g,_);g.flags|=128}if(F=g.memoizedState,F!==null&&(F.rendering=null,F.tail=null,F.lastEffect=null),ne(Oi,Oi.current),C)break;return null;case 22:return g.lanes=0,az(m,g,_,g.pendingProps);case 24:kd(g,Gi,m.memoizedState.cache)}return nu(m,g,_)}function fz(m,g,_){if(m!==null)if(m.memoizedProps!==g.pendingProps)Wi=!0;else{if(!XA(m,_)&&(g.flags&128)===0)return Wi=!1,Ese(m,g,_);Wi=(m.flags&131072)!==0}else Wi=!1,rr&&(g.flags&1048576)!==0&&qI(g,kx,g.index);switch(g.lanes=0,g.tag){case 16:e:{var C=g.pendingProps;if(m=_m(g.elementType),g.type=m,typeof m=="function")eA(m)?(C=Cm(m,C),g.tag=1,g=cz(null,g,m,C,_)):(g.tag=0,g=HA(null,g,m,C,_));else{if(m!=null){var F=m.$$typeof;if(F===A){g.tag=11,g=nz(null,g,m,C,_);break e}else if(F===k){g.tag=14,g=rz(null,g,m,C,_);break e}}throw g=D(m)||m,Error(r(306,g,""))}}return g;case 0:return HA(m,g,g.type,g.pendingProps,_);case 1:return C=g.type,F=Cm(C,g.pendingProps),cz(m,g,C,F,_);case 3:e:{if(De(g,g.stateNode.containerInfo),m===null)throw Error(r(387));C=g.pendingProps;var O=g.memoizedState;F=O.element,pA(m,g),Dx(g,C,null,_);var re=g.memoizedState;if(C=re.cache,kd(g,Gi,C),C!==O.cache&&cA(g,[Gi],_,!0),jx(),C=re.element,O.isDehydrated)if(O={element:C,isDehydrated:!1,cache:re.cache},g.updateQueue.baseState=O,g.memoizedState=O,g.flags&256){g=uz(m,g,C,_);break e}else if(C!==F){F=zo(Error(r(424)),g),Cx(F),g=uz(m,g,C,_);break e}else for(m=g.stateNode.containerInfo,m.nodeType===9?m=m.body:m=m.nodeName==="HTML"?m.ownerDocument.body:m,Jr=Vo(m.firstChild),Ba=g,rr=!0,Sd=null,Ho=!0,_=a5(g,null,C,_),g.child=_;_;)_.flags=_.flags&-3|4096,_=_.sibling;else{if(xm(),C===F){g=nu(m,g,_);break e}$a(m,g,C,_)}g=g.child}return g;case 26:return Pw(m,g),m===null?(_=kU(g.type,null,g.pendingProps,null))?g.memoizedState=_:rr||(_=g.type,m=g.pendingProps,C=Kw(pe.current).createElement(_),C[Pn]=g,C[cr]=m,Va(C,_,m),Ge(C),g.stateNode=C):g.memoizedState=kU(g.type,m.memoizedProps,g.pendingProps,m.memoizedState),null;case 27:return ce(g),m===null&&rr&&(C=g.stateNode=_U(g.type,g.pendingProps,pe.current),Ba=g,Ho=!0,F=Jr,Id(g.type)?(AT=F,Jr=Vo(C.firstChild)):Jr=F),$a(m,g,g.pendingProps.children,_),Pw(m,g),m===null&&(g.flags|=4194304),g.child;case 5:return m===null&&rr&&((F=C=Jr)&&(C=soe(C,g.type,g.pendingProps,Ho),C!==null?(g.stateNode=C,Ba=g,Jr=Vo(C.firstChild),Ho=!1,F=!0):F=!1),F||Nd(g)),ce(g),F=g.type,O=g.pendingProps,re=m!==null?m.memoizedProps:null,C=O.children,ST(F,O)?C=null:re!==null&&ST(F,re)&&(g.flags|=32),g.memoizedState!==null&&(F=_A(m,g,wse,null,null,_),Jx._currentValue=F),Pw(m,g),$a(m,g,C,_),g.child;case 6:return m===null&&rr&&((m=_=Jr)&&(_=ooe(_,g.pendingProps,Ho),_!==null?(g.stateNode=_,Ba=g,Jr=null,m=!0):m=!1),m||Nd(g)),null;case 13:return dz(m,g,_);case 4:return De(g,g.stateNode.containerInfo),C=g.pendingProps,m===null?g.child=Nm(g,null,C,_):$a(m,g,C,_),g.child;case 11:return nz(m,g,g.type,g.pendingProps,_);case 7:return $a(m,g,g.pendingProps,_),g.child;case 8:return $a(m,g,g.pendingProps.children,_),g.child;case 12:return $a(m,g,g.pendingProps.children,_),g.child;case 10:return C=g.pendingProps,kd(g,g.type,C.value),$a(m,g,C.children,_),g.child;case 9:return F=g.type._context,C=g.pendingProps.children,vm(g),F=Ha(F),C=C(F),g.flags|=1,$a(m,g,C,_),g.child;case 14:return rz(m,g,g.type,g.pendingProps,_);case 15:return iz(m,g,g.type,g.pendingProps,_);case 19:return mz(m,g,_);case 31:return Tse(m,g,_);case 22:return az(m,g,_,g.pendingProps);case 24:return vm(g),C=Ha(Gi),m===null?(F=hA(),F===null&&(F=Hr,O=uA(),F.pooledCache=O,O.refCount++,O!==null&&(F.pooledCacheLanes|=_),F=O),g.memoizedState={parent:C,cache:F},fA(g),kd(g,Gi,F)):((m.lanes&_)!==0&&(pA(m,g),Dx(g,null,null,_),jx()),F=m.memoizedState,O=g.memoizedState,F.parent!==C?(F={parent:C,cache:C},g.memoizedState=F,g.lanes===0&&(g.memoizedState=g.updateQueue.baseState=F),kd(g,Gi,C)):(C=O.cache,kd(g,Gi,C),C!==F.cache&&cA(g,[Gi],_,!0))),$a(m,g,g.pendingProps.children,_),g.child;case 29:throw g.pendingProps}throw Error(r(156,g.tag))}function ru(m){m.flags|=4}function YA(m,g,_,C,F){if((g=(m.mode&32)!==0)&&(g=!1),g){if(m.flags|=16777216,(F&335544128)===F)if(m.stateNode.complete)m.flags|=8192;else if(Bz())m.flags|=8192;else throw Sm=gw,mA}else m.flags&=-16777217}function pz(m,g){if(g.type!=="stylesheet"||(g.state.loading&4)!==0)m.flags&=-16777217;else if(m.flags|=16777216,!EU(g))if(Bz())m.flags|=8192;else throw Sm=gw,mA}function Dw(m,g){g!==null&&(m.flags|=4),m.flags&16384&&(g=m.tag!==22?At():536870912,m.lanes|=g,Dp|=g)}function zx(m,g){if(!rr)switch(m.tailMode){case"hidden":g=m.tail;for(var _=null;g!==null;)g.alternate!==null&&(_=g),g=g.sibling;_===null?m.tail=null:_.sibling=null;break;case"collapsed":_=m.tail;for(var C=null;_!==null;)_.alternate!==null&&(C=_),_=_.sibling;C===null?g||m.tail===null?m.tail=null:m.tail.sibling=null:C.sibling=null}}function ei(m){var g=m.alternate!==null&&m.alternate.child===m.child,_=0,C=0;if(g)for(var F=m.child;F!==null;)_|=F.lanes|F.childLanes,C|=F.subtreeFlags&65011712,C|=F.flags&65011712,F.return=m,F=F.sibling;else for(F=m.child;F!==null;)_|=F.lanes|F.childLanes,C|=F.subtreeFlags,C|=F.flags,F.return=m,F=F.sibling;return m.subtreeFlags|=C,m.childLanes=_,g}function Pse(m,g,_){var C=g.pendingProps;switch(iA(g),g.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return ei(g),null;case 1:return ei(g),null;case 3:return _=g.stateNode,C=null,m!==null&&(C=m.memoizedState.cache),g.memoizedState.cache!==C&&(g.flags|=2048),Jc(Gi),de(),_.pendingContext&&(_.context=_.pendingContext,_.pendingContext=null),(m===null||m.child===null)&&(vp(g)?ru(g):m===null||m.memoizedState.isDehydrated&&(g.flags&256)===0||(g.flags|=1024,sA())),ei(g),null;case 26:var F=g.type,O=g.memoizedState;return m===null?(ru(g),O!==null?(ei(g),pz(g,O)):(ei(g),YA(g,F,null,C,_))):O?O!==m.memoizedState?(ru(g),ei(g),pz(g,O)):(ei(g),g.flags&=-16777217):(m=m.memoizedProps,m!==C&&ru(g),ei(g),YA(g,F,m,C,_)),null;case 27:if(Ne(g),_=pe.current,F=g.type,m!==null&&g.stateNode!=null)m.memoizedProps!==C&&ru(g);else{if(!C){if(g.stateNode===null)throw Error(r(166));return ei(g),null}m=te.current,vp(g)?KI(g):(m=_U(F,C,_),g.stateNode=m,ru(g))}return ei(g),null;case 5:if(Ne(g),F=g.type,m!==null&&g.stateNode!=null)m.memoizedProps!==C&&ru(g);else{if(!C){if(g.stateNode===null)throw Error(r(166));return ei(g),null}if(O=te.current,vp(g))KI(g);else{var re=Kw(pe.current);switch(O){case 1:O=re.createElementNS("http://www.w3.org/2000/svg",F);break;case 2:O=re.createElementNS("http://www.w3.org/1998/Math/MathML",F);break;default:switch(F){case"svg":O=re.createElementNS("http://www.w3.org/2000/svg",F);break;case"math":O=re.createElementNS("http://www.w3.org/1998/Math/MathML",F);break;case"script":O=re.createElement("div"),O.innerHTML=" + From be569f7577da93e287b863cb655a90c5f0f30a50 Mon Sep 17 00:00:00 2001 From: maziggy Date: Sun, 15 Feb 2026 15:47:41 +0100 Subject: [PATCH 3/7] fix: prevent spool weight corruption, add AMS weight sync, fix extruder_id MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three bugs fixed and one recovery feature added: 1. AMS remain=0 zeroed all spools on printer power-off. The weight sync treated 0% remain as "fully consumed," setting weight_used to label_weight for every assigned spool. Fix: skip remain=0 in AMS weight sync — empty spools are tracked by the usage tracker. 2. Editing any spool field sent stale weight_used from the React Query cache back to the server, resetting usage-tracked weight. Fix: only include weight_used in PATCH when the user explicitly changes it. 3. K-profile auto-select crashed on dual-nozzle printers for non-BL spools with 'SpoolKProfile has no attribute extruder_id'. The model attribute is 'extruder', not 'extruder_id'. 4. New "Sync Weights from AMS" button in Settings > Filament Tracking (built-in inventory mode) to force-recover spool weights from live AMS sensor data. Bypasses the "only increase" guard for explicit user-initiated recovery. --- CHANGELOG.md | 3 + backend/app/api/routes/inventory.py | 95 ++++++- backend/app/main.py | 2 +- backend/tests/unit/test_sync_ams_weights.py | 242 ++++++++++++++++++ .../components/SpoolFormModal.test.tsx | 186 ++++++++++++++ frontend/src/api/client.ts | 2 + frontend/src/components/SpoolmanSettings.tsx | 66 ++++- frontend/src/i18n/locales/de.ts | 6 + frontend/src/i18n/locales/en.ts | 6 + frontend/src/i18n/locales/fr.ts | 6 + frontend/src/i18n/locales/ja.ts | 6 + .../{index-DDGLa0P-.js => index-LH77R5cV.js} | 94 +++---- static/index.html | 2 +- 13 files changed, 656 insertions(+), 60 deletions(-) create mode 100644 backend/tests/unit/test_sync_ams_weights.py create mode 100644 frontend/src/__tests__/components/SpoolFormModal.test.tsx rename static/assets/{index-DDGLa0P-.js => index-LH77R5cV.js} (80%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 683f0c9f3..588438792 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ All notable changes to Bambuddy will be documented in this file. - **AMS Slot Configuration — Model Filtering & Pre-Population** — The Configure AMS Slot modal now filters filament presets by the connected printer model. Only presets matching the printer (e.g., "@BBL X1C" presets for X1C printers) and generic presets without a model suffix are shown. Local presets are filtered by their `compatible_printers` field. When re-configuring an already-configured slot, the modal pre-selects the saved preset, pre-populates the color, and auto-selects the active K-profile. The preset list auto-scrolls to the selected item. All modal strings are now fully translated in 5 locales (en, de, fr, it, ja). - **K-Profiles View — Accurate Filament Name Resolution** — K-profile filament names are now resolved from builtin filament tables and user cloud presets (via new `/cloud/filament-id-map` endpoint) instead of showing raw IDs like "GFU99" or "P4d64437". Falls back to extracting names from the profile name field. - **Print Log** — New view mode on the Archives page showing a chronological table of all print activity. Columns include date/time, print name, printer, user, status, duration, and filament. Supports filtering by search text, printer, user, status, and date range. Pagination with configurable page size. A dedicated clear button deletes only log entries without affecting archives. Data is stored in a separate `print_log_entries` database table. +- **Sync Spool Weights from AMS** — New button in Settings → Filament Tracking (built-in inventory mode) to force-sync all inventory spool weights from the live AMS remain% values of connected printers. Overwrites the database weight data with current sensor readings. Useful for recovering from corrupted weight data (e.g., after a power-off event zeroed all fill levels). Requires printers to be online. Includes a confirmation modal. ### Fixed - **Firmware Upload Uses Wrong Filename on Cache Hit** — The firmware update uploader cached downloaded firmware files under a mangled name (e.g., `X1C_01_09_00_10.bin`) instead of the original filename from Bambu Lab's CDN. On the first download the correct filename was uploaded to the SD card, but on subsequent attempts the cached file with the wrong name was used — causing the printer to not recognize the firmware file. Now caches using the original filename so the SD card always receives the correct file. @@ -33,7 +34,9 @@ All notable changes to Bambuddy will be documented in this file. - **Archive List View Not Labeling Failed Prints** ([#365](https://github.com/maziggy/bambuddy/issues/365)) — The archive grid view displayed a red "Failed" / "Cancelled" badge on failed and aborted prints, but the list view had no equivalent indicator. Now shows an inline status badge next to the print name in list view. - **Reprint Fails with SD Card Error for Archives Without 3MF File** ([#376](https://github.com/maziggy/bambuddy/issues/376)) — When a print was sent from an external slicer and Bambuddy couldn't download the 3MF from the printer during auto-archiving, the fallback archive had no file. Attempting to reprint such an archive tried to upload the data directory as a file, causing a confusing "SD card error." The backend now returns a clear error for file-less archives, and the frontend disables Print/Schedule/Open in Slicer buttons with a tooltip explaining that the 3MF file is unavailable. - **Inventory Spool Weight Resets After Print Completes** — After a print, the usage tracker correctly updated `weight_used` (e.g., +1.6g), but periodic AMS status updates recalculated `weight_used` from the AMS remain% sensor and overwrote the precise value. For small prints on large spools (e.g., 1.6g on 1000g), the AMS remain% stays at 100% (integer resolution = 10g steps), resetting `weight_used` back to 0. The AMS weight sync now only increases `weight_used`, never decreases it, preserving precise values from the usage tracker. +- **All Spool Fill Levels Drop to Zero When Printers Power Off** — When a printer powers off, the AMS sensor can report `remain=0` for all trays while `tray_type` is still populated. The weight sync treated 0% remain as "100% consumed," computing `weight_used = label_weight` (e.g., 1000g). The "only increase" guard passed because `label_weight > current_used + 1`, marking every assigned spool as fully consumed. The AMS weight sync now skips `remain=0` entirely — a physically empty spool is tracked by the usage tracker during the print, not by a transient AMS sensor reading. - **Spool Edit Form Overwrites Usage-Tracked Weight** — Editing any spool field (note, color, material, etc.) sent the full form data back to the server, including `weight_used`. If the frontend cache was stale (e.g., loaded before the last print completed), saving the form would silently reset `weight_used` to the pre-print value, reverting the remaining weight to full. The form now only includes `weight_used` in the update request when the user explicitly changes the weight field. +- **K-Profile Auto-Select Fails for Non-BL Spools on Dual-Nozzle Printers** — When assigning a third-party spool to an AMS slot on dual-nozzle printers (H2D, H2D Pro), the MQTT auto-configure step crashed with `'SpoolKProfile' object has no attribute 'extruder_id'`. The K-profile model uses `extruder` (not `extruder_id`). Fixed the attribute name so K-profile matching correctly filters by nozzle on dual-extruder printers. - **Loose Archive Name Matching Could Cause Wrong Archive Reuse** ([#374](https://github.com/maziggy/bambuddy/issues/374)) — The `on_print_start` callback used `ilike('%{name}%')` to find existing "printing" archives, which meant a print named "Clip" could incorrectly match "Cable Clip" or "Clip Stand". This could cause a new print to reuse the wrong archive or skip creating one. Tightened to exact `print_name` match or exact filename variants (`.3mf`, `.gcode.3mf`). - **Archive Duplicate Badge Misses Name-Based Duplicates** ([#315](https://github.com/maziggy/bambuddy/issues/315)) — The duplicate badge on archive cards only matched by file content hash, so re-sliced prints of the same model (different GCODE, same print name) were not flagged as duplicates. Now also matches by print name (case-insensitive), consistent with the detail view's duplicate detection. diff --git a/backend/app/api/routes/inventory.py b/backend/app/api/routes/inventory.py index 22f90bd64..fd9195e8e 100644 --- a/backend/app/api/routes/inventory.py +++ b/backend/app/api/routes/inventory.py @@ -748,7 +748,7 @@ async def assign_spool( matching_kp = None for kp in spool.k_profiles: if kp.printer_id == data.printer_id and kp.nozzle_diameter == nozzle_diameter: - if slot_extruder is not None and kp.extruder_id is not None and kp.extruder_id != slot_extruder: + if slot_extruder is not None and kp.extruder is not None and kp.extruder != slot_extruder: continue matching_kp = kp break @@ -954,6 +954,99 @@ async def clear_spool_usage_history( return {"status": "cleared"} +# ── AMS Weight Sync ────────────────────────────────────────────────────────── + + +@router.post("/sync-ams-weights") +async def sync_weights_from_ams( + db: AsyncSession = Depends(get_db), + _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE), +): + """Force-sync spool weight_used from live AMS remain% data. + + Overwrites the database weight_used for every assigned spool using the + current AMS remain% from connected printers. This is a manual recovery + tool — it bypasses the normal "only increase" guard. + """ + from backend.app.services.printer_manager import printer_manager + + result = await db.execute(select(SpoolAssignment).options(selectinload(SpoolAssignment.spool))) + assignments = list(result.scalars().all()) + logger.info("AMS weight sync: found %d assignments", len(assignments)) + + synced = 0 + skipped = 0 + + for assignment in assignments: + spool = assignment.spool + if not spool: + logger.debug("AMS weight sync: assignment %d has no spool", assignment.id) + skipped += 1 + continue + + state = printer_manager.get_status(assignment.printer_id) + if not state or not state.raw_data: + logger.info( + "AMS weight sync: printer %d not connected, skipping spool %d", + assignment.printer_id, + spool.id, + ) + skipped += 1 + continue + + ams_raw = state.raw_data.get("ams", []) + if isinstance(ams_raw, dict): + ams_raw = ams_raw.get("ams", []) + tray = _find_tray_in_ams_data(ams_raw, assignment.ams_id, assignment.tray_id) + if not tray: + logger.info( + "AMS weight sync: no tray data for spool %d (printer %d AMS%d-T%d)", + spool.id, + assignment.printer_id, + assignment.ams_id, + assignment.tray_id, + ) + skipped += 1 + continue + + remain_raw = tray.get("remain") + if remain_raw is None: + logger.debug("AMS weight sync: no remain value for spool %d", spool.id) + skipped += 1 + continue + + try: + remain_val = int(remain_raw) + except (TypeError, ValueError): + skipped += 1 + continue + + if remain_val < 0 or remain_val > 100: + logger.debug("AMS weight sync: invalid remain=%s for spool %d", remain_raw, spool.id) + skipped += 1 + continue + + lw = spool.label_weight or 1000 + new_used = round(lw * (100 - remain_val) / 100.0, 1) + old_used = spool.weight_used or 0 + + if round(old_used, 1) != new_used: + logger.info( + "AMS weight sync: spool %d weight_used %s -> %s (remain=%d%%)", + spool.id, + old_used, + new_used, + remain_val, + ) + spool.weight_used = new_used + synced += 1 + else: + skipped += 1 + + await db.commit() + return {"synced": synced, "skipped": skipped} + + # ── Helpers ────────────────────────────────────────────────────────────────── diff --git a/backend/app/main.py b/backend/app/main.py index d4fafdcab..2101a1a94 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -689,7 +689,7 @@ async def on_ams_change(printer_id: int, ams_data: list): remain_val = int(remain_raw) except (TypeError, ValueError): remain_val = -1 - if 0 <= remain_val <= 100: + if 1 <= remain_val <= 100: lw = existing_assignment.spool.label_weight or 1000 new_used = round(lw * (100 - remain_val) / 100.0, 1) current_used = existing_assignment.spool.weight_used or 0 diff --git a/backend/tests/unit/test_sync_ams_weights.py b/backend/tests/unit/test_sync_ams_weights.py new file mode 100644 index 000000000..349a2899f --- /dev/null +++ b/backend/tests/unit/test_sync_ams_weights.py @@ -0,0 +1,242 @@ +"""Unit tests for the AMS weight sync calculation logic. + +Tests the weight_used calculation and remain% validation extracted from +the POST /inventory/sync-ams-weights endpoint, without requiring a database. +""" + +import pytest + +from backend.app.api.routes.inventory import _find_tray_in_ams_data + + +def _calc_weight_used(label_weight: int | None, remain: int) -> float: + """Reproduce the weight calculation from sync_weights_from_ams.""" + lw = label_weight or 1000 + return round(lw * (100 - remain) / 100.0, 1) + + +def _is_valid_remain(remain_raw) -> tuple[bool, int]: + """Reproduce the remain% validation from sync_weights_from_ams. + + Returns (is_valid, parsed_value). parsed_value is only meaningful + when is_valid is True. + """ + if remain_raw is None: + return False, 0 + try: + val = int(remain_raw) + except (TypeError, ValueError): + return False, 0 + if val < 0 or val > 100: + return False, val + return True, val + + +class TestWeightCalculation: + """Test the weight_used = label_weight * (100 - remain) / 100 formula.""" + + def test_remain_100_means_no_usage(self): + """A full spool (remain=100) should have weight_used=0.""" + assert _calc_weight_used(1000, 100) == 0.0 + + def test_remain_50_with_1000g_spool(self): + """Half-used 1000g spool should have weight_used=500.""" + assert _calc_weight_used(1000, 50) == 500.0 + + def test_remain_0_means_fully_used(self): + """An empty spool (remain=0) should have weight_used equal to label_weight. + + Unlike the on_ams_change guard, the sync endpoint processes remain=0 + since it is a manual recovery tool. + """ + assert _calc_weight_used(1000, 0) == 1000.0 + + def test_respects_label_weight_500g(self): + """500g spool at remain=50 should have weight_used=250.""" + assert _calc_weight_used(500, 50) == 250.0 + + def test_respects_label_weight_250g(self): + """250g spool at remain=75 should have weight_used=62.5.""" + assert _calc_weight_used(250, 75) == 62.5 + + def test_none_label_weight_defaults_to_1000(self): + """When label_weight is None, it defaults to 1000g.""" + assert _calc_weight_used(None, 50) == 500.0 + + def test_result_is_rounded_to_one_decimal(self): + """Weight used should be rounded to 1 decimal place. + + For a 1000g spool at remain=33, weight_used = 1000 * 67 / 100 = 670.0 + """ + assert _calc_weight_used(1000, 33) == 670.0 + + def test_odd_fraction_rounds_correctly(self): + """750g spool at remain=33 → 750 * 67/100 = 502.5.""" + assert _calc_weight_used(750, 33) == 502.5 + + def test_small_spool_small_remain(self): + """200g spool at remain=1 → 200 * 99/100 = 198.0.""" + assert _calc_weight_used(200, 1) == 198.0 + + +class TestRemainValidation: + """Test the remain% bounds and type validation.""" + + def test_remain_minus_1_is_invalid(self): + """remain=-1 (firmware 'unknown') should be skipped.""" + valid, _ = _is_valid_remain(-1) + assert valid is False + + def test_remain_101_is_invalid(self): + """remain=101 (out of range) should be skipped.""" + valid, _ = _is_valid_remain(101) + assert valid is False + + def test_remain_negative_large_is_invalid(self): + """Large negative remain values should be skipped.""" + valid, _ = _is_valid_remain(-50) + assert valid is False + + def test_remain_200_is_invalid(self): + """remain=200 should be skipped.""" + valid, _ = _is_valid_remain(200) + assert valid is False + + def test_remain_none_is_invalid(self): + """remain=None (missing from tray data) should be skipped.""" + valid, _ = _is_valid_remain(None) + assert valid is False + + def test_remain_non_numeric_string_is_invalid(self): + """Non-numeric string remain should be skipped.""" + valid, _ = _is_valid_remain("abc") + assert valid is False + + def test_remain_0_is_valid(self): + """remain=0 should be valid (manual recovery handles empty spools).""" + valid, val = _is_valid_remain(0) + assert valid is True + assert val == 0 + + def test_remain_100_is_valid(self): + """remain=100 should be valid.""" + valid, val = _is_valid_remain(100) + assert valid is True + assert val == 100 + + def test_remain_50_is_valid(self): + """remain=50 should be valid.""" + valid, val = _is_valid_remain(50) + assert valid is True + assert val == 50 + + def test_remain_string_number_is_valid(self): + """Numeric string remain (e.g. '75') should be parsed as int.""" + valid, val = _is_valid_remain("75") + assert valid is True + assert val == 75 + + +class TestFindTrayInAmsData: + """Test the _find_tray_in_ams_data helper used by the sync endpoint.""" + + def test_finds_matching_tray(self): + """Should return the matching tray dict.""" + ams_data = [ + { + "id": 0, + "tray": [ + {"id": 0, "remain": 80}, + {"id": 1, "remain": 50}, + ], + }, + ] + tray = _find_tray_in_ams_data(ams_data, ams_id=0, tray_id=1) + assert tray is not None + assert tray["remain"] == 50 + + def test_returns_none_for_missing_ams_unit(self): + """Should return None when the AMS unit ID is not found.""" + ams_data = [{"id": 0, "tray": [{"id": 0, "remain": 80}]}] + assert _find_tray_in_ams_data(ams_data, ams_id=1, tray_id=0) is None + + def test_returns_none_for_missing_tray(self): + """Should return None when the tray ID is not found.""" + ams_data = [{"id": 0, "tray": [{"id": 0, "remain": 80}]}] + assert _find_tray_in_ams_data(ams_data, ams_id=0, tray_id=3) is None + + def test_returns_none_for_empty_data(self): + """Should return None for empty AMS data.""" + assert _find_tray_in_ams_data([], ams_id=0, tray_id=0) is None + + def test_returns_none_for_none_data(self): + """Should return None for None AMS data.""" + assert _find_tray_in_ams_data(None, ams_id=0, tray_id=0) is None + + def test_multi_ams_unit_lookup(self): + """Should find trays across multiple AMS units.""" + ams_data = [ + {"id": 0, "tray": [{"id": 0, "remain": 80}]}, + {"id": 1, "tray": [{"id": 2, "remain": 30}]}, + ] + tray = _find_tray_in_ams_data(ams_data, ams_id=1, tray_id=2) + assert tray is not None + assert tray["remain"] == 30 + + def test_ams_ht_high_id(self): + """Should find trays in AMS-HT units (id >= 128).""" + ams_data = [{"id": 128, "tray": [{"id": 0, "remain": 65}]}] + tray = _find_tray_in_ams_data(ams_data, ams_id=128, tray_id=0) + assert tray is not None + assert tray["remain"] == 65 + + +class TestSyncSkipLogic: + """Test combinations that exercise the sync/skip decision path.""" + + def test_same_value_is_skipped(self): + """When old weight_used matches new, the spool is skipped (no DB write).""" + # Simulating the endpoint logic: if round(old_used, 1) == new_used → skip + label_weight = 1000 + remain = 50 + new_used = _calc_weight_used(label_weight, remain) + old_used = 500.0 # Already matches + assert round(old_used, 1) == new_used # → would be skipped + + def test_different_value_is_synced(self): + """When old weight_used differs from new, the spool is synced.""" + label_weight = 1000 + remain = 50 + new_used = _calc_weight_used(label_weight, remain) + old_used = 300.0 # Different + assert round(old_used, 1) != new_used # → would be synced + + def test_none_old_used_treated_as_zero(self): + """When old weight_used is None (new spool), it defaults to 0.""" + old_used = None + effective_old = old_used or 0 + new_used = _calc_weight_used(1000, 80) # 200.0 + assert effective_old == 0 + assert round(effective_old, 1) != new_used # → would be synced + + def test_remain_0_synced_not_skipped(self): + """remain=0 is valid and produces weight_used=label_weight. + + This is distinct from on_ams_change behavior where remain=0 is + ignored. The sync endpoint processes it as a manual recovery tool. + """ + valid, val = _is_valid_remain(0) + assert valid is True + new_used = _calc_weight_used(1000, val) + assert new_used == 1000.0 + + def test_remain_minus_1_never_reaches_calc(self): + """remain=-1 fails validation before weight calculation.""" + valid, _ = _is_valid_remain(-1) + assert valid is False + # The endpoint would skip += 1 and continue + + def test_remain_101_never_reaches_calc(self): + """remain=101 fails validation before weight calculation.""" + valid, _ = _is_valid_remain(101) + assert valid is False diff --git a/frontend/src/__tests__/components/SpoolFormModal.test.tsx b/frontend/src/__tests__/components/SpoolFormModal.test.tsx new file mode 100644 index 000000000..a13e49b64 --- /dev/null +++ b/frontend/src/__tests__/components/SpoolFormModal.test.tsx @@ -0,0 +1,186 @@ +/** + * Tests for the SpoolFormModal weightTouched behavior. + * + * Verifies that weight_used is only included in the PATCH payload when the user + * explicitly changes the remaining weight field. This prevents stale React Query + * cache values from overwriting usage-tracked weight data on the backend. + */ + +import React from 'react'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { screen, waitFor, fireEvent } from '@testing-library/react'; +import { render } from '../utils'; +import { SpoolFormModal } from '../../components/SpoolFormModal'; +import type { InventorySpool } from '../../api/client'; + +// Mock the API client +vi.mock('../../api/client', () => ({ + api: { + getSettings: vi.fn().mockResolvedValue({}), + getAuthStatus: vi.fn().mockResolvedValue({ auth_enabled: false }), + getCloudStatus: vi.fn().mockResolvedValue({ is_authenticated: false }), + getFilamentPresets: vi.fn().mockResolvedValue([]), + getSpoolCatalog: vi.fn().mockResolvedValue([]), + getColorCatalog: vi.fn().mockResolvedValue([]), + getLocalPresets: vi.fn().mockResolvedValue({ filament: [] }), + getPrinters: vi.fn().mockResolvedValue([]), + getSpoolUsageHistory: vi.fn().mockResolvedValue([]), + createSpool: vi.fn().mockResolvedValue({ id: 99 }), + updateSpool: vi.fn().mockResolvedValue({ id: 1 }), + saveSpoolKProfiles: vi.fn().mockResolvedValue([]), + }, +})); + +// Mock validateForm so we can bypass validation for the create-mode test +// (editing tests pass validation naturally since the spool has material + slicer_filament) +vi.mock('../../components/spool-form/types', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + validateForm: vi.fn().mockReturnValue({ isValid: true, errors: {} }), + }; +}); + +// Mock the toast context +const mockShowToast = vi.fn(); +vi.mock('../../contexts/ToastContext', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useToast: () => ({ showToast: mockShowToast }), + }; +}); + +import { api } from '../../api/client'; + +const existingSpool: InventorySpool = { + id: 1, + material: 'PLA', + subtype: 'Basic', + brand: 'Polymaker', + color_name: 'Red', + rgba: 'FF0000FF', + label_weight: 1000, + core_weight: 250, + weight_used: 300, + slicer_filament: 'GFL99', + slicer_filament_name: 'Generic PLA', + nozzle_temp_min: null, + nozzle_temp_max: null, + note: null, + added_full: null, + last_used: null, + encode_time: null, + tag_uid: null, + tray_uuid: null, + data_origin: null, + tag_type: null, + archived_at: null, + created_at: '2025-01-01T00:00:00Z', + updated_at: '2025-01-01T00:00:00Z', + k_profiles: [], +}; + +describe('SpoolFormModal weightTouched', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('excludes weight_used from PATCH when editing without changing weight', async () => { + render( + + ); + + // Wait for the modal to render with the edit title + await waitFor(() => { + expect(screen.getByText('Edit Spool')).toBeInTheDocument(); + }); + + // Click Save without touching the weight field + const saveButton = screen.getByRole('button', { name: /save/i }); + fireEvent.click(saveButton); + + await waitFor(() => { + expect(api.updateSpool).toHaveBeenCalledTimes(1); + }); + + const [spoolId, payload] = vi.mocked(api.updateSpool).mock.calls[0]; + expect(spoolId).toBe(1); + // weight_used must NOT be present in the payload + expect(payload).not.toHaveProperty('weight_used'); + // Other fields should still be present + expect(payload).toHaveProperty('material', 'PLA'); + expect(payload).toHaveProperty('label_weight', 1000); + }); + + it('includes weight_used in PATCH when editing and changing remaining weight', async () => { + render( + + ); + + await waitFor(() => { + expect(screen.getByText('Edit Spool')).toBeInTheDocument(); + }); + + // The remaining weight is (label_weight - weight_used) = 1000 - 300 = 700. + // The input is a number input displaying 700. Find it by its displayed value. + const remainingInput = screen.getByDisplayValue('700'); + expect(remainingInput).toBeInTheDocument(); + + // Change the remaining weight from 700 to 500 (weight_used becomes 1000 - 500 = 500) + fireEvent.change(remainingInput, { target: { value: '500' } }); + + // Click Save + const saveButton = screen.getByRole('button', { name: /save/i }); + fireEvent.click(saveButton); + + await waitFor(() => { + expect(api.updateSpool).toHaveBeenCalledTimes(1); + }); + + const [spoolId, payload] = vi.mocked(api.updateSpool).mock.calls[0]; + expect(spoolId).toBe(1); + // weight_used MUST be present since the user changed the weight + expect(payload).toHaveProperty('weight_used', 500); + }); + + it('includes weight_used when creating a new spool', async () => { + render( + + ); + + // Wait for the modal to render with the create title + await waitFor(() => { + expect(screen.getByRole('heading', { name: 'Add Spool' })).toBeInTheDocument(); + }); + + // Click the submit button (validation is mocked to always pass). + // The default form data has weight_used=0, and for create mode the condition + // if (!isEditing || weightTouched) { data.weight_used = formData.weight_used; } + // always includes weight_used since isEditing is false. + // The submit button also says "Add Spool" — use getAllByText and pick the button. + const addButtons = screen.getAllByRole('button', { name: /add spool/i }); + const submitButton = addButtons.find(btn => btn.tagName === 'BUTTON' && btn.querySelector('svg.lucide-save')); + expect(submitButton).toBeTruthy(); + fireEvent.click(submitButton!); + + await waitFor(() => { + expect(api.createSpool).toHaveBeenCalledTimes(1); + }); + + const [payload] = vi.mocked(api.createSpool).mock.calls[0]; + // weight_used MUST be included for new spools (default value 0) + expect(payload).toHaveProperty('weight_used', 0); + }); +}); diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 8b189d5c0..aa1dce68d 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -3497,6 +3497,8 @@ export const api = { request(`/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}`), clearSpoolUsageHistory: (spoolId: number) => request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }), + syncWeightsFromAms: () => + request<{ synced: number; skipped: number }>('/inventory/sync-ams-weights', { method: 'POST' }), getFilamentPresets: () => request('/cloud/filaments'), diff --git a/frontend/src/components/SpoolmanSettings.tsx b/frontend/src/components/SpoolmanSettings.tsx index bc2645f68..3a7ee9b69 100644 --- a/frontend/src/components/SpoolmanSettings.tsx +++ b/frontend/src/components/SpoolmanSettings.tsx @@ -6,6 +6,7 @@ import { api } from '../api/client'; import type { SpoolmanSyncResult, Printer } from '../api/client'; import { Card, CardContent, CardHeader } from './Card'; import { Button } from './Button'; +import { ConfirmModal } from './ConfirmModal'; import { useToast } from '../contexts/ToastContext'; export function SpoolmanSettings() { @@ -20,6 +21,7 @@ export function SpoolmanSettings() { const [selectedPrinterId, setSelectedPrinterId] = useState('all'); const [isInitialized, setIsInitialized] = useState(false); const [showAllSkipped, setShowAllSkipped] = useState(false); + const [showAmsSyncConfirm, setShowAmsSyncConfirm] = useState(false); // Fetch Spoolman settings const { data: settings, isLoading: settingsLoading } = useQuery({ @@ -136,6 +138,21 @@ export function SpoolmanSettings() { } }; + // Inventory AMS weight sync mutation + const amsSyncMutation = useMutation({ + mutationFn: api.syncWeightsFromAms, + onSuccess: (data) => { + queryClient.invalidateQueries({ queryKey: ['spools'] }); + queryClient.invalidateQueries({ queryKey: ['inventory-spools'] }); + showToast(t('settings.amsSyncSuccess', { synced: data.synced, skipped: data.skipped }), 'success'); + setShowAmsSyncConfirm(false); + }, + onError: () => { + showToast(t('settings.amsSyncError'), 'error'); + setShowAmsSyncConfirm(false); + }, + }); + // Combine mutation states const isSyncing = syncAllMutation.isPending || syncPrinterMutation.isPending; const syncResult = selectedPrinterId === 'all' ? syncAllMutation.data : syncPrinterMutation.data; @@ -236,18 +253,34 @@ export function SpoolmanSettings() { {/* Built-in Inventory details */} {!localEnabled && ( -
-
- -
-
    -
  • {t('settings.builtInFeatureRfid')}
  • -
  • {t('settings.builtInFeatureUsage')}
  • -
  • {t('settings.builtInFeatureCatalog')}
  • -
  • {t('settings.builtInFeatureThirdParty')}
  • -
+
+
+
+ +
+
    +
  • {t('settings.builtInFeatureRfid')}
  • +
  • {t('settings.builtInFeatureUsage')}
  • +
  • {t('settings.builtInFeatureCatalog')}
  • +
  • {t('settings.builtInFeatureThirdParty')}
  • +
+
+ +
)} @@ -528,6 +561,19 @@ export function SpoolmanSettings() {
)} + + {showAmsSyncConfirm && ( + amsSyncMutation.mutate()} + onCancel={() => setShowAmsSyncConfirm(false)} + /> + )} ); } diff --git a/frontend/src/i18n/locales/de.ts b/frontend/src/i18n/locales/de.ts index 82fc392db..b1413cecd 100644 --- a/frontend/src/i18n/locales/de.ts +++ b/frontend/src/i18n/locales/de.ts @@ -1203,6 +1203,12 @@ export default { builtInFeatureUsage: 'Erfasst den Filamentverbrauch pro Druck', builtInFeatureCatalog: 'Spulen, Farben und K-Faktor-Profile verwalten', builtInFeatureThirdParty: 'Drittanbieter-Spulen können Inventarspulen zugewiesen werden', + amsSyncButton: 'Gewichte vom AMS synchronisieren', + amsSyncTitle: 'Spulengewichte vom AMS synchronisieren', + amsSyncMessage: 'Alle Inventar-Spulengewichte werden mit den aktuellen AMS-Restwerten der verbundenen Drucker überschrieben. Verwenden Sie dies zur Wiederherstellung beschädigter Gewichtsdaten. Drucker müssen online sein.', + amsSyncing: 'Synchronisiere...', + amsSyncSuccess: '{{synced}} Spule(n) synchronisiert, {{skipped}} übersprungen', + amsSyncError: 'Synchronisierung der Gewichte vom AMS fehlgeschlagen', // Spoolman settings spoolmanUrl: 'Spoolman URL', spoolmanUrlHint: 'URL Ihres Spoolman-Servers (z.B. http://localhost:7912)', diff --git a/frontend/src/i18n/locales/en.ts b/frontend/src/i18n/locales/en.ts index c394f9df0..79f8c5c0c 100644 --- a/frontend/src/i18n/locales/en.ts +++ b/frontend/src/i18n/locales/en.ts @@ -1203,6 +1203,12 @@ export default { builtInFeatureUsage: 'Tracks filament consumption per print', builtInFeatureCatalog: 'Manage spools, colors, and K-factor profiles', builtInFeatureThirdParty: 'Third-party spools can be assigned to inventory spools', + amsSyncButton: 'Sync Weights from AMS', + amsSyncTitle: 'Sync Spool Weights from AMS', + amsSyncMessage: 'This will overwrite all inventory spool weights with the current AMS remain% values from connected printers. Use this to recover from corrupted weight data. Printers must be online.', + amsSyncing: 'Syncing...', + amsSyncSuccess: '{{synced}} spool(s) synced, {{skipped}} skipped', + amsSyncError: 'Failed to sync weights from AMS', // Spoolman settings spoolmanUrl: 'Spoolman URL', spoolmanUrlHint: 'URL of your Spoolman server (e.g., http://localhost:7912)', diff --git a/frontend/src/i18n/locales/fr.ts b/frontend/src/i18n/locales/fr.ts index 4102de98c..34f7805e9 100644 --- a/frontend/src/i18n/locales/fr.ts +++ b/frontend/src/i18n/locales/fr.ts @@ -1199,6 +1199,12 @@ export default { builtInFeatureUsage: 'Suit la consommation par impression', builtInFeatureCatalog: 'Gère bobines, couleurs et profils facteur K', builtInFeatureThirdParty: 'Les bobines tierces peuvent être assignées aux bobines d\'inventaire', + amsSyncButton: 'Synchroniser les poids depuis l\'AMS', + amsSyncTitle: 'Synchroniser les poids des bobines depuis l\'AMS', + amsSyncMessage: 'Tous les poids des bobines de l\'inventaire seront écrasés par les valeurs actuelles de l\'AMS des imprimantes connectées. Utilisez ceci pour récupérer des données de poids corrompues. Les imprimantes doivent être en ligne.', + amsSyncing: 'Synchronisation...', + amsSyncSuccess: '{{synced}} bobine(s) synchronisée(s), {{skipped}} ignorée(s)', + amsSyncError: 'Échec de la synchronisation des poids depuis l\'AMS', // Spoolman settings spoolmanUrl: 'URL Spoolman', spoolmanUrlHint: 'URL de votre serveur Spoolman (ex: http://localhost:7912)', diff --git a/frontend/src/i18n/locales/ja.ts b/frontend/src/i18n/locales/ja.ts index 8fd4537e1..19fb21b5e 100644 --- a/frontend/src/i18n/locales/ja.ts +++ b/frontend/src/i18n/locales/ja.ts @@ -1451,6 +1451,12 @@ export default { builtInFeatureUsage: 'プリントごとのフィラメント消費量を追跡', builtInFeatureCatalog: 'スプール、カラー、K値プロファイルを管理', builtInFeatureThirdParty: 'サードパーティ製スプールをインベントリスプールに割り当て可能', + amsSyncButton: 'AMSから重量を同期', + amsSyncTitle: 'AMSからスプール重量を同期', + amsSyncMessage: '接続されたプリンターの現在のAMS残量値で、すべてのインベントリスプール重量を上書きします。破損した重量データの復旧に使用してください。プリンターがオンラインである必要があります。', + amsSyncing: '同期中...', + amsSyncSuccess: '{{synced}}個のスプールを同期、{{skipped}}個をスキップ', + amsSyncError: 'AMSからの重量同期に失敗しました', // Spoolman設定 spoolmanUrl: 'Spoolman URL', spoolmanUrlHint: 'Spoolmanサーバーのurl(例:http://localhost:7912)', diff --git a/static/assets/index-DDGLa0P-.js b/static/assets/index-LH77R5cV.js similarity index 80% rename from static/assets/index-DDGLa0P-.js rename to static/assets/index-LH77R5cV.js index 078fd5592..4226ec97b 100644 --- a/static/assets/index-DDGLa0P-.js +++ b/static/assets/index-LH77R5cV.js @@ -1,14 +1,14 @@ -function Poe(t,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var l_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var IT={exports:{}},ry={};var VU;function joe(){if(VU)return ry;VU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,i,s){var o=null;if(s!==void 0&&(o=""+s),i.key!==void 0&&(o=""+i.key),"key"in i){s={};for(var l in i)l!=="key"&&(s[l]=i[l])}else s=i;return i=s.ref,{$$typeof:t,type:r,key:o,ref:i!==void 0?i:null,props:s}}return ry.Fragment=e,ry.jsx=n,ry.jsxs=n,ry}var GU;function Doe(){return GU||(GU=1,IT.exports=joe()),IT.exports}var a=Doe(),zT={exports:{}},Nn={};var qU;function Roe(){if(qU)return Nn;qU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),f=Symbol.iterator;function p(V){return V===null||typeof V!="object"?null:(V=f&&V[f]||V["@@iterator"],typeof V=="function"?V:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,b={};function y(V,X,te){this.props=V,this.context=X,this.refs=b,this.updater=te||x}y.prototype.isReactComponent={},y.prototype.setState=function(V,X){if(typeof V!="object"&&typeof V!="function"&&V!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,V,X,"setState")},y.prototype.forceUpdate=function(V){this.updater.enqueueForceUpdate(this,V,"forceUpdate")};function S(){}S.prototype=y.prototype;function N(V,X,te){this.props=V,this.context=X,this.refs=b,this.updater=te||x}var A=N.prototype=new S;A.constructor=N,v(A,y.prototype),A.isPureReactComponent=!0;var M=Array.isArray;function T(){}var k={H:null,A:null,T:null,S:null},j=Object.prototype.hasOwnProperty;function E(V,X,te){var J=te.ref;return{$$typeof:t,type:V,key:X,ref:J!==void 0?J:null,props:te}}function P(V,X){return E(V.type,X,V.props)}function U(V){return typeof V=="object"&&V!==null&&V.$$typeof===t}function L(V){var X={"=":"=0",":":"=2"};return"$"+V.replace(/[=:]/g,function(te){return X[te]})}var B=/\/+/g;function R(V,X){return typeof V=="object"&&V!==null&&V.key!=null?L(""+V.key):X.toString(36)}function $(V){switch(V.status){case"fulfilled":return V.value;case"rejected":throw V.reason;default:switch(typeof V.status=="string"?V.then(T,T):(V.status="pending",V.then(function(X){V.status==="pending"&&(V.status="fulfilled",V.value=X)},function(X){V.status==="pending"&&(V.status="rejected",V.reason=X)})),V.status){case"fulfilled":return V.value;case"rejected":throw V.reason}}throw V}function G(V,X,te,J,Se){var fe=typeof V;(fe==="undefined"||fe==="boolean")&&(V=null);var me=!1;if(V===null)me=!0;else switch(fe){case"bigint":case"string":case"number":me=!0;break;case"object":switch(V.$$typeof){case t:case e:me=!0;break;case d:return me=V._init,G(me(V._payload),X,te,J,Se)}}if(me)return Se=Se(V),me=J===""?"."+R(V,0):J,M(Se)?(te="",me!=null&&(te=me.replace(B,"$&/")+"/"),G(Se,X,te,"",function(ce){return ce})):Se!=null&&(U(Se)&&(Se=P(Se,te+(Se.key==null||V&&V.key===Se.key?"":(""+Se.key).replace(B,"$&/")+"/")+me)),X.push(Se)),1;me=0;var De=J===""?".":J+":";if(M(V))for(var de=0;de>>1,le=G[Z];if(0>>1;Zi(te,K))Ji(Se,te)?(G[Z]=Se,G[J]=K,Z=J):(G[Z]=te,G[X]=K,Z=X);else if(Ji(Se,K))G[Z]=Se,G[J]=K,Z=J;else break e}}return z}function i(G,z){var K=G.sortIndex-z.sortIndex;return K!==0?K:G.id-z.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var c=[],u=[],d=1,h=null,f=3,p=!1,x=!1,v=!1,b=!1,y=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function A(G){for(var z=n(u);z!==null;){if(z.callback===null)r(u);else if(z.startTime<=G)r(u),z.sortIndex=z.expirationTime,e(c,z);else break;z=n(u)}}function M(G){if(v=!1,A(G),!x)if(n(c)!==null)x=!0,T||(T=!0,L());else{var z=n(u);z!==null&&$(M,z.startTime-G)}}var T=!1,k=-1,j=5,E=-1;function P(){return b?!0:!(t.unstable_now()-EG&&P());){var Z=h.callback;if(typeof Z=="function"){h.callback=null,f=h.priorityLevel;var le=Z(h.expirationTime<=G);if(G=t.unstable_now(),typeof le=="function"){h.callback=le,A(G),z=!0;break t}h===n(c)&&r(c),A(G)}else r(c);h=n(c)}if(h!==null)z=!0;else{var V=n(u);V!==null&&$(M,V.startTime-G),z=!1}}break e}finally{h=null,f=K,p=!1}z=void 0}}finally{z?L():T=!1}}}var L;if(typeof N=="function")L=function(){N(U)};else if(typeof MessageChannel<"u"){var B=new MessageChannel,R=B.port2;B.port1.onmessage=U,L=function(){R.postMessage(null)}}else L=function(){y(U,0)};function $(G,z){k=y(function(){G(t.unstable_now())},z)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(G){G.callback=null},t.unstable_forceFrameRate=function(G){0>G||125Z?(G.sortIndex=K,e(u,G),n(c)===null&&G===n(u)&&(v?(S(k),k=-1):v=!0,$(M,K-Z))):(G.sortIndex=le,e(c,G),x||p||(x=!0,T||(T=!0,L()))),G},t.unstable_shouldYield=P,t.unstable_wrapCallback=function(G){var z=f;return function(){var K=f;f=z;try{return G.apply(this,arguments)}finally{f=K}}}})(HT)),HT}var XU;function Ooe(){return XU||(XU=1,BT.exports=Loe()),BT.exports}var $T={exports:{}},ss={};var YU;function Ioe(){if(YU)return ss;YU=1;var t=Bb();function e(c){var u="https://react.dev/errors/"+c;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),$T.exports=Ioe(),$T.exports}var ZU;function zoe(){if(ZU)return iy;ZU=1;var t=Ooe(),e=Bb(),n=gK();function r(m){var g="https://react.dev/errors/"+m;if(1le||(m.current=Z[le],Z[le]=null,le--)}function te(m,g){le++,Z[le]=m.current,m.current=g}var J=V(null),Se=V(null),fe=V(null),me=V(null);function De(m,g){switch(te(fe,g),te(Se,m),te(J,null),g.nodeType){case 9:case 11:m=(m=g.documentElement)&&(m=m.namespaceURI)?mU(m):0;break;default:if(m=g.tagName,g=g.namespaceURI)g=mU(g),m=fU(g,m);else switch(m){case"svg":m=1;break;case"math":m=2;break;default:m=0}}X(J),te(J,m)}function de(){X(J),X(Se),X(fe)}function ce(m){m.memoizedState!==null&&te(me,m);var g=J.current,_=fU(g,m.type);g!==_&&(te(Se,m),te(J,_))}function Ne(m){Se.current===m&&(X(J),X(Se)),me.current===m&&(X(me),Jx._currentValue=K)}var ie,Le;function H(m){if(ie===void 0)try{throw Error()}catch(_){var g=_.stack.trim().match(/\n( *(at )?)/);ie=g&&g[1]||"",Le=-1<_.stack.indexOf(` +function Poe(t,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var l_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var IT={exports:{}},ry={};var VU;function joe(){if(VU)return ry;VU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,i,s){var o=null;if(s!==void 0&&(o=""+s),i.key!==void 0&&(o=""+i.key),"key"in i){s={};for(var l in i)l!=="key"&&(s[l]=i[l])}else s=i;return i=s.ref,{$$typeof:t,type:r,key:o,ref:i!==void 0?i:null,props:s}}return ry.Fragment=e,ry.jsx=n,ry.jsxs=n,ry}var GU;function Doe(){return GU||(GU=1,IT.exports=joe()),IT.exports}var a=Doe(),zT={exports:{}},Nn={};var qU;function Roe(){if(qU)return Nn;qU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),f=Symbol.iterator;function p(H){return H===null||typeof H!="object"?null:(H=f&&H[f]||H["@@iterator"],typeof H=="function"?H:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,b={};function y(H,X,te){this.props=H,this.context=X,this.refs=b,this.updater=te||x}y.prototype.isReactComponent={},y.prototype.setState=function(H,X){if(typeof H!="object"&&typeof H!="function"&&H!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,H,X,"setState")},y.prototype.forceUpdate=function(H){this.updater.enqueueForceUpdate(this,H,"forceUpdate")};function S(){}S.prototype=y.prototype;function N(H,X,te){this.props=H,this.context=X,this.refs=b,this.updater=te||x}var A=N.prototype=new S;A.constructor=N,v(A,y.prototype),A.isPureReactComponent=!0;var M=Array.isArray;function T(){}var k={H:null,A:null,T:null,S:null},j=Object.prototype.hasOwnProperty;function E(H,X,te){var J=te.ref;return{$$typeof:t,type:H,key:X,ref:J!==void 0?J:null,props:te}}function P(H,X){return E(H.type,X,H.props)}function U(H){return typeof H=="object"&&H!==null&&H.$$typeof===t}function L(H){var X={"=":"=0",":":"=2"};return"$"+H.replace(/[=:]/g,function(te){return X[te]})}var B=/\/+/g;function R(H,X){return typeof H=="object"&&H!==null&&H.key!=null?L(""+H.key):X.toString(36)}function V(H){switch(H.status){case"fulfilled":return H.value;case"rejected":throw H.reason;default:switch(typeof H.status=="string"?H.then(T,T):(H.status="pending",H.then(function(X){H.status==="pending"&&(H.status="fulfilled",H.value=X)},function(X){H.status==="pending"&&(H.status="rejected",H.reason=X)})),H.status){case"fulfilled":return H.value;case"rejected":throw H.reason}}throw H}function q(H,X,te,J,Se){var fe=typeof H;(fe==="undefined"||fe==="boolean")&&(H=null);var me=!1;if(H===null)me=!0;else switch(fe){case"bigint":case"string":case"number":me=!0;break;case"object":switch(H.$$typeof){case t:case e:me=!0;break;case d:return me=H._init,q(me(H._payload),X,te,J,Se)}}if(me)return Se=Se(H),me=J===""?"."+R(H,0):J,M(Se)?(te="",me!=null&&(te=me.replace(B,"$&/")+"/"),q(Se,X,te,"",function(ce){return ce})):Se!=null&&(U(Se)&&(Se=P(Se,te+(Se.key==null||H&&H.key===Se.key?"":(""+Se.key).replace(B,"$&/")+"/")+me)),X.push(Se)),1;me=0;var De=J===""?".":J+":";if(M(H))for(var de=0;de>>1,le=q[Y];if(0>>1;Yi(te,K))Ji(Se,te)?(q[Y]=Se,q[J]=K,Y=J):(q[Y]=te,q[X]=K,Y=X);else if(Ji(Se,K))q[Y]=Se,q[J]=K,Y=J;else break e}}return I}function i(q,I){var K=q.sortIndex-I.sortIndex;return K!==0?K:q.id-I.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var c=[],u=[],d=1,h=null,f=3,p=!1,x=!1,v=!1,b=!1,y=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function A(q){for(var I=n(u);I!==null;){if(I.callback===null)r(u);else if(I.startTime<=q)r(u),I.sortIndex=I.expirationTime,e(c,I);else break;I=n(u)}}function M(q){if(v=!1,A(q),!x)if(n(c)!==null)x=!0,T||(T=!0,L());else{var I=n(u);I!==null&&V(M,I.startTime-q)}}var T=!1,k=-1,j=5,E=-1;function P(){return b?!0:!(t.unstable_now()-Eq&&P());){var Y=h.callback;if(typeof Y=="function"){h.callback=null,f=h.priorityLevel;var le=Y(h.expirationTime<=q);if(q=t.unstable_now(),typeof le=="function"){h.callback=le,A(q),I=!0;break t}h===n(c)&&r(c),A(q)}else r(c);h=n(c)}if(h!==null)I=!0;else{var H=n(u);H!==null&&V(M,H.startTime-q),I=!1}}break e}finally{h=null,f=K,p=!1}I=void 0}}finally{I?L():T=!1}}}var L;if(typeof N=="function")L=function(){N(U)};else if(typeof MessageChannel<"u"){var B=new MessageChannel,R=B.port2;B.port1.onmessage=U,L=function(){R.postMessage(null)}}else L=function(){y(U,0)};function V(q,I){k=y(function(){q(t.unstable_now())},I)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(q){q.callback=null},t.unstable_forceFrameRate=function(q){0>q||125Y?(q.sortIndex=K,e(u,q),n(c)===null&&q===n(u)&&(v?(S(k),k=-1):v=!0,V(M,K-Y))):(q.sortIndex=le,e(c,q),x||p||(x=!0,T||(T=!0,L()))),q},t.unstable_shouldYield=P,t.unstable_wrapCallback=function(q){var I=f;return function(){var K=f;f=I;try{return q.apply(this,arguments)}finally{f=K}}}})(HT)),HT}var XU;function Ooe(){return XU||(XU=1,BT.exports=Loe()),BT.exports}var $T={exports:{}},ss={};var YU;function Ioe(){if(YU)return ss;YU=1;var t=Bb();function e(c){var u="https://react.dev/errors/"+c;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),$T.exports=Ioe(),$T.exports}var ZU;function zoe(){if(ZU)return iy;ZU=1;var t=Ooe(),e=Bb(),n=gK();function r(m){var g="https://react.dev/errors/"+m;if(1le||(m.current=Y[le],Y[le]=null,le--)}function te(m,g){le++,Y[le]=m.current,m.current=g}var J=H(null),Se=H(null),fe=H(null),me=H(null);function De(m,g){switch(te(fe,g),te(Se,m),te(J,null),g.nodeType){case 9:case 11:m=(m=g.documentElement)&&(m=m.namespaceURI)?mU(m):0;break;default:if(m=g.tagName,g=g.namespaceURI)g=mU(g),m=fU(g,m);else switch(m){case"svg":m=1;break;case"math":m=2;break;default:m=0}}X(J),te(J,m)}function de(){X(J),X(Se),X(fe)}function ce(m){m.memoizedState!==null&&te(me,m);var g=J.current,_=fU(g,m.type);g!==_&&(te(Se,m),te(J,_))}function Ne(m){Se.current===m&&(X(J),X(Se)),me.current===m&&(X(me),Jx._currentValue=K)}var ie,Le;function $(m){if(ie===void 0)try{throw Error()}catch(_){var g=_.stack.trim().match(/\n( *(at )?)/);ie=g&&g[1]||"",Le=-1<_.stack.indexOf(` at`)?" ()":-1<_.stack.indexOf("@")?"@unknown:0:0":""}return` `+ie+m+Le}var W=!1;function ue(m,g){if(!m||W)return"";W=!0;var _=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var C={DetermineComponentFrameRoot:function(){try{if(g){var Ct=function(){throw Error()};if(Object.defineProperty(Ct.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ct,[])}catch(gt){var mt=gt}Reflect.construct(m,[],Ct)}else{try{Ct.call()}catch(gt){mt=gt}m.call(Ct.prototype)}}else{try{throw Error()}catch(gt){mt=gt}(Ct=m())&&typeof Ct.catch=="function"&&Ct.catch(function(){})}}catch(gt){if(gt&&mt&&typeof gt.stack=="string")return[gt.stack,mt.stack]}return[null,null]}};C.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var F=Object.getOwnPropertyDescriptor(C.DetermineComponentFrameRoot,"name");F&&F.configurable&&Object.defineProperty(C.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var O=C.DetermineComponentFrameRoot(),ne=O[0],Ce=O[1];if(ne&&Ce){var Be=ne.split(` `),ht=Ce.split(` `);for(F=C=0;CF||Be[C]!==ht[F]){var yt=` -`+Be[C].replace(" at new "," at ");return m.displayName&&yt.includes("")&&(yt=yt.replace("",m.displayName)),yt}while(1<=C&&0<=F);break}}}finally{W=!1,Error.prepareStackTrace=_}return(_=m?m.displayName||m.name:"")?H(_):""}function Q(m,g){switch(m.tag){case 26:case 27:case 5:return H(m.type);case 16:return H("Lazy");case 13:return m.child!==g&&g!==null?H("Suspense Fallback"):H("Suspense");case 19:return H("SuspenseList");case 0:case 15:return ue(m.type,!1);case 11:return ue(m.type.render,!1);case 1:return ue(m.type,!0);case 31:return H("Activity");default:return""}}function oe(m){try{var g="",_=null;do g+=Q(m,_),_=m,m=m.return;while(m);return g}catch(C){return` +`+Be[C].replace(" at new "," at ");return m.displayName&&yt.includes("")&&(yt=yt.replace("",m.displayName)),yt}while(1<=C&&0<=F);break}}}finally{W=!1,Error.prepareStackTrace=_}return(_=m?m.displayName||m.name:"")?$(_):""}function Z(m,g){switch(m.tag){case 26:case 27:case 5:return $(m.type);case 16:return $("Lazy");case 13:return m.child!==g&&g!==null?$("Suspense Fallback"):$("Suspense");case 19:return $("SuspenseList");case 0:case 15:return ue(m.type,!1);case 11:return ue(m.type.render,!1);case 1:return ue(m.type,!0);case 31:return $("Activity");default:return""}}function oe(m){try{var g="",_=null;do g+=Z(m,_),_=m,m=m.return;while(m);return g}catch(C){return` Error generating stack: `+C.message+` -`+C.stack}}var Y=Object.prototype.hasOwnProperty,he=t.unstable_scheduleCallback,be=t.unstable_cancelCallback,ee=t.unstable_shouldYield,I=t.unstable_requestPaint,D=t.unstable_now,q=t.unstable_getCurrentPriorityLevel,pe=t.unstable_ImmediatePriority,ve=t.unstable_UserBlockingPriority,xe=t.unstable_NormalPriority,ze=t.unstable_LowPriority,_e=t.unstable_IdlePriority,He=t.log,Ze=t.unstable_setDisableYieldValue,we=null,ye=null;function ke(m){if(typeof He=="function"&&Ze(m),ye&&typeof ye.setStrictMode=="function")try{ye.setStrictMode(we,m)}catch{}}var Ue=Math.clz32?Math.clz32:Ae,je=Math.log,Ve=Math.LN2;function Ae(m){return m>>>=0,m===0?32:31-(je(m)/Ve|0)|0}var Je=256,Pe=262144,Ye=4194304;function Re(m){var g=m&42;if(g!==0)return g;switch(m&-m){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return m&261888;case 262144:case 524288:case 1048576:case 2097152:return m&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return m&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return m}}function Fe(m,g,_){var C=m.pendingLanes;if(C===0)return 0;var F=0,O=m.suspendedLanes,ne=m.pingedLanes;m=m.warmLanes;var Ce=C&134217727;return Ce!==0?(C=Ce&~O,C!==0?F=Re(C):(ne&=Ce,ne!==0?F=Re(ne):_||(_=Ce&~m,_!==0&&(F=Re(_))))):(Ce=C&~O,Ce!==0?F=Re(Ce):ne!==0?F=Re(ne):_||(_=C&~m,_!==0&&(F=Re(_)))),F===0?0:g!==0&&g!==F&&(g&O)===0&&(O=F&-F,_=g&-g,O>=_||O===32&&(_&4194048)!==0)?g:F}function We(m,g){return(m.pendingLanes&~(m.suspendedLanes&~m.pingedLanes)&g)===0}function pt(m,g){switch(m){case 1:case 2:case 4:case 8:case 64:return g+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return g+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function At(){var m=Ye;return Ye<<=1,(Ye&62914560)===0&&(Ye=4194304),m}function Rt(m){for(var g=[],_=0;31>_;_++)g.push(m);return g}function Wt(m,g){m.pendingLanes|=g,g!==268435456&&(m.suspendedLanes=0,m.pingedLanes=0,m.warmLanes=0)}function Tt(m,g,_,C,F,O){var ne=m.pendingLanes;m.pendingLanes=_,m.suspendedLanes=0,m.pingedLanes=0,m.warmLanes=0,m.expiredLanes&=_,m.entangledLanes&=_,m.errorRecoveryDisabledLanes&=_,m.shellSuspendCounter=0;var Ce=m.entanglements,Be=m.expirationTimes,ht=m.hiddenUpdates;for(_=ne&~_;0<_;){var yt=31-Ue(_),Ct=1<"u")return null;try{return m.activeElement||m.body}catch{return m.body}}var Qr=/[\n"\\]/g;function gn(m){return m.replace(Qr,function(g){return"\\"+g.charCodeAt(0).toString(16)+" "})}function Zr(m,g,_,C,F,O,ne,Ce){m.name="",ne!=null&&typeof ne!="function"&&typeof ne!="symbol"&&typeof ne!="boolean"?m.type=ne:m.removeAttribute("type"),g!=null?ne==="number"?(g===0&&m.value===""||m.value!=g)&&(m.value=""+Cn(g)):m.value!==""+Cn(g)&&(m.value=""+Cn(g)):ne!=="submit"&&ne!=="reset"||m.removeAttribute("value"),g!=null?vi(m,ne,Cn(g)):_!=null?vi(m,ne,Cn(_)):C!=null&&m.removeAttribute("value"),F==null&&O!=null&&(m.defaultChecked=!!O),F!=null&&(m.checked=F&&typeof F!="function"&&typeof F!="symbol"),Ce!=null&&typeof Ce!="function"&&typeof Ce!="symbol"&&typeof Ce!="boolean"?m.name=""+Cn(Ce):m.removeAttribute("name")}function Wn(m,g,_,C,F,O,ne,Ce){if(O!=null&&typeof O!="function"&&typeof O!="symbol"&&typeof O!="boolean"&&(m.type=O),g!=null||_!=null){if(!(O!=="submit"&&O!=="reset"||g!=null)){sn(m);return}_=_!=null?""+Cn(_):"",g=g!=null?""+Cn(g):_,Ce||g===m.value||(m.value=g),m.defaultValue=g}C=C??F,C=typeof C!="function"&&typeof C!="symbol"&&!!C,m.checked=Ce?m.checked:!!C,m.defaultChecked=!!C,ne!=null&&typeof ne!="function"&&typeof ne!="symbol"&&typeof ne!="boolean"&&(m.name=ne),sn(m)}function vi(m,g,_){g==="number"&&Cr(m.ownerDocument)===m||m.defaultValue===""+_||(m.defaultValue=""+_)}function mi(m,g,_,C){if(m=m.options,g){g={};for(var F=0;F<_.length;F++)g["$"+_[F]]=!0;for(_=0;_"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),vr=!1;if(Ur)try{var kl={};Object.defineProperty(kl,"passive",{get:function(){vr=!0}}),window.addEventListener("test",kl,kl),window.removeEventListener("test",kl,kl)}catch{vr=!1}var Ca=null,oa=null,rc=null;function Br(){if(rc)return rc;var m,g=oa,_=g.length,C,F="value"in Ca?Ca.value:Ca.textContent,O=F.length;for(m=0;m<_&&g[m]===F[m];m++);var ne=_-m;for(C=1;C<=ne&&g[_-C]===F[O-C];C++);return rc=F.slice(m,1=vx),vI=" ",wI=!1;function _I(m,g){switch(m){case"keyup":return Jae.indexOf(g.keyCode)!==-1;case"keydown":return g.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function SI(m){return m=m.detail,typeof m=="object"&&"data"in m?m.data:null}var mp=!1;function tse(m,g){switch(m){case"compositionend":return SI(g);case"keypress":return g.which!==32?null:(wI=!0,vI);case"textInput":return m=g.data,m===vI&&wI?null:m;default:return null}}function nse(m,g){if(mp)return m==="compositionend"||!VM&&_I(m,g)?(m=Br(),rc=oa=Ca=null,mp=!1,m):null;switch(m){case"paste":return null;case"keypress":if(!(g.ctrlKey||g.altKey||g.metaKey)||g.ctrlKey&&g.altKey){if(g.char&&1=g)return{node:_,offset:g-m};m=C}e:{for(;_;){if(_.nextSibling){_=_.nextSibling;break e}_=_.parentNode}_=void 0}_=PI(_)}}function DI(m,g){return m&&g?m===g?!0:m&&m.nodeType===3?!1:g&&g.nodeType===3?DI(m,g.parentNode):"contains"in m?m.contains(g):m.compareDocumentPosition?!!(m.compareDocumentPosition(g)&16):!1:!1}function RI(m){m=m!=null&&m.ownerDocument!=null&&m.ownerDocument.defaultView!=null?m.ownerDocument.defaultView:window;for(var g=Cr(m.document);g instanceof m.HTMLIFrameElement;){try{var _=typeof g.contentWindow.location.href=="string"}catch{_=!1}if(_)m=g.contentWindow;else break;g=Cr(m.document)}return g}function WM(m){var g=m&&m.nodeName&&m.nodeName.toLowerCase();return g&&(g==="input"&&(m.type==="text"||m.type==="search"||m.type==="tel"||m.type==="url"||m.type==="password")||g==="textarea"||m.contentEditable==="true")}var use=Ur&&"documentMode"in document&&11>=document.documentMode,fp=null,KM=null,Nx=null,XM=!1;function FI(m,g,_){var C=_.window===_?_.document:_.nodeType===9?_:_.ownerDocument;XM||fp==null||fp!==Cr(C)||(C=fp,"selectionStart"in C&&WM(C)?C={start:C.selectionStart,end:C.selectionEnd}:(C=(C.ownerDocument&&C.ownerDocument.defaultView||window).getSelection(),C={anchorNode:C.anchorNode,anchorOffset:C.anchorOffset,focusNode:C.focusNode,focusOffset:C.focusOffset}),Nx&&Sx(Nx,C)||(Nx=C,C=Ww(KM,"onSelect"),0>=ne,F-=ne,ic=1<<32-Ue(g)+F|_<Rn?(tr=Jt,Jt=null):tr=Jt.sibling;var dr=mt(rt,Jt,ut[Rn],St);if(dr===null){Jt===null&&(Jt=tr);break}m&&Jt&&dr.alternate===null&&g(rt,Jt),Ke=O(dr,Ke,Rn),ur===null?an=dr:ur.sibling=dr,ur=dr,Jt=tr}if(Rn===ut.length)return _(rt,Jt),rr&&Qc(rt,Rn),an;if(Jt===null){for(;RnRn?(tr=Jt,Jt=null):tr=Jt.sibling;var $d=mt(rt,Jt,dr.value,St);if($d===null){Jt===null&&(Jt=tr);break}m&&Jt&&$d.alternate===null&&g(rt,Jt),Ke=O($d,Ke,Rn),ur===null?an=$d:ur.sibling=$d,ur=$d,Jt=tr}if(dr.done)return _(rt,Jt),rr&&Qc(rt,Rn),an;if(Jt===null){for(;!dr.done;Rn++,dr=ut.next())dr=Ct(rt,dr.value,St),dr!==null&&(Ke=O(dr,Ke,Rn),ur===null?an=dr:ur.sibling=dr,ur=dr);return rr&&Qc(rt,Rn),an}for(Jt=C(Jt);!dr.done;Rn++,dr=ut.next())dr=gt(Jt,rt,Rn,dr.value,St),dr!==null&&(m&&dr.alternate!==null&&Jt.delete(dr.key===null?Rn:dr.key),Ke=O(dr,Ke,Rn),ur===null?an=dr:ur.sibling=dr,ur=dr);return m&&Jt.forEach(function(Eoe){return g(rt,Eoe)}),rr&&Qc(rt,Rn),an}function Tr(rt,Ke,ut,St){if(typeof ut=="object"&&ut!==null&&ut.type===v&&ut.key===null&&(ut=ut.props.children),typeof ut=="object"&&ut!==null){switch(ut.$$typeof){case p:e:{for(var an=ut.key;Ke!==null;){if(Ke.key===an){if(an=ut.type,an===v){if(Ke.tag===7){_(rt,Ke.sibling),St=F(Ke,ut.props.children),St.return=rt,rt=St;break e}}else if(Ke.elementType===an||typeof an=="object"&&an!==null&&an.$$typeof===j&&_m(an)===Ke.type){_(rt,Ke.sibling),St=F(Ke,ut.props),Ex(St,ut),St.return=rt,rt=St;break e}_(rt,Ke);break}else g(rt,Ke);Ke=Ke.sibling}ut.type===v?(St=bm(ut.props.children,rt.mode,St,ut.key),St.return=rt,rt=St):(St=uw(ut.type,ut.key,ut.props,null,rt.mode,St),Ex(St,ut),St.return=rt,rt=St)}return ne(rt);case x:e:{for(an=ut.key;Ke!==null;){if(Ke.key===an)if(Ke.tag===4&&Ke.stateNode.containerInfo===ut.containerInfo&&Ke.stateNode.implementation===ut.implementation){_(rt,Ke.sibling),St=F(Ke,ut.children||[]),St.return=rt,rt=St;break e}else{_(rt,Ke);break}else g(rt,Ke);Ke=Ke.sibling}St=nA(ut,rt.mode,St),St.return=rt,rt=St}return ne(rt);case j:return ut=_m(ut),Tr(rt,Ke,ut,St)}if($(ut))return Qt(rt,Ke,ut,St);if(L(ut)){if(an=L(ut),typeof an!="function")throw Error(r(150));return ut=an.call(ut),hn(rt,Ke,ut,St)}if(typeof ut.then=="function")return Tr(rt,Ke,bw(ut),St);if(ut.$$typeof===N)return Tr(rt,Ke,mw(rt,ut),St);xw(rt,ut)}return typeof ut=="string"&&ut!==""||typeof ut=="number"||typeof ut=="bigint"?(ut=""+ut,Ke!==null&&Ke.tag===6?(_(rt,Ke.sibling),St=F(Ke,ut),St.return=rt,rt=St):(_(rt,Ke),St=tA(ut,rt.mode,St),St.return=rt,rt=St),ne(rt)):_(rt,Ke)}return function(rt,Ke,ut,St){try{Tx=0;var an=Tr(rt,Ke,ut,St);return kp=null,an}catch(Jt){if(Jt===Np||Jt===pw)throw Jt;var ur=ho(29,Jt,null,rt.mode);return ur.lanes=St,ur.return=rt,ur}}}var Nm=i5(!0),a5=i5(!1),Cd=!1;function fA(m){m.updateQueue={baseState:m.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function pA(m,g){m=m.updateQueue,g.updateQueue===m&&(g.updateQueue={baseState:m.baseState,firstBaseUpdate:m.firstBaseUpdate,lastBaseUpdate:m.lastBaseUpdate,shared:m.shared,callbacks:null})}function Md(m){return{lane:m,tag:0,payload:null,callback:null,next:null}}function Ad(m,g,_){var C=m.updateQueue;if(C===null)return null;if(C=C.shared,(pr&2)!==0){var F=C.pending;return F===null?g.next=g:(g.next=F.next,F.next=g),C.pending=g,g=cw(m),HI(m,null,_),g}return lw(m,C,g,_),cw(m)}function Px(m,g,_){if(g=g.updateQueue,g!==null&&(g=g.shared,(_&4194048)!==0)){var C=g.lanes;C&=m.pendingLanes,_|=C,g.lanes=_,xt(m,_)}}function gA(m,g){var _=m.updateQueue,C=m.alternate;if(C!==null&&(C=C.updateQueue,_===C)){var F=null,O=null;if(_=_.firstBaseUpdate,_!==null){do{var ne={lane:_.lane,tag:_.tag,payload:_.payload,callback:null,next:null};O===null?F=O=ne:O=O.next=ne,_=_.next}while(_!==null);O===null?F=O=g:O=O.next=g}else F=O=g;_={baseState:C.baseState,firstBaseUpdate:F,lastBaseUpdate:O,shared:C.shared,callbacks:C.callbacks},m.updateQueue=_;return}m=_.lastBaseUpdate,m===null?_.firstBaseUpdate=g:m.next=g,_.lastBaseUpdate=g}var bA=!1;function jx(){if(bA){var m=Sp;if(m!==null)throw m}}function Dx(m,g,_,C){bA=!1;var F=m.updateQueue;Cd=!1;var O=F.firstBaseUpdate,ne=F.lastBaseUpdate,Ce=F.shared.pending;if(Ce!==null){F.shared.pending=null;var Be=Ce,ht=Be.next;Be.next=null,ne===null?O=ht:ne.next=ht,ne=Be;var yt=m.alternate;yt!==null&&(yt=yt.updateQueue,Ce=yt.lastBaseUpdate,Ce!==ne&&(Ce===null?yt.firstBaseUpdate=ht:Ce.next=ht,yt.lastBaseUpdate=Be))}if(O!==null){var Ct=F.baseState;ne=0,yt=ht=Be=null,Ce=O;do{var mt=Ce.lane&-536870913,gt=mt!==Ce.lane;if(gt?(er&mt)===mt:(C&mt)===mt){mt!==0&&mt===_p&&(bA=!0),yt!==null&&(yt=yt.next={lane:0,tag:Ce.tag,payload:Ce.payload,callback:null,next:null});e:{var Qt=m,hn=Ce;mt=g;var Tr=_;switch(hn.tag){case 1:if(Qt=hn.payload,typeof Qt=="function"){Ct=Qt.call(Tr,Ct,mt);break e}Ct=Qt;break e;case 3:Qt.flags=Qt.flags&-65537|128;case 0:if(Qt=hn.payload,mt=typeof Qt=="function"?Qt.call(Tr,Ct,mt):Qt,mt==null)break e;Ct=h({},Ct,mt);break e;case 2:Cd=!0}}mt=Ce.callback,mt!==null&&(m.flags|=64,gt&&(m.flags|=8192),gt=F.callbacks,gt===null?F.callbacks=[mt]:gt.push(mt))}else gt={lane:mt,tag:Ce.tag,payload:Ce.payload,callback:Ce.callback,next:null},yt===null?(ht=yt=gt,Be=Ct):yt=yt.next=gt,ne|=mt;if(Ce=Ce.next,Ce===null){if(Ce=F.shared.pending,Ce===null)break;gt=Ce,Ce=gt.next,gt.next=null,F.lastBaseUpdate=gt,F.shared.pending=null}}while(!0);yt===null&&(Be=Ct),F.baseState=Be,F.firstBaseUpdate=ht,F.lastBaseUpdate=yt,O===null&&(F.shared.lanes=0),Dd|=ne,m.lanes=ne,m.memoizedState=Ct}}function s5(m,g){if(typeof m!="function")throw Error(r(191,m));m.call(g)}function o5(m,g){var _=m.callbacks;if(_!==null)for(m.callbacks=null,m=0;m<_.length;m++)s5(_[m],g)}var Cp=V(null),yw=V(0);function l5(m,g){m=lu,te(yw,m),te(Cp,g),lu=m|g.baseLanes}function xA(){te(yw,lu),te(Cp,Cp.current)}function yA(){lu=yw.current,X(Cp),X(yw)}var mo=V(null),$o=null;function Td(m){var g=m.alternate;te(Oi,Oi.current&1),te(mo,m),$o===null&&(g===null||Cp.current!==null||g.memoizedState!==null)&&($o=m)}function vA(m){te(Oi,Oi.current),te(mo,m),$o===null&&($o=m)}function c5(m){m.tag===22?(te(Oi,Oi.current),te(mo,m),$o===null&&($o=m)):Ed()}function Ed(){te(Oi,Oi.current),te(mo,mo.current)}function fo(m){X(mo),$o===m&&($o=null),X(Oi)}var Oi=V(0);function vw(m){for(var g=m;g!==null;){if(g.tag===13){var _=g.memoizedState;if(_!==null&&(_=_.dehydrated,_===null||CT(_)||MT(_)))return g}else if(g.tag===19&&(g.memoizedProps.revealOrder==="forwards"||g.memoizedProps.revealOrder==="backwards"||g.memoizedProps.revealOrder==="unstable_legacy-backwards"||g.memoizedProps.revealOrder==="together")){if((g.flags&128)!==0)return g}else if(g.child!==null){g.child.return=g,g=g.child;continue}if(g===m)break;for(;g.sibling===null;){if(g.return===null||g.return===m)return null;g=g.return}g.sibling.return=g.return,g=g.sibling}return null}var eu=0,En=null,Mr=null,qi=null,ww=!1,Mp=!1,km=!1,_w=0,Rx=0,Ap=null,vse=0;function Ni(){throw Error(r(321))}function wA(m,g){if(g===null)return!1;for(var _=0;_O?O:8;var ne=G.T,Ce={};G.T=Ce,LA(m,!1,g,_);try{var Be=F(),ht=G.S;if(ht!==null&&ht(Ce,Be),Be!==null&&typeof Be=="object"&&typeof Be.then=="function"){var yt=yse(Be,C);Lx(m,g,yt,bo(m))}else Lx(m,g,C,bo(m))}catch(Ct){Lx(m,g,{then:function(){},status:"rejected",reason:Ct},bo())}finally{z.p=O,ne!==null&&Ce.types!==null&&(ne.types=Ce.types),G.T=ne}}function kse(){}function RA(m,g,_,C){if(m.tag!==5)throw Error(r(476));var F=z5(m).queue;I5(m,F,g,K,_===null?kse:function(){return U5(m),_(C)})}function z5(m){var g=m.memoizedState;if(g!==null)return g;g={memoizedState:K,baseState:K,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:tu,lastRenderedState:K},next:null};var _={};return g.next={memoizedState:_,baseState:_,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:tu,lastRenderedState:_},next:null},m.memoizedState=g,m=m.alternate,m!==null&&(m.memoizedState=g),g}function U5(m){var g=z5(m);g.next===null&&(g=m.alternate.memoizedState),Lx(m,g.next.queue,{},bo())}function FA(){return Ha(Jx)}function B5(){return Ii().memoizedState}function H5(){return Ii().memoizedState}function Cse(m){for(var g=m.return;g!==null;){switch(g.tag){case 24:case 3:var _=bo();m=Md(_);var C=Ad(g,m,_);C!==null&&(qs(C,g,_),Px(C,g,_)),g={cache:uA()},m.payload=g;return}g=g.return}}function Mse(m,g,_){var C=bo();_={lane:C,revertLane:0,gesture:null,action:_,hasEagerState:!1,eagerState:null,next:null},Aw(m)?V5(g,_):(_=JM(m,g,_,C),_!==null&&(qs(_,m,C),G5(_,g,C)))}function $5(m,g,_){var C=bo();Lx(m,g,_,C)}function Lx(m,g,_,C){var F={lane:C,revertLane:0,gesture:null,action:_,hasEagerState:!1,eagerState:null,next:null};if(Aw(m))V5(g,F);else{var O=m.alternate;if(m.lanes===0&&(O===null||O.lanes===0)&&(O=g.lastRenderedReducer,O!==null))try{var ne=g.lastRenderedState,Ce=O(ne,_);if(F.hasEagerState=!0,F.eagerState=Ce,uo(Ce,ne))return lw(m,g,F,0),Hr===null&&ow(),!1}catch{}if(_=JM(m,g,F,C),_!==null)return qs(_,m,C),G5(_,g,C),!0}return!1}function LA(m,g,_,C){if(C={lane:2,revertLane:fT(),gesture:null,action:C,hasEagerState:!1,eagerState:null,next:null},Aw(m)){if(g)throw Error(r(479))}else g=JM(m,_,C,2),g!==null&&qs(g,m,2)}function Aw(m){var g=m.alternate;return m===En||g!==null&&g===En}function V5(m,g){Mp=ww=!0;var _=m.pending;_===null?g.next=g:(g.next=_.next,_.next=g),m.pending=g}function G5(m,g,_){if((_&4194048)!==0){var C=g.lanes;C&=m.pendingLanes,_|=C,g.lanes=_,xt(m,_)}}var Ox={readContext:Ha,use:Nw,useCallback:Ni,useContext:Ni,useEffect:Ni,useImperativeHandle:Ni,useLayoutEffect:Ni,useInsertionEffect:Ni,useMemo:Ni,useReducer:Ni,useRef:Ni,useState:Ni,useDebugValue:Ni,useDeferredValue:Ni,useTransition:Ni,useSyncExternalStore:Ni,useId:Ni,useHostTransitionStatus:Ni,useFormState:Ni,useActionState:Ni,useOptimistic:Ni,useMemoCache:Ni,useCacheRefresh:Ni};Ox.useEffectEvent=Ni;var q5={readContext:Ha,use:Nw,useCallback:function(m,g){return Cs().memoizedState=[m,g===void 0?null:g],m},useContext:Ha,useEffect:T5,useImperativeHandle:function(m,g,_){_=_!=null?_.concat([m]):null,Cw(4194308,4,D5.bind(null,g,m),_)},useLayoutEffect:function(m,g){return Cw(4194308,4,m,g)},useInsertionEffect:function(m,g){Cw(4,2,m,g)},useMemo:function(m,g){var _=Cs();g=g===void 0?null:g;var C=m();if(km){ke(!0);try{m()}finally{ke(!1)}}return _.memoizedState=[C,g],C},useReducer:function(m,g,_){var C=Cs();if(_!==void 0){var F=_(g);if(km){ke(!0);try{_(g)}finally{ke(!1)}}}else F=g;return C.memoizedState=C.baseState=F,m={pending:null,lanes:0,dispatch:null,lastRenderedReducer:m,lastRenderedState:F},C.queue=m,m=m.dispatch=Mse.bind(null,En,m),[C.memoizedState,m]},useRef:function(m){var g=Cs();return m={current:m},g.memoizedState=m},useState:function(m){m=TA(m);var g=m.queue,_=$5.bind(null,En,g);return g.dispatch=_,[m.memoizedState,_]},useDebugValue:jA,useDeferredValue:function(m,g){var _=Cs();return DA(_,m,g)},useTransition:function(){var m=TA(!1);return m=I5.bind(null,En,m.queue,!0,!1),Cs().memoizedState=m,[!1,m]},useSyncExternalStore:function(m,g,_){var C=En,F=Cs();if(rr){if(_===void 0)throw Error(r(407));_=_()}else{if(_=g(),Hr===null)throw Error(r(349));(er&127)!==0||m5(C,g,_)}F.memoizedState=_;var O={value:_,getSnapshot:g};return F.queue=O,T5(p5.bind(null,C,O,m),[m]),C.flags|=2048,Tp(9,{destroy:void 0},f5.bind(null,C,O,_,g),null),_},useId:function(){var m=Cs(),g=Hr.identifierPrefix;if(rr){var _=ac,C=ic;_=(C&~(1<<32-Ue(C)-1)).toString(32)+_,g="_"+g+"R_"+_,_=_w++,0<_&&(g+="H"+_.toString(32)),g+="_"}else _=vse++,g="_"+g+"r_"+_.toString(32)+"_";return m.memoizedState=g},useHostTransitionStatus:FA,useFormState:N5,useActionState:N5,useOptimistic:function(m){var g=Cs();g.memoizedState=g.baseState=m;var _={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return g.queue=_,g=LA.bind(null,En,!0,_),_.dispatch=g,[m,g]},useMemoCache:CA,useCacheRefresh:function(){return Cs().memoizedState=Cse.bind(null,En)},useEffectEvent:function(m){var g=Cs(),_={impl:m};return g.memoizedState=_,function(){if((pr&2)!==0)throw Error(r(440));return _.impl.apply(void 0,arguments)}}},OA={readContext:Ha,use:Nw,useCallback:F5,useContext:Ha,useEffect:PA,useImperativeHandle:R5,useInsertionEffect:P5,useLayoutEffect:j5,useMemo:L5,useReducer:kw,useRef:A5,useState:function(){return kw(tu)},useDebugValue:jA,useDeferredValue:function(m,g){var _=Ii();return O5(_,Mr.memoizedState,m,g)},useTransition:function(){var m=kw(tu)[0],g=Ii().memoizedState;return[typeof m=="boolean"?m:Fx(m),g]},useSyncExternalStore:h5,useId:B5,useHostTransitionStatus:FA,useFormState:k5,useActionState:k5,useOptimistic:function(m,g){var _=Ii();return x5(_,Mr,m,g)},useMemoCache:CA,useCacheRefresh:H5};OA.useEffectEvent=E5;var W5={readContext:Ha,use:Nw,useCallback:F5,useContext:Ha,useEffect:PA,useImperativeHandle:R5,useInsertionEffect:P5,useLayoutEffect:j5,useMemo:L5,useReducer:AA,useRef:A5,useState:function(){return AA(tu)},useDebugValue:jA,useDeferredValue:function(m,g){var _=Ii();return Mr===null?DA(_,m,g):O5(_,Mr.memoizedState,m,g)},useTransition:function(){var m=AA(tu)[0],g=Ii().memoizedState;return[typeof m=="boolean"?m:Fx(m),g]},useSyncExternalStore:h5,useId:B5,useHostTransitionStatus:FA,useFormState:M5,useActionState:M5,useOptimistic:function(m,g){var _=Ii();return Mr!==null?x5(_,Mr,m,g):(_.baseState=m,[m,_.queue.dispatch])},useMemoCache:CA,useCacheRefresh:H5};W5.useEffectEvent=E5;function IA(m,g,_,C){g=m.memoizedState,_=_(C,g),_=_==null?g:h({},g,_),m.memoizedState=_,m.lanes===0&&(m.updateQueue.baseState=_)}var zA={enqueueSetState:function(m,g,_){m=m._reactInternals;var C=bo(),F=Md(C);F.payload=g,_!=null&&(F.callback=_),g=Ad(m,F,C),g!==null&&(qs(g,m,C),Px(g,m,C))},enqueueReplaceState:function(m,g,_){m=m._reactInternals;var C=bo(),F=Md(C);F.tag=1,F.payload=g,_!=null&&(F.callback=_),g=Ad(m,F,C),g!==null&&(qs(g,m,C),Px(g,m,C))},enqueueForceUpdate:function(m,g){m=m._reactInternals;var _=bo(),C=Md(_);C.tag=2,g!=null&&(C.callback=g),g=Ad(m,C,_),g!==null&&(qs(g,m,_),Px(g,m,_))}};function K5(m,g,_,C,F,O,ne){return m=m.stateNode,typeof m.shouldComponentUpdate=="function"?m.shouldComponentUpdate(C,O,ne):g.prototype&&g.prototype.isPureReactComponent?!Sx(_,C)||!Sx(F,O):!0}function X5(m,g,_,C){m=g.state,typeof g.componentWillReceiveProps=="function"&&g.componentWillReceiveProps(_,C),typeof g.UNSAFE_componentWillReceiveProps=="function"&&g.UNSAFE_componentWillReceiveProps(_,C),g.state!==m&&zA.enqueueReplaceState(g,g.state,null)}function Cm(m,g){var _=g;if("ref"in g){_={};for(var C in g)C!=="ref"&&(_[C]=g[C])}if(m=m.defaultProps){_===g&&(_=h({},_));for(var F in m)_[F]===void 0&&(_[F]=m[F])}return _}function Y5(m){sw(m)}function Q5(m){console.error(m)}function Z5(m){sw(m)}function Tw(m,g){try{var _=m.onUncaughtError;_(g.value,{componentStack:g.stack})}catch(C){setTimeout(function(){throw C})}}function J5(m,g,_){try{var C=m.onCaughtError;C(_.value,{componentStack:_.stack,errorBoundary:g.tag===1?g.stateNode:null})}catch(F){setTimeout(function(){throw F})}}function UA(m,g,_){return _=Md(_),_.tag=3,_.payload={element:null},_.callback=function(){Tw(m,g)},_}function ez(m){return m=Md(m),m.tag=3,m}function tz(m,g,_,C){var F=_.type.getDerivedStateFromError;if(typeof F=="function"){var O=C.value;m.payload=function(){return F(O)},m.callback=function(){J5(g,_,C)}}var ne=_.stateNode;ne!==null&&typeof ne.componentDidCatch=="function"&&(m.callback=function(){J5(g,_,C),typeof F!="function"&&(Rd===null?Rd=new Set([this]):Rd.add(this));var Ce=C.stack;this.componentDidCatch(C.value,{componentStack:Ce!==null?Ce:""})})}function Ase(m,g,_,C,F){if(_.flags|=32768,C!==null&&typeof C=="object"&&typeof C.then=="function"){if(g=_.alternate,g!==null&&wp(g,_,F,!0),_=mo.current,_!==null){switch(_.tag){case 31:case 13:return $o===null?Bw():_.alternate===null&&ki===0&&(ki=3),_.flags&=-257,_.flags|=65536,_.lanes=F,C===gw?_.flags|=16384:(g=_.updateQueue,g===null?_.updateQueue=new Set([C]):g.add(C),dT(m,C,F)),!1;case 22:return _.flags|=65536,C===gw?_.flags|=16384:(g=_.updateQueue,g===null?(g={transitions:null,markerInstances:null,retryQueue:new Set([C])},_.updateQueue=g):(_=g.retryQueue,_===null?g.retryQueue=new Set([C]):_.add(C)),dT(m,C,F)),!1}throw Error(r(435,_.tag))}return dT(m,C,F),Bw(),!1}if(rr)return g=mo.current,g!==null?((g.flags&65536)===0&&(g.flags|=256),g.flags|=65536,g.lanes=F,C!==aA&&(m=Error(r(422),{cause:C}),Cx(zo(m,_)))):(C!==aA&&(g=Error(r(423),{cause:C}),Cx(zo(g,_))),m=m.current.alternate,m.flags|=65536,F&=-F,m.lanes|=F,C=zo(C,_),F=UA(m.stateNode,C,F),gA(m,F),ki!==4&&(ki=2)),!1;var O=Error(r(520),{cause:C});if(O=zo(O,_),Gx===null?Gx=[O]:Gx.push(O),ki!==4&&(ki=2),g===null)return!0;C=zo(C,_),_=g;do{switch(_.tag){case 3:return _.flags|=65536,m=F&-F,_.lanes|=m,m=UA(_.stateNode,C,m),gA(_,m),!1;case 1:if(g=_.type,O=_.stateNode,(_.flags&128)===0&&(typeof g.getDerivedStateFromError=="function"||O!==null&&typeof O.componentDidCatch=="function"&&(Rd===null||!Rd.has(O))))return _.flags|=65536,F&=-F,_.lanes|=F,F=ez(F),tz(F,m,_,C),gA(_,F),!1}_=_.return}while(_!==null);return!1}var BA=Error(r(461)),Wi=!1;function $a(m,g,_,C){g.child=m===null?a5(g,null,_,C):Nm(g,m.child,_,C)}function nz(m,g,_,C,F){_=_.render;var O=g.ref;if("ref"in C){var ne={};for(var Ce in C)Ce!=="ref"&&(ne[Ce]=C[Ce])}else ne=C;return vm(g),C=_A(m,g,_,ne,O,F),Ce=SA(),m!==null&&!Wi?(NA(m,g,F),nu(m,g,F)):(rr&&Ce&&rA(g),g.flags|=1,$a(m,g,C,F),g.child)}function rz(m,g,_,C,F){if(m===null){var O=_.type;return typeof O=="function"&&!eA(O)&&O.defaultProps===void 0&&_.compare===null?(g.tag=15,g.type=O,iz(m,g,O,C,F)):(m=uw(_.type,null,C,g,g.mode,F),m.ref=g.ref,m.return=g,g.child=m)}if(O=m.child,!XA(m,F)){var ne=O.memoizedProps;if(_=_.compare,_=_!==null?_:Sx,_(ne,C)&&m.ref===g.ref)return nu(m,g,F)}return g.flags|=1,m=Yc(O,C),m.ref=g.ref,m.return=g,g.child=m}function iz(m,g,_,C,F){if(m!==null){var O=m.memoizedProps;if(Sx(O,C)&&m.ref===g.ref)if(Wi=!1,g.pendingProps=C=O,XA(m,F))(m.flags&131072)!==0&&(Wi=!0);else return g.lanes=m.lanes,nu(m,g,F)}return HA(m,g,_,C,F)}function az(m,g,_,C){var F=C.children,O=m!==null?m.memoizedState:null;if(m===null&&g.stateNode===null&&(g.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),C.mode==="hidden"){if((g.flags&128)!==0){if(O=O!==null?O.baseLanes|_:_,m!==null){for(C=g.child=m.child,F=0;C!==null;)F=F|C.lanes|C.childLanes,C=C.sibling;C=F&~O}else C=0,g.child=null;return sz(m,g,O,_,C)}if((_&536870912)!==0)g.memoizedState={baseLanes:0,cachePool:null},m!==null&&fw(g,O!==null?O.cachePool:null),O!==null?l5(g,O):xA(),c5(g);else return C=g.lanes=536870912,sz(m,g,O!==null?O.baseLanes|_:_,_,C)}else O!==null?(fw(g,O.cachePool),l5(g,O),Ed(),g.memoizedState=null):(m!==null&&fw(g,null),xA(),Ed());return $a(m,g,F,_),g.child}function Ix(m,g){return m!==null&&m.tag===22||g.stateNode!==null||(g.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),g.sibling}function sz(m,g,_,C,F){var O=hA();return O=O===null?null:{parent:Gi._currentValue,pool:O},g.memoizedState={baseLanes:_,cachePool:O},m!==null&&fw(g,null),xA(),c5(g),m!==null&&wp(m,g,C,!0),g.childLanes=F,null}function Ew(m,g){return g=jw({mode:g.mode,children:g.children},m.mode),g.ref=m.ref,m.child=g,g.return=m,g}function oz(m,g,_){return Nm(g,m.child,null,_),m=Ew(g,g.pendingProps),m.flags|=2,fo(g),g.memoizedState=null,m}function Tse(m,g,_){var C=g.pendingProps,F=(g.flags&128)!==0;if(g.flags&=-129,m===null){if(rr){if(C.mode==="hidden")return m=Ew(g,C),g.lanes=536870912,Ix(null,m);if(vA(g),(m=Jr)?(m=yU(m,Ho),m=m!==null&&m.data==="&"?m:null,m!==null&&(g.memoizedState={dehydrated:m,treeContext:_d!==null?{id:ic,overflow:ac}:null,retryLane:536870912,hydrationErrors:null},_=VI(m),_.return=g,g.child=_,Ba=g,Jr=null)):m=null,m===null)throw Nd(g);return g.lanes=536870912,null}return Ew(g,C)}var O=m.memoizedState;if(O!==null){var ne=O.dehydrated;if(vA(g),F)if(g.flags&256)g.flags&=-257,g=oz(m,g,_);else if(g.memoizedState!==null)g.child=m.child,g.flags|=128,g=null;else throw Error(r(558));else if(Wi||wp(m,g,_,!1),F=(_&m.childLanes)!==0,Wi||F){if(C=Hr,C!==null&&(ne=vt(C,_),ne!==0&&ne!==O.retryLane))throw O.retryLane=ne,gm(m,ne),qs(C,m,ne),BA;Bw(),g=oz(m,g,_)}else m=O.treeContext,Jr=Vo(ne.nextSibling),Ba=g,rr=!0,Sd=null,Ho=!1,m!==null&&WI(g,m),g=Ew(g,C),g.flags|=4096;return g}return m=Yc(m.child,{mode:C.mode,children:C.children}),m.ref=g.ref,g.child=m,m.return=g,m}function Pw(m,g){var _=g.ref;if(_===null)m!==null&&m.ref!==null&&(g.flags|=4194816);else{if(typeof _!="function"&&typeof _!="object")throw Error(r(284));(m===null||m.ref!==_)&&(g.flags|=4194816)}}function HA(m,g,_,C,F){return vm(g),_=_A(m,g,_,C,void 0,F),C=SA(),m!==null&&!Wi?(NA(m,g,F),nu(m,g,F)):(rr&&C&&rA(g),g.flags|=1,$a(m,g,_,F),g.child)}function lz(m,g,_,C,F,O){return vm(g),g.updateQueue=null,_=d5(g,C,_,F),u5(m),C=SA(),m!==null&&!Wi?(NA(m,g,O),nu(m,g,O)):(rr&&C&&rA(g),g.flags|=1,$a(m,g,_,O),g.child)}function cz(m,g,_,C,F){if(vm(g),g.stateNode===null){var O=bp,ne=_.contextType;typeof ne=="object"&&ne!==null&&(O=Ha(ne)),O=new _(C,O),g.memoizedState=O.state!==null&&O.state!==void 0?O.state:null,O.updater=zA,g.stateNode=O,O._reactInternals=g,O=g.stateNode,O.props=C,O.state=g.memoizedState,O.refs={},fA(g),ne=_.contextType,O.context=typeof ne=="object"&&ne!==null?Ha(ne):bp,O.state=g.memoizedState,ne=_.getDerivedStateFromProps,typeof ne=="function"&&(IA(g,_,ne,C),O.state=g.memoizedState),typeof _.getDerivedStateFromProps=="function"||typeof O.getSnapshotBeforeUpdate=="function"||typeof O.UNSAFE_componentWillMount!="function"&&typeof O.componentWillMount!="function"||(ne=O.state,typeof O.componentWillMount=="function"&&O.componentWillMount(),typeof O.UNSAFE_componentWillMount=="function"&&O.UNSAFE_componentWillMount(),ne!==O.state&&zA.enqueueReplaceState(O,O.state,null),Dx(g,C,O,F),jx(),O.state=g.memoizedState),typeof O.componentDidMount=="function"&&(g.flags|=4194308),C=!0}else if(m===null){O=g.stateNode;var Ce=g.memoizedProps,Be=Cm(_,Ce);O.props=Be;var ht=O.context,yt=_.contextType;ne=bp,typeof yt=="object"&&yt!==null&&(ne=Ha(yt));var Ct=_.getDerivedStateFromProps;yt=typeof Ct=="function"||typeof O.getSnapshotBeforeUpdate=="function",Ce=g.pendingProps!==Ce,yt||typeof O.UNSAFE_componentWillReceiveProps!="function"&&typeof O.componentWillReceiveProps!="function"||(Ce||ht!==ne)&&X5(g,O,C,ne),Cd=!1;var mt=g.memoizedState;O.state=mt,Dx(g,C,O,F),jx(),ht=g.memoizedState,Ce||mt!==ht||Cd?(typeof Ct=="function"&&(IA(g,_,Ct,C),ht=g.memoizedState),(Be=Cd||K5(g,_,Be,C,mt,ht,ne))?(yt||typeof O.UNSAFE_componentWillMount!="function"&&typeof O.componentWillMount!="function"||(typeof O.componentWillMount=="function"&&O.componentWillMount(),typeof O.UNSAFE_componentWillMount=="function"&&O.UNSAFE_componentWillMount()),typeof O.componentDidMount=="function"&&(g.flags|=4194308)):(typeof O.componentDidMount=="function"&&(g.flags|=4194308),g.memoizedProps=C,g.memoizedState=ht),O.props=C,O.state=ht,O.context=ne,C=Be):(typeof O.componentDidMount=="function"&&(g.flags|=4194308),C=!1)}else{O=g.stateNode,pA(m,g),ne=g.memoizedProps,yt=Cm(_,ne),O.props=yt,Ct=g.pendingProps,mt=O.context,ht=_.contextType,Be=bp,typeof ht=="object"&&ht!==null&&(Be=Ha(ht)),Ce=_.getDerivedStateFromProps,(ht=typeof Ce=="function"||typeof O.getSnapshotBeforeUpdate=="function")||typeof O.UNSAFE_componentWillReceiveProps!="function"&&typeof O.componentWillReceiveProps!="function"||(ne!==Ct||mt!==Be)&&X5(g,O,C,Be),Cd=!1,mt=g.memoizedState,O.state=mt,Dx(g,C,O,F),jx();var gt=g.memoizedState;ne!==Ct||mt!==gt||Cd||m!==null&&m.dependencies!==null&&hw(m.dependencies)?(typeof Ce=="function"&&(IA(g,_,Ce,C),gt=g.memoizedState),(yt=Cd||K5(g,_,yt,C,mt,gt,Be)||m!==null&&m.dependencies!==null&&hw(m.dependencies))?(ht||typeof O.UNSAFE_componentWillUpdate!="function"&&typeof O.componentWillUpdate!="function"||(typeof O.componentWillUpdate=="function"&&O.componentWillUpdate(C,gt,Be),typeof O.UNSAFE_componentWillUpdate=="function"&&O.UNSAFE_componentWillUpdate(C,gt,Be)),typeof O.componentDidUpdate=="function"&&(g.flags|=4),typeof O.getSnapshotBeforeUpdate=="function"&&(g.flags|=1024)):(typeof O.componentDidUpdate!="function"||ne===m.memoizedProps&&mt===m.memoizedState||(g.flags|=4),typeof O.getSnapshotBeforeUpdate!="function"||ne===m.memoizedProps&&mt===m.memoizedState||(g.flags|=1024),g.memoizedProps=C,g.memoizedState=gt),O.props=C,O.state=gt,O.context=Be,C=yt):(typeof O.componentDidUpdate!="function"||ne===m.memoizedProps&&mt===m.memoizedState||(g.flags|=4),typeof O.getSnapshotBeforeUpdate!="function"||ne===m.memoizedProps&&mt===m.memoizedState||(g.flags|=1024),C=!1)}return O=C,Pw(m,g),C=(g.flags&128)!==0,O||C?(O=g.stateNode,_=C&&typeof _.getDerivedStateFromError!="function"?null:O.render(),g.flags|=1,m!==null&&C?(g.child=Nm(g,m.child,null,F),g.child=Nm(g,null,_,F)):$a(m,g,_,F),g.memoizedState=O.state,m=g.child):m=nu(m,g,F),m}function uz(m,g,_,C){return xm(),g.flags|=256,$a(m,g,_,C),g.child}var $A={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function VA(m){return{baseLanes:m,cachePool:JI()}}function GA(m,g,_){return m=m!==null?m.childLanes&~_:0,g&&(m|=go),m}function dz(m,g,_){var C=g.pendingProps,F=!1,O=(g.flags&128)!==0,ne;if((ne=O)||(ne=m!==null&&m.memoizedState===null?!1:(Oi.current&2)!==0),ne&&(F=!0,g.flags&=-129),ne=(g.flags&32)!==0,g.flags&=-33,m===null){if(rr){if(F?Td(g):Ed(),(m=Jr)?(m=yU(m,Ho),m=m!==null&&m.data!=="&"?m:null,m!==null&&(g.memoizedState={dehydrated:m,treeContext:_d!==null?{id:ic,overflow:ac}:null,retryLane:536870912,hydrationErrors:null},_=VI(m),_.return=g,g.child=_,Ba=g,Jr=null)):m=null,m===null)throw Nd(g);return MT(m)?g.lanes=32:g.lanes=536870912,null}var Ce=C.children;return C=C.fallback,F?(Ed(),F=g.mode,Ce=jw({mode:"hidden",children:Ce},F),C=bm(C,F,_,null),Ce.return=g,C.return=g,Ce.sibling=C,g.child=Ce,C=g.child,C.memoizedState=VA(_),C.childLanes=GA(m,ne,_),g.memoizedState=$A,Ix(null,C)):(Td(g),qA(g,Ce))}var Be=m.memoizedState;if(Be!==null&&(Ce=Be.dehydrated,Ce!==null)){if(O)g.flags&256?(Td(g),g.flags&=-257,g=WA(m,g,_)):g.memoizedState!==null?(Ed(),g.child=m.child,g.flags|=128,g=null):(Ed(),Ce=C.fallback,F=g.mode,C=jw({mode:"visible",children:C.children},F),Ce=bm(Ce,F,_,null),Ce.flags|=2,C.return=g,Ce.return=g,C.sibling=Ce,g.child=C,Nm(g,m.child,null,_),C=g.child,C.memoizedState=VA(_),C.childLanes=GA(m,ne,_),g.memoizedState=$A,g=Ix(null,C));else if(Td(g),MT(Ce)){if(ne=Ce.nextSibling&&Ce.nextSibling.dataset,ne)var ht=ne.dgst;ne=ht,C=Error(r(419)),C.stack="",C.digest=ne,Cx({value:C,source:null,stack:null}),g=WA(m,g,_)}else if(Wi||wp(m,g,_,!1),ne=(_&m.childLanes)!==0,Wi||ne){if(ne=Hr,ne!==null&&(C=vt(ne,_),C!==0&&C!==Be.retryLane))throw Be.retryLane=C,gm(m,C),qs(ne,m,C),BA;CT(Ce)||Bw(),g=WA(m,g,_)}else CT(Ce)?(g.flags|=192,g.child=m.child,g=null):(m=Be.treeContext,Jr=Vo(Ce.nextSibling),Ba=g,rr=!0,Sd=null,Ho=!1,m!==null&&WI(g,m),g=qA(g,C.children),g.flags|=4096);return g}return F?(Ed(),Ce=C.fallback,F=g.mode,Be=m.child,ht=Be.sibling,C=Yc(Be,{mode:"hidden",children:C.children}),C.subtreeFlags=Be.subtreeFlags&65011712,ht!==null?Ce=Yc(ht,Ce):(Ce=bm(Ce,F,_,null),Ce.flags|=2),Ce.return=g,C.return=g,C.sibling=Ce,g.child=C,Ix(null,C),C=g.child,Ce=m.child.memoizedState,Ce===null?Ce=VA(_):(F=Ce.cachePool,F!==null?(Be=Gi._currentValue,F=F.parent!==Be?{parent:Be,pool:Be}:F):F=JI(),Ce={baseLanes:Ce.baseLanes|_,cachePool:F}),C.memoizedState=Ce,C.childLanes=GA(m,ne,_),g.memoizedState=$A,Ix(m.child,C)):(Td(g),_=m.child,m=_.sibling,_=Yc(_,{mode:"visible",children:C.children}),_.return=g,_.sibling=null,m!==null&&(ne=g.deletions,ne===null?(g.deletions=[m],g.flags|=16):ne.push(m)),g.child=_,g.memoizedState=null,_)}function qA(m,g){return g=jw({mode:"visible",children:g},m.mode),g.return=m,m.child=g}function jw(m,g){return m=ho(22,m,null,g),m.lanes=0,m}function WA(m,g,_){return Nm(g,m.child,null,_),m=qA(g,g.pendingProps.children),m.flags|=2,g.memoizedState=null,m}function hz(m,g,_){m.lanes|=g;var C=m.alternate;C!==null&&(C.lanes|=g),lA(m.return,g,_)}function KA(m,g,_,C,F,O){var ne=m.memoizedState;ne===null?m.memoizedState={isBackwards:g,rendering:null,renderingStartTime:0,last:C,tail:_,tailMode:F,treeForkCount:O}:(ne.isBackwards=g,ne.rendering=null,ne.renderingStartTime=0,ne.last=C,ne.tail=_,ne.tailMode=F,ne.treeForkCount=O)}function mz(m,g,_){var C=g.pendingProps,F=C.revealOrder,O=C.tail;C=C.children;var ne=Oi.current,Ce=(ne&2)!==0;if(Ce?(ne=ne&1|2,g.flags|=128):ne&=1,te(Oi,ne),$a(m,g,C,_),C=rr?kx:0,!Ce&&m!==null&&(m.flags&128)!==0)e:for(m=g.child;m!==null;){if(m.tag===13)m.memoizedState!==null&&hz(m,_,g);else if(m.tag===19)hz(m,_,g);else if(m.child!==null){m.child.return=m,m=m.child;continue}if(m===g)break e;for(;m.sibling===null;){if(m.return===null||m.return===g)break e;m=m.return}m.sibling.return=m.return,m=m.sibling}switch(F){case"forwards":for(_=g.child,F=null;_!==null;)m=_.alternate,m!==null&&vw(m)===null&&(F=_),_=_.sibling;_=F,_===null?(F=g.child,g.child=null):(F=_.sibling,_.sibling=null),KA(g,!1,F,_,O,C);break;case"backwards":case"unstable_legacy-backwards":for(_=null,F=g.child,g.child=null;F!==null;){if(m=F.alternate,m!==null&&vw(m)===null){g.child=F;break}m=F.sibling,F.sibling=_,_=F,F=m}KA(g,!0,_,null,O,C);break;case"together":KA(g,!1,null,null,void 0,C);break;default:g.memoizedState=null}return g.child}function nu(m,g,_){if(m!==null&&(g.dependencies=m.dependencies),Dd|=g.lanes,(_&g.childLanes)===0)if(m!==null){if(wp(m,g,_,!1),(_&g.childLanes)===0)return null}else return null;if(m!==null&&g.child!==m.child)throw Error(r(153));if(g.child!==null){for(m=g.child,_=Yc(m,m.pendingProps),g.child=_,_.return=g;m.sibling!==null;)m=m.sibling,_=_.sibling=Yc(m,m.pendingProps),_.return=g;_.sibling=null}return g.child}function XA(m,g){return(m.lanes&g)!==0?!0:(m=m.dependencies,!!(m!==null&&hw(m)))}function Ese(m,g,_){switch(g.tag){case 3:De(g,g.stateNode.containerInfo),kd(g,Gi,m.memoizedState.cache),xm();break;case 27:case 5:ce(g);break;case 4:De(g,g.stateNode.containerInfo);break;case 10:kd(g,g.type,g.memoizedProps.value);break;case 31:if(g.memoizedState!==null)return g.flags|=128,vA(g),null;break;case 13:var C=g.memoizedState;if(C!==null)return C.dehydrated!==null?(Td(g),g.flags|=128,null):(_&g.child.childLanes)!==0?dz(m,g,_):(Td(g),m=nu(m,g,_),m!==null?m.sibling:null);Td(g);break;case 19:var F=(m.flags&128)!==0;if(C=(_&g.childLanes)!==0,C||(wp(m,g,_,!1),C=(_&g.childLanes)!==0),F){if(C)return mz(m,g,_);g.flags|=128}if(F=g.memoizedState,F!==null&&(F.rendering=null,F.tail=null,F.lastEffect=null),te(Oi,Oi.current),C)break;return null;case 22:return g.lanes=0,az(m,g,_,g.pendingProps);case 24:kd(g,Gi,m.memoizedState.cache)}return nu(m,g,_)}function fz(m,g,_){if(m!==null)if(m.memoizedProps!==g.pendingProps)Wi=!0;else{if(!XA(m,_)&&(g.flags&128)===0)return Wi=!1,Ese(m,g,_);Wi=(m.flags&131072)!==0}else Wi=!1,rr&&(g.flags&1048576)!==0&&qI(g,kx,g.index);switch(g.lanes=0,g.tag){case 16:e:{var C=g.pendingProps;if(m=_m(g.elementType),g.type=m,typeof m=="function")eA(m)?(C=Cm(m,C),g.tag=1,g=cz(null,g,m,C,_)):(g.tag=0,g=HA(null,g,m,C,_));else{if(m!=null){var F=m.$$typeof;if(F===A){g.tag=11,g=nz(null,g,m,C,_);break e}else if(F===k){g.tag=14,g=rz(null,g,m,C,_);break e}}throw g=R(m)||m,Error(r(306,g,""))}}return g;case 0:return HA(m,g,g.type,g.pendingProps,_);case 1:return C=g.type,F=Cm(C,g.pendingProps),cz(m,g,C,F,_);case 3:e:{if(De(g,g.stateNode.containerInfo),m===null)throw Error(r(387));C=g.pendingProps;var O=g.memoizedState;F=O.element,pA(m,g),Dx(g,C,null,_);var ne=g.memoizedState;if(C=ne.cache,kd(g,Gi,C),C!==O.cache&&cA(g,[Gi],_,!0),jx(),C=ne.element,O.isDehydrated)if(O={element:C,isDehydrated:!1,cache:ne.cache},g.updateQueue.baseState=O,g.memoizedState=O,g.flags&256){g=uz(m,g,C,_);break e}else if(C!==F){F=zo(Error(r(424)),g),Cx(F),g=uz(m,g,C,_);break e}else for(m=g.stateNode.containerInfo,m.nodeType===9?m=m.body:m=m.nodeName==="HTML"?m.ownerDocument.body:m,Jr=Vo(m.firstChild),Ba=g,rr=!0,Sd=null,Ho=!0,_=a5(g,null,C,_),g.child=_;_;)_.flags=_.flags&-3|4096,_=_.sibling;else{if(xm(),C===F){g=nu(m,g,_);break e}$a(m,g,C,_)}g=g.child}return g;case 26:return Pw(m,g),m===null?(_=kU(g.type,null,g.pendingProps,null))?g.memoizedState=_:rr||(_=g.type,m=g.pendingProps,C=Kw(fe.current).createElement(_),C[Pn]=g,C[cr]=m,Va(C,_,m),Ge(C),g.stateNode=C):g.memoizedState=kU(g.type,m.memoizedProps,g.pendingProps,m.memoizedState),null;case 27:return ce(g),m===null&&rr&&(C=g.stateNode=_U(g.type,g.pendingProps,fe.current),Ba=g,Ho=!0,F=Jr,Id(g.type)?(AT=F,Jr=Vo(C.firstChild)):Jr=F),$a(m,g,g.pendingProps.children,_),Pw(m,g),m===null&&(g.flags|=4194304),g.child;case 5:return m===null&&rr&&((F=C=Jr)&&(C=soe(C,g.type,g.pendingProps,Ho),C!==null?(g.stateNode=C,Ba=g,Jr=Vo(C.firstChild),Ho=!1,F=!0):F=!1),F||Nd(g)),ce(g),F=g.type,O=g.pendingProps,ne=m!==null?m.memoizedProps:null,C=O.children,ST(F,O)?C=null:ne!==null&&ST(F,ne)&&(g.flags|=32),g.memoizedState!==null&&(F=_A(m,g,wse,null,null,_),Jx._currentValue=F),Pw(m,g),$a(m,g,C,_),g.child;case 6:return m===null&&rr&&((m=_=Jr)&&(_=ooe(_,g.pendingProps,Ho),_!==null?(g.stateNode=_,Ba=g,Jr=null,m=!0):m=!1),m||Nd(g)),null;case 13:return dz(m,g,_);case 4:return De(g,g.stateNode.containerInfo),C=g.pendingProps,m===null?g.child=Nm(g,null,C,_):$a(m,g,C,_),g.child;case 11:return nz(m,g,g.type,g.pendingProps,_);case 7:return $a(m,g,g.pendingProps,_),g.child;case 8:return $a(m,g,g.pendingProps.children,_),g.child;case 12:return $a(m,g,g.pendingProps.children,_),g.child;case 10:return C=g.pendingProps,kd(g,g.type,C.value),$a(m,g,C.children,_),g.child;case 9:return F=g.type._context,C=g.pendingProps.children,vm(g),F=Ha(F),C=C(F),g.flags|=1,$a(m,g,C,_),g.child;case 14:return rz(m,g,g.type,g.pendingProps,_);case 15:return iz(m,g,g.type,g.pendingProps,_);case 19:return mz(m,g,_);case 31:return Tse(m,g,_);case 22:return az(m,g,_,g.pendingProps);case 24:return vm(g),C=Ha(Gi),m===null?(F=hA(),F===null&&(F=Hr,O=uA(),F.pooledCache=O,O.refCount++,O!==null&&(F.pooledCacheLanes|=_),F=O),g.memoizedState={parent:C,cache:F},fA(g),kd(g,Gi,F)):((m.lanes&_)!==0&&(pA(m,g),Dx(g,null,null,_),jx()),F=m.memoizedState,O=g.memoizedState,F.parent!==C?(F={parent:C,cache:C},g.memoizedState=F,g.lanes===0&&(g.memoizedState=g.updateQueue.baseState=F),kd(g,Gi,C)):(C=O.cache,kd(g,Gi,C),C!==F.cache&&cA(g,[Gi],_,!0))),$a(m,g,g.pendingProps.children,_),g.child;case 29:throw g.pendingProps}throw Error(r(156,g.tag))}function ru(m){m.flags|=4}function YA(m,g,_,C,F){if((g=(m.mode&32)!==0)&&(g=!1),g){if(m.flags|=16777216,(F&335544128)===F)if(m.stateNode.complete)m.flags|=8192;else if(Bz())m.flags|=8192;else throw Sm=gw,mA}else m.flags&=-16777217}function pz(m,g){if(g.type!=="stylesheet"||(g.state.loading&4)!==0)m.flags&=-16777217;else if(m.flags|=16777216,!EU(g))if(Bz())m.flags|=8192;else throw Sm=gw,mA}function Dw(m,g){g!==null&&(m.flags|=4),m.flags&16384&&(g=m.tag!==22?At():536870912,m.lanes|=g,Dp|=g)}function zx(m,g){if(!rr)switch(m.tailMode){case"hidden":g=m.tail;for(var _=null;g!==null;)g.alternate!==null&&(_=g),g=g.sibling;_===null?m.tail=null:_.sibling=null;break;case"collapsed":_=m.tail;for(var C=null;_!==null;)_.alternate!==null&&(C=_),_=_.sibling;C===null?g||m.tail===null?m.tail=null:m.tail.sibling=null:C.sibling=null}}function ei(m){var g=m.alternate!==null&&m.alternate.child===m.child,_=0,C=0;if(g)for(var F=m.child;F!==null;)_|=F.lanes|F.childLanes,C|=F.subtreeFlags&65011712,C|=F.flags&65011712,F.return=m,F=F.sibling;else for(F=m.child;F!==null;)_|=F.lanes|F.childLanes,C|=F.subtreeFlags,C|=F.flags,F.return=m,F=F.sibling;return m.subtreeFlags|=C,m.childLanes=_,g}function Pse(m,g,_){var C=g.pendingProps;switch(iA(g),g.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return ei(g),null;case 1:return ei(g),null;case 3:return _=g.stateNode,C=null,m!==null&&(C=m.memoizedState.cache),g.memoizedState.cache!==C&&(g.flags|=2048),Jc(Gi),de(),_.pendingContext&&(_.context=_.pendingContext,_.pendingContext=null),(m===null||m.child===null)&&(vp(g)?ru(g):m===null||m.memoizedState.isDehydrated&&(g.flags&256)===0||(g.flags|=1024,sA())),ei(g),null;case 26:var F=g.type,O=g.memoizedState;return m===null?(ru(g),O!==null?(ei(g),pz(g,O)):(ei(g),YA(g,F,null,C,_))):O?O!==m.memoizedState?(ru(g),ei(g),pz(g,O)):(ei(g),g.flags&=-16777217):(m=m.memoizedProps,m!==C&&ru(g),ei(g),YA(g,F,m,C,_)),null;case 27:if(Ne(g),_=fe.current,F=g.type,m!==null&&g.stateNode!=null)m.memoizedProps!==C&&ru(g);else{if(!C){if(g.stateNode===null)throw Error(r(166));return ei(g),null}m=J.current,vp(g)?KI(g):(m=_U(F,C,_),g.stateNode=m,ru(g))}return ei(g),null;case 5:if(Ne(g),F=g.type,m!==null&&g.stateNode!=null)m.memoizedProps!==C&&ru(g);else{if(!C){if(g.stateNode===null)throw Error(r(166));return ei(g),null}if(O=J.current,vp(g))KI(g);else{var ne=Kw(fe.current);switch(O){case 1:O=ne.createElementNS("http://www.w3.org/2000/svg",F);break;case 2:O=ne.createElementNS("http://www.w3.org/1998/Math/MathML",F);break;default:switch(F){case"svg":O=ne.createElementNS("http://www.w3.org/2000/svg",F);break;case"math":O=ne.createElementNS("http://www.w3.org/1998/Math/MathML",F);break;case"script":O=ne.createElement("div"),O.innerHTML=" + From f35e662e8b09d27804b50d0b49dfd89239a06d1f Mon Sep 17 00:00:00 2001 From: maziggy Date: Mon, 16 Feb 2026 08:12:14 +0100 Subject: [PATCH 4/7] fix: delete uploaded 3MF from SD card after print completes (#374) The print scheduler uploads .3mf files to the printer's SD card root but never cleans them up. Some printers (e.g. P1S) auto-start files found in root on power cycle, causing phantom/ghost prints on every reboot. Now deletes the uploaded file via FTP after print completion (best-effort, non-blocking). --- CHANGELOG.md | 1 + backend/app/main.py | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 588438792..5a70c2fbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,7 @@ All notable changes to Bambuddy will be documented in this file. - **Spool Edit Form Overwrites Usage-Tracked Weight** — Editing any spool field (note, color, material, etc.) sent the full form data back to the server, including `weight_used`. If the frontend cache was stale (e.g., loaded before the last print completed), saving the form would silently reset `weight_used` to the pre-print value, reverting the remaining weight to full. The form now only includes `weight_used` in the update request when the user explicitly changes the weight field. - **K-Profile Auto-Select Fails for Non-BL Spools on Dual-Nozzle Printers** — When assigning a third-party spool to an AMS slot on dual-nozzle printers (H2D, H2D Pro), the MQTT auto-configure step crashed with `'SpoolKProfile' object has no attribute 'extruder_id'`. The K-profile model uses `extruder` (not `extruder_id`). Fixed the attribute name so K-profile matching correctly filters by nozzle on dual-extruder printers. - **Loose Archive Name Matching Could Cause Wrong Archive Reuse** ([#374](https://github.com/maziggy/bambuddy/issues/374)) — The `on_print_start` callback used `ilike('%{name}%')` to find existing "printing" archives, which meant a print named "Clip" could incorrectly match "Cable Clip" or "Clip Stand". This could cause a new print to reuse the wrong archive or skip creating one. Tightened to exact `print_name` match or exact filename variants (`.3mf`, `.gcode.3mf`). +- **Phantom Prints on Power Cycle** ([#374](https://github.com/maziggy/bambuddy/issues/374)) — The print queue uploaded `.3mf` files to the printer's SD card root (`/`) but never deleted them after the print finished. Some printers (e.g. P1S) auto-start files found in the root directory on power cycle, causing ghost prints on every reboot. Now deletes the uploaded file from the SD card after print completion (best-effort, non-blocking). - **Archive Duplicate Badge Misses Name-Based Duplicates** ([#315](https://github.com/maziggy/bambuddy/issues/315)) — The duplicate badge on archive cards only matched by file content hash, so re-sliced prints of the same model (different GCODE, same print name) were not flagged as duplicates. Now also matches by print name (case-insensitive), consistent with the detail view's duplicate detection. ### Improved diff --git a/backend/app/main.py b/backend/app/main.py index 2101a1a94..27fbc66f7 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -2759,6 +2759,31 @@ async def on_print_complete(printer_id: int, data: dict): logging.getLogger(__name__).warning(f"Queue item update failed: {e}") log_timing("Queue item update") + + # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374) + # The print scheduler uploads .3mf files to the SD card root (/). Some printers (e.g. P1S) + # auto-start files found in root on power cycle, causing ghost prints. + try: + printer_info = printer_manager.get_printer(printer_id) + if printer_info and subtask_name: + from backend.app.services.bambu_ftp import delete_file_async + + remote_path = f"/{subtask_name}.3mf" + logger.info("Cleaning up uploaded file from printer SD card: %s", remote_path) + delete_result = await delete_file_async( + printer_info.ip_address, + printer_info.access_code, + remote_path, + printer_model=printer_info.model, + ) + if delete_result: + logger.info("Deleted %s from printer %s SD card", remote_path, printer_info.name) + else: + logger.debug("File delete returned False for %s (may not exist)", remote_path) + except Exception as e: + logger.debug("SD card file cleanup failed for printer %s: %s (non-critical)", printer_id, e) + + log_timing("SD card cleanup") logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id) From 8981c11baccef39b17e4eb66cc09503f8beb604d Mon Sep 17 00:00:00 2001 From: maziggy Date: Mon, 16 Feb 2026 08:21:09 +0100 Subject: [PATCH 5/7] fix: spool form scrollbar flicker in Edge (#364), delete SD card file after print (#374) Add scrollbar-gutter: stable to spool form modal to prevent scrollbar layout thrashing on Windows Edge at non-default zoom levels. Delete uploaded .3mf from printer SD card root after print completion to prevent phantom prints on power cycle (reported on P1S). --- CHANGELOG.md | 1 + frontend/src/components/SpoolFormModal.tsx | 2 +- static/assets/{index-LH77R5cV.js => index-B6_GHLIb.js} | 2 +- static/index.html | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) rename static/assets/{index-LH77R5cV.js => index-B6_GHLIb.js} (99%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a70c2fbf..97c65386c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,7 @@ All notable changes to Bambuddy will be documented in this file. - **K-Profile Auto-Select Fails for Non-BL Spools on Dual-Nozzle Printers** — When assigning a third-party spool to an AMS slot on dual-nozzle printers (H2D, H2D Pro), the MQTT auto-configure step crashed with `'SpoolKProfile' object has no attribute 'extruder_id'`. The K-profile model uses `extruder` (not `extruder_id`). Fixed the attribute name so K-profile matching correctly filters by nozzle on dual-extruder printers. - **Loose Archive Name Matching Could Cause Wrong Archive Reuse** ([#374](https://github.com/maziggy/bambuddy/issues/374)) — The `on_print_start` callback used `ilike('%{name}%')` to find existing "printing" archives, which meant a print named "Clip" could incorrectly match "Cable Clip" or "Clip Stand". This could cause a new print to reuse the wrong archive or skip creating one. Tightened to exact `print_name` match or exact filename variants (`.3mf`, `.gcode.3mf`). - **Phantom Prints on Power Cycle** ([#374](https://github.com/maziggy/bambuddy/issues/374)) — The print queue uploaded `.3mf` files to the printer's SD card root (`/`) but never deleted them after the print finished. Some printers (e.g. P1S) auto-start files found in the root directory on power cycle, causing ghost prints on every reboot. Now deletes the uploaded file from the SD card after print completion (best-effort, non-blocking). +- **Spool Form Scrollbar Flicker in Edge** ([#364](https://github.com/maziggy/bambuddy/issues/364)) — The Add/Edit Spool modal's scrollable area used `overflow-y: auto`, which on Windows Edge (where scrollbars take layout space) caused the scrollbar to appear and disappear on hover — making the color picker unusable at certain zoom levels. Added `scrollbar-gutter: stable` to reserve scrollbar space and prevent layout thrashing. - **Archive Duplicate Badge Misses Name-Based Duplicates** ([#315](https://github.com/maziggy/bambuddy/issues/315)) — The duplicate badge on archive cards only matched by file content hash, so re-sliced prints of the same model (different GCODE, same print name) were not flagged as duplicates. Now also matches by print name (case-insensitive), consistent with the detail view's duplicate detection. ### Improved diff --git a/frontend/src/components/SpoolFormModal.tsx b/frontend/src/components/SpoolFormModal.tsx index 2fab4433a..5b2a8e2eb 100644 --- a/frontend/src/components/SpoolFormModal.tsx +++ b/frontend/src/components/SpoolFormModal.tsx @@ -411,7 +411,7 @@ export function SpoolFormModal({ isOpen, onClose, spool, printersWithCalibration
{/* Content */} -
+
{activeTab === 'filament' ? (
{/* Filament Info Section */} diff --git a/static/assets/index-LH77R5cV.js b/static/assets/index-B6_GHLIb.js similarity index 99% rename from static/assets/index-LH77R5cV.js rename to static/assets/index-B6_GHLIb.js index 4226ec97b..ea83aef99 100644 --- a/static/assets/index-LH77R5cV.js +++ b/static/assets/index-B6_GHLIb.js @@ -8679,6 +8679,6 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${Ug(t. `+n+"]";if(typeof t=="object"){const r=Object.entries(t);return r.length===0?"{}":`{ `+r.map(([s,o])=>n+" "+JSON.stringify(s)+": "+mF(o,e+1)).join(`, `)+` -`+n+"}"}return String(t)}function MZe({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=mn(),c=tn(),[u,d]=w.useState(!1),{data:h,isLoading:f}=tt({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>se.getCloudSettingDetail(t.setting_id)}),p=lt({mutationFn:()=>se.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),x=mv(t.setting_id),v=bI(t.name,h?.setting?.inherits);return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(_t,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:a.jsxs(Nt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),x&&a.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[a.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"•"}),a.jsx("span",{children:v.printer})]})]})]}),a.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Ft,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:f?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?a.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:mF(h)}):a.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),u?a.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[a.jsx(Cn,{className:"w-5 h-5"}),a.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Me,{variant:"secondary",onClick:()=>d(!1),disabled:p.isPending,className:"flex-1",children:o("common.cancel")}),a.jsxs(Me,{variant:"danger",onClick:()=>p.mutate(),disabled:p.isPending,className:"flex-1",children:[p.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin"}):a.jsx(en,{className:"w-4 h-4"}),o("common.delete")]})]})]}):a.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Me,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),a.jsxs(Me,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[a.jsx(Wl,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),x&&a.jsxs(a.Fragment,{children:[a.jsxs(Me,{variant:"secondary",onClick:i,disabled:f||!h||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[a.jsx($i,{className:"w-4 h-4"}),o("common.edit")]}),a.jsx(Me,{variant:"danger",onClick:()=>d(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:a.jsx(en,{className:"w-4 h-4"})})]})]})})]})})})}function Gae(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function qae(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function AZe({onClose:t,onApply:e,t:n}){const{showToast:r}=mn(),[i,s]=w.useState(Gae),[o,l]=w.useState("all"),[c,u]=w.useState(null),[d,h]=w.useState(""),[f,p]=w.useState(""),[x,v]=w.useState("{}"),[b,y]=w.useState(null),[S,N]=w.useState(null),A=o==="all"?i:i.filter(B=>B.type===o),M=B=>{s(B),qae(B)},T=B=>{const R=i.filter(V=>V.id!==B);M(R),N(null),r(n("profiles.templates.toast.deleted"))},k=B=>{u(B.id),h(B.name),p(B.description),v(JSON.stringify(B.settings,null,2)),y(null)},j=()=>{if(!(!c||!d.trim()))try{const B=JSON.parse(x),R=i.map(V=>V.id===c?{...V,name:d.trim(),description:f.trim(),settings:B}:V);M(R),u(null),r(n("profiles.templates.toast.updated"))}catch(B){y(B.message)}},E=()=>{u(null),h(""),p(""),v("{}"),y(null)},P=B=>{const R=i.map(V=>V.id===B?{...V,showInModal:!V.showInModal}:V);M(R)},U={filament:{label:n("profiles.presets.types.filament"),icon:Jk,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:td,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:Cr,color:"text-purple-400"}},L=S?i.find(B=>B.id===S):null;return w.useEffect(()=>{const B=R=>{R.key==="Escape"&&(S?N(null):c?E():t())};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[S,c,t]),a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[L&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:a.jsx(_t,{className:"w-full max-w-md",children:a.jsxs(Nt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:a.jsx(Cn,{className:"w-6 h-6 text-red-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),a.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:L.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Me,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),a.jsxs(Me,{onClick:()=>T(S),className:"flex-1 bg-red-500 hover:bg-red-600",children:[a.jsx(en,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),a.jsx(_t,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:a.jsxs(Nt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(pb,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Ft,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(B=>a.jsx("button",{onClick:()=>l(B),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===B?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:B==="all"?n("common.all"):U[B].label},B))]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:A.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(pb,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:n("profiles.templates.noTemplates")}),a.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):a.jsx("div",{className:"space-y-2",children:A.map(B=>{const R=U[B.type],V=R.icon;return c===B.id?a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[a.jsx("input",{type:"text",value:d,onChange:q=>h(q.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),a.jsx("input",{type:"text",value:f,onChange:q=>p(q.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),a.jsx("textarea",{value:x,onChange:q=>{v(q.target.value),y(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${b?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),b&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Me,{size:"sm",onClick:j,disabled:!d.trim(),children:[a.jsx(bs,{className:"w-4 h-4"}),"Save"]}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:E,children:"Cancel"})]})]},B.id):a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[a.jsx(V,{className:`w-5 h-5 ${R.color} flex-shrink-0`}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:B.name}),a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:B.description})]}),a.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(B.settings).length})}),a.jsx("button",{onClick:()=>P(B.id),className:`p-1 transition-colors ${B.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:B.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:B.showInModal?a.jsx(Kl,{className:"w-4 h-4"}):a.jsx(gv,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>e(B),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),a.jsx("button",{onClick:()=>k(B),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:a.jsx($i,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>N(B.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:a.jsx(en,{className:"w-4 h-4"})})]},B.id)})})})]})})]})}function Wae({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:i,t:s}){const[o,l]=w.useState("changes"),[c,u]=w.useState(""),d=w.useMemo(()=>{const x=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const b of x){if(b==="inherits"||b==="version")continue;const y=e[b],S=n[b],N=b in e,A=b in n;let M;!N&&A?M="added":N&&!A?M="removed":JSON.stringify(y)!==JSON.stringify(S)?M="changed":M="same",v.push({key:b,left:y,right:S,status:M})}return v.sort((b,y)=>{const S={changed:0,added:1,removed:2,same:3};return S[b.status]!==S[y.status]?S[b.status]-S[y.status]:b.key.localeCompare(y.key)})},[e,n]),h=w.useMemo(()=>{let x=[...d];if(o==="changes"&&(x=x.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();x=x.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return x},[d,o,c]),f=w.useMemo(()=>({added:d.filter(x=>x.status==="added").length,removed:d.filter(x=>x.status==="removed").length,changed:d.filter(x=>x.status==="changed").length,same:d.filter(x=>x.status==="same").length}),[d]),p=x=>{if(x===void 0)return"—";if(x===null)return"null";if(Array.isArray(x))return x.length===0?"[]":x.length===1?String(x[0]):x.join(", ");if(typeof x=="object")return JSON.stringify(x);const v=String(x);if(v.includes("\\n")||v.length>100){const b=v.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const x=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsx(_t,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:a.jsxs(Nt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Yg,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Ft,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),a.jsx("p",{className:"text-white font-medium truncate",children:r})]}),a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),a.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx(ar,{className:"w-3.5 h-3.5"}),f.added," ",s("profiles.diff.added")]}),a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(x3,{className:"w-3.5 h-3.5"}),f.removed," ",s("profiles.diff.removed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[a.jsx(d3,{className:"w-3.5 h-3.5"}),f.changed," ",s("profiles.diff.changed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(ZT,{className:"w-3.5 h-3.5"}),f.same," ",s("profiles.diff.same")]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"relative",children:[a.jsx(Or,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c,onChange:x=>u(x.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),f.same>0&&a.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),a.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:h.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(ZT,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:a.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),a.jsx("th",{className:"text-left p-3 w-1/3",children:r}),a.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),a.jsx("tbody",{children:h.map(x=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[x.status],b={added:a.jsx(ar,{className:"w-3.5 h-3.5 text-green-400"}),removed:a.jsx(x3,{className:"w-3.5 h-3.5 text-red-400"}),changed:a.jsx(d3,{className:"w-3.5 h-3.5 text-amber-400"}),same:a.jsx(ZT,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[x.status];return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[a.jsx("td",{className:"p-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[b,a.jsx("span",{className:"text-sm text-white font-mono",children:x.key})]})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${x.status==="removed"?"text-red-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:p(x.left)})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${x.status==="added"?"text-green-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:p(x.right)})})]},x.key)})})]})})]})})})}function TZe({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:i}=mn(),s=tn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[u,d]=w.useState(e?.type||"filament"),[h,f]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[p,x]=w.useState(e?.base_id||""),[v,b]=w.useState(""),[y,S]=w.useState(e?.setting||{inherits:""}),[N,A]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[M,T]=w.useState(null),[k,j]=w.useState(""),[E,P]=w.useState(!1),[U,L]=w.useState(""),[B,R]=w.useState(!1),[V,q]=w.useState(Gae),[I,K]=w.useState(!1),[Y,le]=w.useState(""),[H,X]=w.useState(""),[te,J]=w.useState(!0),[Se,fe]=w.useState(null),[me,De]=w.useState(!1),de=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),ce=w.useMemo(()=>de.filter(ke=>mv(ke.setting_id)),[de]),{data:Ne}=tt({queryKey:["cloudFields",u],queryFn:()=>se.getCloudFields(u==="print"?"process":u),staleTime:1e3*60*60}),{data:ie}=tt({queryKey:["allPresetDetails",u,ce.map(ke=>ke.setting_id).join(",")],queryFn:async()=>{const ke={};for(let je=0;je{try{const Pe=await se.getCloudSettingDetail(Je.setting_id);return{id:Je.setting_id,detail:Pe}}catch{return null}}))).forEach(Je=>{Je&&(ke[Je.id]=Je.detail)})}return ke},enabled:ce.length>0,staleTime:1e3*60*10}),{data:Le,isLoading:$}=tt({queryKey:["cloudSettingDetail",p],queryFn:()=>se.getCloudSettingDetail(p),enabled:!!p});w.useEffect(()=>{l!=="json"&&A(JSON.stringify(y,null,2))},[y,l]);const W=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(Ue=>!mv(Ue.setting_id)).sort((Ue,je)=>Ue.name.localeCompare(je.name)),[n,u]);w.useEffect(()=>{if(!p)return;const ke=W.find(Ue=>Ue.setting_id===p);ke&&(b(ke.name),o||(S({inherits:ke.name}),A(JSON.stringify({inherits:ke.name},null,2))))},[p,W,o]);const ue=w.useMemo(()=>{const ke=Ne?.fields||[],Ue=new Set(ke.map(Je=>Je.key)),je=new Set,Ve=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);ie&&Object.values(ie).forEach(Je=>{Je?.setting&&Object.keys(Je.setting).forEach(Pe=>{!Ue.has(Pe)&&!Ve.has(Pe)&&je.add(Pe)})}),Object.keys(y).forEach(Je=>{!Ue.has(Je)&&!Ve.has(Je)&&je.add(Je)});const Ae=Array.from(je).sort().map(Je=>({key:Je,label:Je.replace(/_/g," ").replace(/\b\w/g,Pe=>Pe.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...ke,...Ae]},[Ne,ie,y,r]),Z=ue.filter(ke=>ke.label.toLowerCase().includes(k.toLowerCase())||ke.key.toLowerCase().includes(k.toLowerCase())),oe=()=>{if(U.trim()){const ke=U.trim().toLowerCase().replace(/\s+/g,"_");Q(ke,""),L(""),R(!1),i(r("profiles.presets.toast.fieldAdded",{key:ke}))}},Q=(ke,Ue)=>{S(je=>{const Ve={...je};return Ue===""||Ue===void 0?delete Ve[ke]:Ve[ke]=Ue,Ve})},he=ke=>{S(Ue=>({...Ue,...ke.settings})),fe(ke.name),i(r("profiles.templates.toast.applied"))},be=()=>{if(!Y.trim())return;const ke={...y};if(delete ke.inherits,Object.keys(ke).length===0){i(r("profiles.presets.noOverridesToSave"),"error");return}const Ue={id:Date.now().toString(),name:Y.trim(),description:H.trim()||r("profiles.presets.customTemplate"),type:u,settings:ke,showInModal:te},je=[...V,Ue];q(je),qae(je),K(!1),le(""),X(""),J(!0),i(r("profiles.templates.toast.created"))},ee=w.useMemo(()=>V.filter(ke=>ke.type===u&&ke.showInModal),[u,V]),z=ke=>{A(ke);try{const Ue=JSON.parse(ke);S(Ue),T(null)}catch(Ue){T(Ue.message)}},D=ke=>{ke.preventDefault(),P(!1);const Ue=ke.dataTransfer.files[0];if(Ue&&Ue.name.endsWith(".json")){const je=new FileReader;je.onload=Ve=>{try{const Ae=Ve.target?.result,Je=JSON.parse(Ae),Pe=Je.setting||Je;S(Ye=>({...Ye,...Pe})),A(JSON.stringify({...y,...Pe},null,2)),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJsonFile"),"error")}},je.readAsText(Ue)}},G=lt({mutationFn:()=>{const ke={...y},Ue=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";ke[Ue]=`"${h}"`;const je={type:u,name:h,base_id:p,setting:ke};return se.createCloudSetting(je)},onSuccess:async()=>{i(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:ke=>i(ke.message,"error")}),pe=lt({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return se.updateCloudSetting(e.setting_id,{name:h,setting:y})},onSuccess:async()=>{i(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:ke=>i(ke.message,"error")}),ve=o?pe:G,xe=Le?.setting?.inherits,ze=xe?W.find(ke=>ke.name===xe):void 0,{data:_e}=tt({queryKey:["cloudSettingDetail",ze?.setting_id],queryFn:()=>se.getCloudSettingDetail(ze.setting_id),enabled:!!ze?.setting_id}),He=w.useMemo(()=>{const ke=_e?.setting||{},Ue=Le?.setting||{},je=p&&ie?.[p]?.setting?ie[p].setting:{};return{...ke,...Ue,...je}},[p,Le,_e,ie]),Ze=ke=>{if(ke==null)return"";if(Array.isArray(ke)){const Ue=[...new Set(ke.map(je=>String(je)))];return Ue.length===1?Ue[0]:ke.join(", ")}return String(ke)},we=ke=>{const Ue=y[ke.key],je=He[ke.key],Ve=Ze(je),Ae=$?r("common.loading"):Ve||"",Je="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(ke.type==="boolean"){const Pe=Ue==="1"||Ue===void 0&&je==="1";return a.jsx("button",{type:"button",onClick:()=>Q(ke.key,Ue==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Pe?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Pe?"translate-x-3.5":"translate-x-0.5"}`})})}return ke.type==="select"?a.jsxs("select",{value:Ue||"",onChange:Pe=>Q(ke.key,Pe.target.value),className:Je,children:[a.jsx("option",{value:"",children:Ae}),ke.options?.map(Pe=>a.jsx("option",{value:Pe.value,children:Pe.label},Pe.value))]}):a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:ke.type==="number"?"number":"text",value:Ue!==void 0?String(Ue):"",onChange:Pe=>Q(ke.key,Pe.target.value),step:ke.step,min:ke.min,max:ke.max,placeholder:Ae,className:Je}),ke.unit&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:ke.unit})]})},ye=w.useMemo(()=>Le?.setting?Le.setting:{},[Le]);return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:ke=>{ke.preventDefault(),P(!0)},onDragLeave:()=>P(!1),onDrop:D,children:[me&&p&&a.jsx(Wae,{onClose:()=>De(!1),leftPreset:ye,rightPreset:y,leftLabel:r("profiles.presets.baseLabel",{name:v||p}),rightLabel:r("profiles.presets.currentLabel",{name:h||r("profiles.presets.newPreset")}),t:r}),a.jsx(_t,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:a.jsxs(Nt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[p&&a.jsxs("button",{onClick:()=>De(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:r("profiles.presets.compareWithBase"),children:[a.jsx(Yg,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),a.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Ft,{className:"w-5 h-5"})})]})]}),E&&a.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:a.jsxs("div",{className:"text-center",children:[a.jsx(ia,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),a.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),a.jsxs("select",{value:u,onChange:ke=>{d(ke.target.value),x("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),a.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),a.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),a.jsxs("select",{value:p,onChange:ke=>x(ke.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),W.map(ke=>a.jsx("option",{value:ke.setting_id,children:ke.name},ke.setting_id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),a.jsx("input",{type:"text",value:h,onChange:ke=>f(ke.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("profiles.presets.myCustomPreset")})]})]}),v&&a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("p",{className:"flex items-center gap-1",children:[a.jsx(Xr,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",a.jsx("span",{className:"text-white",children:v}),$&&a.jsx(at,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[a.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(HB,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),a.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(rC,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),a.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(uX,{className:"w-4 h-4"}),"JSON",M&&a.jsx(Bi,{className:"w-3 h-3 text-red-400"})]}),a.jsx("div",{className:"flex-1 max-[640px]:hidden"}),a.jsxs("button",{onClick:()=>{const ke={name:h,type:u,base_id:p,setting:y},Ue=new Blob([JSON.stringify(ke,null,2)],{type:"application/json"}),je=URL.createObjectURL(Ue),Ve=document.createElement("a");Ve.href=je,Ve.download=`${h||"preset"}.json`,document.body.appendChild(Ve),Ve.click(),document.body.removeChild(Ve),URL.revokeObjectURL(je),i(r("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.exportToJson"),children:[a.jsx(di,{className:"w-4 h-4"}),r("common.download")]}),a.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.importFromJson"),children:[a.jsx(ia,{className:"w-4 h-4"}),r("common.upload")]}),a.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:ke=>{const Ue=ke.target.files?.[0];if(Ue){const je=new FileReader;je.onload=Ve=>{try{const Ae=JSON.parse(Ve.target?.result),Je=Ae.setting||Ae;S(Pe=>({...Pe,...Je})),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJson"),"error")}},je.readAsText(Ue)}}})]}),a.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(pb,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(y).filter(ke=>ke!=="inherits").length>0&&a.jsxs("button",{onClick:()=>K(!I),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[a.jsx(bs,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),I&&a.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[a.jsx("input",{type:"text",value:Y,onChange:ke=>le(ke.target.value),placeholder:r("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),a.jsx("input",{type:"text",value:H,onChange:ke=>X(ke.target.value),placeholder:r("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Me,{size:"sm",onClick:be,disabled:!Y.trim(),children:[a.jsx(bs,{className:"w-3 h-3"}),r("common.save")]}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>K(!1),children:r("common.cancel")})]}),a.jsxs("button",{onClick:()=>J(!te),className:`flex items-center gap-1.5 text-xs transition-colors ${te?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[te?a.jsx(Kl,{className:"w-3.5 h-3.5"}):a.jsx(gv,{className:"w-3.5 h-3.5"}),r(te?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Se&&a.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[a.jsx(Xr,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",a.jsx("span",{className:"font-medium",children:Se})]}),a.jsx("button",{onClick:()=>fe(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:a.jsx(Ft,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[ee.map(ke=>a.jsxs("button",{onClick:()=>he(ke),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:ke.name}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:ke.description})]},ke.id)),ee.length===0&&a.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),a.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),a.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:ue.slice(0,10).map(ke=>a.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[a.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:ke.label}),a.jsx("div",{className:"w-48 max-[640px]:w-full",children:we(ke)})]},ke.key))})]}),Object.keys(y).length>1&&a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(y).filter(([ke])=>ke!=="inherits").map(([ke,Ue])=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[ke,": ",String(Ue).slice(0,20),a.jsx("button",{onClick:()=>Q(ke,void 0),className:"hover:text-white",children:a.jsx(Ft,{className:"w-3 h-3"})})]},ke))})]})]}),l==="fields"&&a.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:ie?r("profiles.templates.fieldsCount",{count:ue.length}):r("common.loading")})]}),a.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[a.jsx(Or,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:k,onChange:ke=>j(ke.target.value),placeholder:r("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[Z.filter(ke=>!(ke.key in y)).map(ke=>{const Ue=He[ke.key],je=Ze(Ue);return a.jsxs("div",{onClick:()=>{S(Ve=>({...Ve,[ke.key]:je||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white truncate",children:ke.label}),a.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:ke.key})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[je&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:je,children:[je.slice(0,20),je.length>20?"...":""]}),a.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:a.jsx(ar,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},ke.key)}),Z.filter(ke=>!(ke.key in y)).length===0&&a.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(k?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:B?a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:U,onChange:ke=>L(ke.target.value),onKeyDown:ke=>ke.key==="Enter"&&oe(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),a.jsx(Me,{size:"sm",onClick:oe,disabled:!U.trim(),children:a.jsx(ar,{className:"w-4 h-4"})}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>{R(!1),L("")},children:a.jsx(Ft,{className:"w-4 h-4"})})]}):a.jsxs("button",{onClick:()=>R(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[a.jsx(ar,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(y).filter(ke=>ke!=="inherits").length})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(y).filter(([ke])=>ke!=="inherits").map(([ke,Ue])=>{const je=ue.find(Ve=>Ve.key===ke);return a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium text-white",children:je?.label||ke}),a.jsx("p",{className:"text-xs text-bambu-gray-dark",children:ke})]}),a.jsx("button",{onClick:()=>Q(ke,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:a.jsx(Ft,{className:"w-4 h-4"})})]}),je?we(je):a.jsx("input",{type:"text",value:String(Ue),onChange:Ve=>Q(ke,Ve.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},ke)}),Object.keys(y).filter(ke=>ke!=="inherits").length===0&&a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(HB,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),a.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(y).filter(ke=>ke!=="inherits").length>0&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:a.jsxs("button",{onClick:()=>{K(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[a.jsx(bs,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&a.jsxs("div",{className:"space-y-2",children:[M&&a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Bi,{className:"w-4 h-4"}),M]}),a.jsx("textarea",{value:N,onChange:ke=>z(ke.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${M?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[a.jsx(Me,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsxs(Me,{onClick:()=>ve.mutate(),disabled:ve.isPending||!h.trim()||!o&&!p||!!M,className:"flex-1",children:[ve.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin"}):o?a.jsx(bs,{className:"w-4 h-4"}):a.jsx(ar,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function EZe({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:i,hasPermission:s,t:o}){const[l,c]=w.useState(""),[u,d]=w.useState("all"),[h,f]=w.useState("all"),[p,x]=w.useState("all"),[v,b]=w.useState("all"),[y,S]=w.useState("all"),[N,A]=w.useState("all"),[M,T]=w.useState(null),[k,j]=w.useState(!1),[E,P]=w.useState(!1),[U,L]=w.useState(null),[B,R]=w.useState(null),[V,q]=w.useState(null),[I,K]=w.useState(!1),[Y,le]=w.useState([null,null]),[H,X]=w.useState(!1),[te,J]=w.useState(null),Se=tn(),fe=w.useMemo(()=>[...t.filament.map(oe=>({...oe,type:"filament"})),...t.printer.map(oe=>({...oe,type:"printer"})),...t.process.map(oe=>({...oe,type:"process"}))].map(oe=>({...oe,meta:bI(oe.name)})),[t]),me=w.useMemo(()=>{const Z=new Set,oe=new Set,Q=new Set;return fe.forEach(he=>{he.meta.nozzle&&Z.add(he.meta.nozzle),he.meta.filamentType&&oe.add(he.meta.filamentType),he.meta.layerHeight&&Q.add(he.meta.layerHeight)}),{printers:i.map(he=>({id:he.id.toString(),name:he.name})),nozzles:Array.from(Z).sort((he,be)=>parseFloat(he)-parseFloat(be)),filaments:Array.from(oe).sort(),layerHeights:Array.from(Q).sort((he,be)=>parseFloat(he)-parseFloat(be))}},[fe,i]),De=w.useMemo(()=>p==="all"?null:i.find(oe=>oe.id.toString()===p)?.model||null,[p,i]),de=w.useMemo(()=>fe.filter(Z=>u==="all"||Z.type===u).filter(Z=>{if(h==="all")return!0;const oe=mv(Z.setting_id);return h==="custom"?oe:!oe}).filter(Z=>{if(p==="all"||!De)return!0;const oe=Z.meta.printer?.toLowerCase()||"",Q=De.toLowerCase();return oe.includes(Q)||Q.includes(oe)}).filter(Z=>v==="all"||Z.meta.nozzle===v).filter(Z=>y==="all"||Z.meta.filamentType===y).filter(Z=>N==="all"||Z.meta.layerHeight===N).filter(Z=>l===""||Z.name.toLowerCase().includes(l.toLowerCase())).sort((Z,oe)=>Z.name.localeCompare(oe.name)),[fe,u,h,p,De,v,y,N,l]),ce=Z=>{if(I){const oe=Y[0]?.setting_id===Z.setting_id,Q=Y[1]?.setting_id===Z.setting_id;if(oe)le([Y[1],null]);else if(Q)le([Y[0],null]);else if(!Y[0])le([Z,null]);else if(Y[1]){if(Y[0].type!==Z.type)return;le([Y[0],Z])}else{if(Y[0].type!==Z.type)return;le([Y[0],Z])}}else T(Z)},Ne=Z=>{if(Y[0]?.setting_id===Z.setting_id)return 0;if(Y[1]?.setting_id===Z.setting_id)return 1},ie=async Z=>{try{const oe=await se.getCloudSettingDetail(Z.setting_id),Q=Z.type==="process"?"print":Z.type;L({type:Q,name:Z.name,base_id:oe.base_id||"GFSA00",setting:oe.setting||{}}),T(null)}catch(oe){console.error("Failed to fetch preset details for duplication:",oe)}},Le=async Z=>{try{Se.removeQueries({queryKey:["cloudSettingDetail",Z.setting_id]});const oe=await se.getCloudSettingDetail(Z.setting_id),Q=Z.type==="process"?"print":Z.type;R({type:Q,name:Z.name,base_id:oe.base_id||"GFSA00",setting:oe.setting||{},setting_id:Z.setting_id}),T(null)}catch(oe){console.error("Failed to fetch preset details for editing:",oe)}},$=()=>{d("all"),f("all"),x("all"),b("all"),S("all"),A("all"),c("")},W=u!=="all"||h!=="all"||p!=="all"||v!=="all"||y!=="all"||N!=="all"||l!=="",ue=t.filament.length+t.printer.length+t.process.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"space-y-4 mb-6",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Or,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:l,onChange:Z=>c(Z.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[a.jsxs(Me,{variant:I?"primary":"secondary",onClick:()=>{I?(K(!1),le([null,null])):K(!0)},children:[a.jsx(Yg,{className:"w-4 h-4"}),o(I?"common.cancel":"profiles.presets.compare")]}),a.jsxs(Me,{variant:"secondary",onClick:()=>P(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[a.jsx(pb,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),a.jsxs(Me,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[a.jsx(kr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),a.jsxs(Me,{onClick:()=>j(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[a.jsx(ar,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(tC,{className:"w-4 h-4 text-bambu-gray"}),a.jsx(jg,{label:o("profiles.cloudView.filters.type"),value:u,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:ue},{value:"filament",label:o("profiles.cloudView.filters.filament"),count:t.filament.length},{value:"printer",label:o("profiles.cloudView.filters.printer"),count:t.printer.length},{value:"process",label:o("profiles.cloudView.filters.process"),count:t.process.length}],onChange:Z=>d(Z)}),a.jsx(jg,{label:o("profiles.cloudView.filters.owner"),value:h,options:[{value:"all",label:o("profiles.cloudView.filters.all")},{value:"custom",label:o("profiles.cloudView.filters.myPresets")},{value:"builtin",label:o("profiles.cloudView.filters.builtIn")}],onChange:Z=>f(Z)}),me.printers.length>0&&a.jsx(jg,{label:o("profiles.cloudView.filters.printer"),value:p,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...me.printers.map(Z=>({value:Z.id,label:Z.name}))],onChange:x}),me.nozzles.length>0&&a.jsx(jg,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...me.nozzles.map(Z=>({value:Z,label:Z}))],onChange:b}),me.filaments.length>0&&(u==="all"||u==="filament")&&a.jsx(jg,{label:o("profiles.cloudView.filters.filament"),value:y,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...me.filaments.map(Z=>({value:Z,label:Z}))],onChange:S}),me.layerHeights.length>0&&(u==="all"||u==="process")&&a.jsx(jg,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...me.layerHeights.map(Z=>({value:Z,label:Z}))],onChange:A}),W&&a.jsx("button",{onClick:$,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),I&&a.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(Yg,{className:"w-5 h-5 text-blue-400"}),a.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),a.jsx("span",{className:"text-bambu-gray",children:Y[0]?o("profiles.cloudView.selectAnotherPreset",{type:Y[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${Y[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Y[0]?Y[0].name:o("profiles.cloudView.selectFirst")}),a.jsx(d3,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${Y[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Y[1]?Y[1].name:o("profiles.cloudView.selectSecond")})]}),Y[0]&&Y[1]&&a.jsxs(Me,{size:"sm",onClick:async()=>{try{const[Z,oe]=await Promise.all([se.getCloudSettingDetail(Y[0].setting_id),se.getCloudSettingDetail(Y[1].setting_id)]);J([Z.setting||{},oe.setting||{}]),X(!0)}catch{}},children:[a.jsx(Yg,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),a.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(Qn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",NZe(e.toISOString(),o)]}),a.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:de.length,total:ue})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),a.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),de.length===0?a.jsxs("div",{className:"text-center py-16",children:[a.jsx(rs,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),a.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),W&&a.jsx("button",{onClick:$,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Jk,{className:"w-4 h-4 text-amber-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",de.filter(Z=>Z.type==="filament").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[de.filter(Z=>Z.type==="filament").map(Z=>a.jsx($j,{setting:Z,onClick:()=>ce(Z),onDuplicate:()=>ie(Z),compareMode:I,isCompareSelected:Ne(Z)!==void 0,compareIndex:Ne(Z),compareDisabled:I&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),de.filter(Z=>Z.type==="filament").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(td,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",de.filter(Z=>Z.type==="process").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[de.filter(Z=>Z.type==="process").map(Z=>a.jsx($j,{setting:Z,onClick:()=>ce(Z),onDuplicate:()=>ie(Z),compareMode:I,isCompareSelected:Ne(Z)!==void 0,compareIndex:Ne(Z),compareDisabled:I&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),de.filter(Z=>Z.type==="process").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Cr,{className:"w-4 h-4 text-purple-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",de.filter(Z=>Z.type==="printer").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[de.filter(Z=>Z.type==="printer").map(Z=>a.jsx($j,{setting:Z,onClick:()=>ce(Z),onDuplicate:()=>ie(Z),compareMode:I,isCompareSelected:Ne(Z)!==void 0,compareIndex:Ne(Z),compareDisabled:I&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),de.filter(Z=>Z.type==="printer").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),M&&a.jsx(MZe,{setting:M,onClose:()=>T(null),onDeleted:()=>T(null),onDuplicate:()=>ie(M),onEdit:()=>Le(M),hasPermission:s,t:o}),(k||U||B||V)&&a.jsx(TZe,{onClose:()=>{j(!1),L(null),R(null),q(null)},initialData:B||U||(V?{type:V.type,name:"",base_id:"",setting:V.setting}:void 0),allPresets:t,t:o}),E&&a.jsx(AZe,{onClose:()=>P(!1),onApply:Z=>{q({type:Z.type,setting:Z.settings}),P(!1)},t:o}),H&&te&&Y[0]&&Y[1]&&a.jsx(Wae,{onClose:()=>{X(!1),J(null)},leftPreset:te[0],rightPreset:te[1],leftLabel:Y[0].name,rightLabel:Y[1].name,t:o})]})}function PZe(){const{t}=Vt(),e=tn(),{showToast:n}=mn(),{hasPermission:r}=Ir(),[i,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:u}=tt({queryKey:["cloudStatus"],queryFn:se.getCloudStatus}),{data:d=[]}=tt({queryKey:["printers"],queryFn:se.getPrinters}),{data:h,isLoading:f,refetch:p,dataUpdatedAt:x}=tt({queryKey:["cloudSettings"],queryFn:()=>se.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{x&&l(new Date(x))},[x]);const v=lt({mutationFn:se.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return u?a.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"p-6 lg:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[a.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(Gb,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),a.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(qb,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),a.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(nC,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&a.jsxs(a.Fragment,{children:[c?.is_authenticated&&a.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",a.jsx("span",{className:"text-white",children:c.email})]})]}),a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[a.jsx(b3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?f?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?a.jsx(EZe,{settings:h,lastSyncTime:o,onRefresh:()=>p(),isRefreshing:f,printers:d,hasPermission:r,t}):a.jsxs("div",{className:"text-center py-16",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),a.jsx(Me,{onClick:()=>p(),children:t("profiles.retry")})]}):a.jsx(kZe,{onSuccess:b,t})]}),i==="local"&&a.jsx(SZe,{}),i==="kprofiles"&&a.jsx(yZe,{}),a.jsx(CZe,{})]})}const Ky={Droplet:Jk,Flame:Xhe,Ruler:Mfe,Sparkles:pb,Square:gl,Cable:Rde,Wrench:Rf,Calendar:ii,Timer:Ou,Cog:xhe,Fan:dX,Zap:Gh,Wind:wX,Thermometer:cC,Layers:rs,Box:Qi,Target:yX,RefreshCw:kr,Settings:lC,Filter:tC,CircleDot:the};function x0(t){return t&&Ky[t]||Rf}function Dg(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return n?n("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:i}):`${i} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const i=r/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function Vj(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function jZe(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),i=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),u=n.includes("H2S"),d=l||c||u,h=n.includes("P2S");switch(t){case"Lubricate Carbon Rods":return r?"https://wiki.bambulab.com/en/x1/maintenance/basic-maintenance":i?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||i?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":d?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":h?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return r?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":i?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":u?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||i||h?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return r||i?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":u?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return d?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}function DZe({item:t,onPerform:e,onToggle:n,hasPermission:r,t:i}){const s=x0(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const p=t.days_since_maintenance??0;return Math.max(0,Math.min(100,p/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),u=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",d=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",h=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",f=()=>{if(!t.enabled)return i("common.disabled");if(o==="days"){const p=t.days_until_due??0;return t.is_due?i("maintenance.overdueBy",{duration:Dg(Math.abs(p),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:Dg(p,"days",i)}):i("maintenance.timeLeft",{duration:Dg(p,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:Dg(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:Dg(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:Dg(t.hours_until_due,"hours",i)})};return a.jsx("div",{className:`rounded-xl border p-4 transition-all ${h()}`,children:a.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[a.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[a.jsx(s,{className:`w-5 h-5 ${u()}`}),t.enabled&&(t.is_due||t.is_warning)&&a.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&a.jsx("span",{title:i("maintenance.timeBasedInterval"),children:a.jsx(ii,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const p=t.maintenance_type_wiki_url||jZe(t.maintenance_type_name,t.printer_model);return p?a.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:i("maintenance.viewDocumentation"),onClick:x=>x.stopPropagation(),children:a.jsx(Kr,{className:"w-3.5 h-3.5"})}):null})()]}),a.jsx("div",{className:"mt-2 mb-1.5",children:a.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${d()}`,style:{width:`${c}%`}})})}),a.jsxs("div",{className:`text-xs flex items-center gap-1 ${u()}`,children:[t.is_due&&a.jsx(Cn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&a.jsx(Qn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&a.jsx(Xr,{className:"w-3 h-3"}),f()]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[a.jsx("span",{title:r("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:a.jsx(zn,{checked:t.enabled,onChange:p=>n(t.id,p),disabled:!r("maintenance:update")})}),a.jsxs(Me,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[a.jsx(Do,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function RZe({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:i,t:s}){const[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(t.total_print_hours.toFixed(1)),f=[...t.maintenance_items].sort((v,b)=>v.is_due&&!b.is_due?-1:!v.is_due&&b.is_due?1:v.is_warning&&!b.is_warning?-1:!v.is_warning&&b.is_warning?1:v.maintenance_type_id-b.maintenance_type_id),p=f.find(v=>v.enabled&&(v.is_due||v.is_warning)),x=()=>{const v=parseFloat(d);!isNaN(v)&&v>=0&&(r(t.printer_id,v),u(!1))};return a.jsxs(_t,{className:"overflow-hidden",children:[a.jsxs("div",{className:"p-5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&a.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[a.jsx(Cn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&a.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[a.jsx(Qn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&a.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[a.jsx(Xr,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),a.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?a.jsx(ql,{className:"w-4 h-4"}):a.jsx(nr,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),a.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:a.jsx(Ou,{className:"w-4 h-4 text-bambu-gray"})}),c?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",value:d,onChange:v=>h(v.target.value),onKeyDown:v=>{v.key==="Enter"&&x(),v.key==="Escape"&&u(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),a.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),a.jsx(Me,{size:"sm",onClick:x,children:s("common.save")}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>u(!1),children:s("common.cancel")})]}):a.jsxs("button",{onClick:()=>{i("maintenance:update")&&(h(Math.round(t.total_print_hours).toString()),u(!0))},className:`group ${i("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:i("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[a.jsxs("div",{className:`text-sm font-medium text-white ${i("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),a.jsx(Pf,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),a.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),a.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),p&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${p.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=x0(p.maintenance_type_icon);return a.jsx(v,{className:`w-4 h-4 ${p.is_due?"text-red-400":"text-amber-400"}`})})()}),a.jsxs("div",{children:[a.jsx("div",{className:`text-sm font-medium ${p.is_due?"text-red-400":"text-amber-400"}`,children:p.maintenance_type_name}),a.jsx("div",{className:`text-xs ${p.is_due?"text-red-400/70":"text-amber-400/70"}`,children:p.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&a.jsx(Nt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:a.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:f.map(v=>a.jsx(DZe,{item:v,onPerform:e,onToggle:n,hasPermission:i,t:s},v.id))})})]})}function FZe({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:u,hasPermission:d,t:h}){const[f,p]=w.useState(null),[x,v]=w.useState(""),[b,y]=w.useState("hours"),[S,N]=w.useState(!1),[A,M]=w.useState(""),[T,k]=w.useState("100"),[j,E]=w.useState("hours"),[P,U]=w.useState("Wrench"),[L,B]=w.useState(""),[R,V]=w.useState(new Set),[q,I]=w.useState(null),[K,Y]=w.useState(null),le=w.useMemo(()=>t?t.map(z=>({id:z.printer_id,name:z.printer_name})):[],[t]),H=z=>t?t.filter(D=>D.maintenance_items.some(G=>G.maintenance_type_id===z)).map(D=>({printerId:D.printer_id,printerName:D.printer_name,itemId:D.maintenance_items.find(G=>G.maintenance_type_id===z)?.id})):[],X=z=>{if(!t)return[];const D=new Set(H(z).map(G=>G.printerId));return le.filter(G=>!D.has(G.id))},[te,J]=w.useState(null),[Se,fe]=w.useState(""),[me,De]=w.useState(""),[de,ce]=w.useState("hours"),[Ne,ie]=w.useState("Wrench"),[Le,$]=w.useState(""),W=z=>{J(z),fe(z.name),De(z.default_interval_hours.toString()),ce(z.interval_type||"hours"),ie(z.icon||"Wrench"),$(z.wiki_url||"")},ue=()=>{te&&Se.trim()&&parseFloat(me)>0&&(i(te.id,{name:Se.trim(),default_interval_hours:parseFloat(me),interval_type:de,icon:Ne,wiki_url:Le.trim()||null}),J(null))},Z=(z,D,G)=>{const pe=parseFloat(x);if(!isNaN(pe)&&pe>0){const ve=Math.abs(pe-D)<.01?null:pe;n(z,{custom_interval_hours:ve,custom_interval_type:b!==G?b:null})}p(null)},oe=z=>{z.preventDefault(),A.trim()&&parseFloat(T)>0&&R.size>0&&(r({name:A.trim(),default_interval_hours:parseFloat(T),interval_type:j,icon:P,wiki_url:L.trim()||null},Array.from(R)),M(""),k("100"),E("hours"),B(""),V(new Set),N(!1))},Q=z=>{V(D=>{const G=new Set(D);return G.has(z)?G.delete(z):G.add(z),G})},he=t?.map(z=>({printerId:z.printer_id,printerName:z.printer_name,items:z.maintenance_items.sort((D,G)=>D.maintenance_type_id-G.maintenance_type_id)})).sort((z,D)=>z.printerName.localeCompare(D.printerName))||[],be=e.filter(z=>z.is_system),ee=e.filter(z=>!z.is_system);return a.jsxs("div",{className:"space-y-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:h("maintenance.maintenanceTypes")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:h("maintenance.maintenanceTypesDescription")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Me,{variant:"secondary",onClick:o,disabled:!d("maintenance:delete")||l,title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),children:h("maintenance.restoreDefaults")}),a.jsxs(Me,{onClick:()=>N(!S),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionEditTypes"),children:[a.jsx(ar,{className:"w-4 h-4"}),h("maintenance.addCustomType")]})]})]}),S&&a.jsx(_t,{className:"mb-6",children:a.jsx(Nt,{className:"py-4",children:a.jsxs("form",{onSubmit:oe,children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"lg:col-span-2",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("common.name")}),a.jsx("input",{type:"text",value:A,onChange:z=>M(z.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("maintenance.exampleName"),autoFocus:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.intervalType")}),a.jsxs("select",{value:j,onChange:z=>{E(z.target.value),z.target.value==="days"?k("30"):k("100")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"hours",children:h("maintenance.printHours")}),a.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.intervalValue",{type:j==="days"?h("maintenance.calendarDays").toLowerCase():h("common.hours")})}),a.jsx("input",{type:"number",value:T,onChange:z=>k(z.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),a.jsx("div",{className:"mt-4 flex items-end justify-between",children:a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.icon")}),a.jsx("div",{className:"flex gap-1",children:Object.keys(Ky).map(z=>{const D=Ky[z];return a.jsx("button",{type:"button",onClick:()=>U(z),className:`p-2 rounded-lg transition-colors ${P===z?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:a.jsx(D,{className:"w-4 h-4"})},z)})})]})}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.documentationLink")}),a.jsx("input",{type:"url",value:L,onChange:z=>B(z.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.assignToPrinters")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:le.map(z=>a.jsx("button",{type:"button",onClick:()=>Q(z.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${R.has(z.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:z.name},z.id))}),R.size===0&&a.jsx("p",{className:"text-xs text-orange-400 mt-1",children:h("maintenance.selectAtLeastOnePrinter")})]}),a.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:()=>{N(!1),V(new Set)},children:h("common.cancel")}),a.jsx(Me,{type:"submit",disabled:!A.trim()||R.size===0,children:h("maintenance.addType")})]})]})})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[be.map(z=>{const D=x0(z.icon),G=z.interval_type||"hours";return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:a.jsx(D,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-sm font-medium text-white truncate",children:z.name}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[G==="days"?a.jsx(ii,{className:"w-3 h-3"}):a.jsx(Ou,{className:"w-3 h-3"}),Vj(z.default_interval_hours,G,h)]})]}),a.jsx("button",{onClick:()=>{d("maintenance:delete")&&Y(z)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(en,{className:"w-4 h-4"})})]})},z.id)}),ee.map(z=>{const D=x0(z.icon),G=z.interval_type||"hours";if(te?.id===z.id)return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:a.jsxs("div",{className:"space-y-3",children:[a.jsx("input",{type:"text",value:Se,onChange:_e=>fe(_e.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("common.name"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:de,onChange:_e=>ce(_e.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"hours",children:h("maintenance.printHours")}),a.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:me,onChange:_e=>De(_e.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(Ky).map(_e=>{const He=Ky[_e];return a.jsx("button",{type:"button",onClick:()=>ie(_e),className:`p-1.5 rounded transition-colors ${Ne===_e?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a.jsx(He,{className:"w-3.5 h-3.5"})},_e)})}),a.jsx("input",{type:"url",value:Le,onChange:_e=>$(_e.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("maintenance.documentationLink")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Me,{size:"sm",onClick:ue,disabled:!Se.trim(),children:h("common.save")}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>J(null),children:h("common.cancel")})]})]})},z.id);const ve=H(z.id),xe=X(z.id),ze=q===z.id;return a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:a.jsx(D,{className:"w-5 h-5 text-bambu-green"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-white truncate",children:z.name}),a.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:h("maintenance.custom")})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[G==="days"?a.jsx(ii,{className:"w-3 h-3"}):a.jsx(Ou,{className:"w-3 h-3"}),Vj(z.default_interval_hours,G,h)]})]}),a.jsxs("button",{onClick:()=>I(ze?null:z.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${ve.length>0?"border-bambu-green/50 bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20":"border-orange-400/50 bg-orange-400/10 text-orange-400 hover:bg-orange-400/20"}`,title:h("maintenance.printersAssignedClick",{count:ve.length}),children:[a.jsx(Cr,{className:"w-3 h-3"}),a.jsx("span",{className:"text-xs font-medium",children:ve.length}),a.jsx(nr,{className:`w-3 h-3 transition-transform ${ze?"rotate-180":""}`})]}),a.jsx("button",{onClick:()=>W(z),disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:h("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${d("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(Pf,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{confirm(h("maintenance.deleteTypeConfirm",{name:z.name}))&&s(z.id)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(en,{className:"w-4 h-4"})})]}),ze&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:h("maintenance.assignedToPrinters")}),ve.length===0?a.jsx("p",{className:"text-xs text-orange-400",children:h("maintenance.noPrintersAssigned")}):a.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:ve.map(_e=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[_e.printerName,a.jsx("button",{onClick:()=>_e.itemId&&u(_e.itemId),disabled:!d("maintenance:delete"),title:d("maintenance:delete")?h("maintenance.removeFromPrinter"):h("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${d("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},_e.printerId))}),xe.length>0&&a.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:h("maintenance.addPrinterShort")}),xe.map(_e=>a.jsxs("button",{onClick:()=>c(_e.id,z.id),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${d("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",_e.name]},_e.id))]})]})]},z.id)})]})]}),he.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:h("maintenance.intervalOverrides")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:h("maintenance.intervalOverridesDescription")})]}),a.jsx("div",{className:"space-y-4",children:he.map(z=>a.jsx(_t,{children:a.jsxs(Nt,{className:"py-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:z.printerName}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:z.items.map(D=>{const G=x0(D.maintenance_type_icon),pe=e.find(He=>He.id===D.maintenance_type_id),ve=pe?.default_interval_hours||D.interval_hours,xe=pe?.interval_type||"hours",ze=D.interval_type||"hours",_e=f===D.id;return a.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[a.jsx(G,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:D.maintenance_type_name}),_e?a.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?a.jsx(ii,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):a.jsx(Ou,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),a.jsxs("select",{value:b,onChange:He=>y(He.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[a.jsx("option",{value:"hours",children:h("maintenance.printHours")}),a.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:x,onChange:He=>v(He.target.value),onKeyDown:He=>{He.key==="Enter"&&Z(D.id,ve,xe),He.key==="Escape"&&p(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),a.jsx(Me,{size:"sm",onClick:()=>Z(D.id,ve,xe),children:"OK"})]}):a.jsxs("button",{onClick:()=>{d("maintenance:update")&&(p(D.id),v(D.interval_hours.toString()),y(ze))},disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:h("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${d("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[ze==="days"?a.jsx(ii,{className:"w-3 h-3"}):a.jsx(Ou,{className:"w-3 h-3"}),Vj(D.interval_hours,ze,h),a.jsx(Pf,{className:"w-3 h-3 text-bambu-gray"})]})]},D.id)})})]})},z.printerId))})]}),he.length===0&&a.jsx(_t,{children:a.jsxs(Nt,{className:"text-center py-12",children:[a.jsx(Qn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-bambu-gray",children:h("common.noPrinters")}),a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:h("maintenance.intervalOverridesDescription")})]})}),K&&a.jsx(kn,{title:h("maintenance.deleteSystemTypeTitle"),message:h("maintenance.deleteSystemTypeMessage",{name:K.name}),confirmText:h("common.delete"),cancelText:h("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(K.id),Y(null)},onCancel:()=>Y(null)})]})}function LZe(){const{t}=Vt(),e=tn(),{showToast:n}=mn(),{hasPermission:r}=Ir(),[i,s]=w.useState("status"),{data:o,isLoading:l}=tt({queryKey:["maintenanceOverview"],queryFn:se.getMaintenanceOverview}),{data:c}=tt({queryKey:["maintenanceTypes"],queryFn:se.getMaintenanceTypes}),u=lt({mutationFn:({id:T,notes:k})=>se.performMaintenance(T,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:T=>{n(T.message,"error")}}),d=lt({mutationFn:({id:T,data:k})=>se.updateMaintenanceItem(T,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:T=>{n(T.message,"error")}}),h=lt({mutationFn:({id:T,data:k})=>se.updateMaintenanceType(T,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:T=>{n(T.message,"error")}}),f=lt({mutationFn:se.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:T=>{n(T.message,"error")}}),p=lt({mutationFn:se.restoreDefaultMaintenanceTypes,onSuccess:T=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:T.restored}))},onError:T=>{n(T.message,"error")}}),x=lt({mutationFn:({printerId:T,hours:k})=>se.setPrinterHours(T,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:T=>{n(T.message,"error")}}),v=lt({mutationFn:({printerId:T,typeId:k})=>se.assignMaintenanceType(T,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:T=>{n(T.message,"error")}}),b=lt({mutationFn:se.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:T=>{n(T.message,"error")}}),y=T=>{u.mutate({id:T})},S=(T,k)=>{d.mutate({id:T,data:{enabled:k}})},N=(T,k)=>{x.mutate({printerId:T,hours:k})};if(l)return a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})});const A=o?.reduce((T,k)=>T+k.due_count,0)||0,M=o?.reduce((T,k)=>T+k.warning_count,0)||0;return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:i==="status"?a.jsxs(a.Fragment,{children:[A>0&&a.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:A})}),A>0&&M>0&&" · ",M>0&&a.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:M})}),A===0&&M===0&&a.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),a.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),a.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),i==="status"?a.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((T,k)=>{const j=T.due_count*10+T.warning_count,E=k.due_count*10+k.warning_count;return j!==E?E-j:T.printer_name.localeCompare(k.printer_name)}).map(T=>a.jsx(RZe,{overview:T,onPerform:y,onToggle:S,onSetHours:N,hasPermission:r,t},T.printer_id)):a.jsx(_t,{children:a.jsxs(Nt,{className:"text-center py-16",children:[a.jsx(Rf,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):a.jsx(FZe,{overview:o,types:c||[],onUpdateInterval:(T,k)=>d.mutate({id:T,data:k}),onAddType:async(T,k)=>{const j=await se.createMaintenanceType(T);for(const E of k)await se.assignMaintenanceType(E,j.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(T,k)=>h.mutate({id:T,data:k}),onDeleteType:T=>f.mutate(T),onRestoreDefaults:()=>p.mutate(),isRestoringDefaults:p.isPending,onAssignType:(T,k)=>v.mutate({printerId:T,typeId:k}),onRemoveItem:T=>b.mutate(T),hasPermission:r,t})]})}const cK=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Kae({project:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=w.useState(t?.name||""),[l,c]=w.useState(t?.description||""),[u,d]=w.useState(t?.color||cK[0]),[h,f]=w.useState(t?.target_count?.toString()||""),[p,x]=w.useState(t?.target_parts_count?.toString()||""),[v,b]=w.useState(t?.status||"active"),[y,S]=w.useState(t?.tags||""),[N,A]=w.useState(t?.due_date?.split("T")[0]||""),[M,T]=w.useState(t?.priority||"normal"),k=j=>{j.preventDefault(),n({name:s.trim(),description:l.trim()||void 0,color:u,target_count:h?parseInt(h,10):void 0,target_parts_count:p?parseInt(p,10):void 0,tags:y.trim()||void 0,due_date:N||void 0,priority:M,...t&&{status:v}})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i(t?"projects.editProject":"projects.newProject")})}),a.jsxs("form",{onSubmit:k,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("common.name")}),a.jsx("input",{type:"text",value:s,onChange:j=>o(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("projects.namePlaceholder"),required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("common.description")}),a.jsx("textarea",{value:l,onChange:j=>c(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:i("projects.descriptionPlaceholder"),rows:2})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("projects.color")}),a.jsx("div",{className:"flex gap-2 flex-wrap",children:cK.map(j=>a.jsx("button",{type:"button",onClick:()=>d(j),className:`w-8 h-8 rounded-full transition-transform ${u===j?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:j}},j))})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("projects.targetPlates")}),a.jsx("input",{type:"number",value:h,onChange:j=>f(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("projects.targetPlatesPlaceholder"),min:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("projects.targetPlatesHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("projects.targetParts")}),a.jsx("input",{type:"number",value:p,onChange:j=>x(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("projects.targetPartsPlaceholder"),min:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("projects.targetPartsHelp")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("projects.tagsLabel")}),a.jsx("input",{type:"text",value:y,onChange:j=>S(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("projects.tagsPlaceholder")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("projects.dueDate")}),a.jsx("input",{type:"date",value:N,onChange:j=>A(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("projects.priority")}),a.jsxs("select",{value:M,onChange:j=>T(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"low",children:i("projects.priorityLow")}),a.jsx("option",{value:"normal",children:i("projects.priorityNormal")}),a.jsx("option",{value:"high",children:i("projects.priorityHigh")}),a.jsx("option",{value:"urgent",children:i("projects.priorityUrgent")})]})]})]}),t&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("common.status")}),a.jsxs("select",{value:v,onChange:j=>b(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"active",children:i("projects.statusActive")}),a.jsx("option",{value:"completed",children:i("projects.statusCompleted")}),a.jsx("option",{value:"archived",children:i("projects.statusArchived")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Me,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(at,{className:"w-4 h-4 animate-spin"}):i(t?"common.save":"projects.create")})]})]})]})})}function OZe({project:t,onClick:e,onEdit:n,onDelete:r,hasPermission:i,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",u=t.status==="archived",[d,h]=w.useState(!1),p=c?{icon:fb,color:"text-bambu-green",bg:"bg-bambu-green/10"}:u?{icon:Rs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Qn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:xs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return a.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[a.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),a.jsxs("div",{className:"p-5 pl-6",children:[a.jsxs("div",{className:"flex items-start justify-between mb-4",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg ${p.bg} flex-shrink-0`,children:a.jsx(p.icon,{className:`w-5 h-5 ${p.color}`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?a.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?a.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?a.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&a.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),u&&a.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const x=t.archives.map(S=>S.filament_type).filter(Boolean).flatMap(S=>S.split(",").map(N=>N.trim())).filter(Boolean),v=[...new Set(x)],b=t.archives.map(S=>S.filament_color).filter(Boolean).flatMap(S=>S.split(",").map(N=>N.trim())).filter(S=>S.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(S)),y=[...new Set(b)];return v.length===0&&y.length===0?null:a.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(S=>a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:S},S)),y.length>0&&a.jsxs("div",{className:"flex items-center gap-0.5",children:[y.slice(0,5).map(S=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:S.startsWith("#")?S:`#${S}`},title:S},S)),y.length>5&&a.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",y.length-5]})]})]})})()]})]}),a.jsxs("div",{className:"relative",onClick:x=>x.stopPropagation(),children:[a.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>h(!d),children:a.jsx(Ah,{className:"w-4 h-4"})}),d&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>h(!1)}),a.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[a.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:update")&&(n(),h(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[a.jsx(Pf,{className:"w-4 h-4"}),s("common.edit")]}),a.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:delete")&&(r(),h(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[a.jsx(en,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),a.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?a.jsxs("div",{className:"space-y-3",children:[t.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),a.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),a.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&a.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?a.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(Rs,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[a.jsx(Cn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[a.jsx(Qn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):a.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(x=>a.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:x.print_name||"Unknown",children:[x.thumbnail_path?a.jsx("img",{src:se.getArchiveThumbnail(x.id),alt:x.print_name||"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:a.jsx(ma,{className:"w-6 h-6"})}),x.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:a.jsx(Cn,{className:"w-4 h-4 text-white"})})]},x.id))}),t.archive_count>4&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),a.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[a.jsx(rs,{className:"w-3.5 h-3.5 text-blue-400"}),a.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[a.jsx(ma,{className:"w-3.5 h-3.5 text-bambu-green"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[a.jsx(Cn,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[a.jsx(g3,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.queue_count})]})]}),a.jsx(fa,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function IZe(){const{t}=Vt(),e=Hc(),n=tn(),{showToast:r}=mn(),{hasPermission:i}=Ir(),[s,o]=w.useState(!1),[l,c]=w.useState(),[u,d]=w.useState("active"),[h,f]=w.useState(null),{data:p,isLoading:x}=tt({queryKey:["projects",u==="all"?void 0:u],queryFn:()=>se.getProjects(u==="all"?void 0:u)}),v=lt({mutationFn:B=>se.createProject(B),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:B=>{r(B.message,"error")}}),b=lt({mutationFn:({id:B,data:R})=>se.updateProject(B,R),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:B=>{r(B.message,"error")}}),y=lt({mutationFn:B=>se.deleteProject(B),onSuccess:()=>{f(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:B=>{f(null),r(B.message,"error")}}),S=lt({mutationFn:B=>se.importProject(B),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:B=>{r(B.message,"error")}}),N=w.useRef(null),A=async()=>{try{const B=await se.getProjects(),R=await Promise.all(B.map(async K=>await se.exportProjectJson(K.id))),V=new Blob([JSON.stringify(R,null,2)],{type:"application/json"}),q=URL.createObjectURL(V),I=document.createElement("a");I.href=q,I.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,I.click(),URL.revokeObjectURL(q),r(t("projects.toast.exported"),"success")}catch(B){r(B.message,"error")}},M=()=>{N.current?.click()},T=async B=>{const R=B.target.files?.[0];if(R){try{if(R.name.toLowerCase().endsWith(".zip"))await se.importProjectFile(R),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const q=await R.text(),I=JSON.parse(q),K=Array.isArray(I)?I:[I];for(const Y of K)await S.mutateAsync(Y);K.length>1&&r(t("projects.toast.multipleImported",{count:K.length}),"success")}}catch(V){r(`${t("projects.toast.importFailed")}: ${V.message}`,"error")}B.target.value=""}},k=B=>{l?b.mutate({id:l.id,data:B}):v.mutate(B)},j=B=>{c(B),o(!0)},E=B=>{e(`/projects/${B.id}`)},P=B=>{f(B)},U=()=>{h!==null&&y.mutate(h)},L=p?.reduce((B,R)=>(B[R.status]=(B[R.status]||0)+1,B.all=(B.all||0)+1,B),{})||{};return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:T,className:"hidden"}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(xs,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Me,{variant:"secondary",onClick:M,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[a.jsx(ia,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),a.jsxs(Me,{variant:"secondary",onClick:A,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[a.jsx(di,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),a.jsxs(Me,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(ar,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),a.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Qn},{key:"completed",label:t("projects.statusCompleted"),icon:fb},{key:"archived",label:t("projects.statusArchived"),icon:Rs},{key:"all",label:t("common.all"),icon:xs}].map(({key:B,label:R,icon:V})=>a.jsxs("button",{onClick:()=>d(B),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===B?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[a.jsx(V,{className:"w-4 h-4"}),a.jsx("span",{children:R}),L[B]>0&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===B?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[B]})]},B))}),x?a.jsx("div",{className:"flex items-center justify-center py-20",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(at,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):p?.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(xs,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:u==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:u})}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:u==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:u})}),u==="all"&&a.jsxs(Me,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(ar,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:p?.map(B=>a.jsx(OZe,{project:B,onClick:()=>E(B),onEdit:()=>j(B),onDelete:()=>P(B.id),hasPermission:i,t},B.id))}),h!==null&&a.jsx(kn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:U,onCancel:()=>f(null)}),s&&a.jsx(Kae,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:k,isLoading:v.isPending||b.isPending,t})]})}function zZe(t){if(t<1)return`${Math.round(t*60)}m`;const e=Math.floor(t),n=Math.round((t-e)*60);return n>0?`${e}h ${n}m`:`${e}h`}function UZe(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function BZe({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return a.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function uK({icon:t,label:e,value:n,subValue:r,hint:i,color:s="text-bambu-gray"}){return a.jsx(_t,{children:a.jsx(Nt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",title:i,children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:a.jsx(t,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:e}),a.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function HZe({archives:t,t:e}){return t.length===0?a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(ma,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:e("projectDetail.noPrints")})]}):a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(n=>a.jsxs(Xs,{to:`/archives?search=${encodeURIComponent(n.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[n.thumbnail_path?a.jsx("img",{src:se.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(ma,{className:"w-8 h-8"})}),n.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:a.jsx(ha,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&a.jsx("div",{className:"absolute top-1 right-1",children:a.jsx(gr,{className:"w-4 h-4 text-bambu-green"})}),a.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function $Ze({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:r,label:i}=n[t]||n.normal;return a.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&a.jsx(Cn,{className:"w-3 h-3"}),i]})}function VZe(t){return t?gb(t,{year:"numeric",month:"short",day:"numeric"}):""}function Gj(t,e){if(!t)return null;const n=Zi(t);if(!n)return null;const r=new Date,i=Math.ceil((n.getTime()-r.getTime())/(1e3*60*60*24));return i<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:i===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:i<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:i})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:i})}}function GZe(){const{id:t}=Yk(),e=Hc(),{t:n}=Vt(),r=tn(),{showToast:i}=mn(),{hasPermission:s}=Ir(),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(""),f=parseInt(t||"0",10),{data:p,isLoading:x,error:v}=tt({queryKey:["project",f],queryFn:()=>se.getProject(f),enabled:f>0}),{data:b,isLoading:y}=tt({queryKey:["project-archives",f],queryFn:()=>se.getProjectArchives(f),enabled:f>0}),{data:S,isLoading:N}=tt({queryKey:["project-bom",f],queryFn:()=>se.getProjectBOM(f),enabled:f>0}),{data:A,isLoading:M}=tt({queryKey:["project-timeline",f],queryFn:()=>se.getProjectTimeline(f,20),enabled:f>0}),{data:T}=tt({queryKey:["settings"],queryFn:se.getSettings}),{data:k}=tt({queryKey:["project-folders",f],queryFn:()=>se.getLibraryFoldersByProject(f),enabled:f>0}),j=Pu(T?.currency||"USD"),E=T?.time_format||"system",P=lt({mutationFn:je=>se.updateProject(f,je),onSuccess:()=>{r.invalidateQueries({queryKey:["project",f]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:je=>{i(je.message,"error")}}),U=()=>{h(p?.notes||""),u(!0)},L=()=>{P.mutate({notes:d})},B=()=>{u(!1),h("")},[R,V]=w.useState(""),[q,I]=w.useState(1),[K,Y]=w.useState(""),[le,H]=w.useState(""),[X,te]=w.useState(""),[J,Se]=w.useState(!1),[fe,me]=w.useState(!1),[De,de]=w.useState(null),[ce,Ne]=w.useState(""),[ie,Le]=w.useState(1),[$,W]=w.useState(""),[ue,Z]=w.useState(""),[oe,Q]=w.useState(""),[he,be]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),ee=lt({mutationFn:je=>se.createBOMItem(f,je),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),V(""),I(1),Y(""),H(""),te(""),Se(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:je=>i(je.message,"error")}),z=lt({mutationFn:({itemId:je,data:Ve})=>se.updateBOMItem(f,je,Ve),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),de(null)},onError:je=>i(je.message,"error")}),D=lt({mutationFn:je=>se.deleteBOMItem(f,je),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:je=>i(je.message,"error")}),G=je=>{je.preventDefault(),R.trim()&&ee.mutate({name:R.trim(),quantity_needed:q,unit_price:K?parseFloat(K):void 0,sourcing_url:le.trim()||void 0,remarks:X.trim()||void 0})},pe=je=>{const Ve=je.is_complete?0:je.quantity_needed;z.mutate({itemId:je.id,data:{quantity_acquired:Ve}})},ve=(je,Ve)=>{be({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Ve}),onConfirm:()=>{be(Ae=>({...Ae,isOpen:!1})),D.mutate(je)}})},xe=je=>{de(je),Ne(je.name),Le(je.quantity_needed),W(je.unit_price?.toString()||""),Z(je.sourcing_url||""),Q(je.remarks||"")},ze=je=>{je.preventDefault(),!(!De||!ce.trim())&&z.mutate({itemId:De.id,data:{name:ce.trim(),quantity_needed:ie,unit_price:$?parseFloat($):void 0,sourcing_url:ue.trim()||void 0,remarks:oe.trim()||void 0}})},_e=()=>{de(null)},He=async()=>{try{const{blob:je,filename:Ve}=await se.exportProjectZip(Number(f)),Ae=URL.createObjectURL(je),Je=document.createElement("a");Je.href=Ae,Je.download=Ve||`${p?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,Je.click(),URL.revokeObjectURL(Ae),i(n("projectDetail.toast.projectExported"),"success")}catch(je){i(je.message,"error")}},Ze=lt({mutationFn:()=>se.createTemplateFromProject(f),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:je=>i(je.message,"error")}),we=je=>Ff(je,E,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(x)return a.jsx("div",{className:"flex items-center justify-center py-24",children:a.jsx(at,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!p)return a.jsxs("div",{className:"text-center py-24",children:[a.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),a.jsx(Me,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const ye=p.stats,ke=ye?.progress_percent??0,Ue=ye?.parts_progress_percent??0;return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(Xs,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),a.jsx(fa,{className:"w-4 h-4"}),a.jsx("span",{className:"text-white",children:p.name})]}),a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:a.jsx(fde,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:p.color||"#6b7280"}}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:p.name}),p.description&&a.jsx("p",{className:"text-bambu-gray mt-1",children:p.description})]})]}),a.jsx(BZe,{status:p.status,t:n})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Me,{variant:"secondary",onClick:He,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[a.jsx(di,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),a.jsxs(Me,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[a.jsx(Pf,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(p.target_count||p.target_parts_count)&&a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4 space-y-4",children:[p.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[ye?.total_archives||0," / ",p.target_count," ",n("projectDetail.progress.printJobs")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(ke,100)}%`,backgroundColor:ke>=100?"#22c55e":p.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:ke.toFixed(0)})}),ye?.remaining_prints!=null&&ye.remaining_prints>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:ye.remaining_prints})})]})]}),p.target_parts_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[ye?.completed_prints||0," / ",p.target_parts_count," ",n("projectDetail.progress.parts")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ue,100)}%`,backgroundColor:Ue>=100?"#22c55e":p.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Ue.toFixed(0)})}),ye?.remaining_parts!=null&&ye.remaining_parts>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:ye.remaining_parts})})]})]})]})}),ye&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(_t,{children:a.jsx(Nt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:a.jsx(ma,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),a.jsxs("p",{className:"text-xl font-semibold text-white",children:[ye.total_archives," ",a.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),ye.failed_prints>0&&a.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:ye.failed_prints})}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:ye.completed_prints})})]})]})})}),a.jsx(uK,{icon:Qn,label:n("projectDetail.stats.printTime"),value:zZe(ye.total_print_time_hours),color:"text-yellow-400"}),a.jsx(uK,{icon:Cr,label:n("projectDetail.stats.filamentUsed"),value:UZe(ye.total_filament_grams),color:"text-purple-400"})]}),ye&&(ye.estimated_cost>0||p.budget)&&a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[j,ye.estimated_cost.toFixed(2)]})]}),ye.total_energy_kwh>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[ye.total_energy_kwh.toFixed(2)," kWh",ye.total_energy_cost>0&&a.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",j,ye.total_energy_cost.toFixed(2),")"]})]})]}),p.budget&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[j,p.budget.toFixed(2)]})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.remaining")}),a.jsxs("p",{className:`text-lg font-semibold ${p.budget-ye.estimated_cost>=0?"text-bambu-green":"text-red-400"}`,children:[j,(p.budget-ye.estimated_cost).toFixed(2)]})]})]})]})]})}),p.children&&p.children.length>0&&a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[a.jsx(tme,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:p.children.length})]}),a.jsx("div",{className:"space-y-2",children:p.children.map(je=>a.jsxs(Xs,{to:`/projects/${je.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:je.color||"#6b7280"}}),a.jsx("span",{className:"text-white",children:je.name}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${je.status==="completed"?"bg-status-ok/20 text-status-ok":je.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:je.status})]}),je.progress_percent!==null&&a.jsxs("span",{className:"text-sm text-bambu-gray",children:[je.progress_percent.toFixed(0),"%"]})]},je.id))})]})}),p.parent_id&&p.parent_name&&a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(rs,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),a.jsx(Xs,{to:`/projects/${p.parent_id}`,className:"text-bambu-green hover:underline",children:p.parent_name})]}),(p.tags||p.due_date||p.priority!=="normal")&&a.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[p.priority&&p.priority!=="normal"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),a.jsx($Ze,{priority:p.priority,t:n})]}),p.due_date&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ii,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:VZe(p.due_date)}),Gj(p.due_date,n)&&a.jsxs("span",{className:`text-xs ${Gj(p.due_date,n).color}`,children:["(",Gj(p.due_date,n).label,")"]})]}),p.tags&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Vh,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:p.tags.split(",").map((je,Ve)=>a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:je.trim()},Ve))})]})]}),a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ps,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Me,{variant:"secondary",size:"sm",onClick:B,disabled:P.isPending,children:[a.jsx(Ft,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),a.jsxs(Me,{size:"sm",onClick:L,disabled:P.isPending,children:[P.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin mr-1"}):a.jsx(bs,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):a.jsxs(Me,{variant:"secondary",size:"sm",onClick:U,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[a.jsx(Pf,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?a.jsx(oF,{content:d,onChange:h,placeholder:n("projectDetail.notes.placeholder")}):p.notes?a.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.notes}}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Xl,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),a.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[a.jsx(Xs,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),k&&k.length>0?a.jsx("div",{className:"space-y-2",children:k.map(je=>a.jsxs(Xs,{to:`/files?folder=${je.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsx(Xl,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:je.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:je.file_count})})]})]}),a.jsx(fa,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},je.id))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(bX,{className:"w-5 h-5"}),n("projectDetail.bom.title"),ye&&ye.bom_total_items>0&&a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:ye.bom_completed_items,total:ye.bom_total_items}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[S&&S.some(je=>je.is_complete)&&a.jsx("button",{onClick:()=>me(!fe),className:`text-xs px-2 py-1 rounded transition-colors ${fe?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(fe?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!J&&a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>Se(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[a.jsx(ar,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),J&&a.jsxs("form",{onSubmit:G,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:R,onChange:je=>V(je.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:q,onChange:je=>I(parseInt(je.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:K,onChange:je=>Y(je.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:j})})]})]}),a.jsx("input",{type:"url",value:le,onChange:je=>H(je.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:X,onChange:je=>te(je.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Me,{type:"button",variant:"secondary",size:"sm",onClick:()=>Se(!1),children:n("common.cancel")}),a.jsx(Me,{type:"submit",size:"sm",disabled:!R.trim()||ee.isPending,children:ee.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),N?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(at,{className:"w-6 h-6 animate-spin text-bambu-green"})}):S&&S.length>0?a.jsxs("div",{className:"space-y-2",children:[S.filter(je=>!fe||!je.is_complete).map(je=>a.jsx("div",{className:`p-3 rounded-lg transition-colors ${je.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:De?.id===je.id?a.jsxs("form",{onSubmit:ze,className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:ce,onChange:Ve=>Ne(Ve.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partName"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:ie,onChange:Ve=>Le(parseInt(Ve.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:$,onChange:Ve=>W(Ve.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:j})})]})]}),a.jsx("input",{type:"url",value:ue,onChange:Ve=>Z(Ve.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:oe,onChange:Ve=>Q(Ve.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Me,{type:"button",variant:"secondary",size:"sm",onClick:_e,children:n("common.cancel")}),a.jsx(Me,{type:"submit",size:"sm",disabled:!ce.trim()||z.isPending,children:z.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("button",{onClick:()=>s("projects:update")&&pe(je),disabled:z.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors flex-shrink-0 ${je.is_complete?"bg-status-ok border-status-ok text-white":s("projects:update")?"border-bambu-gray hover:border-bambu-green":"border-bambu-gray/50 cursor-not-allowed"}`,children:je.is_complete&&a.jsx(gr,{className:"w-3 h-3"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsxs("p",{className:`text-sm font-medium ${je.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[je.name,a.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",je.quantity_needed]})]}),je.unit_price!==null&&a.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[j,(je.unit_price*je.quantity_needed).toFixed(2)]})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>s("projects:update")&&xe(je),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:a.jsx($i,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("projects:update")&&ve(je.id,je.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:a.jsx(en,{className:"w-4 h-4"})})]})]}),je.sourcing_url&&a.jsxs("a",{href:je.sourcing_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 mt-1 text-xs text-blue-400 hover:text-blue-300 transition-colors",onClick:Ve=>Ve.stopPropagation(),children:[a.jsx(Kr,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"truncate",children:(()=>{try{return new URL(je.sourcing_url).hostname.replace("www.","")}catch{return je.sourcing_url}})()})]}),je.remarks&&a.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:je.remarks})]})]})},je.id)),S.some(je=>je.unit_price!==null)&&a.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),a.jsxs("span",{className:"text-white font-medium",children:[j,S.reduce((je,Ve)=>je+(Ve.unit_price||0)*Ve.quantity_needed,0).toFixed(2)]})]})]}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(N0,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),M?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(at,{className:"w-6 h-6 animate-spin text-bambu-green"})}):A&&A.length>0?a.jsx("div",{className:"space-y-3",children:A.slice(0,10).map((je,Ve)=>a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${je.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":je.event_type==="print_failed"?"bg-status-error/20 text-status-error":je.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[je.event_type==="print_completed"&&a.jsx(gr,{className:"w-4 h-4"}),je.event_type==="print_failed"&&a.jsx(ha,{className:"w-4 h-4"}),je.event_type==="print_started"&&a.jsx(Cr,{className:"w-4 h-4"}),je.event_type==="queued"&&a.jsx(g3,{className:"w-4 h-4"}),je.event_type==="project_created"&&a.jsx(ar,{className:"w-4 h-4"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white",children:je.title}),je.description&&a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:je.description}),a.jsx("p",{className:"text-xs text-bambu-gray/70",children:we(je.timestamp)})]})]},Ve))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!p.is_template&&a.jsx("div",{className:"flex justify-end",children:a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>Ze.mutate(),disabled:Ze.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[Ze.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(Wl,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),ye&&(ye.queued_prints>0||ye.in_progress_prints>0)&&a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(g3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),a.jsx(Xs,{to:`/queue?project=${f}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[ye.in_progress_prints>0&&a.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:ye.in_progress_prints})}),ye.queued_prints>0&&a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:ye.queued_prints})})]})]})}),a.jsxs("div",{children:[a.jsx("div",{className:"flex items-center justify-between mb-4",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ma,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:b?.length||0})]})}),y?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(at,{className:"w-6 h-6 animate-spin text-bambu-green"})}):a.jsx(HZe,{archives:b||[],t:n})]}),o&&a.jsx(Kae,{t:n,project:{...p,archive_count:ye?.total_archives||0,total_items:ye?.total_items||0,completed_count:ye?.completed_prints||0,failed_count:ye?.failed_prints||0,queue_count:ye?.queued_prints||0,progress_percent:ye?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:je=>P.mutate(je),isLoading:P.isPending}),he.isOpen&&a.jsx(kn,{title:he.title,message:he.message,confirmText:n("common.delete"),variant:"danger",onConfirm:he.onConfirm,onCancel:()=>be(je=>({...je,isOpen:!1}))})]})}function Bg(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(2)} GB`}function qZe(t){if(!t)return"-";const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function WZe({parentId:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),a.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),a.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Me,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(at,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function KZe({type:t,currentName:e,onClose:n,onSave:r,isLoading:i,t:s}){const[o,l]=w.useState(e),c=u=>{u.preventDefault(),o.trim()&&o.trim()!==e&&r(o.trim())};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),a.jsxs("form",{onSubmit:c,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsx("input",{type:"text",value:o,onChange:u=>l(u.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",autoFocus:!0,required:!0})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),a.jsx(Me,{type:"submit",disabled:!o.trim()||o.trim()===e||i,children:i?a.jsx(at,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function XZe({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:i,isLoading:s,t:o}){const[l,c]=w.useState(null),u=(h,f=0)=>{const p=[];for(const x of h)p.push({id:x.id,name:x.name,depth:f}),x.children.length>0&&p.push(...u(x.children,f+1));return p},d=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...u(t)];return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:d.map(h=>a.jsxs("button",{onClick:()=>c(h.id),disabled:h.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===h.id?"bg-bambu-green/20 text-bambu-green":h.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+h.depth*16}px`},children:[a.jsx(Xl,{className:"w-4 h-4"}),h.name,h.id===n&&a.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},h.id??"root"))}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),a.jsx(Me,{onClick:()=>i(l),disabled:s,children:s?a.jsx(at,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function YZe({folder:t,onClose:e,onLink:n,isLoading:r,t:i}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:u}=tt({queryKey:["projects"],queryFn:()=>se.getProjects()}),{data:d}=tt({queryKey:["archives-for-link"],queryFn:()=>se.getArchives(void 0,void 0,100)}),h=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},f=()=>{n({project_id:0,archive_id:0})},p=t.project_id||t.archive_id;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(jh,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Ft,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[a.jsx(oX,{className:"w-4 h-4"}),i("fileManager.project")]}),a.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[a.jsx(Rs,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?u&&u.length>0?u.map(x=>a.jsxs("button",{onClick:()=>c(x.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===x.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:x.color||"#00ae42"}}),a.jsx("span",{className:"truncate",children:x.name})]},x.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):d&&d.length>0?d.map(x=>a.jsxs("button",{onClick:()=>c(x.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===x.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx(ff,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"truncate",children:x.print_name||x.filename})]},x.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[p&&a.jsxs(Me,{variant:"danger",onClick:f,disabled:r,children:[a.jsx(uC,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),a.jsxs("div",{className:`flex gap-2 ${p?"":"ml-auto"}`,children:[a.jsx(Me,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Me,{onClick:h,disabled:!l||r,children:r?a.jsx(at,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function QZe({folderId:t,onClose:e,onUploadComplete:n,t:r}){const[i,s]=w.useState([]),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(!0),[f,p]=w.useState(!1),[x,v]=w.useState(!0),b=w.useRef(null),y=V=>{V.preventDefault(),l(!0)},S=V=>{V.preventDefault(),l(!1)},N=V=>{V.preventDefault(),l(!1);const q=Array.from(V.dataTransfer.files);M(q)},A=V=>{V.target.files&&M(Array.from(V.target.files))},M=V=>{const q=V.map(I=>({file:I,status:"pending",isZip:I.name.toLowerCase().endsWith(".zip"),is3mf:I.name.toLowerCase().endsWith(".3mf")}));s(I=>[...I,...q])},T=V=>{s(q=>q.filter((I,K)=>K!==V))},k=i.some(V=>V.isZip&&V.status==="pending"),j=i.some(V=>V.file.name.toLowerCase().endsWith(".stl")&&V.status==="pending"),E=i.some(V=>V.is3mf&&V.status==="pending"),P=async()=>{if(i.length!==0){u(!0);for(let V=0;Vq.map((I,K)=>K===V?{...I,status:"uploading"}:I));try{if(i[V].isZip){const q=await se.extractZipFile(i[V].file,t,d,f,x);s(I=>I.map((K,Y)=>Y===V?{...K,status:q.errors.length>0&&q.extracted===0?"error":"success",extractedCount:q.extracted,error:q.errors.length>0?`${q.errors.length} files failed`:void 0}:K))}else await se.uploadLibraryFile(i[V].file,t,x),s(q=>q.map((I,K)=>K===V?{...I,status:"success"}:I))}catch(q){s(I=>I.map((K,Y)=>Y===V?{...K,status:"error",error:q instanceof Error?q.message:"Upload failed"}:K))}}u(!1),n(),e()}},U=i.filter(V=>V.status==="pending").length,L=i.filter(V=>V.status==="success").length,B=i.filter(V=>V.status==="error").length,R=i.length>0&&U===0&&!c;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("fileManager.uploadFiles")}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Ft,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("div",{onDragOver:y,onDragLeave:S,onDrop:N,onClick:()=>b.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${o?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[a.jsx(ia,{className:`w-10 h-10 mx-auto mb-3 ${o?"text-bambu-green":"text-bambu-gray"}`}),a.jsx("p",{className:"text-white font-medium",children:r(o?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("fileManager.orClickToBrowse")}),a.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:r("fileManager.allFileTypesSupported")})]}),a.jsx("input",{ref:b,type:"file",multiple:!0,className:"hidden",onChange:A}),k&&a.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Rs,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-blue-300 font-medium",children:r("fileManager.zipFilesDetected")}),a.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:r("fileManager.zipExtractOptions")}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:d,onChange:V=>h(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.preserveZipStructure")})]}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:f,onChange:V=>p(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.createFolderFromZip")})]})]})]})}),E&&a.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Cr,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-purple-300 font-medium",children:r("fileManager.threemfDetected")}),a.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:r("fileManager.threemfExtractionInfo")})]})]})}),(j||k)&&a.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(ed,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium",children:r("fileManager.stlThumbnailGeneration")}),a.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:r(k&&!j?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:x,onChange:V=>v(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.generateThumbnailsForStl")})]})]})]})}),i.length>0&&a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:i.map((V,q)=>a.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[V.isZip?a.jsx(Rs,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):a.jsx(eC,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:V.file.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[(V.file.size/1024/1024).toFixed(2)," MB",V.isZip&&V.status==="pending"&&a.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",r("fileManager.willBeExtracted")]}),V.extractedCount!==void 0&&a.jsxs("span",{className:"text-green-400 ml-2",children:["• ",r("fileManager.filesExtracted",{count:V.extractedCount})]})]})]}),V.status==="pending"&&a.jsx("button",{onClick:()=>T(q),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Ft,{className:"w-4 h-4 text-bambu-gray"})}),V.status==="uploading"&&a.jsx(at,{className:"w-4 h-4 text-bambu-green animate-spin"}),V.status==="success"&&a.jsx(gr,{className:"w-4 h-4 text-green-500"}),V.status==="error"&&a.jsx("span",{title:V.error,children:a.jsx(ha,{className:"w-4 h-4 text-red-500"})})]},q))}),R&&a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[r("fileManager.uploadComplete",{succeeded:L}),B>0&&a.jsxs("span",{className:"text-red-400",children:[", ",r("fileManager.uploadFailed",{count:B})]})]})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[a.jsx(Me,{variant:"secondary",onClick:e,children:r(R?"common.close":"common.cancel")}),!R&&a.jsx(Me,{onClick:P,disabled:U===0||c,children:c?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 mr-2 animate-spin"}),r("fileManager.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(ia,{className:"w-4 h-4 mr-2"}),r("common.upload")," ",U>0?`(${U})`:""]})})]})]})})}function Xae({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:u}){const[d,h]=w.useState(!0),[f,p]=w.useState(!1),x=t.children.length>0,v=t.project_id||t.archive_id;return a.jsxs("div",{children:[a.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>n(t.id),children:[x?a.jsx("button",{onClick:b=>{b.stopPropagation(),h(!d)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(fa,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-90":""}`})}):a.jsx("div",{className:"w-4.5"}),a.jsx(Xl,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),a.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&a.jsxs("button",{onClick:b=>{b.stopPropagation(),i(t)},className:"flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors",title:`${t.project_name?`Project: ${t.project_name}`:`Archive: ${t.archive_name}`} (click to change)`,children:[a.jsx(jh,{className:"w-3 h-3"}),t.project_name?a.jsx(oX,{className:"w-3 h-3"}):a.jsx(Rs,{className:"w-3 h-3"})]}),t.file_count>0&&a.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&a.jsx("button",{onClick:b=>{b.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:a.jsx(jh,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),a.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:b=>b.stopPropagation(),children:a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:()=>p(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:a.jsx(Ah,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>p(!1)}),a.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(s(t),p(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[a.jsx($i,{className:"w-3.5 h-3.5"}),u("common.rename")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(i(t),p(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[a.jsx(jh,{className:"w-3.5 h-3.5"}),u(v?"fileManager.changeLink":"fileManager.linkTo")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:delete_all")&&(r(t.id),p(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[a.jsx(en,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),x&&d&&a.jsx("div",{children:t.children.map(b=>a.jsx(Xae,{folder:b,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},b.id))})]})}function fF(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function ZZe({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:u,onGenerateThumbnail:d,thumbnailVersion:h,hasPermission:f,canModify:p,authEnabled:x,t:v}){const[b,y]=w.useState(!1);return a.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>r(t.id),children:[a.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?a.jsx("img",{src:`${se.getLibraryFileThumbnailUrl(t.id)}${h?`?v=${h}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):a.jsx(ff,{className:"w-12 h-12 text-bambu-gray/30"}),a.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),a.jsxs("div",{className:"p-3",children:[a.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),a.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[a.jsx("span",{children:Bg(t.file_size)}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Qn,{className:"w-3 h-3"}),qZe(t.print_time_seconds)]})]}),t.sliced_for_model&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(Cr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&a.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),x&&t.created_by_username&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(nd,{className:"w-3 h-3"}),t.created_by_username]})]}),a.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:S=>S.stopPropagation(),children:[a.jsx("button",{onClick:()=>y(!b),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:a.jsx(Ah,{className:"w-4 h-4 text-bambu-gray"})}),b&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>y(!1)}),a.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&fF(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("printers:control")&&(l(t),y(!1))},disabled:!f("printers:control"),title:f("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[a.jsx(Cr,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&fF(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("queue:create")&&(o(t.id),y(!1))},disabled:!f("queue:create"),title:f("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[a.jsx(Qn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library:read")&&(c(t),y(!1))},disabled:!f("library:read"),title:f("library:read")?void 0:"You do not have permission to preview files",children:[a.jsx(Qi,{className:"w-3.5 h-3.5"}),"3D Preview"]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library:read")&&(s(t.id),y(!1))},disabled:!f("library:read"),title:f("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[a.jsx(di,{className:"w-3.5 h-3.5"}),v("common.download")]}),u&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","update",t.created_by_id)&&(u(t),y(!1))},disabled:!p("library","update",t.created_by_id),title:p("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[a.jsx($i,{className:"w-3.5 h-3.5"}),v("common.rename")]}),d&&t.file_type==="stl"&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","update",t.created_by_id)&&(d(t),y(!1))},disabled:!p("library","update",t.created_by_id),title:p("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[a.jsx(ed,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","delete",t.created_by_id)&&(i(t.id),y(!1))},disabled:!p("library","delete",t.created_by_id),title:p("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[a.jsx(en,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),a.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function JZe(){const{t}=Vt(),e=tn(),{showToast:n}=mn(),{hasPermission:r,hasAnyPermission:i,canModify:s,authEnabled:o}=Ir(),[l]=NF(),c=l.get("folder"),u=c?parseInt(c,10):null,[d,h]=w.useState(u),[f,p]=w.useState([]),[x,v]=w.useState(!1),[b,y]=w.useState(!1),[S,N]=w.useState(!1),[A,M]=w.useState(null),[T,k]=w.useState(null),[j,E]=w.useState(null),[P,U]=w.useState(null),[L,B]=w.useState(null),[R,V]=w.useState(null),[q,I]=w.useState({}),[K,Y]=w.useState(null),[le,H]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[X,te]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[J,Se]=w.useState(()=>{const Oe=localStorage.getItem("library-sidebar-width");return Oe?parseInt(Oe,10):256}),[fe,me]=w.useState(!1),De=w.useRef(null);w.useEffect(()=>{if(!fe)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Oe=vt=>{if(!De.current)return;const Bt=De.current.parentElement?.getBoundingClientRect();if(!Bt)return;const Tn=vt.clientX-Bt.left,fr=Math.min(500,Math.max(200,Tn));Se(fr)},xt=()=>{me(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(J))};return document.addEventListener("mousemove",Oe),document.addEventListener("mouseup",xt),()=>{document.removeEventListener("mousemove",Oe),document.removeEventListener("mouseup",xt),document.body.style.userSelect="",document.body.style.cursor=""}},[fe,J]);const[de,ce]=w.useState(""),[Ne,ie]=w.useState("all"),[Le,$]=w.useState(""),[W,ue]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[Z,oe]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),Q=fne();w.useEffect(()=>{const Oe=l.get("folder");if(Oe){const xt=parseInt(Oe,10);h(xt)}},[l]);const{data:he}=tt({queryKey:["settings"],queryFn:()=>se.getSettings()}),{data:be,isLoading:ee}=tt({queryKey:["library-folders"],queryFn:()=>se.getLibraryFolders()}),{data:z,isLoading:D}=tt({queryKey:["library-files",d],queryFn:()=>se.getLibraryFiles(d,d===null)}),{data:G}=tt({queryKey:["library-stats"],queryFn:()=>se.getLibraryStats()}),{data:pe}=tt({queryKey:["users"],queryFn:()=>se.getUsers()}),ve=w.useMemo(()=>{if(!z)return[];const Oe=new Set(z.map(xt=>xt.file_type));return Array.from(Oe).sort()},[z]),xe=w.useMemo(()=>{if(!z)return[];let Oe=[...z];if(de.trim()){const xt=de.toLowerCase();Oe=Oe.filter(vt=>vt.filename.toLowerCase().includes(xt)||vt.print_name&&vt.print_name.toLowerCase().includes(xt))}if(Ne!=="all"&&(Oe=Oe.filter(xt=>xt.file_type===Ne)),Le.trim()){const xt=Le.toLowerCase();Oe=Oe.filter(vt=>vt.created_by_username&&vt.created_by_username.toLowerCase().includes(xt))}return Oe.sort((xt,vt)=>{let Bt=0;switch(W){case"name":Bt=(xt.print_name||xt.filename).localeCompare(vt.print_name||vt.filename);break;case"date":Bt=new Date(xt.created_at).getTime()-new Date(vt.created_at).getTime();break;case"size":Bt=xt.file_size-vt.file_size;break;case"type":Bt=xt.file_type.localeCompare(vt.file_type);break;case"prints":Bt=xt.print_count-vt.print_count;break}return Z==="asc"?Bt:-Bt}),Oe},[z,de,Ne,Le,W,Z]),ze=w.useMemo(()=>{if(!G||!he)return!1;const Oe=(he.library_disk_warning_gb||5)*1024*1024*1024;return G.disk_free_bytesse.createLibraryFolder(Oe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Oe=>n(Oe.message,"error")}),He=lt({mutationFn:Oe=>se.deleteLibraryFolder(Oe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===T?.id&&h(null),k(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Oe=>{k(null),n(Oe.message,"error")}}),Ze=lt({mutationFn:Oe=>se.deleteLibraryFile(Oe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),p(Oe=>Oe.filter(xt=>xt!==T?.id)),k(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Oe=>{k(null),n(Oe.message,"error")}}),we=lt({mutationFn:Oe=>se.bulkDeleteLibrary(Oe,[]),onSuccess:(Oe,xt)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:xt.length}),"success"),p([]),k(null)},onError:Oe=>{k(null),n(Oe.message,"error")}}),ye=lt({mutationFn:({fileIds:Oe,folderId:xt})=>se.moveLibraryFiles(Oe,xt),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),p([]),y(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Oe=>n(Oe.message,"error")}),ke=lt({mutationFn:({id:Oe,data:xt})=>se.updateLibraryFolder(Oe,xt),onSuccess:(Oe,xt)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),M(null);const vt=xt.data.project_id===0&&xt.data.archive_id===0;n(t(vt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Oe=>n(Oe.message,"error")}),Ue=lt({mutationFn:({id:Oe,filename:xt})=>se.updateLibraryFile(Oe,{filename:xt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),V(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Oe=>{V(null),n(Oe.message,"error")}}),je=lt({mutationFn:({id:Oe,name:xt})=>se.updateLibraryFolder(Oe,{name:xt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),V(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Oe=>{V(null),n(Oe.message,"error")}}),Ve=lt({mutationFn:()=>se.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Oe=>{if(e.invalidateQueries({queryKey:["library-files"]}),Oe.succeeded>0){const xt=Date.now(),vt={};Oe.results.forEach(Bt=>{Bt.success&&(vt[Bt.file_id]=xt)}),I(Bt=>({...Bt,...vt}))}Oe.succeeded>0&&Oe.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Oe.succeeded}),"success"):Oe.succeeded>0&&Oe.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Oe.succeeded,failed:Oe.failed}),"success"):Oe.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Oe.results[0]?.error||"Unknown error"}),"error")},onError:Oe=>n(Oe.message,"error")}),Ae=lt({mutationFn:Oe=>se.batchGenerateStlThumbnails({file_ids:[Oe]}),onSuccess:Oe=>{if(e.invalidateQueries({queryKey:["library-files"]}),Oe.succeeded>0){const xt=Oe.results[0]?.file_id;xt&&I(vt=>({...vt,[xt]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Oe.results[0]?.error||"Unknown error"}),"error")},onError:Oe=>n(Oe.message,"error")}),Je=w.useCallback(Oe=>{const xt=Oe.toLowerCase();return xt.endsWith(".gcode")||xt.includes(".gcode.")},[]),Pe=w.useMemo(()=>z?z.filter(Oe=>f.includes(Oe.id)&&Je(Oe.filename)):[],[z,f,Je]),Ye=w.useCallback(Oe=>{p(xt=>xt.includes(Oe)?xt.filter(vt=>vt!==Oe):[...xt,Oe])},[]),Re=w.useCallback(()=>{xe.length>0&&p(xe.map(Oe=>Oe.id))},[xe]),Fe=w.useCallback(()=>{p([])},[]),We=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},pt=Oe=>{se.downloadLibraryFile(Oe).catch(xt=>{console.error("Library file download failed:",xt)})},At=()=>{T&&(T.type==="file"?Ze.mutate(T.id):T.type==="folder"?He.mutate(T.id):T.type==="bulk"&&we.mutate(f))},Rt=He.isPending||Ze.isPending||we.isPending,Wt=Oe=>{H(Oe),localStorage.setItem("library-view-mode",Oe)},Tt=ee||D;return a.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(Xl,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[a.jsx("button",{onClick:()=>Wt("grid"),className:`p-1.5 rounded transition-colors ${le==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:a.jsx(xv,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>Wt("list"),className:`p-1.5 rounded transition-colors ${le==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:a.jsx(rC,{className:"w-4 h-4"})})]}),a.jsxs(Me,{variant:"secondary",onClick:()=>Ve.mutate(),disabled:Ve.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[Ve.isPending?a.jsx(at,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(ed,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),a.jsxs(Me,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[a.jsx(Jhe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a.jsxs(Me,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(ia,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),ze&&G&&he&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[a.jsx(Cn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),a.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:Bg(G.disk_free_bytes),total:Bg(G.disk_total_bytes),threshold:he.library_disk_warning_gb})})]})]}),G&&a.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(eC,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),a.jsx("span",{className:"text-white font-medium",children:G.total_files})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Xl,{className:"w-4 h-4 text-blue-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),a.jsx("span",{className:"text-white font-medium",children:G.total_folders})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(qb,{className:"w-4 h-4 text-amber-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Bg(G.total_size_bytes)})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),a.jsx("span",{className:`font-medium ${ze?"text-amber-500":"text-white"}`,children:Bg(G.disk_free_bytes)})]})]}),a.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[a.jsx("div",{className:"lg:hidden",children:a.jsxs("select",{value:d??"",onChange:Oe=>h(Oe.target.value?parseInt(Oe.target.value,10):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[a.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),be&&(()=>{const Oe=(xt,vt=0)=>{const Bt=[];for(const Tn of xt)Bt.push({id:Tn.id,name:Tn.name,fileCount:Tn.file_count,depth:vt}),Tn.children.length>0&&Bt.push(...Oe(Tn.children,vt+1));return Bt};return Oe(be).map(xt=>a.jsxs("option",{value:xt.id,children:["│ ".repeat(xt.depth),"📂 ",xt.name," ",xt.fileCount>0?`(${xt.fileCount})`:""]},xt.id))})()]})}),a.jsxs("div",{ref:De,className:"hidden lg:flex flex-shrink-0 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden flex-col relative",style:{width:`${J}px`},children:[a.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${fe?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Oe=>{Oe.preventDefault(),me(!0)},onDoubleClick:()=>{Se(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:a.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${fe?"opacity-100":""}`,children:[a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),a.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),a.jsx("button",{onClick:()=>{const Oe=!X;te(Oe),localStorage.setItem("library-wrap-folders",String(Oe))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${X?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(X?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[a.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${d===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>h(null),children:[a.jsx(ff,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),be?.map(Oe=>a.jsx(Xae,{folder:Oe,selectedFolderId:d,onSelect:h,onDelete:xt=>k({type:"folder",id:xt}),onLink:M,onRename:xt=>V({type:"folder",id:xt.id,name:xt.name}),wrapNames:X,hasPermission:r,t},Oe.id))]})]}),a.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[z&&z.length>0&&a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[a.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[a.jsx(Or,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:de,onChange:Oe=>ce(Oe.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tC,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),a.jsxs("select",{value:Ne,onChange:Oe=>ie(Oe.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"all",children:t("fileManager.allTypes")}),ve.map(Oe=>a.jsx("option",{value:Oe,children:Oe.toUpperCase()},Oe))]})]}),o&&a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:Le,onChange:Oe=>$(Oe.target.value),list:"usernames-list",className:`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${Le?"pr-7":""}`,style:Le?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),Le&&a.jsx("button",{onClick:()=>$(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:a.jsx(Ft,{className:"w-3 h-3"})}),a.jsx("datalist",{id:"usernames-list",children:pe?.map(Oe=>a.jsx("option",{value:Oe.username},Oe.id))})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{value:W,onChange:Oe=>{const xt=Oe.target.value;ue(xt),localStorage.setItem("library-sort-field",xt)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"name",children:t("common.name")}),a.jsx("option",{value:"date",children:t("common.date")}),a.jsx("option",{value:"size",children:t("fileManager.size")}),a.jsx("option",{value:"type",children:t("common.type")}),a.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),a.jsx("button",{onClick:()=>oe(Oe=>{const xt=Oe==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",xt),xt}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(Z==="asc"?"fileManager.ascending":"fileManager.descending"),children:Z==="asc"?a.jsx(yde,{className:"w-4 h-4 text-white"}):a.jsx(dde,{className:"w-4 h-4 text-white"})})]}),(de||Ne!=="all"||Le)&&a.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:xe.length,total:z.length})})]}),xe.length>0&&a.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[f.length===xe.length&&f.length>0?a.jsxs(Me,{variant:"secondary",size:"sm",onClick:Fe,children:[a.jsx(gl,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):a.jsxs(Me,{variant:"secondary",size:"sm",onClick:Re,children:[a.jsx(ao,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),f.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:f.length})}),a.jsx("div",{className:"hidden sm:block flex-1"}),a.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Pe.length===1&&a.jsxs(Me,{variant:"primary",size:"sm",onClick:()=>U(Pe[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[a.jsx(jo,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Pe.length===1&&a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>B(Pe[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[a.jsx(Qn,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>y(!0),disabled:!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[a.jsx(sfe,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),a.jsxs(Me,{variant:"danger",size:"sm",onClick:()=>{f.length===1?k({type:"file",id:f[0]}):k({type:"bulk",id:0,count:f.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[a.jsx(en,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),a.jsxs(Me,{variant:"secondary",size:"sm",onClick:Fe,children:[a.jsx(Ft,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Tt?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(at,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):z?.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(ff,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(d!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(d!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),a.jsxs(Me,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(ar,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):xe.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(Or,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),a.jsx(Me,{variant:"secondary",onClick:()=>{ce(""),ie("all")},children:t("fileManager.clearFilters")})]}):le==="grid"?a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:xe.map(Oe=>a.jsx(ZZe,{file:Oe,isSelected:f.includes(Oe.id),isMobile:Q,t,onSelect:Ye,onDelete:xt=>k({type:"file",id:xt}),onDownload:pt,onAddToQueue:xt=>{const vt=z?.find(Bt=>Bt.id===xt);vt&&B(vt)},onPrint:E,onPreview3d:Y,onRename:xt=>V({type:"file",id:xt.id,name:xt.filename}),onGenerateThumbnail:xt=>Ae.mutate(xt.id),thumbnailVersion:q[Oe.id],hasPermission:r,canModify:s,authEnabled:o},Oe.id))})}):a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[a.jsx("div",{className:"w-6"}),a.jsx("div",{children:t("common.name")}),o&&a.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),a.jsx("div",{children:t("common.type")}),a.jsx("div",{children:t("fileManager.size")}),a.jsx("div",{children:t("fileManager.prints")}),a.jsx("div",{})]}),xe.map(Oe=>a.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${f.includes(Oe.id)?"bg-bambu-green/10":""}`,onClick:()=>Ye(Oe.id),children:[a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(Oe.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(Oe.id)&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsxs("div",{className:"relative group/thumb",children:[a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Oe.thumbnail_path?a.jsx("img",{src:`${se.getLibraryFileThumbnailUrl(Oe.id)}${q[Oe.id]?`?v=${q[Oe.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(ff,{className:"w-5 h-5 text-bambu-gray/50"})})}),Oe.thumbnail_path&&a.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:a.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:a.jsx("img",{src:`${se.getLibraryFileThumbnailUrl(Oe.id)}${q[Oe.id]?`?v=${q[Oe.id]}`:""}`,alt:Oe.filename,className:"w-full h-full object-contain"})})})]}),a.jsx("div",{className:"min-w-0",children:a.jsx("div",{className:"text-sm text-white truncate",children:Oe.print_name||Oe.filename})})]}),o&&a.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Oe.created_by_username?a.jsxs(a.Fragment,{children:[a.jsx(nd,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate",children:Oe.created_by_username})]}):"-"}),a.jsx("div",{children:a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Oe.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Oe.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Oe.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Oe.file_type.toUpperCase()})}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Bg(Oe.file_size)}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Oe.print_count>0?`${Oe.print_count}x`:"-"}),a.jsxs("div",{className:"flex items-center gap-1",onClick:xt=>xt.stopPropagation(),children:[fF(Oe.filename)&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>r("printers:control")&&E(Oe),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:a.jsx(Cr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{r("queue:create")&&B(Oe)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:a.jsx(Qn,{className:"w-4 h-4"})})]}),(Oe.file_type==="3mf"||Oe.file_type==="gcode"||Oe.file_type==="stl")&&a.jsx("button",{onClick:()=>r("library:read")&&Y(Oe),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:a.jsx(Qi,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>r("library:read")&&pt(Oe.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:a.jsx(di,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","update",Oe.created_by_id)&&V({type:"file",id:Oe.id,name:Oe.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Oe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Oe.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Oe.created_by_id),children:a.jsx($i,{className:"w-4 h-4"})}),Oe.file_type==="stl"&&a.jsx("button",{onClick:()=>s("library","update",Oe.created_by_id)&&Ae.mutate(Oe.id),className:`p-1.5 rounded transition-colors ${s("library","update",Oe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Oe.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:Ae.isPending||!s("library","update",Oe.created_by_id),children:a.jsx(ed,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","delete",Oe.created_by_id)&&k({type:"file",id:Oe.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Oe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","delete",Oe.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Oe.created_by_id),children:a.jsx(en,{className:"w-4 h-4"})})]})]},Oe.id))]})})]})]}),x&&a.jsx(WZe,{parentId:d,onClose:()=>v(!1),onSave:Oe=>_e.mutate(Oe),isLoading:_e.isPending,t}),b&&be&&a.jsx(XZe,{folders:be,selectedFiles:f,currentFolderId:d,onClose:()=>y(!1),onMove:Oe=>ye.mutate({fileIds:f,folderId:Oe}),isLoading:ye.isPending,t}),S&&a.jsx(QZe,{folderId:d,onClose:()=>N(!1),onUploadComplete:We,t}),A&&a.jsx(YZe,{folder:A,onClose:()=>M(null),onLink:Oe=>ke.mutate({id:A.id,data:Oe}),isLoading:ke.isPending,t}),T&&a.jsx(kn,{title:T.type==="folder"?t("fileManager.deleteFolder"):T.type==="bulk"?t("fileManager.deleteFilesCount",{count:T.count}):t("fileManager.deleteFile"),message:T.type==="folder"?t("fileManager.deleteFolderConfirm"):T.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:T.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Rt,loadingText:t("fileManager.deleting"),onConfirm:At,onCancel:()=>k(null)}),j&&a.jsx(Yu,{mode:"reprint",libraryFileId:j.id,archiveName:j.print_name||j.filename,onClose:()=>E(null),onSuccess:()=>{E(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),P&&a.jsx(Yu,{mode:"reprint",libraryFileId:P.id,archiveName:P.print_name||P.filename,onClose:()=>U(null),onSuccess:()=>{U(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),L&&a.jsx(Yu,{mode:"add-to-queue",libraryFileId:L.id,archiveName:L.print_name||L.filename,onClose:()=>B(null),onSuccess:()=>{B(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),K&&a.jsx(S4,{libraryFileId:K.id,title:K.print_name||K.filename,fileType:K.file_type,onClose:()=>Y(null)}),R&&a.jsx(KZe,{type:R.type,currentName:R.name,onClose:()=>V(null),onSave:Oe=>{R.type==="file"?Ue.mutate({id:R.id,filename:Oe}):je.mutate({id:R.id,name:Oe})},isLoading:Ue.isPending||je.isPending,t})]})}const qj=5,eJe=2e3,tJe=3e4,nJe=5e3;function rJe(){const{t}=Vt(),e=tn(),{showToast:n}=mn(),{hasPermission:r}=Ir(),{printerId:i}=Yk(),s=parseInt(i||"0",10),[o,l]=w.useState("stream"),[c,u]=w.useState(!1),[d,h]=w.useState(!1),[f,p]=w.useState(!0),[x,v]=w.useState(Date.now()),[b,y]=w.useState(!1),[S,N]=w.useState(!1),[A,M]=w.useState(0),[T,k]=w.useState(!1),[j,E]=w.useState(0),[P,U]=w.useState(1),[L,B]=w.useState({x:0,y:0}),[R,V]=w.useState(!1),[q,I]=w.useState({x:0,y:0}),[K,Y]=w.useState(null),[le,H]=w.useState(null),X=w.useRef(null),te=w.useRef(null),J=w.useRef(null),Se=w.useRef(null),fe=w.useRef(null),{data:me}=tt({queryKey:["printer",s],queryFn:()=>se.getPrinter(s),enabled:s>0}),{data:De}=tt({queryKey:["printerStatus",s],queryFn:()=>se.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),de=lt({mutationFn:ye=>se.setChamberLight(s,ye),onMutate:async ye=>{await e.cancelQueries({queryKey:["printerStatus",s]});const ke=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],Ue=>({...Ue,chamber_light:ye})),{previousStatus:ke}},onSuccess:(ye,ke)=>{n(`Chamber light ${ke?"on":"off"}`)},onError:(ye,ke,Ue)=>{Ue?.previousStatus&&e.setQueryData(["printerStatus",s],Ue.previousStatus),n(ye.message||t("printers.toast.failedToControlChamberLight"),"error")}}),ce=(De?.state==="RUNNING"||De?.state==="PAUSE"||De?.state==="PAUSED")&&(De?.printable_objects_count??0)>=2;w.useEffect(()=>(me&&(document.title=`${me.name} - Camera`),()=>{document.title="Bambuddy"}),[me]);const Ne=w.useRef(!1);w.useEffect(()=>{const ye=`/api/v1/printers/${s}/camera/stop`;Ne.current=!1;const ke=()=>{if(s>0&&!Ne.current){Ne.current=!0;const Ve={},Ae=rd();Ae&&(Ve.Authorization=`Bearer ${Ae}`),fetch(ye,{method:"POST",keepalive:!0,headers:Ve}).catch(()=>{})}},Ue=()=>{ke()};window.addEventListener("beforeunload",Ue);const je=X.current;return()=>{window.removeEventListener("beforeunload",Ue),je&&(je.src=""),ke()}},[s]),w.useEffect(()=>{if(f&&!b){const ke=setTimeout(()=>{p(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(ke)}},[o,f,x,b]),w.useEffect(()=>{const ye=()=>{const ke=!!document.fullscreenElement;N(ke),U(1),B({x:0,y:0}),o==="stream"&&!b&&(X.current&&(X.current.src=""),setTimeout(()=>{p(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",ye),()=>document.removeEventListener("fullscreenchange",ye)},[o,b]),w.useEffect(()=>{let ye;const ke=()=>{clearTimeout(ye),ye=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",ke),()=>{clearTimeout(ye),window.removeEventListener("resize",ke)}},[]),w.useEffect(()=>()=>{J.current&&clearTimeout(J.current),Se.current&&clearInterval(Se.current),fe.current&&clearInterval(fe.current)},[]);const ie=w.useCallback(()=>{if(A>=qj){k(!1),h(!0);return}const ye=Math.min(eJe*Math.pow(2,A),tJe);k(!0),E(Math.ceil(ye/1e3)),Se.current=setInterval(()=>{E(ke=>ke<=1?(Se.current&&clearInterval(Se.current),0):ke-1)},1e3),J.current=setTimeout(()=>{M(ke=>ke+1),k(!1),p(!0),h(!1),X.current&&(X.current.src=""),v(Date.now())},ye)},[A]);w.useEffect(()=>{if(o!=="stream"||f||T||b){fe.current&&(clearInterval(fe.current),fe.current=null);return}return fe.current=setInterval(async()=>{try{const ye=await se.getCameraStatus(s);(ye.stalled||!ye.active&&!d)&&(console.log(`Stream issue detected: stalled=${ye.stalled}, active=${ye.active}, reconnecting...`),fe.current&&(clearInterval(fe.current),fe.current=null),p(!1),ie())}catch{}},nJe),()=>{fe.current&&(clearInterval(fe.current),fe.current=null)}},[o,f,d,T,b,s,ie]);const Le=()=>{p(!1),o==="stream"&&A{if(p(!1),h(!1),M(0),k(!1),J.current&&clearTimeout(J.current),Se.current&&clearInterval(Se.current),X.current&&!localStorage.getItem("cameraWindowState")){const ye=X.current,ke=ye.naturalWidth,Ue=ye.naturalHeight;if(ke>0&&Ue>0){const Ae=window.outerWidth-window.innerWidth,Je=window.outerHeight-window.innerHeight,Pe=ke+16+Ae,Ye=Ue+45+16+Je;try{window.resizeTo(Pe,Ye)}catch{}}}},W=()=>{if(s>0){const ye={},ke=rd();ke&&(ye.Authorization=`Bearer ${ke}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:ye}).catch(()=>{})}},ue=ye=>{o===ye||b||(y(!0),p(!0),h(!1),M(0),k(!1),U(1),B({x:0,y:0}),J.current&&clearTimeout(J.current),Se.current&&clearInterval(Se.current),X.current&&(X.current.src=""),o==="stream"&&W(),setTimeout(()=>{l(ye),v(Date.now()),y(!1)},100))},Z=()=>{b||(y(!0),p(!0),h(!1),M(0),k(!1),J.current&&clearTimeout(J.current),Se.current&&clearInterval(Se.current),X.current&&(X.current.src=""),o==="stream"&&W(),setTimeout(()=>{v(Date.now()),y(!1)},100))},oe=()=>{te.current&&(document.fullscreenElement?document.exitFullscreen():te.current.requestFullscreen())},Q=()=>{U(ye=>Math.min(ye+.5,4))},he=()=>{U(ye=>{const ke=Math.max(ye-.5,1);return ke===1&&B({x:0,y:0}),ke})},be=ye=>{ye.preventDefault(),ye.deltaY<0?Q():he()},ee=ye=>{P>1&&(ye.preventDefault(),V(!0),I({x:ye.clientX-L.x,y:ye.clientY-L.y}))},z=w.useCallback(()=>{if(!te.current)return{x:300,y:200};const ye=te.current.getBoundingClientRect(),ke=ye.width*(P-1)/2,Ue=ye.height*(P-1)/2;return{x:Math.max(50,ke),y:Math.max(50,Ue)}},[P]),D=ye=>{if(R&&P>1){const ke=ye.clientX-q.x,Ue=ye.clientY-q.y,je=z();B({x:Math.max(-je.x,Math.min(je.x,ke)),y:Math.max(-je.y,Math.min(je.y,Ue))})}},G=()=>{V(!1)},pe=ye=>{if(ye.length<2)return 0;const ke=ye[0].clientX-ye[1].clientX,Ue=ye[0].clientY-ye[1].clientY;return Math.sqrt(ke*ke+Ue*Ue)},ve=ye=>ye.length<2?{x:ye[0].clientX,y:ye[0].clientY}:{x:(ye[0].clientX+ye[1].clientX)/2,y:(ye[0].clientY+ye[1].clientY)/2},xe=ye=>{ye.touches.length===2?(ye.preventDefault(),Y(pe(ye.touches)),H(ve(ye.touches))):ye.touches.length===1&&P>1&&(ye.preventDefault(),V(!0),I({x:ye.touches[0].clientX-L.x,y:ye.touches[0].clientY-L.y}))},ze=ye=>{if(ye.touches.length===2&&K!==null){ye.preventDefault();const ke=pe(ye.touches),Ue=ke/K;U(Ve=>{const Ae=Math.max(1,Math.min(4,Ve*Ue));return Ae===1&&B({x:0,y:0}),Ae}),Y(ke);const je=ve(ye.touches);if(le){const Ve=z();B(Ae=>({x:Math.max(-Ve.x,Math.min(Ve.x,Ae.x+(je.x-le.x))),y:Math.max(-Ve.y,Math.min(Ve.y,Ae.y+(je.y-le.y)))}))}H(je)}else if(ye.touches.length===1&&R&&P>1){ye.preventDefault();const ke=ye.touches[0].clientX-q.x,Ue=ye.touches[0].clientY-q.y,je=z();B({x:Math.max(-je.x,Math.min(je.x,ke)),y:Math.max(-je.y,Math.min(je.y,Ue))})}},_e=ye=>{ye.touches.length<2&&(Y(null),H(null)),ye.touches.length===0&&V(!1)},He=()=>{U(1),B({x:0,y:0})},Ze=b?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${x}`:`/api/v1/printers/${s}/camera/snapshot?t=${x}`,we=f||b||T;return s?a.jsxs("div",{ref:te,className:"min-h-screen bg-black flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[a.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(mb,{className:"w-4 h-4"}),me?.name||`Printer ${s}`]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[a.jsx("button",{onClick:()=>ue("stream"),disabled:we,className:`px-3 py-1 text-xs rounded transition-colors ${o==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),a.jsx("button",{onClick:()=>ue("snapshot"),disabled:we,className:`px-3 py-1 text-xs rounded transition-colors ${o==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),a.jsx("button",{onClick:()=>de.mutate(!De?.chamber_light),disabled:!De?.connected||de.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${De?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:a.jsx(bL,{on:De?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>u(!0),disabled:!ce||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${ce&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(ce?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:a.jsx(_C,{className:"w-4 h-4 text-bambu-gray"})}),a.jsx("button",{onClick:Z,disabled:we,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:a.jsx(kr,{className:`w-4 h-4 text-bambu-gray ${we?"animate-spin":""}`})}),a.jsx("button",{onClick:oe,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(S?"camera.exitFullscreen":"camera.fullscreen"),children:S?a.jsx(pX,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Kme,{className:"w-4 h-4 text-bambu-gray"})})]})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:be,onMouseMove:D,onMouseUp:G,onMouseLeave:G,onTouchStart:xe,onTouchMove:ze,onTouchEnd:_e,style:{touchAction:"none"},children:a.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(f||b)&&!T&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:a.jsxs("div",{className:"text-center",children:[a.jsx(kr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),T&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Df,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:j,attempt:A+1,max:qj})}),a.jsx("button",{onClick:Z,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),d&&!T&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Cn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),a.jsx("button",{onClick:Z,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),a.jsx("img",{ref:X,src:Ze,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${P}) translate(${L.x/P}px, ${L.y/P}px)`,cursor:P>1?R?"grabbing":"grab":"default"},onError:Ze?Le:void 0,onLoad:Ze?$:void 0,onMouseDown:ee,draggable:!1},x),a.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[a.jsx("button",{onClick:he,disabled:P<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:a.jsx(HF,{className:"w-4 h-4 text-white"})}),a.jsxs("button",{onClick:He,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(P*100),"%"]}),a.jsx("button",{onClick:Q,disabled:P>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:a.jsx(BF,{className:"w-4 h-4 text-white"})})]})]})}),a.jsx(xL,{printerId:s,isOpen:c,onClose:()=>u(!1)})]}):a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function iJe(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:r,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function aJe(t){const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function sJe(t,e){const n=new Date,r=new Date(n.getTime()+t*60*1e3),i=new Date;i.setHours(0,0,0,0);const s=new Date(r);s.setHours(0,0,0,0);const o=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return s.getTime()===i.getTime()?o:s.getTime()===i.getTime()+864e5?`${e("streamOverlay.tomorrow")} ${o}`:r.toLocaleDateString([],{weekday:"short"})+" "+o}function oJe(t,e){if(t.stg_cur_name)return t.stg_cur_name;switch(t.state){case"RUNNING":return e("streamOverlay.status.printing");case"PAUSE":return e("streamOverlay.status.paused");case"FINISH":return e("streamOverlay.status.finished");case"FAILED":return e("streamOverlay.status.failed");case"IDLE":return e("streamOverlay.status.idle");default:return t.state||e("streamOverlay.status.unknown")}}function lJe(t){switch(t){case"small":return{container:"p-3",text:"text-sm",textLarge:"text-lg",progressHeight:"h-2",icon:"w-3 h-3",gap:"gap-2",logoHeight:"h-12"};case"large":return{container:"p-6",text:"text-xl",textLarge:"text-3xl",progressHeight:"h-4",icon:"w-6 h-6",gap:"gap-4",logoHeight:"h-24"};default:return{container:"p-4",text:"text-base",textLarge:"text-xl",progressHeight:"h-3",icon:"w-4 h-4",gap:"gap-3",logoHeight:"h-16"}}}function cJe(){const{printerId:t}=Yk(),[e]=NF(),{t:n}=Vt(),r=tn(),i=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>iJe(e),[e]),c=lJe(l.size),{data:u}=tt({queryKey:["printer",i],queryFn:()=>se.getPrinter(i),enabled:i>0}),{data:d}=tt({queryKey:["printerStatus",i],queryFn:()=>se.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3});w.useEffect(()=>{if(!i)return;const b=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,y=new WebSocket(b);return y.onmessage=S=>{try{const N=JSON.parse(S.data);N.type==="printer_status"&&N.printer_id===i&&r.setQueryData(["printerStatus",i],N.status)}catch{}},y.onerror=()=>{},()=>{y.close()}},[i,r]),w.useEffect(()=>(document.title=u?`${u.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[u,n]);const h=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!d)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const f=d.state==="RUNNING"||d.state==="PAUSE",p=d.progress||0,x=`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`;return a.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&a.jsx("img",{src:x,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",onError:h},s),a.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:a.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),a.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:a.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&u&&a.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[a.jsx(Cr,{className:`${c.icon} text-white/70`}),a.jsx("span",{className:`${c.text} text-white font-medium`,children:u.name})]}),l.showFilename&&d.current_print&&a.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:d.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,"")}),l.showStatus&&a.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:oJe(d,n)}),l.showProgress&&f&&a.jsxs("div",{className:"mb-3",children:[a.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[a.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),a.jsxs("span",{className:"text-white font-bold",children:[Math.round(p),"%"]})]}),a.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:a.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${p}%`}})})]}),f&&(l.showLayers||l.showEta)&&a.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&d.layer_num!=null&&d.total_layers!=null&&d.total_layers>0&&a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(rs,{className:c.icon}),a.jsxs("span",{className:c.text,children:[a.jsx("span",{className:"text-white",children:d.layer_num}),a.jsx("span",{className:"mx-1",children:"/"}),a.jsx("span",{children:d.total_layers})]})]}),l.showEta&&d.remaining_time!=null&&d.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(Ou,{className:c.icon}),a.jsx("span",{className:`${c.text} text-white`,children:aJe(d.remaining_time*60)})]}),a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(Qn,{className:c.icon}),a.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",sJe(d.remaining_time,n)]})]})]})]}),!f&&a.jsx("div",{className:`${c.text} text-white/70 py-2`,children:d.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function uJe(){const{t}=Vt(),{id:e}=Yk(),{mode:n}=np(),{data:r,isLoading:i,error:s}=tt({queryKey:["external-link",e],queryFn:()=>se.getExternalLink(Number(e)),enabled:!!e});return i?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[a.jsx(Cn,{className:"w-12 h-12"}),a.jsx("p",{children:t("common.linkNotFound")})]}):a.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}const dK={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,weight_used:0,slicer_filament:"",note:""};function dJe(t){const e={};return t.slicer_filament||(e.slicer_filament="Slicer preset is required"),t.material||(e.material="Material is required"),{isValid:Object.keys(e).length===0,errors:e}}const hJe=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],mJe=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],y0=["Basic","Matte","Silk","Tough","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],Yae=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"}],fJe=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],hK=[...Yae,...fJe],Qae="bambuddy-recent-colors",pJe=8,gJe=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function Wk(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PCTG","PEEK","PEI"];let r="",i=-1;for(const c of n){const u=e.toUpperCase().indexOf(c.toUpperCase());if(u!==-1){r=c,i=u;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&r&&(o=e.substring(i+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of y0)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of y0){const u=new RegExp(`\\s+${c}$`,"i");if(u.test(s)){l=c,s=s.replace(u,"").trim();break}}return{brand:s,material:r,variant:l}}function bJe(t,e){const n=new Set(mJe);for(const r of t){const{brand:i}=Wk(r.name);i&&i.length>1&&n.add(i)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:i}=Wk(r.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((r,i)=>r.localeCompare(i))}function xJe(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const i=r.name.replace(/@.*$/,"").trim(),s=n.get(i);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(i,{code:o,name:i,displayName:i,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,i)=>r.displayName.localeCompare(i.displayName))}function yJe(t,e,n){if(t.length>0){const r=[],i=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=i.get(o);l?l.allCodes.push(s.setting_id):i.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(i.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=xJe(n);if(r.length>0)return r}return gJe}function vJe(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(i=>i.code.toLowerCase()===r||i.allCodes.some(s=>s.toLowerCase()===r))}return n}function wJe(){try{const t=localStorage.getItem(Qae);if(t)return JSON.parse(t)}catch{}return[]}function _Je(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,pJe);try{localStorage.setItem(Qae,JSON.stringify(r))}catch{}return r}function Wj(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=Wk(r);return!(!(i.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(i.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(i.brand.toLowerCase()))||e.subtype&&!(i.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(i.variant.toLowerCase())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function SJe({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c}){const{t:u}=Vt(),[d,h]=w.useState(!1),[f,p]=w.useState(!1),[x,v]=w.useState(!1),[b,y]=w.useState(""),[S,N]=w.useState(""),A=w.useRef(null),M=w.useRef(null),T=w.useRef(null);w.useEffect(()=>{const U=L=>{A.current&&!A.current.contains(L.target)&&h(!1),M.current&&!M.current.contains(L.target)&&p(!1),T.current&&!T.current.contains(L.target)&&v(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[]);const k=w.useMemo(()=>{if(!i)return l;const U=i.toLowerCase();return l.filter(L=>L.displayName.toLowerCase().includes(U)||L.code.toLowerCase().includes(U))},[l,i]),j=w.useMemo(()=>{if(!b)return c;const U=b.toLowerCase();return c.filter(L=>L.toLowerCase().includes(U))},[c,b]),E=w.useMemo(()=>{if(!S)return y0;const U=S.toLowerCase();return y0.filter(L=>L.toLowerCase().includes(U))},[S]),P=U=>{e("slicer_filament",U.code),s(U.displayName),h(!1);const L=Wk(U.name);L.material&&e("material",L.material),L.brand&&e("brand",L.brand),L.variant&&e("subtype",L.variant)};return a.jsxs("div",{className:"space-y-4",children:[a.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-3 h-3 animate-spin"})," ",u("inventory.loadingPresets")]}):n?a.jsxs(a.Fragment,{children:[a.jsx(Gb,{className:"w-3 h-3 text-bambu-green"})," ",u("inventory.cloudConnected")]}):a.jsxs(a.Fragment,{children:[a.jsx(uhe,{className:"w-3 h-3"})," ",u("inventory.cloudNotConnected")]})}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[u("inventory.slicerPreset")," *"]}),a.jsxs("div",{className:"relative",ref:A,children:[a.jsx(Or,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:u("inventory.searchPresets"),value:i,onChange:U=>{s(U.target.value),h(!0)},onFocus:()=>{h(!0),s("")}}),d&&a.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:k.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:u("inventory.noPresetsFound")}):k.map(U=>a.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${o?.code===U.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>P(U),children:[a.jsx("span",{className:"truncate",children:U.displayName}),a.jsx("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:U.code})]},U.code))})]}),o&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[u("inventory.selectedPreset"),": ",a.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[u("inventory.material")," *"]}),a.jsxs("select",{value:t.material,onChange:U=>e("material",U.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"",children:u("inventory.selectMaterial")}),hJe.map(U=>a.jsx("option",{value:U,children:U},U))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:u("inventory.brand")}),a.jsxs("div",{className:"relative",ref:M,children:[a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:u("inventory.searchBrand"),value:f?b:t.brand,onChange:U=>{y(U.target.value),p(!0)},onFocus:()=>{p(!0),y("")}}),a.jsx(nr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),f&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[j.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:u("inventory.noResults")}):j.map(U=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===U?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",U),p(!1),y("")},children:U},U)),b&&!j.includes(b)&&a.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",b),p(!1),y("")},children:u("inventory.useCustomBrand",{brand:b})})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:u("inventory.subtype")}),a.jsxs("div",{className:"relative",ref:T,children:[a.jsx("input",{type:"text",value:x?S:t.subtype,onChange:U=>{N(U.target.value),v(!0)},onFocus:()=>{v(!0),N("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),a.jsx(nr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),x&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[E.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:u("inventory.noResults")}):E.map(U=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===U?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",U),v(!1),N("")},children:U},U)),S&&!y0.some(U=>U.toLowerCase()===S.toLowerCase().trim())&&a.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",S),v(!1),N("")},children:u("inventory.useCustomBrand",{brand:S})})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:u("inventory.labelWeight")}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"number",value:t.label_weight,onChange:U=>e("label_weight",parseInt(U.target.value)||0),className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]})]})}function NJe({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:i}){const{t:s}=Vt(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=t.rgba.replace("#","").substring(0,6),h=y=>d.toUpperCase()===y.toUpperCase(),f=(y,S)=>{e("rgba",y.toUpperCase()+"FF"),e("color_name",S),r({name:S,hex:y})},p=w.useMemo(()=>{if(i.length===0)return[];const y=t.brand?.trim(),S=t.material?.toLowerCase().trim(),N=t.subtype?.toLowerCase().trim();if(!y&&!S)return[];const A=y?y.toLowerCase().split(/[\s\-_]+/).filter(k=>k.length>=2):[],M=k=>{if(A.length===0)return!0;const j=k.toLowerCase();return A.some(E=>j.includes(E))},T=S&&N?`${S} ${N}`:"";if(T){const k=i.filter(E=>M(E.manufacturer)&&E.material?.toLowerCase()===T);if(k.length>0)return k.map(E=>({name:E.color_name,hex:E.hex_color.replace("#","").substring(0,6)}));const j=T.replace(/\+$/,"");if(j!==T){const E=i.filter(P=>M(P.manufacturer)&&P.material?.toLowerCase()===j);if(E.length>0)return E.map(P=>({name:P.color_name,hex:P.hex_color.replace("#","").substring(0,6)}))}}if(S){const k=i.filter(j=>M(j.manufacturer)&&(!j.material||j.material.toLowerCase().startsWith(S)));if(k.length>0)return k.map(j=>({name:j.color_name,hex:j.hex_color.replace("#","").substring(0,6)}))}return[]},[i,t.brand,t.material,t.subtype]),x=p.length>0,v=w.useMemo(()=>{if(!c)return p;const y=c.toLowerCase();return p.filter(S=>S.name.toLowerCase().includes(y))},[p,c]),b=w.useMemo(()=>c?hK.filter(y=>y.name.toLowerCase().includes(c.toLowerCase())):o?hK:Yae,[c,o]);return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${d}`}}),n.length>0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[a.jsx(Qn,{className:"w-3 h-3"}),a.jsx("span",{children:s("inventory.recentColors")})]}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(y=>a.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name},y.hex))})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Or,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:y=>u(y.target.value)})]}),x?a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[v.map(y=>a.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 relative group ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name,children:a.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10 shadow-lg text-white",children:y.name})},`${y.hex}-${y.name}`)),v.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&a.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?a.jsxs(a.Fragment,{children:[s("inventory.showLess")," ",a.jsx(ql,{className:"w-3 h-3"})]}):a.jsxs(a.Fragment,{children:[s("inventory.showAll")," ",a.jsx(nr,{className:"w-3 h-3"})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(y=>a.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 relative group ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name,children:a.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10 shadow-lg text-white",children:y.name})},y.hex)),b.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:y=>e("color_name",y.target.value)})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),a.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:d.toUpperCase(),onChange:y=>{const S=y.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");S.length<=8&&e("rgba",S.toUpperCase()+(S.length<=6?"FF":""))}})]}),a.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${d}`,onChange:y=>{const S=y.target.value.replace("#","").toUpperCase();e("rgba",S+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function kJe({catalog:t,value:e,onChange:n}){const{t:r}=Vt(),[i,s]=w.useState(!1),[o,l]=w.useState(""),[c,u]=w.useState(null),d=w.useRef(null),h=w.useRef(null);w.useEffect(()=>{const x=v=>{d.current&&!d.current.contains(v.target)&&s(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[]);const f=w.useMemo(()=>{if(!o)return t;const x=o.toLowerCase();return t.filter(v=>v.name.toLowerCase().includes(x)||v.weight.toString().includes(x))},[t,o]),p=w.useMemo(()=>{if(i)return o;if(c){const v=t.find(b=>b.id===c);if(v)return v.name}const x=t.find(v=>v.weight===e);return x?x.name:""},[i,o,c,t,e]);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Efe,{className:"w-3.5 h-3.5 text-bambu-gray"}),r("inventory.coreWeight")]})}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsxs("div",{className:"flex-1 min-w-0 relative",ref:d,children:[a.jsx("input",{ref:h,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:r("inventory.searchSpoolWeight"),value:p,onFocus:()=>{s(!0),l("")},onChange:x=>{l(x.target.value),s(!0)}}),i&&a.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:f.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:r("inventory.noResults")}):f.map(x=>a.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(c?x.id===c:x.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{u(x.id),n(x.weight),s(!1),l("")},children:[a.jsx("span",{className:"truncate",children:x.name}),a.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[x.weight,"g"]})]},x.id))})]}),a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[a.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:x=>{const v=parseInt(x.target.value);!isNaN(v)&&v>=0&&n(v)}}),a.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function CJe({formData:t,updateField:e,spoolCatalog:n}){const{t:r}=Vt(),{showToast:i}=mn(),[s,o]=w.useState(""),[l,c]=w.useState(!1),u=Math.max(0,t.label_weight-t.weight_used),d=t.core_weight+u;return w.useEffect(()=>{l||o(String(d))},[l,d]),a.jsxs("div",{className:"space-y-4",children:[a.jsx(kJe,{catalog:n,value:t.core_weight,onChange:h=>e("core_weight",h)}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r("inventory.currentWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:u,min:0,max:t.label_weight,onChange:h=>{const f=parseInt(h.target.value)||0;e("weight_used",Math.max(0,t.label_weight-f))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r("inventory.measuredWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:s,min:0,onFocus:()=>c(!0),onChange:h=>{o(h.target.value)},onBlur:()=>{c(!1);const h=s.trim(),f=Number(h),p=t.core_weight,x=t.core_weight+t.label_weight;if(!h||!Number.isFinite(f)||fx){i(r("inventory.measuredWeightError",{min:p,max:x}),"error"),o(String(d));return}const v=Math.round(f),b=Math.max(0,Math.min(t.label_weight,v-t.core_weight));e("weight_used",Math.max(0,t.label_weight-b)),o(String(v))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r("inventory.note")}),a.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:r("inventory.notePlaceholder"),value:t.note,onChange:h=>e("note",h.target.value)})]})]})}function MJe({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=Vt(),l=f=>{s(p=>{const x=new Set(p);return x.has(f)?x.delete(f):x.add(f),x})},c=(f,p,x)=>{const v=`${f}:${p}:${x??"null"}`,b=`${f}:${x??"null"}`;r(y=>{const S=new Set(y);if(S.has(v))S.delete(v);else{for(const N of Array.from(S)){const A=N.split(":");`${A[0]}:${A[2]}`===b&&S.delete(N)}S.add(v)}return S})},u=()=>{const f=new Set;for(const{printer:p,calibrations:x}of e){if(!p.connected)continue;const v=x.filter(y=>Wj(y,t)),b=new Map;for(const y of v){const S=`${y.extruder_id??"null"}`;b.has(S)||b.set(S,[]),b.get(S).push(y)}for(const[y,S]of b)if(S.length>0){const A=[...S].sort((M,T)=>T.k_value-M.k_value)[0];f.add(`${p.id}:${A.cali_idx}:${y}`)}}r(f)};if(!t.material)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const d=e.reduce((f,{printer:p,calibrations:x})=>p.connected?f+x.filter(v=>Wj(v,t)).length:f,0),h=(f,p)=>{const x=`${f.id}:${p.cali_idx}:${p.extruder_id??"null"}`,v=n.has(x);return a.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[a.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(f.id),p.cali_idx,p.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:p.name||p.filament_id})}),a.jsx("div",{className:"flex items-center gap-2 shrink-0",children:a.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",p.k_value.toFixed(3)]})})]},`${p.cali_idx}-${p.extruder_id}`)};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),d>0&&a.jsxs("button",{type:"button",onClick:u,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[a.jsx(pb,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",d,")"]})]}),a.jsx("div",{className:"space-y-3",children:e.map(({printer:f,calibrations:p})=>{const x=i.has(String(f.id)),v=p.filter(A=>Wj(A,t)),b=v.length,y=v.some(A=>A.extruder_id!==void 0&&A.extruder_id!==null&&A.extruder_id>0),S=v.filter(A=>A.extruder_id===1),N=v.filter(A=>A.extruder_id===0||A.extruder_id===void 0||A.extruder_id===null);return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("button",{type:"button",onClick:()=>l(String(f.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[x?a.jsx(nr,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(fa,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"font-medium text-white",children:f.name}),b>0?a.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[b," ",o(b!==1?"inventory.matches":"inventory.match")]}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),a.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${f.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:f.connected?o("inventory.connected"):o("inventory.offline")})]}),x&&a.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:f.connected?b===0?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):y?a.jsxs(a.Fragment,{children:[S.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),a.jsx("div",{className:"space-y-2",children:S.map(A=>h(f,A))})]}),N.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),a.jsx("div",{className:"space-y-2",children:N.map(A=>h(f,A))})]})]}):a.jsx("div",{className:"space-y-2",children:v.map(A=>h(f,A))}):a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},f.id)})}),n.size>0&&a.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function AJe(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const TJe={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function EJe({spoolId:t}){const{t:e}=Vt(),n=tn(),{showToast:r}=mn(),{data:i,isLoading:s}=tt({queryKey:["spool-usage",t],queryFn:()=>se.getSpoolUsageHistory(t)}),o=lt({mutationFn:()=>se.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(at,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?a.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[a.jsx(Qn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),a.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[a.jsx(en,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>a.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-bambu-gray",children:AJe(l.created_at)}),l.print_name&&a.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[a.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),a.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),a.jsx("span",{className:TJe[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function PJe({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[]}){const{t:i}=Vt(),s=tn(),{showToast:o}=mn(),l=!!n,[c,u]=w.useState(dK),[d,h]=w.useState({}),[f,p]=w.useState("filament"),[x,v]=w.useState(!1),[b,y]=w.useState(!1),[S,N]=w.useState(!1),[A,M]=w.useState([]),[T,k]=w.useState(""),[j,E]=w.useState([]),[P,U]=w.useState([]),[L,B]=w.useState([]),[R,V]=w.useState([]),[q,I]=w.useState([]),[K,Y]=w.useState(new Set),[le,H]=w.useState(new Set),X=r.length>0?r:q,te=w.useMemo(()=>K.size,[K]);w.useEffect(()=>{V(wJe())},[]),w.useEffect(()=>{t&&((async()=>{N(!0);try{const W=await se.getCloudStatus();if(y(W.is_authenticated),W.is_authenticated){const ue=await se.getFilamentPresets();M(ue)}}catch(W){console.error("Failed to fetch cloud presets:",W),y(!1)}finally{N(!1)}})(),se.getSpoolCatalog().then(E).catch(console.error),se.getColorCatalog().then(B).catch(console.error),se.getLocalPresets().then(W=>U(W.filament)).catch(console.error),r.length===0&&(async()=>{try{const W=await se.getPrinters(),ue=await Promise.all(W.map(oe=>se.getPrinterStatus(oe.id).catch(()=>null))),Z=[];for(let oe=0;oe({cali_idx:D.slot_id,filament_id:D.filament_id,setting_id:D.setting_id||"",name:D.name,k_value:parseFloat(D.k_value)||0,n_coef:parseFloat(D.n_coef)||0,extruder_id:D.extruder_id,nozzle_diameter:D.nozzle_diameter}))}catch{}Z.push({printer:{...Q,connected:be},calibrations:ee})}I(Z)}catch(W){console.error("Failed to fetch printer calibrations:",W)}})())},[t,r.length]);const J=w.useMemo(()=>yJe(A,new Set,P),[A,P]),Se=w.useMemo(()=>bJe(A,P),[A,P]),fe=w.useMemo(()=>vJe(c.slicer_filament,J),[c.slicer_filament,J]);w.useEffect(()=>{if(t){if(n)if(u({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||""}),k(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const $=new Set;for(const W of n.k_profiles)W.cali_idx!==null&&W.cali_idx!==void 0&&$.add(`${W.printer_id}:${W.cali_idx}:${W.extruder??"null"}`);Y($)}else Y(new Set);else u(dK),k(""),Y(new Set);h({}),p("filament"),v(!1)}},[t,n]),w.useEffect(()=>{t&&X.length>0&&H(new Set(X.map($=>String($.printer.id))))},[t,X]);const me=($,W)=>{u(ue=>({...ue,[$]:W})),$==="weight_used"&&v(!0),d[$]&&h(ue=>({...ue,[$]:void 0}))},De=$=>{V(W=>_Je($,W))},de=lt({mutationFn:$=>se.createSpool($),onSuccess:async $=>{K.size>0&&$?.id&&await Ne($.id),await s.invalidateQueries({queryKey:["inventory-spools"]}),o(i("inventory.spoolCreated"),"success"),e()},onError:$=>{o($.message,"error")}}),ce=lt({mutationFn:$=>se.updateSpool(n.id,$),onSuccess:async()=>{n?.id&&await Ne(n.id),await s.invalidateQueries({queryKey:["inventory-spools"]}),o(i("inventory.spoolUpdated"),"success"),e()},onError:$=>{o($.message,"error")}}),Ne=async $=>{if(K.size===0){try{await se.saveSpoolKProfiles($,[])}catch{}return}const W=[];for(const ue of K){const[Z,oe,Q]=ue.split(":"),he=parseInt(Z),be=parseInt(oe),ee=Q==="null"?0:parseInt(Q),z=X.find(D=>D.printer.id===he);if(z){const D=z.calibrations.find(G=>G.cali_idx===be);D&&W.push({printer_id:he,extruder:ee,nozzle_diameter:D.nozzle_diameter||"0.4",k_value:D.k_value,name:D.name||null,cali_idx:D.cali_idx,setting_id:D.setting_id||null})}}if(W.length>0)try{await se.saveSpoolKProfiles($,W)}catch(ue){console.error("Failed to save K-profiles:",ue)}};if(w.useEffect(()=>{if(!t)return;const $=W=>{W.key==="Escape"&&e()};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[t,e]),!t)return null;const ie=()=>{const $=dJe(c);if(!$.isValid){h($.errors),($.errors.slicer_filament||$.errors.material)&&p("filament");return}const W=fe?.displayName||T||null,ue={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,slicer_filament:c.slicer_filament||null,slicer_filament_name:W,nozzle_temp_min:null,nozzle_temp_max:null,note:c.note||null};(!l||x)&&(ue.weight_used=c.weight_used),l?ce.mutate(ue):de.mutate(ue)},Le=de.isPending||ce.isPending;return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.jsxs("div",{className:"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:i(l?"inventory.editSpool":"inventory.addSpool")}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Ft,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("button",{onClick:()=>p("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${f==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(iC,{className:"w-4 h-4"}),i("inventory.filamentInfoTab")]}),a.jsxs("button",{onClick:()=>p("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${f==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(_de,{className:"w-4 h-4"}),i("inventory.paProfileTab"),te>0&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:te})]})]}),a.jsx("div",{className:"p-4 overflow-y-auto flex-1",children:f==="filament"?a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:i("inventory.filamentInfo")}),a.jsx(SJe,{formData:c,updateField:me,cloudAuthenticated:b,loadingCloudPresets:S,presetInputValue:T,setPresetInputValue:k,selectedPresetOption:fe,filamentOptions:J,availableBrands:Se}),d.slicer_filament&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:d.slicer_filament}),d.material&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:d.material})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:i("inventory.color")}),a.jsx(NJe,{formData:c,updateField:me,recentColors:R,onColorUsed:De,catalogColors:L})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:i("inventory.additional")}),a.jsx(CJe,{formData:c,updateField:me,spoolCatalog:j})]}),l&&n&&a.jsx("div",{children:a.jsx(EJe,{spoolId:n.id})})]}):a.jsx(MJe,{formData:c,updateField:me,printersWithCalibrations:X,selectedProfiles:K,setSelectedProfiles:Y,expandedPrinters:le,setExpandedPrinters:H})}),a.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx(Me,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Me,{onClick:ie,disabled:Le,children:Le?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),i("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(bs,{className:"w-4 h-4"}),i(l?"common.save":"inventory.addSpool")]})})]})]})]})}function jJe({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:i}){const{t:s}=Vt(),[o,l]=w.useState(n),[c,u]=w.useState(null),d=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(A=>({...A})))},[t,n]),w.useEffect(()=>{if(!t)return;const A=M=>{M.key==="Escape"&&e()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[t,e]),!t)return null;const h=A=>{l(M=>M.map((T,k)=>k===A?{...T,visible:!T.visible}:T))},f=(A,M)=>{M<0||M>=o.length||l(T=>{const k=[...T],[j]=k.splice(A,1);return k.splice(M,0,j),k})},p=(A,M)=>{d.current=M,u(M),A.dataTransfer.effectAllowed="move"},x=(A,M)=>{A.preventDefault(),A.dataTransfer.dropEffect="move";const T=d.current;T!==null&&T!==M&&(f(T,M),d.current=M,u(M))},v=A=>{A.preventDefault()},b=()=>{d.current=null,u(null)},y=()=>{l(r.map(A=>({...A})))},S=()=>{i(o),e()},N=o.filter(A=>A.visible).length;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsx(_t,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:A=>A.stopPropagation(),children:a.jsxs(Nt,{className:"p-6 flex flex-col min-h-0",children:[a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),a.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),a.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),a.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((A,M)=>a.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===M?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${A.visible?"":"opacity-50"}`,draggable:!0,onDragStart:T=>p(T,M),onDragOver:T=>x(T,M),onDrop:v,onDragEnd:b,children:[a.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:a.jsx(Ph,{className:"w-4 h-4"})}),a.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:A.label}),a.jsxs("div",{className:"flex items-center gap-0.5",children:[a.jsx("button",{onClick:()=>f(M,M-1),disabled:M===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:a.jsx(ql,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>f(M,M+1),disabled:M===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:a.jsx(nr,{className:"w-4 h-4"})})]}),a.jsx("button",{onClick:()=>h(M),className:`p-1.5 rounded transition-colors ${A.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:A.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:A.visible?a.jsx(Kl,{className:"w-4 h-4"}):a.jsx(gv,{className:"w-4 h-4"})})]},A.id))}),a.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs(Me,{variant:"secondary",onClick:y,className:"mr-auto",children:[a.jsx(Do,{className:"w-4 h-4"}),s("inventory.reset")]}),a.jsx(Me,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),a.jsx(Me,{onClick:S,children:s("inventory.applyChanges")})]})]})})})}const Zae="bambuddy-inventory-columns",S1=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"remaining",label:"Remaining",visible:!0}];function DJe(){try{const t=localStorage.getItem(Zae);if(t){const e=JSON.parse(t),n=new Set(S1.map(o=>o.id)),r=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=S1.filter(o=>!r.has(o.id));return[...i,...s]}}catch{}return S1.map(t=>({...t}))}function RJe(t){try{localStorage.setItem(Zae,JSON.stringify(t))}catch{}}function Fu(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const FJe={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function Kj(t){return t?new Date(t).toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"}):"-"}const LJe={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",remaining:t=>t("inventory.remaining")},OJe={id:({spool:t})=>a.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:Kj(t.created_at)}),encode_time:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:Kj(t.encode_time)}),last_used_time:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?Kj(t.last_used):"Never"}),rgba:({spool:t})=>a.jsx("div",{className:"flex items-center justify-center",children:a.jsx("span",{className:"w-5 h-5 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:pne(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,i=String.fromCharCode(65+n.ams_id),s=n.tray_id+1;return a.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[r," ",i,s]})},label_weight:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:Fu(t.label_weight)}),net:({remaining:t})=>a.jsx("span",{className:"text-sm text-white",children:Fu(t)}),gross:({spool:t,remaining:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:Fu(e+t.core_weight)}),added_full:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?Fu(t.weight_used):"-"}),printed_total:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?a.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),remaining:({remaining:t,pct:e})=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),a.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]})},Xj={id:t=>t.id,added_time:t=>t.created_at||"",encode_time:t=>t.encode_time||"",last_used_time:t=>t.last_used||"",material:t=>(t.material||"").toLowerCase(),subtype:t=>(t.subtype||"").toLowerCase(),color_name:t=>(t.color_name||"").toLowerCase(),brand:t=>(t.brand||"").toLowerCase(),slicer_filament:t=>(t.slicer_filament_name||t.slicer_filament||"").toLowerCase(),location:(t,e)=>{const n=e[t.id];return n?`${n.printer_name||""} ${String.fromCharCode(65+n.ams_id)}${n.tray_id+1}`:""},label_weight:t=>t.label_weight,net:t=>Math.max(0,t.label_weight-t.weight_used),gross:t=>Math.max(0,t.label_weight-t.weight_used)+t.core_weight,used:t=>t.weight_used,remaining:t=>t.label_weight>0?Math.max(0,t.label_weight-t.weight_used)/t.label_weight:0,note:t=>(t.note||"").toLowerCase(),data_origin:t=>(t.data_origin||"").toLowerCase(),tag_type:t=>(t.tag_type||"").toLowerCase()},pF="bambuddy-inventory-sort";function IJe(){try{const t=localStorage.getItem(pF);if(t)return JSON.parse(t)}catch{}return null}function zJe(t){try{t?localStorage.setItem(pF,JSON.stringify(t)):localStorage.removeItem(pF)}catch{}}function UJe(){const{t}=Vt(),e=tn(),{showToast:n}=mn(),[r,i]=w.useState(null),[s,o]=w.useState(null),[l,c]=w.useState("active"),[u,d]=w.useState("all"),[h,f]=w.useState(""),[p,x]=w.useState(""),[v,b]=w.useState(""),[y,S]=w.useState("table"),[N,A]=w.useState(IJe),[M,T]=w.useState(DJe),[k,j]=w.useState(!1),[E,P]=w.useState(0),[U,L]=w.useState(()=>{try{const Q=localStorage.getItem("bambuddy-inventory-pageSize");if(Q){const he=Number(Q);if([15,30,50,100,-1].includes(he))return he}}catch{}return 15}),{data:B,isLoading:R}=tt({queryKey:["inventory-spools"],queryFn:()=>se.getSpools(!0),refetchInterval:3e4}),{data:V}=tt({queryKey:["spool-assignments"],queryFn:()=>se.getAssignments(),refetchInterval:3e4}),q=lt({mutationFn:Q=>se.deleteSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolDeleted"),"success")}}),I=lt({mutationFn:Q=>se.archiveSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolArchived"),"success")}}),K=lt({mutationFn:Q=>se.restoreSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolRestored"),"success")}}),Y=w.useMemo(()=>{if(!B)return null;let Q=0,he=0,be=0,ee=0;const z={};for(const D of B){if(D.archived_at)continue;ee++;const G=Math.max(0,D.label_weight-D.weight_used);Q+=G,he+=D.weight_used,(D.label_weight>0?G/D.label_weight*100:0)<20&&be++;const ve=D.material||"Unknown";z[ve]||(z[ve]={count:0,weight:0}),z[ve].count++,z[ve].weight+=G}return{totalWeight:Q,totalConsumed:he,lowStock:be,byMaterial:z,totalSpools:ee}},[B]),le=V?.length??0,H=w.useMemo(()=>{const Q={};for(const he of V||[])Q[he.spool_id]=he;return Q},[V]),X=w.useMemo(()=>Y?Object.entries(Y.byMaterial).sort((Q,he)=>he[1].weight-Q[1].weight).slice(0,4):[],[Y]),te=w.useMemo(()=>{let Q=B||[];if(l==="active"?Q=Q.filter(he=>!he.archived_at):Q=Q.filter(he=>!!he.archived_at),u==="used"?Q=Q.filter(he=>he.weight_used>0):u==="new"&&(Q=Q.filter(he=>he.weight_used===0)),h&&(Q=Q.filter(he=>he.material===h)),p&&(Q=Q.filter(he=>he.brand===p)),v){const he=v.toLowerCase();Q=Q.filter(be=>be.brand?.toLowerCase().includes(he)||be.material.toLowerCase().includes(he)||be.color_name?.toLowerCase().includes(he)||be.subtype?.toLowerCase().includes(he)||be.note?.toLowerCase().includes(he)||be.slicer_filament_name?.toLowerCase().includes(he))}return Q},[B,l,u,h,p,v]),J=()=>P(0),Se=[...new Set(B?.map(Q=>Q.material)||[])].sort(),fe=[...new Set(B?.map(Q=>Q.brand).filter(Boolean)||[])].sort(),me=l!=="active"||u!=="all"||!!h||!!p||!!v,De=Q=>{T(Q),RJe(Q)},de=w.useMemo(()=>M.filter(Q=>Q.visible).map(Q=>Q.id),[M]),ce=Q=>{Xj[Q]&&(A(he=>{let be;return he?.column===Q?be=he.direction==="asc"?{column:Q,direction:"desc"}:null:be={column:Q,direction:"asc"},zJe(be),be}),J())},Ne=w.useMemo(()=>{if(!N)return te;const Q=Xj[N.column];return Q?[...te].sort((be,ee)=>{const z=Q(be,H),D=Q(ee,H);return zD?N.direction==="asc"?1:-1:0}):te},[te,N,H]),ie=U===-1,Le=ie?Ne.length||1:U,$=Math.max(1,Math.ceil(Ne.length/Le)),W=ie?0:Math.min(E,$-1),ue=ie?Ne:Ne.slice(W*Le,(W+1)*Le),Z=Q=>{L(Q),P(0);try{localStorage.setItem("bambuddy-inventory-pageSize",String(Q))}catch{}},oe=()=>{c("active"),d("all"),f(""),x(""),b(""),J()};return a.jsxs("div",{className:"p-4 md:p-6 space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(ma,{className:"w-6 h-6 text-bambu-green"}),a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("inventory.title")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-9",children:(t("inventory.noSpools").split(".")[0],"")})]}),a.jsxs(Me,{onClick:()=>i({spool:null}),children:[a.jsx(ar,{className:"w-4 h-4"}),t("inventory.addSpool")]})]}),Y&&!R&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3",children:[a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(ma,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalInventory")})]}),a.jsx("div",{className:"text-xl font-bold text-white",children:Fu(Y.totalWeight,!0)}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[Y.totalSpools," ",Y.totalSpools!==1?t("inventory.spools"):t("inventory.spool")]})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(zF,{className:"w-4 h-4 text-blue-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalConsumed")})]}),a.jsx("div",{className:"text-xl font-bold text-white",children:Fu(Y.totalConsumed,!0)}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.sinceTracking")})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(rs,{className:"w-4 h-4 text-green-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.byMaterial")})]}),a.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:X.map(([Q,he])=>a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${FJe[Q]||"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Q," ",a.jsx("span",{className:"opacity-70",children:Fu(he.weight,!0)})]},Q))})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(Cr,{className:"w-4 h-4 text-purple-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.inPrinter")})]}),a.jsx("div",{className:"text-xl font-bold text-white",children:le}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.loadedInAms")})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(Cn,{className:"w-4 h-4 text-yellow-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.lowStock")})]}),a.jsx("div",{className:`text-xl font-bold ${Y.lowStock>0?"text-yellow-400":"text-white"}`,children:Y.lowStock}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.lowStockThreshold")})]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between",children:[a.jsxs("div",{className:"relative flex-1 max-w-md",children:[a.jsx(Or,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),a.jsx("input",{type:"text",value:v,onChange:Q=>{b(Q.target.value),J()},placeholder:t("inventory.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),v&&a.jsx("button",{onClick:()=>{b(""),J()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Ft,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[y==="table"&&a.jsxs("button",{onClick:()=>j(!0),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-bambu-gray border border-bambu-dark-tertiary rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t("inventory.configureColumns"),children:[a.jsx(vhe,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.columns")})]}),a.jsxs("div",{className:"flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>S("table"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${y==="table"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(npe,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.table")})]}),a.jsxs("button",{onClick:()=>S("cards"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${y==="cards"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(xv,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.cards")})]})]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsxs("button",{onClick:()=>{c("active"),J()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="active"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(ma,{className:"w-3.5 h-3.5"}),t("inventory.active")]}),a.jsxs("button",{onClick:()=>{c("archived"),J()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="archived"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(Rs,{className:"w-3.5 h-3.5"}),t("inventory.archived")]})]}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),a.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsx("button",{onClick:()=>{d("all"),J()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),a.jsxs("button",{onClick:()=>{d("used"),J()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${u==="used"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(Qn,{className:"w-3.5 h-3.5"}),t("inventory.used")]}),a.jsx("button",{onClick:()=>{d("new"),J()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="new"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.new")})]}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),a.jsxs("select",{value:h,onChange:Q=>{f(Q.target.value),J()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${h?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[a.jsx("option",{value:"",children:t("inventory.material")}),Se.map(Q=>a.jsx("option",{value:Q,children:Q},Q))]}),a.jsxs("select",{value:p,onChange:Q=>{x(Q.target.value),J()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${p?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[a.jsx("option",{value:"",children:t("inventory.brand")}),fe.map(Q=>a.jsx("option",{value:Q,children:Q},Q))]}),me&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),a.jsxs("button",{onClick:oe,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:[a.jsx(Ft,{className:"w-3.5 h-3.5"}),t("inventory.clearFilters")]})]}),a.jsxs("span",{className:"ml-auto text-xs text-bambu-gray",children:[Ne.length," ",Ne.length!==1?t("inventory.spools"):t("inventory.spool")]})]}),R?a.jsx("div",{className:"flex justify-center py-16",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})}):y==="cards"?ue.length>0?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:ue.map(Q=>{const he=Math.max(0,Q.label_weight-Q.weight_used),be=Q.label_weight>0?he/Q.label_weight*100:0,ee=Q.rgba?`#${Q.rgba.substring(0,6)}`:"#808080";return a.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors cursor-pointer ${Q.archived_at?"opacity-50":""}`,onClick:()=>i({spool:Q}),children:[a.jsx("div",{className:"h-14 flex items-center justify-center",style:{backgroundColor:ee},children:a.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:pne(Q.color_name,Q.rgba)||"-"})}),a.jsxs("div",{className:"p-4 space-y-3",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{children:[a.jsxs("h3",{className:"font-semibold text-white",children:[Q.material,Q.subtype?` ${Q.subtype}`:""]}),a.jsx("p",{className:"text-sm text-bambu-gray",children:Q.brand||"-"})]}),a.jsxs("span",{className:"text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:["#",Q.id]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[a.jsx("span",{children:t("inventory.remaining")}),a.jsxs("span",{children:[Math.round(be),"%"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full ${be>50?"bg-bambu-green":be>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(be,100)}%`}})}),a.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(he),"g"]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[a.jsxs("div",{children:[a.jsxs("span",{className:"text-bambu-gray/60",children:[t("inventory.labelWeight"),": "]}),a.jsx("span",{className:"text-bambu-gray",children:Fu(Q.label_weight)})]}),a.jsxs("div",{children:[a.jsxs("span",{className:"text-bambu-gray/60",children:[t("inventory.weightUsed"),": "]}),a.jsx("span",{className:"text-bambu-gray",children:Q.weight_used>0?Fu(Q.weight_used):"-"})]})]}),Q.note&&a.jsx("div",{className:"text-xs text-bambu-gray/60 pt-2 border-t border-bambu-dark-tertiary truncate",title:Q.note,children:Q.note})]})]},Q.id)})}),a.jsx(BJe,{pageIndex:W,pageSize:U,totalRows:Ne.length,totalPages:$,onPageChange:P,onPageSizeChange:Z,t})]}):a.jsx(mK,{hasFilters:me,onAddSpool:()=>i({spool:null}),t}):ue.length>0?a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[de.map(Q=>{const he=!!Xj[Q],be=N?.column===Q;return a.jsx("th",{className:`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${Q==="remaining"?"min-w-[150px]":""} ${he?"cursor-pointer hover:text-bambu-green transition-colors":""} ${be?"text-bambu-green":"text-bambu-gray"}`,onClick:he?()=>ce(Q):void 0,children:a.jsxs("span",{className:"inline-flex items-center gap-1",children:[LJe[Q]?.(t)??Q,he&&(be?N.direction==="asc"?a.jsx(Ef,{className:"w-3 h-3"}):a.jsx(hb,{className:"w-3 h-3"}):a.jsx(DF,{className:"w-3 h-3 opacity-30"}))]})},Q)}),a.jsx("th",{className:"text-right py-3 px-4 text-xs font-medium text-bambu-gray uppercase tracking-wide",children:t("common.actions")})]})}),a.jsx("tbody",{children:ue.map(Q=>{const he=Math.max(0,Q.label_weight-Q.weight_used),be=Q.label_weight>0?he/Q.label_weight*100:0;return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer ${Q.archived_at?"opacity-50":""}`,onClick:()=>i({spool:Q}),children:[de.map(ee=>a.jsx("td",{className:"py-3 px-4",children:OJe[ee]?.({spool:Q,remaining:he,pct:be,assignmentMap:H})},ee)),a.jsx("td",{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-center justify-end gap-1",onClick:ee=>ee.stopPropagation(),children:[a.jsx("button",{onClick:()=>i({spool:Q}),className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:t("inventory.editSpool"),children:a.jsx(rf,{className:"w-4 h-4"})}),Q.archived_at?a.jsx("button",{onClick:()=>K.mutate(Q.id),className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:t("inventory.restore"),children:a.jsx(Do,{className:"w-4 h-4"})}):a.jsx("button",{onClick:()=>o({type:"archive",spoolId:Q.id}),className:"p-1.5 text-bambu-gray hover:text-yellow-400 rounded transition-colors",title:t("inventory.archive"),children:a.jsx(Rs,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>o({type:"delete",spoolId:Q.id}),className:"p-1.5 text-bambu-gray hover:text-red-400 rounded transition-colors",title:t("common.delete"),children:a.jsx(en,{className:"w-4 h-4"})})]})})]},Q.id)})})]})}),a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-bambu-dark-tertiary/50 border-t border-bambu-dark-tertiary text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:ie?`${Ne.length} ${Ne.length!==1?t("inventory.spools"):t("inventory.spool")}`:a.jsxs(a.Fragment,{children:[t("inventory.showing")," ",W*Le+1," ",t("inventory.to")," ",Math.min((W+1)*Le,Ne.length)," ",t("inventory.of")," ",Ne.length," ",t("inventory.spools")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-gray",children:t("inventory.show")}),a.jsxs("select",{value:U,onChange:Q=>Z(Number(Q.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(Q=>a.jsx("option",{value:Q,children:Q},Q)),a.jsx("option",{value:-1,children:t("inventory.all")})]}),!ie&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>P(0),disabled:W===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"First page",children:a.jsx(lX,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>P(Q=>Math.max(0,Q-1)),disabled:W===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(Gl,{className:"w-4 h-4"})}),a.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[t("inventory.page")," ",W+1," ",t("inventory.of")," ",$]}),a.jsx("button",{onClick:()=>P(Q=>Math.min($-1,Q+1)),disabled:W>=$-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(fa,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>P($-1),disabled:W>=$-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Last page",children:a.jsx(cX,{className:"w-4 h-4"})})]})]})]})]}):a.jsx(mK,{hasFilters:me,onAddSpool:()=>i({spool:null}),t}),r!==null&&a.jsx(PJe,{isOpen:!0,onClose:()=>i(null),spool:r.spool}),s&&a.jsx(kn,{title:s.type==="delete"?t("common.delete"):t("inventory.archive"),message:s.type==="delete"?t("inventory.deleteConfirm"):t("inventory.archiveConfirm"),confirmText:s.type==="delete"?t("common.delete"):t("inventory.archive"),variant:s.type==="delete"?"danger":"warning",onConfirm:()=>{s.type==="delete"?q.mutate(s.spoolId):I.mutate(s.spoolId),o(null)},onCancel:()=>o(null)}),a.jsx(jJe,{isOpen:k,onClose:()=>j(!1),columns:M,defaultColumns:S1,onSave:De})]})}function BJe({pageIndex:t,pageSize:e,totalRows:n,totalPages:r,onPageChange:i,onPageSizeChange:s,t:o}){const l=e===-1;if(r<=1&&!l)return null;const c=l?n||1:e;return a.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o(n!==1?"inventory.spools":"inventory.spool")}`:a.jsxs(a.Fragment,{children:[o("inventory.showing")," ",t*c+1," ",o("inventory.to")," ",Math.min((t+1)*c,n)," ",o("inventory.of")," ",n," ",o("inventory.spools")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-gray",children:o("inventory.show")}),a.jsxs("select",{value:e,onChange:u=>s(Number(u.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(u=>a.jsx("option",{value:u,children:u},u)),a.jsx("option",{value:-1,children:o("inventory.all")})]}),!l&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>i(0),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(lX,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>i(Math.max(0,t-1)),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(Gl,{className:"w-4 h-4"})}),a.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("inventory.page")," ",t+1," ",o("inventory.of")," ",r]}),a.jsx("button",{onClick:()=>i(Math.min(r-1,t+1)),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(fa,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>i(r-1),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(cX,{className:"w-4 h-4"})})]})]})]})}function mK({hasFilters:t,onAddSpool:e,t:n}){return a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[a.jsxs("div",{className:"relative mb-6",children:[a.jsx("div",{className:"absolute inset-0 -m-4 bg-bambu-green/5 rounded-full blur-2xl"}),a.jsxs("div",{className:"relative flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-bambu-dark-secondary to-bambu-dark-tertiary border border-bambu-dark-tertiary shadow-lg",children:[a.jsx("div",{className:"absolute -top-1 -right-1 w-3 h-3 rounded-full bg-bambu-green/30"}),a.jsx("div",{className:"absolute -bottom-2 -left-2 w-2 h-2 rounded-full bg-bambu-green/20"}),t?a.jsx(Or,{className:"w-10 h-10 text-bambu-gray/40",strokeWidth:1.5}):a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-14 h-14 rounded-full border-4 border-bambu-gray/20 flex items-center justify-center",children:a.jsx("div",{className:"w-6 h-6 rounded-full bg-bambu-gray/10 border-2 border-bambu-gray/20"})}),a.jsx("div",{className:"absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-bambu-green flex items-center justify-center shadow-md",children:a.jsx("span",{className:"text-white text-lg font-bold leading-none",children:"+"})})]})]})]}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2 text-center",children:t?n("inventory.noSpoolsMatch"):n("inventory.noSpools").split(".")[0]}),a.jsx("p",{className:"text-sm text-bambu-gray text-center max-w-sm mb-6",children:n(t?"inventory.noSpoolsMatchDesc":"inventory.noSpools")}),!t&&a.jsxs(Me,{onClick:e,children:[a.jsx(ma,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})}const fK=["DEBUG","INFO","WARNING","ERROR"],Yj={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},HJe={DEBUG:Zk,INFO:Zs,WARNING:Cn,ERROR:Bi};function $Je(){const t=tn(),[e,n]=w.useState(!0),[r,i]=w.useState(new Set),[s,o]=w.useState(""),[l,c]=w.useState("ALL"),[u,d]=w.useState(!1),[h,f]=w.useState(!1),p=w.useRef(null),{data:x,isLoading:v,refetch:b}=tt({queryKey:["application-logs",l,s],queryFn:()=>Zg.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:h?2e3:!1,enabled:u});w.useEffect(()=>{u||f(!1)},[u]);const y=lt({mutationFn:()=>Zg.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});w.useEffect(()=>{e&&p.current&&x?.entries&&(p.current.scrollTop=p.current.scrollHeight)},[x?.entries,e]);const S=k=>{i(j=>{const E=new Set(j);return E.has(k)?E.delete(k):E.add(k),E})},N=k=>{const j=k.split(" ");return j.length>=2?j[1]:k},A=w.useMemo(()=>x?.entries??[],[x?.entries]),M=w.useMemo(()=>[...A].reverse(),[A]),T=({level:k})=>{const j=HJe[k]||Zs;return a.jsx(j,{className:`w-3.5 h-3.5 ${Yj[k]||"text-gray-400"}`})};return a.jsxs("div",{className:"bg-bambu-dark rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>d(!u),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/50 transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${h?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:a.jsx(Zk,{className:"w-5 h-5"})}),a.jsxs("div",{className:"text-left",children:[a.jsx("p",{className:"font-medium text-white",children:"Application Logs"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:h?`Live streaming - ${x?.filtered_count??0} entries`:"View and filter application logs"})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[h&&a.jsxs("span",{className:"flex items-center gap-1.5 px-2 py-1 bg-bambu-green/20 rounded text-bambu-green text-xs",children:[a.jsx("span",{className:"w-1.5 h-1.5 bg-bambu-green rounded-full animate-pulse"}),"Live"]}),u?a.jsx(ql,{className:"w-5 h-5 text-bambu-gray"}):a.jsx(nr,{className:"w-5 h-5 text-bambu-gray"})]})]}),u&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h?a.jsxs("button",{onClick:k=>{k.stopPropagation(),f(!1)},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded transition-colors",children:[a.jsx(gl,{className:"w-4 h-4"}),"Stop"]}):a.jsxs("button",{onClick:k=>{k.stopPropagation(),f(!0),b()},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 rounded transition-colors",children:[a.jsx(jo,{className:"w-4 h-4"}),"Start"]}),a.jsxs("button",{onClick:()=>y.mutate(),disabled:y.isPending||A.length===0,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:[a.jsx(en,{className:"w-4 h-4"}),"Clear"]}),a.jsx("button",{onClick:()=>b(),disabled:v,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:a.jsx(kr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),a.jsx("div",{className:"flex-1"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:e,onChange:k=>n(k.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark-tertiary"}),"Auto-scroll"]}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[x?.filtered_count??0,"/",x?.total_in_file??0]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Or,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:"Search message or logger name...",value:s,onChange:k=>o(k.target.value),className:"w-full pl-8 pr-8 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),s&&a.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Ft,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark-secondary rounded border border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>c("ALL"),className:`px-2 py-1.5 text-xs rounded-l transition-colors ${l==="ALL"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"All"}),fK.map((k,j)=>a.jsx("button",{onClick:()=>c(k),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${j===fK.length-1?"rounded-r":""} ${l===k?`${Yj[k]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:k},k))]})]})]}),a.jsx("div",{ref:p,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:A.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-[300px] text-bambu-gray",children:[a.jsx("p",{className:"mb-2",children:"No log entries found"}),a.jsx("p",{className:"text-sm",children:"Log file may be empty or cleared"})]}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary/30",children:M.map((k,j)=>{const E=r.has(j),P=k.message.includes(` +`+n+"}"}return String(t)}function MZe({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=mn(),c=tn(),[u,d]=w.useState(!1),{data:h,isLoading:f}=tt({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>se.getCloudSettingDetail(t.setting_id)}),p=lt({mutationFn:()=>se.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),x=mv(t.setting_id),v=bI(t.name,h?.setting?.inherits);return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(_t,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:a.jsxs(Nt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),x&&a.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[a.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"•"}),a.jsx("span",{children:v.printer})]})]})]}),a.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Ft,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:f?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?a.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:mF(h)}):a.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),u?a.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[a.jsx(Cn,{className:"w-5 h-5"}),a.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Me,{variant:"secondary",onClick:()=>d(!1),disabled:p.isPending,className:"flex-1",children:o("common.cancel")}),a.jsxs(Me,{variant:"danger",onClick:()=>p.mutate(),disabled:p.isPending,className:"flex-1",children:[p.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin"}):a.jsx(en,{className:"w-4 h-4"}),o("common.delete")]})]})]}):a.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Me,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),a.jsxs(Me,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[a.jsx(Wl,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),x&&a.jsxs(a.Fragment,{children:[a.jsxs(Me,{variant:"secondary",onClick:i,disabled:f||!h||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[a.jsx($i,{className:"w-4 h-4"}),o("common.edit")]}),a.jsx(Me,{variant:"danger",onClick:()=>d(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:a.jsx(en,{className:"w-4 h-4"})})]})]})})]})})})}function Gae(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function qae(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function AZe({onClose:t,onApply:e,t:n}){const{showToast:r}=mn(),[i,s]=w.useState(Gae),[o,l]=w.useState("all"),[c,u]=w.useState(null),[d,h]=w.useState(""),[f,p]=w.useState(""),[x,v]=w.useState("{}"),[b,y]=w.useState(null),[S,N]=w.useState(null),A=o==="all"?i:i.filter(B=>B.type===o),M=B=>{s(B),qae(B)},T=B=>{const R=i.filter(V=>V.id!==B);M(R),N(null),r(n("profiles.templates.toast.deleted"))},k=B=>{u(B.id),h(B.name),p(B.description),v(JSON.stringify(B.settings,null,2)),y(null)},j=()=>{if(!(!c||!d.trim()))try{const B=JSON.parse(x),R=i.map(V=>V.id===c?{...V,name:d.trim(),description:f.trim(),settings:B}:V);M(R),u(null),r(n("profiles.templates.toast.updated"))}catch(B){y(B.message)}},E=()=>{u(null),h(""),p(""),v("{}"),y(null)},P=B=>{const R=i.map(V=>V.id===B?{...V,showInModal:!V.showInModal}:V);M(R)},U={filament:{label:n("profiles.presets.types.filament"),icon:Jk,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:td,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:Cr,color:"text-purple-400"}},L=S?i.find(B=>B.id===S):null;return w.useEffect(()=>{const B=R=>{R.key==="Escape"&&(S?N(null):c?E():t())};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[S,c,t]),a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[L&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:a.jsx(_t,{className:"w-full max-w-md",children:a.jsxs(Nt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:a.jsx(Cn,{className:"w-6 h-6 text-red-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),a.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:L.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Me,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),a.jsxs(Me,{onClick:()=>T(S),className:"flex-1 bg-red-500 hover:bg-red-600",children:[a.jsx(en,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),a.jsx(_t,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:a.jsxs(Nt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(pb,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Ft,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(B=>a.jsx("button",{onClick:()=>l(B),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===B?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:B==="all"?n("common.all"):U[B].label},B))]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:A.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(pb,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:n("profiles.templates.noTemplates")}),a.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):a.jsx("div",{className:"space-y-2",children:A.map(B=>{const R=U[B.type],V=R.icon;return c===B.id?a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[a.jsx("input",{type:"text",value:d,onChange:q=>h(q.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),a.jsx("input",{type:"text",value:f,onChange:q=>p(q.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),a.jsx("textarea",{value:x,onChange:q=>{v(q.target.value),y(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${b?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),b&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Me,{size:"sm",onClick:j,disabled:!d.trim(),children:[a.jsx(bs,{className:"w-4 h-4"}),"Save"]}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:E,children:"Cancel"})]})]},B.id):a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[a.jsx(V,{className:`w-5 h-5 ${R.color} flex-shrink-0`}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:B.name}),a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:B.description})]}),a.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(B.settings).length})}),a.jsx("button",{onClick:()=>P(B.id),className:`p-1 transition-colors ${B.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:B.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:B.showInModal?a.jsx(Kl,{className:"w-4 h-4"}):a.jsx(gv,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>e(B),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),a.jsx("button",{onClick:()=>k(B),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:a.jsx($i,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>N(B.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:a.jsx(en,{className:"w-4 h-4"})})]},B.id)})})})]})})]})}function Wae({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:i,t:s}){const[o,l]=w.useState("changes"),[c,u]=w.useState(""),d=w.useMemo(()=>{const x=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const b of x){if(b==="inherits"||b==="version")continue;const y=e[b],S=n[b],N=b in e,A=b in n;let M;!N&&A?M="added":N&&!A?M="removed":JSON.stringify(y)!==JSON.stringify(S)?M="changed":M="same",v.push({key:b,left:y,right:S,status:M})}return v.sort((b,y)=>{const S={changed:0,added:1,removed:2,same:3};return S[b.status]!==S[y.status]?S[b.status]-S[y.status]:b.key.localeCompare(y.key)})},[e,n]),h=w.useMemo(()=>{let x=[...d];if(o==="changes"&&(x=x.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();x=x.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return x},[d,o,c]),f=w.useMemo(()=>({added:d.filter(x=>x.status==="added").length,removed:d.filter(x=>x.status==="removed").length,changed:d.filter(x=>x.status==="changed").length,same:d.filter(x=>x.status==="same").length}),[d]),p=x=>{if(x===void 0)return"—";if(x===null)return"null";if(Array.isArray(x))return x.length===0?"[]":x.length===1?String(x[0]):x.join(", ");if(typeof x=="object")return JSON.stringify(x);const v=String(x);if(v.includes("\\n")||v.length>100){const b=v.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const x=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsx(_t,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:a.jsxs(Nt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Yg,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Ft,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),a.jsx("p",{className:"text-white font-medium truncate",children:r})]}),a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),a.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx(ar,{className:"w-3.5 h-3.5"}),f.added," ",s("profiles.diff.added")]}),a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(x3,{className:"w-3.5 h-3.5"}),f.removed," ",s("profiles.diff.removed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[a.jsx(d3,{className:"w-3.5 h-3.5"}),f.changed," ",s("profiles.diff.changed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(ZT,{className:"w-3.5 h-3.5"}),f.same," ",s("profiles.diff.same")]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"relative",children:[a.jsx(Or,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c,onChange:x=>u(x.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),f.same>0&&a.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),a.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:h.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(ZT,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:a.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),a.jsx("th",{className:"text-left p-3 w-1/3",children:r}),a.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),a.jsx("tbody",{children:h.map(x=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[x.status],b={added:a.jsx(ar,{className:"w-3.5 h-3.5 text-green-400"}),removed:a.jsx(x3,{className:"w-3.5 h-3.5 text-red-400"}),changed:a.jsx(d3,{className:"w-3.5 h-3.5 text-amber-400"}),same:a.jsx(ZT,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[x.status];return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[a.jsx("td",{className:"p-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[b,a.jsx("span",{className:"text-sm text-white font-mono",children:x.key})]})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${x.status==="removed"?"text-red-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:p(x.left)})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${x.status==="added"?"text-green-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:p(x.right)})})]},x.key)})})]})})]})})})}function TZe({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:i}=mn(),s=tn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[u,d]=w.useState(e?.type||"filament"),[h,f]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[p,x]=w.useState(e?.base_id||""),[v,b]=w.useState(""),[y,S]=w.useState(e?.setting||{inherits:""}),[N,A]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[M,T]=w.useState(null),[k,j]=w.useState(""),[E,P]=w.useState(!1),[U,L]=w.useState(""),[B,R]=w.useState(!1),[V,q]=w.useState(Gae),[I,K]=w.useState(!1),[Y,le]=w.useState(""),[H,X]=w.useState(""),[te,J]=w.useState(!0),[Se,fe]=w.useState(null),[me,De]=w.useState(!1),de=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),ce=w.useMemo(()=>de.filter(ke=>mv(ke.setting_id)),[de]),{data:Ne}=tt({queryKey:["cloudFields",u],queryFn:()=>se.getCloudFields(u==="print"?"process":u),staleTime:1e3*60*60}),{data:ie}=tt({queryKey:["allPresetDetails",u,ce.map(ke=>ke.setting_id).join(",")],queryFn:async()=>{const ke={};for(let je=0;je{try{const Pe=await se.getCloudSettingDetail(Je.setting_id);return{id:Je.setting_id,detail:Pe}}catch{return null}}))).forEach(Je=>{Je&&(ke[Je.id]=Je.detail)})}return ke},enabled:ce.length>0,staleTime:1e3*60*10}),{data:Le,isLoading:$}=tt({queryKey:["cloudSettingDetail",p],queryFn:()=>se.getCloudSettingDetail(p),enabled:!!p});w.useEffect(()=>{l!=="json"&&A(JSON.stringify(y,null,2))},[y,l]);const W=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(Ue=>!mv(Ue.setting_id)).sort((Ue,je)=>Ue.name.localeCompare(je.name)),[n,u]);w.useEffect(()=>{if(!p)return;const ke=W.find(Ue=>Ue.setting_id===p);ke&&(b(ke.name),o||(S({inherits:ke.name}),A(JSON.stringify({inherits:ke.name},null,2))))},[p,W,o]);const ue=w.useMemo(()=>{const ke=Ne?.fields||[],Ue=new Set(ke.map(Je=>Je.key)),je=new Set,Ve=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);ie&&Object.values(ie).forEach(Je=>{Je?.setting&&Object.keys(Je.setting).forEach(Pe=>{!Ue.has(Pe)&&!Ve.has(Pe)&&je.add(Pe)})}),Object.keys(y).forEach(Je=>{!Ue.has(Je)&&!Ve.has(Je)&&je.add(Je)});const Ae=Array.from(je).sort().map(Je=>({key:Je,label:Je.replace(/_/g," ").replace(/\b\w/g,Pe=>Pe.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...ke,...Ae]},[Ne,ie,y,r]),Z=ue.filter(ke=>ke.label.toLowerCase().includes(k.toLowerCase())||ke.key.toLowerCase().includes(k.toLowerCase())),oe=()=>{if(U.trim()){const ke=U.trim().toLowerCase().replace(/\s+/g,"_");Q(ke,""),L(""),R(!1),i(r("profiles.presets.toast.fieldAdded",{key:ke}))}},Q=(ke,Ue)=>{S(je=>{const Ve={...je};return Ue===""||Ue===void 0?delete Ve[ke]:Ve[ke]=Ue,Ve})},he=ke=>{S(Ue=>({...Ue,...ke.settings})),fe(ke.name),i(r("profiles.templates.toast.applied"))},be=()=>{if(!Y.trim())return;const ke={...y};if(delete ke.inherits,Object.keys(ke).length===0){i(r("profiles.presets.noOverridesToSave"),"error");return}const Ue={id:Date.now().toString(),name:Y.trim(),description:H.trim()||r("profiles.presets.customTemplate"),type:u,settings:ke,showInModal:te},je=[...V,Ue];q(je),qae(je),K(!1),le(""),X(""),J(!0),i(r("profiles.templates.toast.created"))},ee=w.useMemo(()=>V.filter(ke=>ke.type===u&&ke.showInModal),[u,V]),z=ke=>{A(ke);try{const Ue=JSON.parse(ke);S(Ue),T(null)}catch(Ue){T(Ue.message)}},D=ke=>{ke.preventDefault(),P(!1);const Ue=ke.dataTransfer.files[0];if(Ue&&Ue.name.endsWith(".json")){const je=new FileReader;je.onload=Ve=>{try{const Ae=Ve.target?.result,Je=JSON.parse(Ae),Pe=Je.setting||Je;S(Ye=>({...Ye,...Pe})),A(JSON.stringify({...y,...Pe},null,2)),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJsonFile"),"error")}},je.readAsText(Ue)}},G=lt({mutationFn:()=>{const ke={...y},Ue=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";ke[Ue]=`"${h}"`;const je={type:u,name:h,base_id:p,setting:ke};return se.createCloudSetting(je)},onSuccess:async()=>{i(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:ke=>i(ke.message,"error")}),pe=lt({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return se.updateCloudSetting(e.setting_id,{name:h,setting:y})},onSuccess:async()=>{i(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:ke=>i(ke.message,"error")}),ve=o?pe:G,xe=Le?.setting?.inherits,ze=xe?W.find(ke=>ke.name===xe):void 0,{data:_e}=tt({queryKey:["cloudSettingDetail",ze?.setting_id],queryFn:()=>se.getCloudSettingDetail(ze.setting_id),enabled:!!ze?.setting_id}),He=w.useMemo(()=>{const ke=_e?.setting||{},Ue=Le?.setting||{},je=p&&ie?.[p]?.setting?ie[p].setting:{};return{...ke,...Ue,...je}},[p,Le,_e,ie]),Ze=ke=>{if(ke==null)return"";if(Array.isArray(ke)){const Ue=[...new Set(ke.map(je=>String(je)))];return Ue.length===1?Ue[0]:ke.join(", ")}return String(ke)},we=ke=>{const Ue=y[ke.key],je=He[ke.key],Ve=Ze(je),Ae=$?r("common.loading"):Ve||"",Je="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(ke.type==="boolean"){const Pe=Ue==="1"||Ue===void 0&&je==="1";return a.jsx("button",{type:"button",onClick:()=>Q(ke.key,Ue==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Pe?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Pe?"translate-x-3.5":"translate-x-0.5"}`})})}return ke.type==="select"?a.jsxs("select",{value:Ue||"",onChange:Pe=>Q(ke.key,Pe.target.value),className:Je,children:[a.jsx("option",{value:"",children:Ae}),ke.options?.map(Pe=>a.jsx("option",{value:Pe.value,children:Pe.label},Pe.value))]}):a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:ke.type==="number"?"number":"text",value:Ue!==void 0?String(Ue):"",onChange:Pe=>Q(ke.key,Pe.target.value),step:ke.step,min:ke.min,max:ke.max,placeholder:Ae,className:Je}),ke.unit&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:ke.unit})]})},ye=w.useMemo(()=>Le?.setting?Le.setting:{},[Le]);return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:ke=>{ke.preventDefault(),P(!0)},onDragLeave:()=>P(!1),onDrop:D,children:[me&&p&&a.jsx(Wae,{onClose:()=>De(!1),leftPreset:ye,rightPreset:y,leftLabel:r("profiles.presets.baseLabel",{name:v||p}),rightLabel:r("profiles.presets.currentLabel",{name:h||r("profiles.presets.newPreset")}),t:r}),a.jsx(_t,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:a.jsxs(Nt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[p&&a.jsxs("button",{onClick:()=>De(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:r("profiles.presets.compareWithBase"),children:[a.jsx(Yg,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),a.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Ft,{className:"w-5 h-5"})})]})]}),E&&a.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:a.jsxs("div",{className:"text-center",children:[a.jsx(ia,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),a.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),a.jsxs("select",{value:u,onChange:ke=>{d(ke.target.value),x("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),a.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),a.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),a.jsxs("select",{value:p,onChange:ke=>x(ke.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),W.map(ke=>a.jsx("option",{value:ke.setting_id,children:ke.name},ke.setting_id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),a.jsx("input",{type:"text",value:h,onChange:ke=>f(ke.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("profiles.presets.myCustomPreset")})]})]}),v&&a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("p",{className:"flex items-center gap-1",children:[a.jsx(Xr,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",a.jsx("span",{className:"text-white",children:v}),$&&a.jsx(at,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[a.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(HB,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),a.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(rC,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),a.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(uX,{className:"w-4 h-4"}),"JSON",M&&a.jsx(Bi,{className:"w-3 h-3 text-red-400"})]}),a.jsx("div",{className:"flex-1 max-[640px]:hidden"}),a.jsxs("button",{onClick:()=>{const ke={name:h,type:u,base_id:p,setting:y},Ue=new Blob([JSON.stringify(ke,null,2)],{type:"application/json"}),je=URL.createObjectURL(Ue),Ve=document.createElement("a");Ve.href=je,Ve.download=`${h||"preset"}.json`,document.body.appendChild(Ve),Ve.click(),document.body.removeChild(Ve),URL.revokeObjectURL(je),i(r("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.exportToJson"),children:[a.jsx(di,{className:"w-4 h-4"}),r("common.download")]}),a.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.importFromJson"),children:[a.jsx(ia,{className:"w-4 h-4"}),r("common.upload")]}),a.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:ke=>{const Ue=ke.target.files?.[0];if(Ue){const je=new FileReader;je.onload=Ve=>{try{const Ae=JSON.parse(Ve.target?.result),Je=Ae.setting||Ae;S(Pe=>({...Pe,...Je})),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJson"),"error")}},je.readAsText(Ue)}}})]}),a.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(pb,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(y).filter(ke=>ke!=="inherits").length>0&&a.jsxs("button",{onClick:()=>K(!I),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[a.jsx(bs,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),I&&a.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[a.jsx("input",{type:"text",value:Y,onChange:ke=>le(ke.target.value),placeholder:r("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),a.jsx("input",{type:"text",value:H,onChange:ke=>X(ke.target.value),placeholder:r("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Me,{size:"sm",onClick:be,disabled:!Y.trim(),children:[a.jsx(bs,{className:"w-3 h-3"}),r("common.save")]}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>K(!1),children:r("common.cancel")})]}),a.jsxs("button",{onClick:()=>J(!te),className:`flex items-center gap-1.5 text-xs transition-colors ${te?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[te?a.jsx(Kl,{className:"w-3.5 h-3.5"}):a.jsx(gv,{className:"w-3.5 h-3.5"}),r(te?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Se&&a.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[a.jsx(Xr,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",a.jsx("span",{className:"font-medium",children:Se})]}),a.jsx("button",{onClick:()=>fe(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:a.jsx(Ft,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[ee.map(ke=>a.jsxs("button",{onClick:()=>he(ke),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:ke.name}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:ke.description})]},ke.id)),ee.length===0&&a.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),a.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),a.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:ue.slice(0,10).map(ke=>a.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[a.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:ke.label}),a.jsx("div",{className:"w-48 max-[640px]:w-full",children:we(ke)})]},ke.key))})]}),Object.keys(y).length>1&&a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(y).filter(([ke])=>ke!=="inherits").map(([ke,Ue])=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[ke,": ",String(Ue).slice(0,20),a.jsx("button",{onClick:()=>Q(ke,void 0),className:"hover:text-white",children:a.jsx(Ft,{className:"w-3 h-3"})})]},ke))})]})]}),l==="fields"&&a.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:ie?r("profiles.templates.fieldsCount",{count:ue.length}):r("common.loading")})]}),a.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[a.jsx(Or,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:k,onChange:ke=>j(ke.target.value),placeholder:r("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[Z.filter(ke=>!(ke.key in y)).map(ke=>{const Ue=He[ke.key],je=Ze(Ue);return a.jsxs("div",{onClick:()=>{S(Ve=>({...Ve,[ke.key]:je||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white truncate",children:ke.label}),a.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:ke.key})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[je&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:je,children:[je.slice(0,20),je.length>20?"...":""]}),a.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:a.jsx(ar,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},ke.key)}),Z.filter(ke=>!(ke.key in y)).length===0&&a.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(k?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:B?a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:U,onChange:ke=>L(ke.target.value),onKeyDown:ke=>ke.key==="Enter"&&oe(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),a.jsx(Me,{size:"sm",onClick:oe,disabled:!U.trim(),children:a.jsx(ar,{className:"w-4 h-4"})}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>{R(!1),L("")},children:a.jsx(Ft,{className:"w-4 h-4"})})]}):a.jsxs("button",{onClick:()=>R(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[a.jsx(ar,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(y).filter(ke=>ke!=="inherits").length})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(y).filter(([ke])=>ke!=="inherits").map(([ke,Ue])=>{const je=ue.find(Ve=>Ve.key===ke);return a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium text-white",children:je?.label||ke}),a.jsx("p",{className:"text-xs text-bambu-gray-dark",children:ke})]}),a.jsx("button",{onClick:()=>Q(ke,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:a.jsx(Ft,{className:"w-4 h-4"})})]}),je?we(je):a.jsx("input",{type:"text",value:String(Ue),onChange:Ve=>Q(ke,Ve.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},ke)}),Object.keys(y).filter(ke=>ke!=="inherits").length===0&&a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(HB,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),a.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(y).filter(ke=>ke!=="inherits").length>0&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:a.jsxs("button",{onClick:()=>{K(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[a.jsx(bs,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&a.jsxs("div",{className:"space-y-2",children:[M&&a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Bi,{className:"w-4 h-4"}),M]}),a.jsx("textarea",{value:N,onChange:ke=>z(ke.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${M?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[a.jsx(Me,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsxs(Me,{onClick:()=>ve.mutate(),disabled:ve.isPending||!h.trim()||!o&&!p||!!M,className:"flex-1",children:[ve.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin"}):o?a.jsx(bs,{className:"w-4 h-4"}):a.jsx(ar,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function EZe({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:i,hasPermission:s,t:o}){const[l,c]=w.useState(""),[u,d]=w.useState("all"),[h,f]=w.useState("all"),[p,x]=w.useState("all"),[v,b]=w.useState("all"),[y,S]=w.useState("all"),[N,A]=w.useState("all"),[M,T]=w.useState(null),[k,j]=w.useState(!1),[E,P]=w.useState(!1),[U,L]=w.useState(null),[B,R]=w.useState(null),[V,q]=w.useState(null),[I,K]=w.useState(!1),[Y,le]=w.useState([null,null]),[H,X]=w.useState(!1),[te,J]=w.useState(null),Se=tn(),fe=w.useMemo(()=>[...t.filament.map(oe=>({...oe,type:"filament"})),...t.printer.map(oe=>({...oe,type:"printer"})),...t.process.map(oe=>({...oe,type:"process"}))].map(oe=>({...oe,meta:bI(oe.name)})),[t]),me=w.useMemo(()=>{const Z=new Set,oe=new Set,Q=new Set;return fe.forEach(he=>{he.meta.nozzle&&Z.add(he.meta.nozzle),he.meta.filamentType&&oe.add(he.meta.filamentType),he.meta.layerHeight&&Q.add(he.meta.layerHeight)}),{printers:i.map(he=>({id:he.id.toString(),name:he.name})),nozzles:Array.from(Z).sort((he,be)=>parseFloat(he)-parseFloat(be)),filaments:Array.from(oe).sort(),layerHeights:Array.from(Q).sort((he,be)=>parseFloat(he)-parseFloat(be))}},[fe,i]),De=w.useMemo(()=>p==="all"?null:i.find(oe=>oe.id.toString()===p)?.model||null,[p,i]),de=w.useMemo(()=>fe.filter(Z=>u==="all"||Z.type===u).filter(Z=>{if(h==="all")return!0;const oe=mv(Z.setting_id);return h==="custom"?oe:!oe}).filter(Z=>{if(p==="all"||!De)return!0;const oe=Z.meta.printer?.toLowerCase()||"",Q=De.toLowerCase();return oe.includes(Q)||Q.includes(oe)}).filter(Z=>v==="all"||Z.meta.nozzle===v).filter(Z=>y==="all"||Z.meta.filamentType===y).filter(Z=>N==="all"||Z.meta.layerHeight===N).filter(Z=>l===""||Z.name.toLowerCase().includes(l.toLowerCase())).sort((Z,oe)=>Z.name.localeCompare(oe.name)),[fe,u,h,p,De,v,y,N,l]),ce=Z=>{if(I){const oe=Y[0]?.setting_id===Z.setting_id,Q=Y[1]?.setting_id===Z.setting_id;if(oe)le([Y[1],null]);else if(Q)le([Y[0],null]);else if(!Y[0])le([Z,null]);else if(Y[1]){if(Y[0].type!==Z.type)return;le([Y[0],Z])}else{if(Y[0].type!==Z.type)return;le([Y[0],Z])}}else T(Z)},Ne=Z=>{if(Y[0]?.setting_id===Z.setting_id)return 0;if(Y[1]?.setting_id===Z.setting_id)return 1},ie=async Z=>{try{const oe=await se.getCloudSettingDetail(Z.setting_id),Q=Z.type==="process"?"print":Z.type;L({type:Q,name:Z.name,base_id:oe.base_id||"GFSA00",setting:oe.setting||{}}),T(null)}catch(oe){console.error("Failed to fetch preset details for duplication:",oe)}},Le=async Z=>{try{Se.removeQueries({queryKey:["cloudSettingDetail",Z.setting_id]});const oe=await se.getCloudSettingDetail(Z.setting_id),Q=Z.type==="process"?"print":Z.type;R({type:Q,name:Z.name,base_id:oe.base_id||"GFSA00",setting:oe.setting||{},setting_id:Z.setting_id}),T(null)}catch(oe){console.error("Failed to fetch preset details for editing:",oe)}},$=()=>{d("all"),f("all"),x("all"),b("all"),S("all"),A("all"),c("")},W=u!=="all"||h!=="all"||p!=="all"||v!=="all"||y!=="all"||N!=="all"||l!=="",ue=t.filament.length+t.printer.length+t.process.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"space-y-4 mb-6",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Or,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:l,onChange:Z=>c(Z.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[a.jsxs(Me,{variant:I?"primary":"secondary",onClick:()=>{I?(K(!1),le([null,null])):K(!0)},children:[a.jsx(Yg,{className:"w-4 h-4"}),o(I?"common.cancel":"profiles.presets.compare")]}),a.jsxs(Me,{variant:"secondary",onClick:()=>P(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[a.jsx(pb,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),a.jsxs(Me,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[a.jsx(kr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),a.jsxs(Me,{onClick:()=>j(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[a.jsx(ar,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(tC,{className:"w-4 h-4 text-bambu-gray"}),a.jsx(jg,{label:o("profiles.cloudView.filters.type"),value:u,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:ue},{value:"filament",label:o("profiles.cloudView.filters.filament"),count:t.filament.length},{value:"printer",label:o("profiles.cloudView.filters.printer"),count:t.printer.length},{value:"process",label:o("profiles.cloudView.filters.process"),count:t.process.length}],onChange:Z=>d(Z)}),a.jsx(jg,{label:o("profiles.cloudView.filters.owner"),value:h,options:[{value:"all",label:o("profiles.cloudView.filters.all")},{value:"custom",label:o("profiles.cloudView.filters.myPresets")},{value:"builtin",label:o("profiles.cloudView.filters.builtIn")}],onChange:Z=>f(Z)}),me.printers.length>0&&a.jsx(jg,{label:o("profiles.cloudView.filters.printer"),value:p,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...me.printers.map(Z=>({value:Z.id,label:Z.name}))],onChange:x}),me.nozzles.length>0&&a.jsx(jg,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...me.nozzles.map(Z=>({value:Z,label:Z}))],onChange:b}),me.filaments.length>0&&(u==="all"||u==="filament")&&a.jsx(jg,{label:o("profiles.cloudView.filters.filament"),value:y,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...me.filaments.map(Z=>({value:Z,label:Z}))],onChange:S}),me.layerHeights.length>0&&(u==="all"||u==="process")&&a.jsx(jg,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...me.layerHeights.map(Z=>({value:Z,label:Z}))],onChange:A}),W&&a.jsx("button",{onClick:$,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),I&&a.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(Yg,{className:"w-5 h-5 text-blue-400"}),a.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),a.jsx("span",{className:"text-bambu-gray",children:Y[0]?o("profiles.cloudView.selectAnotherPreset",{type:Y[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${Y[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Y[0]?Y[0].name:o("profiles.cloudView.selectFirst")}),a.jsx(d3,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${Y[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Y[1]?Y[1].name:o("profiles.cloudView.selectSecond")})]}),Y[0]&&Y[1]&&a.jsxs(Me,{size:"sm",onClick:async()=>{try{const[Z,oe]=await Promise.all([se.getCloudSettingDetail(Y[0].setting_id),se.getCloudSettingDetail(Y[1].setting_id)]);J([Z.setting||{},oe.setting||{}]),X(!0)}catch{}},children:[a.jsx(Yg,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),a.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(Qn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",NZe(e.toISOString(),o)]}),a.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:de.length,total:ue})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),a.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),de.length===0?a.jsxs("div",{className:"text-center py-16",children:[a.jsx(rs,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),a.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),W&&a.jsx("button",{onClick:$,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Jk,{className:"w-4 h-4 text-amber-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",de.filter(Z=>Z.type==="filament").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[de.filter(Z=>Z.type==="filament").map(Z=>a.jsx($j,{setting:Z,onClick:()=>ce(Z),onDuplicate:()=>ie(Z),compareMode:I,isCompareSelected:Ne(Z)!==void 0,compareIndex:Ne(Z),compareDisabled:I&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),de.filter(Z=>Z.type==="filament").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(td,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",de.filter(Z=>Z.type==="process").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[de.filter(Z=>Z.type==="process").map(Z=>a.jsx($j,{setting:Z,onClick:()=>ce(Z),onDuplicate:()=>ie(Z),compareMode:I,isCompareSelected:Ne(Z)!==void 0,compareIndex:Ne(Z),compareDisabled:I&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),de.filter(Z=>Z.type==="process").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Cr,{className:"w-4 h-4 text-purple-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",de.filter(Z=>Z.type==="printer").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[de.filter(Z=>Z.type==="printer").map(Z=>a.jsx($j,{setting:Z,onClick:()=>ce(Z),onDuplicate:()=>ie(Z),compareMode:I,isCompareSelected:Ne(Z)!==void 0,compareIndex:Ne(Z),compareDisabled:I&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),de.filter(Z=>Z.type==="printer").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),M&&a.jsx(MZe,{setting:M,onClose:()=>T(null),onDeleted:()=>T(null),onDuplicate:()=>ie(M),onEdit:()=>Le(M),hasPermission:s,t:o}),(k||U||B||V)&&a.jsx(TZe,{onClose:()=>{j(!1),L(null),R(null),q(null)},initialData:B||U||(V?{type:V.type,name:"",base_id:"",setting:V.setting}:void 0),allPresets:t,t:o}),E&&a.jsx(AZe,{onClose:()=>P(!1),onApply:Z=>{q({type:Z.type,setting:Z.settings}),P(!1)},t:o}),H&&te&&Y[0]&&Y[1]&&a.jsx(Wae,{onClose:()=>{X(!1),J(null)},leftPreset:te[0],rightPreset:te[1],leftLabel:Y[0].name,rightLabel:Y[1].name,t:o})]})}function PZe(){const{t}=Vt(),e=tn(),{showToast:n}=mn(),{hasPermission:r}=Ir(),[i,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:u}=tt({queryKey:["cloudStatus"],queryFn:se.getCloudStatus}),{data:d=[]}=tt({queryKey:["printers"],queryFn:se.getPrinters}),{data:h,isLoading:f,refetch:p,dataUpdatedAt:x}=tt({queryKey:["cloudSettings"],queryFn:()=>se.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{x&&l(new Date(x))},[x]);const v=lt({mutationFn:se.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return u?a.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"p-6 lg:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[a.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(Gb,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),a.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(qb,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),a.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(nC,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&a.jsxs(a.Fragment,{children:[c?.is_authenticated&&a.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",a.jsx("span",{className:"text-white",children:c.email})]})]}),a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[a.jsx(b3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?f?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?a.jsx(EZe,{settings:h,lastSyncTime:o,onRefresh:()=>p(),isRefreshing:f,printers:d,hasPermission:r,t}):a.jsxs("div",{className:"text-center py-16",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),a.jsx(Me,{onClick:()=>p(),children:t("profiles.retry")})]}):a.jsx(kZe,{onSuccess:b,t})]}),i==="local"&&a.jsx(SZe,{}),i==="kprofiles"&&a.jsx(yZe,{}),a.jsx(CZe,{})]})}const Ky={Droplet:Jk,Flame:Xhe,Ruler:Mfe,Sparkles:pb,Square:gl,Cable:Rde,Wrench:Rf,Calendar:ii,Timer:Ou,Cog:xhe,Fan:dX,Zap:Gh,Wind:wX,Thermometer:cC,Layers:rs,Box:Qi,Target:yX,RefreshCw:kr,Settings:lC,Filter:tC,CircleDot:the};function x0(t){return t&&Ky[t]||Rf}function Dg(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return n?n("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:i}):`${i} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const i=r/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function Vj(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function jZe(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),i=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),u=n.includes("H2S"),d=l||c||u,h=n.includes("P2S");switch(t){case"Lubricate Carbon Rods":return r?"https://wiki.bambulab.com/en/x1/maintenance/basic-maintenance":i?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||i?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":d?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":h?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return r?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":i?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":u?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||i||h?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return r||i?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":u?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return d?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}function DZe({item:t,onPerform:e,onToggle:n,hasPermission:r,t:i}){const s=x0(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const p=t.days_since_maintenance??0;return Math.max(0,Math.min(100,p/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),u=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",d=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",h=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",f=()=>{if(!t.enabled)return i("common.disabled");if(o==="days"){const p=t.days_until_due??0;return t.is_due?i("maintenance.overdueBy",{duration:Dg(Math.abs(p),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:Dg(p,"days",i)}):i("maintenance.timeLeft",{duration:Dg(p,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:Dg(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:Dg(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:Dg(t.hours_until_due,"hours",i)})};return a.jsx("div",{className:`rounded-xl border p-4 transition-all ${h()}`,children:a.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[a.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[a.jsx(s,{className:`w-5 h-5 ${u()}`}),t.enabled&&(t.is_due||t.is_warning)&&a.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&a.jsx("span",{title:i("maintenance.timeBasedInterval"),children:a.jsx(ii,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const p=t.maintenance_type_wiki_url||jZe(t.maintenance_type_name,t.printer_model);return p?a.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:i("maintenance.viewDocumentation"),onClick:x=>x.stopPropagation(),children:a.jsx(Kr,{className:"w-3.5 h-3.5"})}):null})()]}),a.jsx("div",{className:"mt-2 mb-1.5",children:a.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${d()}`,style:{width:`${c}%`}})})}),a.jsxs("div",{className:`text-xs flex items-center gap-1 ${u()}`,children:[t.is_due&&a.jsx(Cn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&a.jsx(Qn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&a.jsx(Xr,{className:"w-3 h-3"}),f()]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[a.jsx("span",{title:r("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:a.jsx(zn,{checked:t.enabled,onChange:p=>n(t.id,p),disabled:!r("maintenance:update")})}),a.jsxs(Me,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[a.jsx(Do,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function RZe({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:i,t:s}){const[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(t.total_print_hours.toFixed(1)),f=[...t.maintenance_items].sort((v,b)=>v.is_due&&!b.is_due?-1:!v.is_due&&b.is_due?1:v.is_warning&&!b.is_warning?-1:!v.is_warning&&b.is_warning?1:v.maintenance_type_id-b.maintenance_type_id),p=f.find(v=>v.enabled&&(v.is_due||v.is_warning)),x=()=>{const v=parseFloat(d);!isNaN(v)&&v>=0&&(r(t.printer_id,v),u(!1))};return a.jsxs(_t,{className:"overflow-hidden",children:[a.jsxs("div",{className:"p-5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&a.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[a.jsx(Cn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&a.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[a.jsx(Qn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&a.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[a.jsx(Xr,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),a.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?a.jsx(ql,{className:"w-4 h-4"}):a.jsx(nr,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),a.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:a.jsx(Ou,{className:"w-4 h-4 text-bambu-gray"})}),c?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",value:d,onChange:v=>h(v.target.value),onKeyDown:v=>{v.key==="Enter"&&x(),v.key==="Escape"&&u(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),a.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),a.jsx(Me,{size:"sm",onClick:x,children:s("common.save")}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>u(!1),children:s("common.cancel")})]}):a.jsxs("button",{onClick:()=>{i("maintenance:update")&&(h(Math.round(t.total_print_hours).toString()),u(!0))},className:`group ${i("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:i("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[a.jsxs("div",{className:`text-sm font-medium text-white ${i("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),a.jsx(Pf,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),a.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),a.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),p&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${p.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=x0(p.maintenance_type_icon);return a.jsx(v,{className:`w-4 h-4 ${p.is_due?"text-red-400":"text-amber-400"}`})})()}),a.jsxs("div",{children:[a.jsx("div",{className:`text-sm font-medium ${p.is_due?"text-red-400":"text-amber-400"}`,children:p.maintenance_type_name}),a.jsx("div",{className:`text-xs ${p.is_due?"text-red-400/70":"text-amber-400/70"}`,children:p.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&a.jsx(Nt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:a.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:f.map(v=>a.jsx(DZe,{item:v,onPerform:e,onToggle:n,hasPermission:i,t:s},v.id))})})]})}function FZe({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:u,hasPermission:d,t:h}){const[f,p]=w.useState(null),[x,v]=w.useState(""),[b,y]=w.useState("hours"),[S,N]=w.useState(!1),[A,M]=w.useState(""),[T,k]=w.useState("100"),[j,E]=w.useState("hours"),[P,U]=w.useState("Wrench"),[L,B]=w.useState(""),[R,V]=w.useState(new Set),[q,I]=w.useState(null),[K,Y]=w.useState(null),le=w.useMemo(()=>t?t.map(z=>({id:z.printer_id,name:z.printer_name})):[],[t]),H=z=>t?t.filter(D=>D.maintenance_items.some(G=>G.maintenance_type_id===z)).map(D=>({printerId:D.printer_id,printerName:D.printer_name,itemId:D.maintenance_items.find(G=>G.maintenance_type_id===z)?.id})):[],X=z=>{if(!t)return[];const D=new Set(H(z).map(G=>G.printerId));return le.filter(G=>!D.has(G.id))},[te,J]=w.useState(null),[Se,fe]=w.useState(""),[me,De]=w.useState(""),[de,ce]=w.useState("hours"),[Ne,ie]=w.useState("Wrench"),[Le,$]=w.useState(""),W=z=>{J(z),fe(z.name),De(z.default_interval_hours.toString()),ce(z.interval_type||"hours"),ie(z.icon||"Wrench"),$(z.wiki_url||"")},ue=()=>{te&&Se.trim()&&parseFloat(me)>0&&(i(te.id,{name:Se.trim(),default_interval_hours:parseFloat(me),interval_type:de,icon:Ne,wiki_url:Le.trim()||null}),J(null))},Z=(z,D,G)=>{const pe=parseFloat(x);if(!isNaN(pe)&&pe>0){const ve=Math.abs(pe-D)<.01?null:pe;n(z,{custom_interval_hours:ve,custom_interval_type:b!==G?b:null})}p(null)},oe=z=>{z.preventDefault(),A.trim()&&parseFloat(T)>0&&R.size>0&&(r({name:A.trim(),default_interval_hours:parseFloat(T),interval_type:j,icon:P,wiki_url:L.trim()||null},Array.from(R)),M(""),k("100"),E("hours"),B(""),V(new Set),N(!1))},Q=z=>{V(D=>{const G=new Set(D);return G.has(z)?G.delete(z):G.add(z),G})},he=t?.map(z=>({printerId:z.printer_id,printerName:z.printer_name,items:z.maintenance_items.sort((D,G)=>D.maintenance_type_id-G.maintenance_type_id)})).sort((z,D)=>z.printerName.localeCompare(D.printerName))||[],be=e.filter(z=>z.is_system),ee=e.filter(z=>!z.is_system);return a.jsxs("div",{className:"space-y-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:h("maintenance.maintenanceTypes")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:h("maintenance.maintenanceTypesDescription")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Me,{variant:"secondary",onClick:o,disabled:!d("maintenance:delete")||l,title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),children:h("maintenance.restoreDefaults")}),a.jsxs(Me,{onClick:()=>N(!S),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionEditTypes"),children:[a.jsx(ar,{className:"w-4 h-4"}),h("maintenance.addCustomType")]})]})]}),S&&a.jsx(_t,{className:"mb-6",children:a.jsx(Nt,{className:"py-4",children:a.jsxs("form",{onSubmit:oe,children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"lg:col-span-2",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("common.name")}),a.jsx("input",{type:"text",value:A,onChange:z=>M(z.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("maintenance.exampleName"),autoFocus:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.intervalType")}),a.jsxs("select",{value:j,onChange:z=>{E(z.target.value),z.target.value==="days"?k("30"):k("100")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"hours",children:h("maintenance.printHours")}),a.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.intervalValue",{type:j==="days"?h("maintenance.calendarDays").toLowerCase():h("common.hours")})}),a.jsx("input",{type:"number",value:T,onChange:z=>k(z.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),a.jsx("div",{className:"mt-4 flex items-end justify-between",children:a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.icon")}),a.jsx("div",{className:"flex gap-1",children:Object.keys(Ky).map(z=>{const D=Ky[z];return a.jsx("button",{type:"button",onClick:()=>U(z),className:`p-2 rounded-lg transition-colors ${P===z?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:a.jsx(D,{className:"w-4 h-4"})},z)})})]})}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.documentationLink")}),a.jsx("input",{type:"url",value:L,onChange:z=>B(z.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.assignToPrinters")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:le.map(z=>a.jsx("button",{type:"button",onClick:()=>Q(z.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${R.has(z.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:z.name},z.id))}),R.size===0&&a.jsx("p",{className:"text-xs text-orange-400 mt-1",children:h("maintenance.selectAtLeastOnePrinter")})]}),a.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:()=>{N(!1),V(new Set)},children:h("common.cancel")}),a.jsx(Me,{type:"submit",disabled:!A.trim()||R.size===0,children:h("maintenance.addType")})]})]})})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[be.map(z=>{const D=x0(z.icon),G=z.interval_type||"hours";return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:a.jsx(D,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-sm font-medium text-white truncate",children:z.name}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[G==="days"?a.jsx(ii,{className:"w-3 h-3"}):a.jsx(Ou,{className:"w-3 h-3"}),Vj(z.default_interval_hours,G,h)]})]}),a.jsx("button",{onClick:()=>{d("maintenance:delete")&&Y(z)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(en,{className:"w-4 h-4"})})]})},z.id)}),ee.map(z=>{const D=x0(z.icon),G=z.interval_type||"hours";if(te?.id===z.id)return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:a.jsxs("div",{className:"space-y-3",children:[a.jsx("input",{type:"text",value:Se,onChange:_e=>fe(_e.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("common.name"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:de,onChange:_e=>ce(_e.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"hours",children:h("maintenance.printHours")}),a.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:me,onChange:_e=>De(_e.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(Ky).map(_e=>{const He=Ky[_e];return a.jsx("button",{type:"button",onClick:()=>ie(_e),className:`p-1.5 rounded transition-colors ${Ne===_e?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a.jsx(He,{className:"w-3.5 h-3.5"})},_e)})}),a.jsx("input",{type:"url",value:Le,onChange:_e=>$(_e.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("maintenance.documentationLink")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Me,{size:"sm",onClick:ue,disabled:!Se.trim(),children:h("common.save")}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>J(null),children:h("common.cancel")})]})]})},z.id);const ve=H(z.id),xe=X(z.id),ze=q===z.id;return a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:a.jsx(D,{className:"w-5 h-5 text-bambu-green"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-white truncate",children:z.name}),a.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:h("maintenance.custom")})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[G==="days"?a.jsx(ii,{className:"w-3 h-3"}):a.jsx(Ou,{className:"w-3 h-3"}),Vj(z.default_interval_hours,G,h)]})]}),a.jsxs("button",{onClick:()=>I(ze?null:z.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${ve.length>0?"border-bambu-green/50 bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20":"border-orange-400/50 bg-orange-400/10 text-orange-400 hover:bg-orange-400/20"}`,title:h("maintenance.printersAssignedClick",{count:ve.length}),children:[a.jsx(Cr,{className:"w-3 h-3"}),a.jsx("span",{className:"text-xs font-medium",children:ve.length}),a.jsx(nr,{className:`w-3 h-3 transition-transform ${ze?"rotate-180":""}`})]}),a.jsx("button",{onClick:()=>W(z),disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:h("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${d("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(Pf,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{confirm(h("maintenance.deleteTypeConfirm",{name:z.name}))&&s(z.id)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(en,{className:"w-4 h-4"})})]}),ze&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:h("maintenance.assignedToPrinters")}),ve.length===0?a.jsx("p",{className:"text-xs text-orange-400",children:h("maintenance.noPrintersAssigned")}):a.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:ve.map(_e=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[_e.printerName,a.jsx("button",{onClick:()=>_e.itemId&&u(_e.itemId),disabled:!d("maintenance:delete"),title:d("maintenance:delete")?h("maintenance.removeFromPrinter"):h("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${d("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},_e.printerId))}),xe.length>0&&a.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:h("maintenance.addPrinterShort")}),xe.map(_e=>a.jsxs("button",{onClick:()=>c(_e.id,z.id),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${d("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",_e.name]},_e.id))]})]})]},z.id)})]})]}),he.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:h("maintenance.intervalOverrides")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:h("maintenance.intervalOverridesDescription")})]}),a.jsx("div",{className:"space-y-4",children:he.map(z=>a.jsx(_t,{children:a.jsxs(Nt,{className:"py-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:z.printerName}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:z.items.map(D=>{const G=x0(D.maintenance_type_icon),pe=e.find(He=>He.id===D.maintenance_type_id),ve=pe?.default_interval_hours||D.interval_hours,xe=pe?.interval_type||"hours",ze=D.interval_type||"hours",_e=f===D.id;return a.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[a.jsx(G,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:D.maintenance_type_name}),_e?a.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?a.jsx(ii,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):a.jsx(Ou,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),a.jsxs("select",{value:b,onChange:He=>y(He.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[a.jsx("option",{value:"hours",children:h("maintenance.printHours")}),a.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:x,onChange:He=>v(He.target.value),onKeyDown:He=>{He.key==="Enter"&&Z(D.id,ve,xe),He.key==="Escape"&&p(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),a.jsx(Me,{size:"sm",onClick:()=>Z(D.id,ve,xe),children:"OK"})]}):a.jsxs("button",{onClick:()=>{d("maintenance:update")&&(p(D.id),v(D.interval_hours.toString()),y(ze))},disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:h("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${d("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[ze==="days"?a.jsx(ii,{className:"w-3 h-3"}):a.jsx(Ou,{className:"w-3 h-3"}),Vj(D.interval_hours,ze,h),a.jsx(Pf,{className:"w-3 h-3 text-bambu-gray"})]})]},D.id)})})]})},z.printerId))})]}),he.length===0&&a.jsx(_t,{children:a.jsxs(Nt,{className:"text-center py-12",children:[a.jsx(Qn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-bambu-gray",children:h("common.noPrinters")}),a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:h("maintenance.intervalOverridesDescription")})]})}),K&&a.jsx(kn,{title:h("maintenance.deleteSystemTypeTitle"),message:h("maintenance.deleteSystemTypeMessage",{name:K.name}),confirmText:h("common.delete"),cancelText:h("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(K.id),Y(null)},onCancel:()=>Y(null)})]})}function LZe(){const{t}=Vt(),e=tn(),{showToast:n}=mn(),{hasPermission:r}=Ir(),[i,s]=w.useState("status"),{data:o,isLoading:l}=tt({queryKey:["maintenanceOverview"],queryFn:se.getMaintenanceOverview}),{data:c}=tt({queryKey:["maintenanceTypes"],queryFn:se.getMaintenanceTypes}),u=lt({mutationFn:({id:T,notes:k})=>se.performMaintenance(T,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:T=>{n(T.message,"error")}}),d=lt({mutationFn:({id:T,data:k})=>se.updateMaintenanceItem(T,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:T=>{n(T.message,"error")}}),h=lt({mutationFn:({id:T,data:k})=>se.updateMaintenanceType(T,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:T=>{n(T.message,"error")}}),f=lt({mutationFn:se.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:T=>{n(T.message,"error")}}),p=lt({mutationFn:se.restoreDefaultMaintenanceTypes,onSuccess:T=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:T.restored}))},onError:T=>{n(T.message,"error")}}),x=lt({mutationFn:({printerId:T,hours:k})=>se.setPrinterHours(T,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:T=>{n(T.message,"error")}}),v=lt({mutationFn:({printerId:T,typeId:k})=>se.assignMaintenanceType(T,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:T=>{n(T.message,"error")}}),b=lt({mutationFn:se.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:T=>{n(T.message,"error")}}),y=T=>{u.mutate({id:T})},S=(T,k)=>{d.mutate({id:T,data:{enabled:k}})},N=(T,k)=>{x.mutate({printerId:T,hours:k})};if(l)return a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})});const A=o?.reduce((T,k)=>T+k.due_count,0)||0,M=o?.reduce((T,k)=>T+k.warning_count,0)||0;return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:i==="status"?a.jsxs(a.Fragment,{children:[A>0&&a.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:A})}),A>0&&M>0&&" · ",M>0&&a.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:M})}),A===0&&M===0&&a.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),a.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),a.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),i==="status"?a.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((T,k)=>{const j=T.due_count*10+T.warning_count,E=k.due_count*10+k.warning_count;return j!==E?E-j:T.printer_name.localeCompare(k.printer_name)}).map(T=>a.jsx(RZe,{overview:T,onPerform:y,onToggle:S,onSetHours:N,hasPermission:r,t},T.printer_id)):a.jsx(_t,{children:a.jsxs(Nt,{className:"text-center py-16",children:[a.jsx(Rf,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):a.jsx(FZe,{overview:o,types:c||[],onUpdateInterval:(T,k)=>d.mutate({id:T,data:k}),onAddType:async(T,k)=>{const j=await se.createMaintenanceType(T);for(const E of k)await se.assignMaintenanceType(E,j.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(T,k)=>h.mutate({id:T,data:k}),onDeleteType:T=>f.mutate(T),onRestoreDefaults:()=>p.mutate(),isRestoringDefaults:p.isPending,onAssignType:(T,k)=>v.mutate({printerId:T,typeId:k}),onRemoveItem:T=>b.mutate(T),hasPermission:r,t})]})}const cK=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Kae({project:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=w.useState(t?.name||""),[l,c]=w.useState(t?.description||""),[u,d]=w.useState(t?.color||cK[0]),[h,f]=w.useState(t?.target_count?.toString()||""),[p,x]=w.useState(t?.target_parts_count?.toString()||""),[v,b]=w.useState(t?.status||"active"),[y,S]=w.useState(t?.tags||""),[N,A]=w.useState(t?.due_date?.split("T")[0]||""),[M,T]=w.useState(t?.priority||"normal"),k=j=>{j.preventDefault(),n({name:s.trim(),description:l.trim()||void 0,color:u,target_count:h?parseInt(h,10):void 0,target_parts_count:p?parseInt(p,10):void 0,tags:y.trim()||void 0,due_date:N||void 0,priority:M,...t&&{status:v}})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i(t?"projects.editProject":"projects.newProject")})}),a.jsxs("form",{onSubmit:k,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("common.name")}),a.jsx("input",{type:"text",value:s,onChange:j=>o(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("projects.namePlaceholder"),required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("common.description")}),a.jsx("textarea",{value:l,onChange:j=>c(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:i("projects.descriptionPlaceholder"),rows:2})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("projects.color")}),a.jsx("div",{className:"flex gap-2 flex-wrap",children:cK.map(j=>a.jsx("button",{type:"button",onClick:()=>d(j),className:`w-8 h-8 rounded-full transition-transform ${u===j?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:j}},j))})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("projects.targetPlates")}),a.jsx("input",{type:"number",value:h,onChange:j=>f(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("projects.targetPlatesPlaceholder"),min:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("projects.targetPlatesHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("projects.targetParts")}),a.jsx("input",{type:"number",value:p,onChange:j=>x(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("projects.targetPartsPlaceholder"),min:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("projects.targetPartsHelp")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("projects.tagsLabel")}),a.jsx("input",{type:"text",value:y,onChange:j=>S(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("projects.tagsPlaceholder")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("projects.dueDate")}),a.jsx("input",{type:"date",value:N,onChange:j=>A(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("projects.priority")}),a.jsxs("select",{value:M,onChange:j=>T(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"low",children:i("projects.priorityLow")}),a.jsx("option",{value:"normal",children:i("projects.priorityNormal")}),a.jsx("option",{value:"high",children:i("projects.priorityHigh")}),a.jsx("option",{value:"urgent",children:i("projects.priorityUrgent")})]})]})]}),t&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("common.status")}),a.jsxs("select",{value:v,onChange:j=>b(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"active",children:i("projects.statusActive")}),a.jsx("option",{value:"completed",children:i("projects.statusCompleted")}),a.jsx("option",{value:"archived",children:i("projects.statusArchived")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Me,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(at,{className:"w-4 h-4 animate-spin"}):i(t?"common.save":"projects.create")})]})]})]})})}function OZe({project:t,onClick:e,onEdit:n,onDelete:r,hasPermission:i,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",u=t.status==="archived",[d,h]=w.useState(!1),p=c?{icon:fb,color:"text-bambu-green",bg:"bg-bambu-green/10"}:u?{icon:Rs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Qn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:xs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return a.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[a.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),a.jsxs("div",{className:"p-5 pl-6",children:[a.jsxs("div",{className:"flex items-start justify-between mb-4",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg ${p.bg} flex-shrink-0`,children:a.jsx(p.icon,{className:`w-5 h-5 ${p.color}`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?a.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?a.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?a.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&a.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),u&&a.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const x=t.archives.map(S=>S.filament_type).filter(Boolean).flatMap(S=>S.split(",").map(N=>N.trim())).filter(Boolean),v=[...new Set(x)],b=t.archives.map(S=>S.filament_color).filter(Boolean).flatMap(S=>S.split(",").map(N=>N.trim())).filter(S=>S.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(S)),y=[...new Set(b)];return v.length===0&&y.length===0?null:a.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(S=>a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:S},S)),y.length>0&&a.jsxs("div",{className:"flex items-center gap-0.5",children:[y.slice(0,5).map(S=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:S.startsWith("#")?S:`#${S}`},title:S},S)),y.length>5&&a.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",y.length-5]})]})]})})()]})]}),a.jsxs("div",{className:"relative",onClick:x=>x.stopPropagation(),children:[a.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>h(!d),children:a.jsx(Ah,{className:"w-4 h-4"})}),d&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>h(!1)}),a.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[a.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:update")&&(n(),h(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[a.jsx(Pf,{className:"w-4 h-4"}),s("common.edit")]}),a.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:delete")&&(r(),h(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[a.jsx(en,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),a.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?a.jsxs("div",{className:"space-y-3",children:[t.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),a.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),a.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&a.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?a.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(Rs,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[a.jsx(Cn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[a.jsx(Qn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):a.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(x=>a.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:x.print_name||"Unknown",children:[x.thumbnail_path?a.jsx("img",{src:se.getArchiveThumbnail(x.id),alt:x.print_name||"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:a.jsx(ma,{className:"w-6 h-6"})}),x.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:a.jsx(Cn,{className:"w-4 h-4 text-white"})})]},x.id))}),t.archive_count>4&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),a.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[a.jsx(rs,{className:"w-3.5 h-3.5 text-blue-400"}),a.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[a.jsx(ma,{className:"w-3.5 h-3.5 text-bambu-green"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[a.jsx(Cn,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[a.jsx(g3,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.queue_count})]})]}),a.jsx(fa,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function IZe(){const{t}=Vt(),e=Hc(),n=tn(),{showToast:r}=mn(),{hasPermission:i}=Ir(),[s,o]=w.useState(!1),[l,c]=w.useState(),[u,d]=w.useState("active"),[h,f]=w.useState(null),{data:p,isLoading:x}=tt({queryKey:["projects",u==="all"?void 0:u],queryFn:()=>se.getProjects(u==="all"?void 0:u)}),v=lt({mutationFn:B=>se.createProject(B),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:B=>{r(B.message,"error")}}),b=lt({mutationFn:({id:B,data:R})=>se.updateProject(B,R),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:B=>{r(B.message,"error")}}),y=lt({mutationFn:B=>se.deleteProject(B),onSuccess:()=>{f(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:B=>{f(null),r(B.message,"error")}}),S=lt({mutationFn:B=>se.importProject(B),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:B=>{r(B.message,"error")}}),N=w.useRef(null),A=async()=>{try{const B=await se.getProjects(),R=await Promise.all(B.map(async K=>await se.exportProjectJson(K.id))),V=new Blob([JSON.stringify(R,null,2)],{type:"application/json"}),q=URL.createObjectURL(V),I=document.createElement("a");I.href=q,I.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,I.click(),URL.revokeObjectURL(q),r(t("projects.toast.exported"),"success")}catch(B){r(B.message,"error")}},M=()=>{N.current?.click()},T=async B=>{const R=B.target.files?.[0];if(R){try{if(R.name.toLowerCase().endsWith(".zip"))await se.importProjectFile(R),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const q=await R.text(),I=JSON.parse(q),K=Array.isArray(I)?I:[I];for(const Y of K)await S.mutateAsync(Y);K.length>1&&r(t("projects.toast.multipleImported",{count:K.length}),"success")}}catch(V){r(`${t("projects.toast.importFailed")}: ${V.message}`,"error")}B.target.value=""}},k=B=>{l?b.mutate({id:l.id,data:B}):v.mutate(B)},j=B=>{c(B),o(!0)},E=B=>{e(`/projects/${B.id}`)},P=B=>{f(B)},U=()=>{h!==null&&y.mutate(h)},L=p?.reduce((B,R)=>(B[R.status]=(B[R.status]||0)+1,B.all=(B.all||0)+1,B),{})||{};return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:T,className:"hidden"}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(xs,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Me,{variant:"secondary",onClick:M,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[a.jsx(ia,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),a.jsxs(Me,{variant:"secondary",onClick:A,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[a.jsx(di,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),a.jsxs(Me,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(ar,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),a.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Qn},{key:"completed",label:t("projects.statusCompleted"),icon:fb},{key:"archived",label:t("projects.statusArchived"),icon:Rs},{key:"all",label:t("common.all"),icon:xs}].map(({key:B,label:R,icon:V})=>a.jsxs("button",{onClick:()=>d(B),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===B?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[a.jsx(V,{className:"w-4 h-4"}),a.jsx("span",{children:R}),L[B]>0&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===B?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[B]})]},B))}),x?a.jsx("div",{className:"flex items-center justify-center py-20",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(at,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):p?.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(xs,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:u==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:u})}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:u==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:u})}),u==="all"&&a.jsxs(Me,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(ar,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:p?.map(B=>a.jsx(OZe,{project:B,onClick:()=>E(B),onEdit:()=>j(B),onDelete:()=>P(B.id),hasPermission:i,t},B.id))}),h!==null&&a.jsx(kn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:U,onCancel:()=>f(null)}),s&&a.jsx(Kae,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:k,isLoading:v.isPending||b.isPending,t})]})}function zZe(t){if(t<1)return`${Math.round(t*60)}m`;const e=Math.floor(t),n=Math.round((t-e)*60);return n>0?`${e}h ${n}m`:`${e}h`}function UZe(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function BZe({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return a.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function uK({icon:t,label:e,value:n,subValue:r,hint:i,color:s="text-bambu-gray"}){return a.jsx(_t,{children:a.jsx(Nt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",title:i,children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:a.jsx(t,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:e}),a.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function HZe({archives:t,t:e}){return t.length===0?a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(ma,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:e("projectDetail.noPrints")})]}):a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(n=>a.jsxs(Xs,{to:`/archives?search=${encodeURIComponent(n.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[n.thumbnail_path?a.jsx("img",{src:se.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(ma,{className:"w-8 h-8"})}),n.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:a.jsx(ha,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&a.jsx("div",{className:"absolute top-1 right-1",children:a.jsx(gr,{className:"w-4 h-4 text-bambu-green"})}),a.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function $Ze({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:r,label:i}=n[t]||n.normal;return a.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&a.jsx(Cn,{className:"w-3 h-3"}),i]})}function VZe(t){return t?gb(t,{year:"numeric",month:"short",day:"numeric"}):""}function Gj(t,e){if(!t)return null;const n=Zi(t);if(!n)return null;const r=new Date,i=Math.ceil((n.getTime()-r.getTime())/(1e3*60*60*24));return i<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:i===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:i<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:i})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:i})}}function GZe(){const{id:t}=Yk(),e=Hc(),{t:n}=Vt(),r=tn(),{showToast:i}=mn(),{hasPermission:s}=Ir(),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(""),f=parseInt(t||"0",10),{data:p,isLoading:x,error:v}=tt({queryKey:["project",f],queryFn:()=>se.getProject(f),enabled:f>0}),{data:b,isLoading:y}=tt({queryKey:["project-archives",f],queryFn:()=>se.getProjectArchives(f),enabled:f>0}),{data:S,isLoading:N}=tt({queryKey:["project-bom",f],queryFn:()=>se.getProjectBOM(f),enabled:f>0}),{data:A,isLoading:M}=tt({queryKey:["project-timeline",f],queryFn:()=>se.getProjectTimeline(f,20),enabled:f>0}),{data:T}=tt({queryKey:["settings"],queryFn:se.getSettings}),{data:k}=tt({queryKey:["project-folders",f],queryFn:()=>se.getLibraryFoldersByProject(f),enabled:f>0}),j=Pu(T?.currency||"USD"),E=T?.time_format||"system",P=lt({mutationFn:je=>se.updateProject(f,je),onSuccess:()=>{r.invalidateQueries({queryKey:["project",f]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:je=>{i(je.message,"error")}}),U=()=>{h(p?.notes||""),u(!0)},L=()=>{P.mutate({notes:d})},B=()=>{u(!1),h("")},[R,V]=w.useState(""),[q,I]=w.useState(1),[K,Y]=w.useState(""),[le,H]=w.useState(""),[X,te]=w.useState(""),[J,Se]=w.useState(!1),[fe,me]=w.useState(!1),[De,de]=w.useState(null),[ce,Ne]=w.useState(""),[ie,Le]=w.useState(1),[$,W]=w.useState(""),[ue,Z]=w.useState(""),[oe,Q]=w.useState(""),[he,be]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),ee=lt({mutationFn:je=>se.createBOMItem(f,je),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),V(""),I(1),Y(""),H(""),te(""),Se(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:je=>i(je.message,"error")}),z=lt({mutationFn:({itemId:je,data:Ve})=>se.updateBOMItem(f,je,Ve),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),de(null)},onError:je=>i(je.message,"error")}),D=lt({mutationFn:je=>se.deleteBOMItem(f,je),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:je=>i(je.message,"error")}),G=je=>{je.preventDefault(),R.trim()&&ee.mutate({name:R.trim(),quantity_needed:q,unit_price:K?parseFloat(K):void 0,sourcing_url:le.trim()||void 0,remarks:X.trim()||void 0})},pe=je=>{const Ve=je.is_complete?0:je.quantity_needed;z.mutate({itemId:je.id,data:{quantity_acquired:Ve}})},ve=(je,Ve)=>{be({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Ve}),onConfirm:()=>{be(Ae=>({...Ae,isOpen:!1})),D.mutate(je)}})},xe=je=>{de(je),Ne(je.name),Le(je.quantity_needed),W(je.unit_price?.toString()||""),Z(je.sourcing_url||""),Q(je.remarks||"")},ze=je=>{je.preventDefault(),!(!De||!ce.trim())&&z.mutate({itemId:De.id,data:{name:ce.trim(),quantity_needed:ie,unit_price:$?parseFloat($):void 0,sourcing_url:ue.trim()||void 0,remarks:oe.trim()||void 0}})},_e=()=>{de(null)},He=async()=>{try{const{blob:je,filename:Ve}=await se.exportProjectZip(Number(f)),Ae=URL.createObjectURL(je),Je=document.createElement("a");Je.href=Ae,Je.download=Ve||`${p?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,Je.click(),URL.revokeObjectURL(Ae),i(n("projectDetail.toast.projectExported"),"success")}catch(je){i(je.message,"error")}},Ze=lt({mutationFn:()=>se.createTemplateFromProject(f),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:je=>i(je.message,"error")}),we=je=>Ff(je,E,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(x)return a.jsx("div",{className:"flex items-center justify-center py-24",children:a.jsx(at,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!p)return a.jsxs("div",{className:"text-center py-24",children:[a.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),a.jsx(Me,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const ye=p.stats,ke=ye?.progress_percent??0,Ue=ye?.parts_progress_percent??0;return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(Xs,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),a.jsx(fa,{className:"w-4 h-4"}),a.jsx("span",{className:"text-white",children:p.name})]}),a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:a.jsx(fde,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:p.color||"#6b7280"}}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:p.name}),p.description&&a.jsx("p",{className:"text-bambu-gray mt-1",children:p.description})]})]}),a.jsx(BZe,{status:p.status,t:n})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Me,{variant:"secondary",onClick:He,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[a.jsx(di,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),a.jsxs(Me,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[a.jsx(Pf,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(p.target_count||p.target_parts_count)&&a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4 space-y-4",children:[p.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[ye?.total_archives||0," / ",p.target_count," ",n("projectDetail.progress.printJobs")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(ke,100)}%`,backgroundColor:ke>=100?"#22c55e":p.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:ke.toFixed(0)})}),ye?.remaining_prints!=null&&ye.remaining_prints>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:ye.remaining_prints})})]})]}),p.target_parts_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[ye?.completed_prints||0," / ",p.target_parts_count," ",n("projectDetail.progress.parts")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ue,100)}%`,backgroundColor:Ue>=100?"#22c55e":p.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Ue.toFixed(0)})}),ye?.remaining_parts!=null&&ye.remaining_parts>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:ye.remaining_parts})})]})]})]})}),ye&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(_t,{children:a.jsx(Nt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:a.jsx(ma,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),a.jsxs("p",{className:"text-xl font-semibold text-white",children:[ye.total_archives," ",a.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),ye.failed_prints>0&&a.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:ye.failed_prints})}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:ye.completed_prints})})]})]})})}),a.jsx(uK,{icon:Qn,label:n("projectDetail.stats.printTime"),value:zZe(ye.total_print_time_hours),color:"text-yellow-400"}),a.jsx(uK,{icon:Cr,label:n("projectDetail.stats.filamentUsed"),value:UZe(ye.total_filament_grams),color:"text-purple-400"})]}),ye&&(ye.estimated_cost>0||p.budget)&&a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[j,ye.estimated_cost.toFixed(2)]})]}),ye.total_energy_kwh>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[ye.total_energy_kwh.toFixed(2)," kWh",ye.total_energy_cost>0&&a.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",j,ye.total_energy_cost.toFixed(2),")"]})]})]}),p.budget&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[j,p.budget.toFixed(2)]})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.remaining")}),a.jsxs("p",{className:`text-lg font-semibold ${p.budget-ye.estimated_cost>=0?"text-bambu-green":"text-red-400"}`,children:[j,(p.budget-ye.estimated_cost).toFixed(2)]})]})]})]})]})}),p.children&&p.children.length>0&&a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[a.jsx(tme,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:p.children.length})]}),a.jsx("div",{className:"space-y-2",children:p.children.map(je=>a.jsxs(Xs,{to:`/projects/${je.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:je.color||"#6b7280"}}),a.jsx("span",{className:"text-white",children:je.name}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${je.status==="completed"?"bg-status-ok/20 text-status-ok":je.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:je.status})]}),je.progress_percent!==null&&a.jsxs("span",{className:"text-sm text-bambu-gray",children:[je.progress_percent.toFixed(0),"%"]})]},je.id))})]})}),p.parent_id&&p.parent_name&&a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(rs,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),a.jsx(Xs,{to:`/projects/${p.parent_id}`,className:"text-bambu-green hover:underline",children:p.parent_name})]}),(p.tags||p.due_date||p.priority!=="normal")&&a.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[p.priority&&p.priority!=="normal"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),a.jsx($Ze,{priority:p.priority,t:n})]}),p.due_date&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ii,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:VZe(p.due_date)}),Gj(p.due_date,n)&&a.jsxs("span",{className:`text-xs ${Gj(p.due_date,n).color}`,children:["(",Gj(p.due_date,n).label,")"]})]}),p.tags&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Vh,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:p.tags.split(",").map((je,Ve)=>a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:je.trim()},Ve))})]})]}),a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ps,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Me,{variant:"secondary",size:"sm",onClick:B,disabled:P.isPending,children:[a.jsx(Ft,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),a.jsxs(Me,{size:"sm",onClick:L,disabled:P.isPending,children:[P.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin mr-1"}):a.jsx(bs,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):a.jsxs(Me,{variant:"secondary",size:"sm",onClick:U,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[a.jsx(Pf,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?a.jsx(oF,{content:d,onChange:h,placeholder:n("projectDetail.notes.placeholder")}):p.notes?a.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.notes}}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Xl,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),a.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[a.jsx(Xs,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),k&&k.length>0?a.jsx("div",{className:"space-y-2",children:k.map(je=>a.jsxs(Xs,{to:`/files?folder=${je.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsx(Xl,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:je.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:je.file_count})})]})]}),a.jsx(fa,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},je.id))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(bX,{className:"w-5 h-5"}),n("projectDetail.bom.title"),ye&&ye.bom_total_items>0&&a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:ye.bom_completed_items,total:ye.bom_total_items}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[S&&S.some(je=>je.is_complete)&&a.jsx("button",{onClick:()=>me(!fe),className:`text-xs px-2 py-1 rounded transition-colors ${fe?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(fe?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!J&&a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>Se(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[a.jsx(ar,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),J&&a.jsxs("form",{onSubmit:G,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:R,onChange:je=>V(je.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:q,onChange:je=>I(parseInt(je.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:K,onChange:je=>Y(je.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:j})})]})]}),a.jsx("input",{type:"url",value:le,onChange:je=>H(je.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:X,onChange:je=>te(je.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Me,{type:"button",variant:"secondary",size:"sm",onClick:()=>Se(!1),children:n("common.cancel")}),a.jsx(Me,{type:"submit",size:"sm",disabled:!R.trim()||ee.isPending,children:ee.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),N?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(at,{className:"w-6 h-6 animate-spin text-bambu-green"})}):S&&S.length>0?a.jsxs("div",{className:"space-y-2",children:[S.filter(je=>!fe||!je.is_complete).map(je=>a.jsx("div",{className:`p-3 rounded-lg transition-colors ${je.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:De?.id===je.id?a.jsxs("form",{onSubmit:ze,className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:ce,onChange:Ve=>Ne(Ve.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partName"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:ie,onChange:Ve=>Le(parseInt(Ve.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:$,onChange:Ve=>W(Ve.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:j})})]})]}),a.jsx("input",{type:"url",value:ue,onChange:Ve=>Z(Ve.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:oe,onChange:Ve=>Q(Ve.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Me,{type:"button",variant:"secondary",size:"sm",onClick:_e,children:n("common.cancel")}),a.jsx(Me,{type:"submit",size:"sm",disabled:!ce.trim()||z.isPending,children:z.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("button",{onClick:()=>s("projects:update")&&pe(je),disabled:z.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors flex-shrink-0 ${je.is_complete?"bg-status-ok border-status-ok text-white":s("projects:update")?"border-bambu-gray hover:border-bambu-green":"border-bambu-gray/50 cursor-not-allowed"}`,children:je.is_complete&&a.jsx(gr,{className:"w-3 h-3"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsxs("p",{className:`text-sm font-medium ${je.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[je.name,a.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",je.quantity_needed]})]}),je.unit_price!==null&&a.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[j,(je.unit_price*je.quantity_needed).toFixed(2)]})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>s("projects:update")&&xe(je),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:a.jsx($i,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("projects:update")&&ve(je.id,je.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:a.jsx(en,{className:"w-4 h-4"})})]})]}),je.sourcing_url&&a.jsxs("a",{href:je.sourcing_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 mt-1 text-xs text-blue-400 hover:text-blue-300 transition-colors",onClick:Ve=>Ve.stopPropagation(),children:[a.jsx(Kr,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"truncate",children:(()=>{try{return new URL(je.sourcing_url).hostname.replace("www.","")}catch{return je.sourcing_url}})()})]}),je.remarks&&a.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:je.remarks})]})]})},je.id)),S.some(je=>je.unit_price!==null)&&a.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),a.jsxs("span",{className:"text-white font-medium",children:[j,S.reduce((je,Ve)=>je+(Ve.unit_price||0)*Ve.quantity_needed,0).toFixed(2)]})]})]}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(N0,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),M?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(at,{className:"w-6 h-6 animate-spin text-bambu-green"})}):A&&A.length>0?a.jsx("div",{className:"space-y-3",children:A.slice(0,10).map((je,Ve)=>a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${je.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":je.event_type==="print_failed"?"bg-status-error/20 text-status-error":je.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[je.event_type==="print_completed"&&a.jsx(gr,{className:"w-4 h-4"}),je.event_type==="print_failed"&&a.jsx(ha,{className:"w-4 h-4"}),je.event_type==="print_started"&&a.jsx(Cr,{className:"w-4 h-4"}),je.event_type==="queued"&&a.jsx(g3,{className:"w-4 h-4"}),je.event_type==="project_created"&&a.jsx(ar,{className:"w-4 h-4"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white",children:je.title}),je.description&&a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:je.description}),a.jsx("p",{className:"text-xs text-bambu-gray/70",children:we(je.timestamp)})]})]},Ve))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!p.is_template&&a.jsx("div",{className:"flex justify-end",children:a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>Ze.mutate(),disabled:Ze.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[Ze.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(Wl,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),ye&&(ye.queued_prints>0||ye.in_progress_prints>0)&&a.jsx(_t,{children:a.jsxs(Nt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(g3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),a.jsx(Xs,{to:`/queue?project=${f}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[ye.in_progress_prints>0&&a.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:ye.in_progress_prints})}),ye.queued_prints>0&&a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:ye.queued_prints})})]})]})}),a.jsxs("div",{children:[a.jsx("div",{className:"flex items-center justify-between mb-4",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ma,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:b?.length||0})]})}),y?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(at,{className:"w-6 h-6 animate-spin text-bambu-green"})}):a.jsx(HZe,{archives:b||[],t:n})]}),o&&a.jsx(Kae,{t:n,project:{...p,archive_count:ye?.total_archives||0,total_items:ye?.total_items||0,completed_count:ye?.completed_prints||0,failed_count:ye?.failed_prints||0,queue_count:ye?.queued_prints||0,progress_percent:ye?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:je=>P.mutate(je),isLoading:P.isPending}),he.isOpen&&a.jsx(kn,{title:he.title,message:he.message,confirmText:n("common.delete"),variant:"danger",onConfirm:he.onConfirm,onCancel:()=>be(je=>({...je,isOpen:!1}))})]})}function Bg(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(2)} GB`}function qZe(t){if(!t)return"-";const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function WZe({parentId:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),a.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),a.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Me,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(at,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function KZe({type:t,currentName:e,onClose:n,onSave:r,isLoading:i,t:s}){const[o,l]=w.useState(e),c=u=>{u.preventDefault(),o.trim()&&o.trim()!==e&&r(o.trim())};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),a.jsxs("form",{onSubmit:c,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsx("input",{type:"text",value:o,onChange:u=>l(u.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",autoFocus:!0,required:!0})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),a.jsx(Me,{type:"submit",disabled:!o.trim()||o.trim()===e||i,children:i?a.jsx(at,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function XZe({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:i,isLoading:s,t:o}){const[l,c]=w.useState(null),u=(h,f=0)=>{const p=[];for(const x of h)p.push({id:x.id,name:x.name,depth:f}),x.children.length>0&&p.push(...u(x.children,f+1));return p},d=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...u(t)];return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:d.map(h=>a.jsxs("button",{onClick:()=>c(h.id),disabled:h.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===h.id?"bg-bambu-green/20 text-bambu-green":h.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+h.depth*16}px`},children:[a.jsx(Xl,{className:"w-4 h-4"}),h.name,h.id===n&&a.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},h.id??"root"))}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),a.jsx(Me,{onClick:()=>i(l),disabled:s,children:s?a.jsx(at,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function YZe({folder:t,onClose:e,onLink:n,isLoading:r,t:i}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:u}=tt({queryKey:["projects"],queryFn:()=>se.getProjects()}),{data:d}=tt({queryKey:["archives-for-link"],queryFn:()=>se.getArchives(void 0,void 0,100)}),h=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},f=()=>{n({project_id:0,archive_id:0})},p=t.project_id||t.archive_id;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(jh,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Ft,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[a.jsx(oX,{className:"w-4 h-4"}),i("fileManager.project")]}),a.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[a.jsx(Rs,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?u&&u.length>0?u.map(x=>a.jsxs("button",{onClick:()=>c(x.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===x.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:x.color||"#00ae42"}}),a.jsx("span",{className:"truncate",children:x.name})]},x.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):d&&d.length>0?d.map(x=>a.jsxs("button",{onClick:()=>c(x.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===x.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx(ff,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"truncate",children:x.print_name||x.filename})]},x.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[p&&a.jsxs(Me,{variant:"danger",onClick:f,disabled:r,children:[a.jsx(uC,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),a.jsxs("div",{className:`flex gap-2 ${p?"":"ml-auto"}`,children:[a.jsx(Me,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Me,{onClick:h,disabled:!l||r,children:r?a.jsx(at,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function QZe({folderId:t,onClose:e,onUploadComplete:n,t:r}){const[i,s]=w.useState([]),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(!0),[f,p]=w.useState(!1),[x,v]=w.useState(!0),b=w.useRef(null),y=V=>{V.preventDefault(),l(!0)},S=V=>{V.preventDefault(),l(!1)},N=V=>{V.preventDefault(),l(!1);const q=Array.from(V.dataTransfer.files);M(q)},A=V=>{V.target.files&&M(Array.from(V.target.files))},M=V=>{const q=V.map(I=>({file:I,status:"pending",isZip:I.name.toLowerCase().endsWith(".zip"),is3mf:I.name.toLowerCase().endsWith(".3mf")}));s(I=>[...I,...q])},T=V=>{s(q=>q.filter((I,K)=>K!==V))},k=i.some(V=>V.isZip&&V.status==="pending"),j=i.some(V=>V.file.name.toLowerCase().endsWith(".stl")&&V.status==="pending"),E=i.some(V=>V.is3mf&&V.status==="pending"),P=async()=>{if(i.length!==0){u(!0);for(let V=0;Vq.map((I,K)=>K===V?{...I,status:"uploading"}:I));try{if(i[V].isZip){const q=await se.extractZipFile(i[V].file,t,d,f,x);s(I=>I.map((K,Y)=>Y===V?{...K,status:q.errors.length>0&&q.extracted===0?"error":"success",extractedCount:q.extracted,error:q.errors.length>0?`${q.errors.length} files failed`:void 0}:K))}else await se.uploadLibraryFile(i[V].file,t,x),s(q=>q.map((I,K)=>K===V?{...I,status:"success"}:I))}catch(q){s(I=>I.map((K,Y)=>Y===V?{...K,status:"error",error:q instanceof Error?q.message:"Upload failed"}:K))}}u(!1),n(),e()}},U=i.filter(V=>V.status==="pending").length,L=i.filter(V=>V.status==="success").length,B=i.filter(V=>V.status==="error").length,R=i.length>0&&U===0&&!c;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("fileManager.uploadFiles")}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Ft,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("div",{onDragOver:y,onDragLeave:S,onDrop:N,onClick:()=>b.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${o?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[a.jsx(ia,{className:`w-10 h-10 mx-auto mb-3 ${o?"text-bambu-green":"text-bambu-gray"}`}),a.jsx("p",{className:"text-white font-medium",children:r(o?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("fileManager.orClickToBrowse")}),a.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:r("fileManager.allFileTypesSupported")})]}),a.jsx("input",{ref:b,type:"file",multiple:!0,className:"hidden",onChange:A}),k&&a.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Rs,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-blue-300 font-medium",children:r("fileManager.zipFilesDetected")}),a.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:r("fileManager.zipExtractOptions")}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:d,onChange:V=>h(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.preserveZipStructure")})]}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:f,onChange:V=>p(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.createFolderFromZip")})]})]})]})}),E&&a.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Cr,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-purple-300 font-medium",children:r("fileManager.threemfDetected")}),a.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:r("fileManager.threemfExtractionInfo")})]})]})}),(j||k)&&a.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(ed,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium",children:r("fileManager.stlThumbnailGeneration")}),a.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:r(k&&!j?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:x,onChange:V=>v(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.generateThumbnailsForStl")})]})]})]})}),i.length>0&&a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:i.map((V,q)=>a.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[V.isZip?a.jsx(Rs,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):a.jsx(eC,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:V.file.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[(V.file.size/1024/1024).toFixed(2)," MB",V.isZip&&V.status==="pending"&&a.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",r("fileManager.willBeExtracted")]}),V.extractedCount!==void 0&&a.jsxs("span",{className:"text-green-400 ml-2",children:["• ",r("fileManager.filesExtracted",{count:V.extractedCount})]})]})]}),V.status==="pending"&&a.jsx("button",{onClick:()=>T(q),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Ft,{className:"w-4 h-4 text-bambu-gray"})}),V.status==="uploading"&&a.jsx(at,{className:"w-4 h-4 text-bambu-green animate-spin"}),V.status==="success"&&a.jsx(gr,{className:"w-4 h-4 text-green-500"}),V.status==="error"&&a.jsx("span",{title:V.error,children:a.jsx(ha,{className:"w-4 h-4 text-red-500"})})]},q))}),R&&a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[r("fileManager.uploadComplete",{succeeded:L}),B>0&&a.jsxs("span",{className:"text-red-400",children:[", ",r("fileManager.uploadFailed",{count:B})]})]})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[a.jsx(Me,{variant:"secondary",onClick:e,children:r(R?"common.close":"common.cancel")}),!R&&a.jsx(Me,{onClick:P,disabled:U===0||c,children:c?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 mr-2 animate-spin"}),r("fileManager.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(ia,{className:"w-4 h-4 mr-2"}),r("common.upload")," ",U>0?`(${U})`:""]})})]})]})})}function Xae({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:u}){const[d,h]=w.useState(!0),[f,p]=w.useState(!1),x=t.children.length>0,v=t.project_id||t.archive_id;return a.jsxs("div",{children:[a.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>n(t.id),children:[x?a.jsx("button",{onClick:b=>{b.stopPropagation(),h(!d)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(fa,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-90":""}`})}):a.jsx("div",{className:"w-4.5"}),a.jsx(Xl,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),a.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&a.jsxs("button",{onClick:b=>{b.stopPropagation(),i(t)},className:"flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors",title:`${t.project_name?`Project: ${t.project_name}`:`Archive: ${t.archive_name}`} (click to change)`,children:[a.jsx(jh,{className:"w-3 h-3"}),t.project_name?a.jsx(oX,{className:"w-3 h-3"}):a.jsx(Rs,{className:"w-3 h-3"})]}),t.file_count>0&&a.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&a.jsx("button",{onClick:b=>{b.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:a.jsx(jh,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),a.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:b=>b.stopPropagation(),children:a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:()=>p(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:a.jsx(Ah,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>p(!1)}),a.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(s(t),p(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[a.jsx($i,{className:"w-3.5 h-3.5"}),u("common.rename")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(i(t),p(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[a.jsx(jh,{className:"w-3.5 h-3.5"}),u(v?"fileManager.changeLink":"fileManager.linkTo")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:delete_all")&&(r(t.id),p(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[a.jsx(en,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),x&&d&&a.jsx("div",{children:t.children.map(b=>a.jsx(Xae,{folder:b,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},b.id))})]})}function fF(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function ZZe({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:u,onGenerateThumbnail:d,thumbnailVersion:h,hasPermission:f,canModify:p,authEnabled:x,t:v}){const[b,y]=w.useState(!1);return a.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>r(t.id),children:[a.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?a.jsx("img",{src:`${se.getLibraryFileThumbnailUrl(t.id)}${h?`?v=${h}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):a.jsx(ff,{className:"w-12 h-12 text-bambu-gray/30"}),a.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),a.jsxs("div",{className:"p-3",children:[a.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),a.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[a.jsx("span",{children:Bg(t.file_size)}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Qn,{className:"w-3 h-3"}),qZe(t.print_time_seconds)]})]}),t.sliced_for_model&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(Cr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&a.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),x&&t.created_by_username&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(nd,{className:"w-3 h-3"}),t.created_by_username]})]}),a.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:S=>S.stopPropagation(),children:[a.jsx("button",{onClick:()=>y(!b),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:a.jsx(Ah,{className:"w-4 h-4 text-bambu-gray"})}),b&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>y(!1)}),a.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&fF(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("printers:control")&&(l(t),y(!1))},disabled:!f("printers:control"),title:f("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[a.jsx(Cr,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&fF(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("queue:create")&&(o(t.id),y(!1))},disabled:!f("queue:create"),title:f("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[a.jsx(Qn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library:read")&&(c(t),y(!1))},disabled:!f("library:read"),title:f("library:read")?void 0:"You do not have permission to preview files",children:[a.jsx(Qi,{className:"w-3.5 h-3.5"}),"3D Preview"]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library:read")&&(s(t.id),y(!1))},disabled:!f("library:read"),title:f("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[a.jsx(di,{className:"w-3.5 h-3.5"}),v("common.download")]}),u&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","update",t.created_by_id)&&(u(t),y(!1))},disabled:!p("library","update",t.created_by_id),title:p("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[a.jsx($i,{className:"w-3.5 h-3.5"}),v("common.rename")]}),d&&t.file_type==="stl"&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","update",t.created_by_id)&&(d(t),y(!1))},disabled:!p("library","update",t.created_by_id),title:p("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[a.jsx(ed,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","delete",t.created_by_id)&&(i(t.id),y(!1))},disabled:!p("library","delete",t.created_by_id),title:p("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[a.jsx(en,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),a.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function JZe(){const{t}=Vt(),e=tn(),{showToast:n}=mn(),{hasPermission:r,hasAnyPermission:i,canModify:s,authEnabled:o}=Ir(),[l]=NF(),c=l.get("folder"),u=c?parseInt(c,10):null,[d,h]=w.useState(u),[f,p]=w.useState([]),[x,v]=w.useState(!1),[b,y]=w.useState(!1),[S,N]=w.useState(!1),[A,M]=w.useState(null),[T,k]=w.useState(null),[j,E]=w.useState(null),[P,U]=w.useState(null),[L,B]=w.useState(null),[R,V]=w.useState(null),[q,I]=w.useState({}),[K,Y]=w.useState(null),[le,H]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[X,te]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[J,Se]=w.useState(()=>{const Oe=localStorage.getItem("library-sidebar-width");return Oe?parseInt(Oe,10):256}),[fe,me]=w.useState(!1),De=w.useRef(null);w.useEffect(()=>{if(!fe)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Oe=vt=>{if(!De.current)return;const Bt=De.current.parentElement?.getBoundingClientRect();if(!Bt)return;const Tn=vt.clientX-Bt.left,fr=Math.min(500,Math.max(200,Tn));Se(fr)},xt=()=>{me(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(J))};return document.addEventListener("mousemove",Oe),document.addEventListener("mouseup",xt),()=>{document.removeEventListener("mousemove",Oe),document.removeEventListener("mouseup",xt),document.body.style.userSelect="",document.body.style.cursor=""}},[fe,J]);const[de,ce]=w.useState(""),[Ne,ie]=w.useState("all"),[Le,$]=w.useState(""),[W,ue]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[Z,oe]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),Q=fne();w.useEffect(()=>{const Oe=l.get("folder");if(Oe){const xt=parseInt(Oe,10);h(xt)}},[l]);const{data:he}=tt({queryKey:["settings"],queryFn:()=>se.getSettings()}),{data:be,isLoading:ee}=tt({queryKey:["library-folders"],queryFn:()=>se.getLibraryFolders()}),{data:z,isLoading:D}=tt({queryKey:["library-files",d],queryFn:()=>se.getLibraryFiles(d,d===null)}),{data:G}=tt({queryKey:["library-stats"],queryFn:()=>se.getLibraryStats()}),{data:pe}=tt({queryKey:["users"],queryFn:()=>se.getUsers()}),ve=w.useMemo(()=>{if(!z)return[];const Oe=new Set(z.map(xt=>xt.file_type));return Array.from(Oe).sort()},[z]),xe=w.useMemo(()=>{if(!z)return[];let Oe=[...z];if(de.trim()){const xt=de.toLowerCase();Oe=Oe.filter(vt=>vt.filename.toLowerCase().includes(xt)||vt.print_name&&vt.print_name.toLowerCase().includes(xt))}if(Ne!=="all"&&(Oe=Oe.filter(xt=>xt.file_type===Ne)),Le.trim()){const xt=Le.toLowerCase();Oe=Oe.filter(vt=>vt.created_by_username&&vt.created_by_username.toLowerCase().includes(xt))}return Oe.sort((xt,vt)=>{let Bt=0;switch(W){case"name":Bt=(xt.print_name||xt.filename).localeCompare(vt.print_name||vt.filename);break;case"date":Bt=new Date(xt.created_at).getTime()-new Date(vt.created_at).getTime();break;case"size":Bt=xt.file_size-vt.file_size;break;case"type":Bt=xt.file_type.localeCompare(vt.file_type);break;case"prints":Bt=xt.print_count-vt.print_count;break}return Z==="asc"?Bt:-Bt}),Oe},[z,de,Ne,Le,W,Z]),ze=w.useMemo(()=>{if(!G||!he)return!1;const Oe=(he.library_disk_warning_gb||5)*1024*1024*1024;return G.disk_free_bytesse.createLibraryFolder(Oe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Oe=>n(Oe.message,"error")}),He=lt({mutationFn:Oe=>se.deleteLibraryFolder(Oe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===T?.id&&h(null),k(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Oe=>{k(null),n(Oe.message,"error")}}),Ze=lt({mutationFn:Oe=>se.deleteLibraryFile(Oe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),p(Oe=>Oe.filter(xt=>xt!==T?.id)),k(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Oe=>{k(null),n(Oe.message,"error")}}),we=lt({mutationFn:Oe=>se.bulkDeleteLibrary(Oe,[]),onSuccess:(Oe,xt)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:xt.length}),"success"),p([]),k(null)},onError:Oe=>{k(null),n(Oe.message,"error")}}),ye=lt({mutationFn:({fileIds:Oe,folderId:xt})=>se.moveLibraryFiles(Oe,xt),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),p([]),y(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Oe=>n(Oe.message,"error")}),ke=lt({mutationFn:({id:Oe,data:xt})=>se.updateLibraryFolder(Oe,xt),onSuccess:(Oe,xt)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),M(null);const vt=xt.data.project_id===0&&xt.data.archive_id===0;n(t(vt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Oe=>n(Oe.message,"error")}),Ue=lt({mutationFn:({id:Oe,filename:xt})=>se.updateLibraryFile(Oe,{filename:xt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),V(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Oe=>{V(null),n(Oe.message,"error")}}),je=lt({mutationFn:({id:Oe,name:xt})=>se.updateLibraryFolder(Oe,{name:xt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),V(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Oe=>{V(null),n(Oe.message,"error")}}),Ve=lt({mutationFn:()=>se.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Oe=>{if(e.invalidateQueries({queryKey:["library-files"]}),Oe.succeeded>0){const xt=Date.now(),vt={};Oe.results.forEach(Bt=>{Bt.success&&(vt[Bt.file_id]=xt)}),I(Bt=>({...Bt,...vt}))}Oe.succeeded>0&&Oe.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Oe.succeeded}),"success"):Oe.succeeded>0&&Oe.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Oe.succeeded,failed:Oe.failed}),"success"):Oe.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Oe.results[0]?.error||"Unknown error"}),"error")},onError:Oe=>n(Oe.message,"error")}),Ae=lt({mutationFn:Oe=>se.batchGenerateStlThumbnails({file_ids:[Oe]}),onSuccess:Oe=>{if(e.invalidateQueries({queryKey:["library-files"]}),Oe.succeeded>0){const xt=Oe.results[0]?.file_id;xt&&I(vt=>({...vt,[xt]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Oe.results[0]?.error||"Unknown error"}),"error")},onError:Oe=>n(Oe.message,"error")}),Je=w.useCallback(Oe=>{const xt=Oe.toLowerCase();return xt.endsWith(".gcode")||xt.includes(".gcode.")},[]),Pe=w.useMemo(()=>z?z.filter(Oe=>f.includes(Oe.id)&&Je(Oe.filename)):[],[z,f,Je]),Ye=w.useCallback(Oe=>{p(xt=>xt.includes(Oe)?xt.filter(vt=>vt!==Oe):[...xt,Oe])},[]),Re=w.useCallback(()=>{xe.length>0&&p(xe.map(Oe=>Oe.id))},[xe]),Fe=w.useCallback(()=>{p([])},[]),We=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},pt=Oe=>{se.downloadLibraryFile(Oe).catch(xt=>{console.error("Library file download failed:",xt)})},At=()=>{T&&(T.type==="file"?Ze.mutate(T.id):T.type==="folder"?He.mutate(T.id):T.type==="bulk"&&we.mutate(f))},Rt=He.isPending||Ze.isPending||we.isPending,Wt=Oe=>{H(Oe),localStorage.setItem("library-view-mode",Oe)},Tt=ee||D;return a.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(Xl,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[a.jsx("button",{onClick:()=>Wt("grid"),className:`p-1.5 rounded transition-colors ${le==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:a.jsx(xv,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>Wt("list"),className:`p-1.5 rounded transition-colors ${le==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:a.jsx(rC,{className:"w-4 h-4"})})]}),a.jsxs(Me,{variant:"secondary",onClick:()=>Ve.mutate(),disabled:Ve.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[Ve.isPending?a.jsx(at,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(ed,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),a.jsxs(Me,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[a.jsx(Jhe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a.jsxs(Me,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(ia,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),ze&&G&&he&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[a.jsx(Cn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),a.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:Bg(G.disk_free_bytes),total:Bg(G.disk_total_bytes),threshold:he.library_disk_warning_gb})})]})]}),G&&a.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(eC,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),a.jsx("span",{className:"text-white font-medium",children:G.total_files})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Xl,{className:"w-4 h-4 text-blue-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),a.jsx("span",{className:"text-white font-medium",children:G.total_folders})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(qb,{className:"w-4 h-4 text-amber-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Bg(G.total_size_bytes)})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),a.jsx("span",{className:`font-medium ${ze?"text-amber-500":"text-white"}`,children:Bg(G.disk_free_bytes)})]})]}),a.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[a.jsx("div",{className:"lg:hidden",children:a.jsxs("select",{value:d??"",onChange:Oe=>h(Oe.target.value?parseInt(Oe.target.value,10):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[a.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),be&&(()=>{const Oe=(xt,vt=0)=>{const Bt=[];for(const Tn of xt)Bt.push({id:Tn.id,name:Tn.name,fileCount:Tn.file_count,depth:vt}),Tn.children.length>0&&Bt.push(...Oe(Tn.children,vt+1));return Bt};return Oe(be).map(xt=>a.jsxs("option",{value:xt.id,children:["│ ".repeat(xt.depth),"📂 ",xt.name," ",xt.fileCount>0?`(${xt.fileCount})`:""]},xt.id))})()]})}),a.jsxs("div",{ref:De,className:"hidden lg:flex flex-shrink-0 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden flex-col relative",style:{width:`${J}px`},children:[a.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${fe?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Oe=>{Oe.preventDefault(),me(!0)},onDoubleClick:()=>{Se(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:a.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${fe?"opacity-100":""}`,children:[a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),a.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),a.jsx("button",{onClick:()=>{const Oe=!X;te(Oe),localStorage.setItem("library-wrap-folders",String(Oe))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${X?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(X?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[a.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${d===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>h(null),children:[a.jsx(ff,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),be?.map(Oe=>a.jsx(Xae,{folder:Oe,selectedFolderId:d,onSelect:h,onDelete:xt=>k({type:"folder",id:xt}),onLink:M,onRename:xt=>V({type:"folder",id:xt.id,name:xt.name}),wrapNames:X,hasPermission:r,t},Oe.id))]})]}),a.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[z&&z.length>0&&a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[a.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[a.jsx(Or,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:de,onChange:Oe=>ce(Oe.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tC,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),a.jsxs("select",{value:Ne,onChange:Oe=>ie(Oe.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"all",children:t("fileManager.allTypes")}),ve.map(Oe=>a.jsx("option",{value:Oe,children:Oe.toUpperCase()},Oe))]})]}),o&&a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:Le,onChange:Oe=>$(Oe.target.value),list:"usernames-list",className:`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${Le?"pr-7":""}`,style:Le?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),Le&&a.jsx("button",{onClick:()=>$(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:a.jsx(Ft,{className:"w-3 h-3"})}),a.jsx("datalist",{id:"usernames-list",children:pe?.map(Oe=>a.jsx("option",{value:Oe.username},Oe.id))})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{value:W,onChange:Oe=>{const xt=Oe.target.value;ue(xt),localStorage.setItem("library-sort-field",xt)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"name",children:t("common.name")}),a.jsx("option",{value:"date",children:t("common.date")}),a.jsx("option",{value:"size",children:t("fileManager.size")}),a.jsx("option",{value:"type",children:t("common.type")}),a.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),a.jsx("button",{onClick:()=>oe(Oe=>{const xt=Oe==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",xt),xt}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(Z==="asc"?"fileManager.ascending":"fileManager.descending"),children:Z==="asc"?a.jsx(yde,{className:"w-4 h-4 text-white"}):a.jsx(dde,{className:"w-4 h-4 text-white"})})]}),(de||Ne!=="all"||Le)&&a.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:xe.length,total:z.length})})]}),xe.length>0&&a.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[f.length===xe.length&&f.length>0?a.jsxs(Me,{variant:"secondary",size:"sm",onClick:Fe,children:[a.jsx(gl,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):a.jsxs(Me,{variant:"secondary",size:"sm",onClick:Re,children:[a.jsx(ao,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),f.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:f.length})}),a.jsx("div",{className:"hidden sm:block flex-1"}),a.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Pe.length===1&&a.jsxs(Me,{variant:"primary",size:"sm",onClick:()=>U(Pe[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[a.jsx(jo,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Pe.length===1&&a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>B(Pe[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[a.jsx(Qn,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>y(!0),disabled:!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[a.jsx(sfe,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),a.jsxs(Me,{variant:"danger",size:"sm",onClick:()=>{f.length===1?k({type:"file",id:f[0]}):k({type:"bulk",id:0,count:f.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[a.jsx(en,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),a.jsxs(Me,{variant:"secondary",size:"sm",onClick:Fe,children:[a.jsx(Ft,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Tt?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(at,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):z?.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(ff,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(d!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(d!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),a.jsxs(Me,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(ar,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):xe.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(Or,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),a.jsx(Me,{variant:"secondary",onClick:()=>{ce(""),ie("all")},children:t("fileManager.clearFilters")})]}):le==="grid"?a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:xe.map(Oe=>a.jsx(ZZe,{file:Oe,isSelected:f.includes(Oe.id),isMobile:Q,t,onSelect:Ye,onDelete:xt=>k({type:"file",id:xt}),onDownload:pt,onAddToQueue:xt=>{const vt=z?.find(Bt=>Bt.id===xt);vt&&B(vt)},onPrint:E,onPreview3d:Y,onRename:xt=>V({type:"file",id:xt.id,name:xt.filename}),onGenerateThumbnail:xt=>Ae.mutate(xt.id),thumbnailVersion:q[Oe.id],hasPermission:r,canModify:s,authEnabled:o},Oe.id))})}):a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[a.jsx("div",{className:"w-6"}),a.jsx("div",{children:t("common.name")}),o&&a.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),a.jsx("div",{children:t("common.type")}),a.jsx("div",{children:t("fileManager.size")}),a.jsx("div",{children:t("fileManager.prints")}),a.jsx("div",{})]}),xe.map(Oe=>a.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${f.includes(Oe.id)?"bg-bambu-green/10":""}`,onClick:()=>Ye(Oe.id),children:[a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(Oe.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(Oe.id)&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsxs("div",{className:"relative group/thumb",children:[a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Oe.thumbnail_path?a.jsx("img",{src:`${se.getLibraryFileThumbnailUrl(Oe.id)}${q[Oe.id]?`?v=${q[Oe.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(ff,{className:"w-5 h-5 text-bambu-gray/50"})})}),Oe.thumbnail_path&&a.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:a.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:a.jsx("img",{src:`${se.getLibraryFileThumbnailUrl(Oe.id)}${q[Oe.id]?`?v=${q[Oe.id]}`:""}`,alt:Oe.filename,className:"w-full h-full object-contain"})})})]}),a.jsx("div",{className:"min-w-0",children:a.jsx("div",{className:"text-sm text-white truncate",children:Oe.print_name||Oe.filename})})]}),o&&a.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Oe.created_by_username?a.jsxs(a.Fragment,{children:[a.jsx(nd,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate",children:Oe.created_by_username})]}):"-"}),a.jsx("div",{children:a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Oe.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Oe.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Oe.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Oe.file_type.toUpperCase()})}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Bg(Oe.file_size)}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Oe.print_count>0?`${Oe.print_count}x`:"-"}),a.jsxs("div",{className:"flex items-center gap-1",onClick:xt=>xt.stopPropagation(),children:[fF(Oe.filename)&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>r("printers:control")&&E(Oe),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:a.jsx(Cr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{r("queue:create")&&B(Oe)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:a.jsx(Qn,{className:"w-4 h-4"})})]}),(Oe.file_type==="3mf"||Oe.file_type==="gcode"||Oe.file_type==="stl")&&a.jsx("button",{onClick:()=>r("library:read")&&Y(Oe),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:a.jsx(Qi,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>r("library:read")&&pt(Oe.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:a.jsx(di,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","update",Oe.created_by_id)&&V({type:"file",id:Oe.id,name:Oe.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Oe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Oe.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Oe.created_by_id),children:a.jsx($i,{className:"w-4 h-4"})}),Oe.file_type==="stl"&&a.jsx("button",{onClick:()=>s("library","update",Oe.created_by_id)&&Ae.mutate(Oe.id),className:`p-1.5 rounded transition-colors ${s("library","update",Oe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Oe.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:Ae.isPending||!s("library","update",Oe.created_by_id),children:a.jsx(ed,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","delete",Oe.created_by_id)&&k({type:"file",id:Oe.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Oe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","delete",Oe.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Oe.created_by_id),children:a.jsx(en,{className:"w-4 h-4"})})]})]},Oe.id))]})})]})]}),x&&a.jsx(WZe,{parentId:d,onClose:()=>v(!1),onSave:Oe=>_e.mutate(Oe),isLoading:_e.isPending,t}),b&&be&&a.jsx(XZe,{folders:be,selectedFiles:f,currentFolderId:d,onClose:()=>y(!1),onMove:Oe=>ye.mutate({fileIds:f,folderId:Oe}),isLoading:ye.isPending,t}),S&&a.jsx(QZe,{folderId:d,onClose:()=>N(!1),onUploadComplete:We,t}),A&&a.jsx(YZe,{folder:A,onClose:()=>M(null),onLink:Oe=>ke.mutate({id:A.id,data:Oe}),isLoading:ke.isPending,t}),T&&a.jsx(kn,{title:T.type==="folder"?t("fileManager.deleteFolder"):T.type==="bulk"?t("fileManager.deleteFilesCount",{count:T.count}):t("fileManager.deleteFile"),message:T.type==="folder"?t("fileManager.deleteFolderConfirm"):T.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:T.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Rt,loadingText:t("fileManager.deleting"),onConfirm:At,onCancel:()=>k(null)}),j&&a.jsx(Yu,{mode:"reprint",libraryFileId:j.id,archiveName:j.print_name||j.filename,onClose:()=>E(null),onSuccess:()=>{E(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),P&&a.jsx(Yu,{mode:"reprint",libraryFileId:P.id,archiveName:P.print_name||P.filename,onClose:()=>U(null),onSuccess:()=>{U(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),L&&a.jsx(Yu,{mode:"add-to-queue",libraryFileId:L.id,archiveName:L.print_name||L.filename,onClose:()=>B(null),onSuccess:()=>{B(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),K&&a.jsx(S4,{libraryFileId:K.id,title:K.print_name||K.filename,fileType:K.file_type,onClose:()=>Y(null)}),R&&a.jsx(KZe,{type:R.type,currentName:R.name,onClose:()=>V(null),onSave:Oe=>{R.type==="file"?Ue.mutate({id:R.id,filename:Oe}):je.mutate({id:R.id,name:Oe})},isLoading:Ue.isPending||je.isPending,t})]})}const qj=5,eJe=2e3,tJe=3e4,nJe=5e3;function rJe(){const{t}=Vt(),e=tn(),{showToast:n}=mn(),{hasPermission:r}=Ir(),{printerId:i}=Yk(),s=parseInt(i||"0",10),[o,l]=w.useState("stream"),[c,u]=w.useState(!1),[d,h]=w.useState(!1),[f,p]=w.useState(!0),[x,v]=w.useState(Date.now()),[b,y]=w.useState(!1),[S,N]=w.useState(!1),[A,M]=w.useState(0),[T,k]=w.useState(!1),[j,E]=w.useState(0),[P,U]=w.useState(1),[L,B]=w.useState({x:0,y:0}),[R,V]=w.useState(!1),[q,I]=w.useState({x:0,y:0}),[K,Y]=w.useState(null),[le,H]=w.useState(null),X=w.useRef(null),te=w.useRef(null),J=w.useRef(null),Se=w.useRef(null),fe=w.useRef(null),{data:me}=tt({queryKey:["printer",s],queryFn:()=>se.getPrinter(s),enabled:s>0}),{data:De}=tt({queryKey:["printerStatus",s],queryFn:()=>se.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),de=lt({mutationFn:ye=>se.setChamberLight(s,ye),onMutate:async ye=>{await e.cancelQueries({queryKey:["printerStatus",s]});const ke=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],Ue=>({...Ue,chamber_light:ye})),{previousStatus:ke}},onSuccess:(ye,ke)=>{n(`Chamber light ${ke?"on":"off"}`)},onError:(ye,ke,Ue)=>{Ue?.previousStatus&&e.setQueryData(["printerStatus",s],Ue.previousStatus),n(ye.message||t("printers.toast.failedToControlChamberLight"),"error")}}),ce=(De?.state==="RUNNING"||De?.state==="PAUSE"||De?.state==="PAUSED")&&(De?.printable_objects_count??0)>=2;w.useEffect(()=>(me&&(document.title=`${me.name} - Camera`),()=>{document.title="Bambuddy"}),[me]);const Ne=w.useRef(!1);w.useEffect(()=>{const ye=`/api/v1/printers/${s}/camera/stop`;Ne.current=!1;const ke=()=>{if(s>0&&!Ne.current){Ne.current=!0;const Ve={},Ae=rd();Ae&&(Ve.Authorization=`Bearer ${Ae}`),fetch(ye,{method:"POST",keepalive:!0,headers:Ve}).catch(()=>{})}},Ue=()=>{ke()};window.addEventListener("beforeunload",Ue);const je=X.current;return()=>{window.removeEventListener("beforeunload",Ue),je&&(je.src=""),ke()}},[s]),w.useEffect(()=>{if(f&&!b){const ke=setTimeout(()=>{p(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(ke)}},[o,f,x,b]),w.useEffect(()=>{const ye=()=>{const ke=!!document.fullscreenElement;N(ke),U(1),B({x:0,y:0}),o==="stream"&&!b&&(X.current&&(X.current.src=""),setTimeout(()=>{p(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",ye),()=>document.removeEventListener("fullscreenchange",ye)},[o,b]),w.useEffect(()=>{let ye;const ke=()=>{clearTimeout(ye),ye=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",ke),()=>{clearTimeout(ye),window.removeEventListener("resize",ke)}},[]),w.useEffect(()=>()=>{J.current&&clearTimeout(J.current),Se.current&&clearInterval(Se.current),fe.current&&clearInterval(fe.current)},[]);const ie=w.useCallback(()=>{if(A>=qj){k(!1),h(!0);return}const ye=Math.min(eJe*Math.pow(2,A),tJe);k(!0),E(Math.ceil(ye/1e3)),Se.current=setInterval(()=>{E(ke=>ke<=1?(Se.current&&clearInterval(Se.current),0):ke-1)},1e3),J.current=setTimeout(()=>{M(ke=>ke+1),k(!1),p(!0),h(!1),X.current&&(X.current.src=""),v(Date.now())},ye)},[A]);w.useEffect(()=>{if(o!=="stream"||f||T||b){fe.current&&(clearInterval(fe.current),fe.current=null);return}return fe.current=setInterval(async()=>{try{const ye=await se.getCameraStatus(s);(ye.stalled||!ye.active&&!d)&&(console.log(`Stream issue detected: stalled=${ye.stalled}, active=${ye.active}, reconnecting...`),fe.current&&(clearInterval(fe.current),fe.current=null),p(!1),ie())}catch{}},nJe),()=>{fe.current&&(clearInterval(fe.current),fe.current=null)}},[o,f,d,T,b,s,ie]);const Le=()=>{p(!1),o==="stream"&&A{if(p(!1),h(!1),M(0),k(!1),J.current&&clearTimeout(J.current),Se.current&&clearInterval(Se.current),X.current&&!localStorage.getItem("cameraWindowState")){const ye=X.current,ke=ye.naturalWidth,Ue=ye.naturalHeight;if(ke>0&&Ue>0){const Ae=window.outerWidth-window.innerWidth,Je=window.outerHeight-window.innerHeight,Pe=ke+16+Ae,Ye=Ue+45+16+Je;try{window.resizeTo(Pe,Ye)}catch{}}}},W=()=>{if(s>0){const ye={},ke=rd();ke&&(ye.Authorization=`Bearer ${ke}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:ye}).catch(()=>{})}},ue=ye=>{o===ye||b||(y(!0),p(!0),h(!1),M(0),k(!1),U(1),B({x:0,y:0}),J.current&&clearTimeout(J.current),Se.current&&clearInterval(Se.current),X.current&&(X.current.src=""),o==="stream"&&W(),setTimeout(()=>{l(ye),v(Date.now()),y(!1)},100))},Z=()=>{b||(y(!0),p(!0),h(!1),M(0),k(!1),J.current&&clearTimeout(J.current),Se.current&&clearInterval(Se.current),X.current&&(X.current.src=""),o==="stream"&&W(),setTimeout(()=>{v(Date.now()),y(!1)},100))},oe=()=>{te.current&&(document.fullscreenElement?document.exitFullscreen():te.current.requestFullscreen())},Q=()=>{U(ye=>Math.min(ye+.5,4))},he=()=>{U(ye=>{const ke=Math.max(ye-.5,1);return ke===1&&B({x:0,y:0}),ke})},be=ye=>{ye.preventDefault(),ye.deltaY<0?Q():he()},ee=ye=>{P>1&&(ye.preventDefault(),V(!0),I({x:ye.clientX-L.x,y:ye.clientY-L.y}))},z=w.useCallback(()=>{if(!te.current)return{x:300,y:200};const ye=te.current.getBoundingClientRect(),ke=ye.width*(P-1)/2,Ue=ye.height*(P-1)/2;return{x:Math.max(50,ke),y:Math.max(50,Ue)}},[P]),D=ye=>{if(R&&P>1){const ke=ye.clientX-q.x,Ue=ye.clientY-q.y,je=z();B({x:Math.max(-je.x,Math.min(je.x,ke)),y:Math.max(-je.y,Math.min(je.y,Ue))})}},G=()=>{V(!1)},pe=ye=>{if(ye.length<2)return 0;const ke=ye[0].clientX-ye[1].clientX,Ue=ye[0].clientY-ye[1].clientY;return Math.sqrt(ke*ke+Ue*Ue)},ve=ye=>ye.length<2?{x:ye[0].clientX,y:ye[0].clientY}:{x:(ye[0].clientX+ye[1].clientX)/2,y:(ye[0].clientY+ye[1].clientY)/2},xe=ye=>{ye.touches.length===2?(ye.preventDefault(),Y(pe(ye.touches)),H(ve(ye.touches))):ye.touches.length===1&&P>1&&(ye.preventDefault(),V(!0),I({x:ye.touches[0].clientX-L.x,y:ye.touches[0].clientY-L.y}))},ze=ye=>{if(ye.touches.length===2&&K!==null){ye.preventDefault();const ke=pe(ye.touches),Ue=ke/K;U(Ve=>{const Ae=Math.max(1,Math.min(4,Ve*Ue));return Ae===1&&B({x:0,y:0}),Ae}),Y(ke);const je=ve(ye.touches);if(le){const Ve=z();B(Ae=>({x:Math.max(-Ve.x,Math.min(Ve.x,Ae.x+(je.x-le.x))),y:Math.max(-Ve.y,Math.min(Ve.y,Ae.y+(je.y-le.y)))}))}H(je)}else if(ye.touches.length===1&&R&&P>1){ye.preventDefault();const ke=ye.touches[0].clientX-q.x,Ue=ye.touches[0].clientY-q.y,je=z();B({x:Math.max(-je.x,Math.min(je.x,ke)),y:Math.max(-je.y,Math.min(je.y,Ue))})}},_e=ye=>{ye.touches.length<2&&(Y(null),H(null)),ye.touches.length===0&&V(!1)},He=()=>{U(1),B({x:0,y:0})},Ze=b?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${x}`:`/api/v1/printers/${s}/camera/snapshot?t=${x}`,we=f||b||T;return s?a.jsxs("div",{ref:te,className:"min-h-screen bg-black flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[a.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(mb,{className:"w-4 h-4"}),me?.name||`Printer ${s}`]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[a.jsx("button",{onClick:()=>ue("stream"),disabled:we,className:`px-3 py-1 text-xs rounded transition-colors ${o==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),a.jsx("button",{onClick:()=>ue("snapshot"),disabled:we,className:`px-3 py-1 text-xs rounded transition-colors ${o==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),a.jsx("button",{onClick:()=>de.mutate(!De?.chamber_light),disabled:!De?.connected||de.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${De?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:a.jsx(bL,{on:De?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>u(!0),disabled:!ce||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${ce&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(ce?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:a.jsx(_C,{className:"w-4 h-4 text-bambu-gray"})}),a.jsx("button",{onClick:Z,disabled:we,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:a.jsx(kr,{className:`w-4 h-4 text-bambu-gray ${we?"animate-spin":""}`})}),a.jsx("button",{onClick:oe,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(S?"camera.exitFullscreen":"camera.fullscreen"),children:S?a.jsx(pX,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Kme,{className:"w-4 h-4 text-bambu-gray"})})]})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:be,onMouseMove:D,onMouseUp:G,onMouseLeave:G,onTouchStart:xe,onTouchMove:ze,onTouchEnd:_e,style:{touchAction:"none"},children:a.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(f||b)&&!T&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:a.jsxs("div",{className:"text-center",children:[a.jsx(kr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),T&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Df,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:j,attempt:A+1,max:qj})}),a.jsx("button",{onClick:Z,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),d&&!T&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Cn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),a.jsx("button",{onClick:Z,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),a.jsx("img",{ref:X,src:Ze,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${P}) translate(${L.x/P}px, ${L.y/P}px)`,cursor:P>1?R?"grabbing":"grab":"default"},onError:Ze?Le:void 0,onLoad:Ze?$:void 0,onMouseDown:ee,draggable:!1},x),a.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[a.jsx("button",{onClick:he,disabled:P<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:a.jsx(HF,{className:"w-4 h-4 text-white"})}),a.jsxs("button",{onClick:He,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(P*100),"%"]}),a.jsx("button",{onClick:Q,disabled:P>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:a.jsx(BF,{className:"w-4 h-4 text-white"})})]})]})}),a.jsx(xL,{printerId:s,isOpen:c,onClose:()=>u(!1)})]}):a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function iJe(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:r,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function aJe(t){const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function sJe(t,e){const n=new Date,r=new Date(n.getTime()+t*60*1e3),i=new Date;i.setHours(0,0,0,0);const s=new Date(r);s.setHours(0,0,0,0);const o=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return s.getTime()===i.getTime()?o:s.getTime()===i.getTime()+864e5?`${e("streamOverlay.tomorrow")} ${o}`:r.toLocaleDateString([],{weekday:"short"})+" "+o}function oJe(t,e){if(t.stg_cur_name)return t.stg_cur_name;switch(t.state){case"RUNNING":return e("streamOverlay.status.printing");case"PAUSE":return e("streamOverlay.status.paused");case"FINISH":return e("streamOverlay.status.finished");case"FAILED":return e("streamOverlay.status.failed");case"IDLE":return e("streamOverlay.status.idle");default:return t.state||e("streamOverlay.status.unknown")}}function lJe(t){switch(t){case"small":return{container:"p-3",text:"text-sm",textLarge:"text-lg",progressHeight:"h-2",icon:"w-3 h-3",gap:"gap-2",logoHeight:"h-12"};case"large":return{container:"p-6",text:"text-xl",textLarge:"text-3xl",progressHeight:"h-4",icon:"w-6 h-6",gap:"gap-4",logoHeight:"h-24"};default:return{container:"p-4",text:"text-base",textLarge:"text-xl",progressHeight:"h-3",icon:"w-4 h-4",gap:"gap-3",logoHeight:"h-16"}}}function cJe(){const{printerId:t}=Yk(),[e]=NF(),{t:n}=Vt(),r=tn(),i=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>iJe(e),[e]),c=lJe(l.size),{data:u}=tt({queryKey:["printer",i],queryFn:()=>se.getPrinter(i),enabled:i>0}),{data:d}=tt({queryKey:["printerStatus",i],queryFn:()=>se.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3});w.useEffect(()=>{if(!i)return;const b=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,y=new WebSocket(b);return y.onmessage=S=>{try{const N=JSON.parse(S.data);N.type==="printer_status"&&N.printer_id===i&&r.setQueryData(["printerStatus",i],N.status)}catch{}},y.onerror=()=>{},()=>{y.close()}},[i,r]),w.useEffect(()=>(document.title=u?`${u.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[u,n]);const h=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!d)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const f=d.state==="RUNNING"||d.state==="PAUSE",p=d.progress||0,x=`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`;return a.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&a.jsx("img",{src:x,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",onError:h},s),a.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:a.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),a.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:a.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&u&&a.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[a.jsx(Cr,{className:`${c.icon} text-white/70`}),a.jsx("span",{className:`${c.text} text-white font-medium`,children:u.name})]}),l.showFilename&&d.current_print&&a.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:d.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,"")}),l.showStatus&&a.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:oJe(d,n)}),l.showProgress&&f&&a.jsxs("div",{className:"mb-3",children:[a.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[a.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),a.jsxs("span",{className:"text-white font-bold",children:[Math.round(p),"%"]})]}),a.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:a.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${p}%`}})})]}),f&&(l.showLayers||l.showEta)&&a.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&d.layer_num!=null&&d.total_layers!=null&&d.total_layers>0&&a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(rs,{className:c.icon}),a.jsxs("span",{className:c.text,children:[a.jsx("span",{className:"text-white",children:d.layer_num}),a.jsx("span",{className:"mx-1",children:"/"}),a.jsx("span",{children:d.total_layers})]})]}),l.showEta&&d.remaining_time!=null&&d.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(Ou,{className:c.icon}),a.jsx("span",{className:`${c.text} text-white`,children:aJe(d.remaining_time*60)})]}),a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(Qn,{className:c.icon}),a.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",sJe(d.remaining_time,n)]})]})]})]}),!f&&a.jsx("div",{className:`${c.text} text-white/70 py-2`,children:d.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function uJe(){const{t}=Vt(),{id:e}=Yk(),{mode:n}=np(),{data:r,isLoading:i,error:s}=tt({queryKey:["external-link",e],queryFn:()=>se.getExternalLink(Number(e)),enabled:!!e});return i?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[a.jsx(Cn,{className:"w-12 h-12"}),a.jsx("p",{children:t("common.linkNotFound")})]}):a.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}const dK={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,weight_used:0,slicer_filament:"",note:""};function dJe(t){const e={};return t.slicer_filament||(e.slicer_filament="Slicer preset is required"),t.material||(e.material="Material is required"),{isValid:Object.keys(e).length===0,errors:e}}const hJe=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],mJe=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],y0=["Basic","Matte","Silk","Tough","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],Yae=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"}],fJe=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],hK=[...Yae,...fJe],Qae="bambuddy-recent-colors",pJe=8,gJe=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function Wk(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PCTG","PEEK","PEI"];let r="",i=-1;for(const c of n){const u=e.toUpperCase().indexOf(c.toUpperCase());if(u!==-1){r=c,i=u;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&r&&(o=e.substring(i+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of y0)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of y0){const u=new RegExp(`\\s+${c}$`,"i");if(u.test(s)){l=c,s=s.replace(u,"").trim();break}}return{brand:s,material:r,variant:l}}function bJe(t,e){const n=new Set(mJe);for(const r of t){const{brand:i}=Wk(r.name);i&&i.length>1&&n.add(i)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:i}=Wk(r.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((r,i)=>r.localeCompare(i))}function xJe(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const i=r.name.replace(/@.*$/,"").trim(),s=n.get(i);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(i,{code:o,name:i,displayName:i,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,i)=>r.displayName.localeCompare(i.displayName))}function yJe(t,e,n){if(t.length>0){const r=[],i=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=i.get(o);l?l.allCodes.push(s.setting_id):i.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(i.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=xJe(n);if(r.length>0)return r}return gJe}function vJe(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(i=>i.code.toLowerCase()===r||i.allCodes.some(s=>s.toLowerCase()===r))}return n}function wJe(){try{const t=localStorage.getItem(Qae);if(t)return JSON.parse(t)}catch{}return[]}function _Je(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,pJe);try{localStorage.setItem(Qae,JSON.stringify(r))}catch{}return r}function Wj(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=Wk(r);return!(!(i.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(i.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(i.brand.toLowerCase()))||e.subtype&&!(i.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(i.variant.toLowerCase())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function SJe({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c}){const{t:u}=Vt(),[d,h]=w.useState(!1),[f,p]=w.useState(!1),[x,v]=w.useState(!1),[b,y]=w.useState(""),[S,N]=w.useState(""),A=w.useRef(null),M=w.useRef(null),T=w.useRef(null);w.useEffect(()=>{const U=L=>{A.current&&!A.current.contains(L.target)&&h(!1),M.current&&!M.current.contains(L.target)&&p(!1),T.current&&!T.current.contains(L.target)&&v(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[]);const k=w.useMemo(()=>{if(!i)return l;const U=i.toLowerCase();return l.filter(L=>L.displayName.toLowerCase().includes(U)||L.code.toLowerCase().includes(U))},[l,i]),j=w.useMemo(()=>{if(!b)return c;const U=b.toLowerCase();return c.filter(L=>L.toLowerCase().includes(U))},[c,b]),E=w.useMemo(()=>{if(!S)return y0;const U=S.toLowerCase();return y0.filter(L=>L.toLowerCase().includes(U))},[S]),P=U=>{e("slicer_filament",U.code),s(U.displayName),h(!1);const L=Wk(U.name);L.material&&e("material",L.material),L.brand&&e("brand",L.brand),L.variant&&e("subtype",L.variant)};return a.jsxs("div",{className:"space-y-4",children:[a.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-3 h-3 animate-spin"})," ",u("inventory.loadingPresets")]}):n?a.jsxs(a.Fragment,{children:[a.jsx(Gb,{className:"w-3 h-3 text-bambu-green"})," ",u("inventory.cloudConnected")]}):a.jsxs(a.Fragment,{children:[a.jsx(uhe,{className:"w-3 h-3"})," ",u("inventory.cloudNotConnected")]})}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[u("inventory.slicerPreset")," *"]}),a.jsxs("div",{className:"relative",ref:A,children:[a.jsx(Or,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:u("inventory.searchPresets"),value:i,onChange:U=>{s(U.target.value),h(!0)},onFocus:()=>{h(!0),s("")}}),d&&a.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:k.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:u("inventory.noPresetsFound")}):k.map(U=>a.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${o?.code===U.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>P(U),children:[a.jsx("span",{className:"truncate",children:U.displayName}),a.jsx("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:U.code})]},U.code))})]}),o&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[u("inventory.selectedPreset"),": ",a.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[u("inventory.material")," *"]}),a.jsxs("select",{value:t.material,onChange:U=>e("material",U.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",children:[a.jsx("option",{value:"",children:u("inventory.selectMaterial")}),hJe.map(U=>a.jsx("option",{value:U,children:U},U))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:u("inventory.brand")}),a.jsxs("div",{className:"relative",ref:M,children:[a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:u("inventory.searchBrand"),value:f?b:t.brand,onChange:U=>{y(U.target.value),p(!0)},onFocus:()=>{p(!0),y("")}}),a.jsx(nr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),f&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[j.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:u("inventory.noResults")}):j.map(U=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===U?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",U),p(!1),y("")},children:U},U)),b&&!j.includes(b)&&a.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",b),p(!1),y("")},children:u("inventory.useCustomBrand",{brand:b})})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:u("inventory.subtype")}),a.jsxs("div",{className:"relative",ref:T,children:[a.jsx("input",{type:"text",value:x?S:t.subtype,onChange:U=>{N(U.target.value),v(!0)},onFocus:()=>{v(!0),N("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),a.jsx(nr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),x&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[E.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:u("inventory.noResults")}):E.map(U=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===U?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",U),v(!1),N("")},children:U},U)),S&&!y0.some(U=>U.toLowerCase()===S.toLowerCase().trim())&&a.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",S),v(!1),N("")},children:u("inventory.useCustomBrand",{brand:S})})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:u("inventory.labelWeight")}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"number",value:t.label_weight,onChange:U=>e("label_weight",parseInt(U.target.value)||0),className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]})]})}function NJe({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:i}){const{t:s}=Vt(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=t.rgba.replace("#","").substring(0,6),h=y=>d.toUpperCase()===y.toUpperCase(),f=(y,S)=>{e("rgba",y.toUpperCase()+"FF"),e("color_name",S),r({name:S,hex:y})},p=w.useMemo(()=>{if(i.length===0)return[];const y=t.brand?.trim(),S=t.material?.toLowerCase().trim(),N=t.subtype?.toLowerCase().trim();if(!y&&!S)return[];const A=y?y.toLowerCase().split(/[\s\-_]+/).filter(k=>k.length>=2):[],M=k=>{if(A.length===0)return!0;const j=k.toLowerCase();return A.some(E=>j.includes(E))},T=S&&N?`${S} ${N}`:"";if(T){const k=i.filter(E=>M(E.manufacturer)&&E.material?.toLowerCase()===T);if(k.length>0)return k.map(E=>({name:E.color_name,hex:E.hex_color.replace("#","").substring(0,6)}));const j=T.replace(/\+$/,"");if(j!==T){const E=i.filter(P=>M(P.manufacturer)&&P.material?.toLowerCase()===j);if(E.length>0)return E.map(P=>({name:P.color_name,hex:P.hex_color.replace("#","").substring(0,6)}))}}if(S){const k=i.filter(j=>M(j.manufacturer)&&(!j.material||j.material.toLowerCase().startsWith(S)));if(k.length>0)return k.map(j=>({name:j.color_name,hex:j.hex_color.replace("#","").substring(0,6)}))}return[]},[i,t.brand,t.material,t.subtype]),x=p.length>0,v=w.useMemo(()=>{if(!c)return p;const y=c.toLowerCase();return p.filter(S=>S.name.toLowerCase().includes(y))},[p,c]),b=w.useMemo(()=>c?hK.filter(y=>y.name.toLowerCase().includes(c.toLowerCase())):o?hK:Yae,[c,o]);return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${d}`}}),n.length>0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[a.jsx(Qn,{className:"w-3 h-3"}),a.jsx("span",{children:s("inventory.recentColors")})]}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(y=>a.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name},y.hex))})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Or,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:y=>u(y.target.value)})]}),x?a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[v.map(y=>a.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 relative group ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name,children:a.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10 shadow-lg text-white",children:y.name})},`${y.hex}-${y.name}`)),v.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&a.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?a.jsxs(a.Fragment,{children:[s("inventory.showLess")," ",a.jsx(ql,{className:"w-3 h-3"})]}):a.jsxs(a.Fragment,{children:[s("inventory.showAll")," ",a.jsx(nr,{className:"w-3 h-3"})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(y=>a.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 relative group ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name,children:a.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10 shadow-lg text-white",children:y.name})},y.hex)),b.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:y=>e("color_name",y.target.value)})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),a.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:d.toUpperCase(),onChange:y=>{const S=y.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");S.length<=8&&e("rgba",S.toUpperCase()+(S.length<=6?"FF":""))}})]}),a.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${d}`,onChange:y=>{const S=y.target.value.replace("#","").toUpperCase();e("rgba",S+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function kJe({catalog:t,value:e,onChange:n}){const{t:r}=Vt(),[i,s]=w.useState(!1),[o,l]=w.useState(""),[c,u]=w.useState(null),d=w.useRef(null),h=w.useRef(null);w.useEffect(()=>{const x=v=>{d.current&&!d.current.contains(v.target)&&s(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[]);const f=w.useMemo(()=>{if(!o)return t;const x=o.toLowerCase();return t.filter(v=>v.name.toLowerCase().includes(x)||v.weight.toString().includes(x))},[t,o]),p=w.useMemo(()=>{if(i)return o;if(c){const v=t.find(b=>b.id===c);if(v)return v.name}const x=t.find(v=>v.weight===e);return x?x.name:""},[i,o,c,t,e]);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Efe,{className:"w-3.5 h-3.5 text-bambu-gray"}),r("inventory.coreWeight")]})}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsxs("div",{className:"flex-1 min-w-0 relative",ref:d,children:[a.jsx("input",{ref:h,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:r("inventory.searchSpoolWeight"),value:p,onFocus:()=>{s(!0),l("")},onChange:x=>{l(x.target.value),s(!0)}}),i&&a.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:f.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:r("inventory.noResults")}):f.map(x=>a.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(c?x.id===c:x.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{u(x.id),n(x.weight),s(!1),l("")},children:[a.jsx("span",{className:"truncate",children:x.name}),a.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[x.weight,"g"]})]},x.id))})]}),a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[a.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:x=>{const v=parseInt(x.target.value);!isNaN(v)&&v>=0&&n(v)}}),a.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function CJe({formData:t,updateField:e,spoolCatalog:n}){const{t:r}=Vt(),{showToast:i}=mn(),[s,o]=w.useState(""),[l,c]=w.useState(!1),u=Math.max(0,t.label_weight-t.weight_used),d=t.core_weight+u;return w.useEffect(()=>{l||o(String(d))},[l,d]),a.jsxs("div",{className:"space-y-4",children:[a.jsx(kJe,{catalog:n,value:t.core_weight,onChange:h=>e("core_weight",h)}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r("inventory.currentWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:u,min:0,max:t.label_weight,onChange:h=>{const f=parseInt(h.target.value)||0;e("weight_used",Math.max(0,t.label_weight-f))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r("inventory.measuredWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:s,min:0,onFocus:()=>c(!0),onChange:h=>{o(h.target.value)},onBlur:()=>{c(!1);const h=s.trim(),f=Number(h),p=t.core_weight,x=t.core_weight+t.label_weight;if(!h||!Number.isFinite(f)||fx){i(r("inventory.measuredWeightError",{min:p,max:x}),"error"),o(String(d));return}const v=Math.round(f),b=Math.max(0,Math.min(t.label_weight,v-t.core_weight));e("weight_used",Math.max(0,t.label_weight-b)),o(String(v))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r("inventory.note")}),a.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:r("inventory.notePlaceholder"),value:t.note,onChange:h=>e("note",h.target.value)})]})]})}function MJe({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=Vt(),l=f=>{s(p=>{const x=new Set(p);return x.has(f)?x.delete(f):x.add(f),x})},c=(f,p,x)=>{const v=`${f}:${p}:${x??"null"}`,b=`${f}:${x??"null"}`;r(y=>{const S=new Set(y);if(S.has(v))S.delete(v);else{for(const N of Array.from(S)){const A=N.split(":");`${A[0]}:${A[2]}`===b&&S.delete(N)}S.add(v)}return S})},u=()=>{const f=new Set;for(const{printer:p,calibrations:x}of e){if(!p.connected)continue;const v=x.filter(y=>Wj(y,t)),b=new Map;for(const y of v){const S=`${y.extruder_id??"null"}`;b.has(S)||b.set(S,[]),b.get(S).push(y)}for(const[y,S]of b)if(S.length>0){const A=[...S].sort((M,T)=>T.k_value-M.k_value)[0];f.add(`${p.id}:${A.cali_idx}:${y}`)}}r(f)};if(!t.material)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const d=e.reduce((f,{printer:p,calibrations:x})=>p.connected?f+x.filter(v=>Wj(v,t)).length:f,0),h=(f,p)=>{const x=`${f.id}:${p.cali_idx}:${p.extruder_id??"null"}`,v=n.has(x);return a.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[a.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(f.id),p.cali_idx,p.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:p.name||p.filament_id})}),a.jsx("div",{className:"flex items-center gap-2 shrink-0",children:a.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",p.k_value.toFixed(3)]})})]},`${p.cali_idx}-${p.extruder_id}`)};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),d>0&&a.jsxs("button",{type:"button",onClick:u,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[a.jsx(pb,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",d,")"]})]}),a.jsx("div",{className:"space-y-3",children:e.map(({printer:f,calibrations:p})=>{const x=i.has(String(f.id)),v=p.filter(A=>Wj(A,t)),b=v.length,y=v.some(A=>A.extruder_id!==void 0&&A.extruder_id!==null&&A.extruder_id>0),S=v.filter(A=>A.extruder_id===1),N=v.filter(A=>A.extruder_id===0||A.extruder_id===void 0||A.extruder_id===null);return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("button",{type:"button",onClick:()=>l(String(f.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[x?a.jsx(nr,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(fa,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"font-medium text-white",children:f.name}),b>0?a.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[b," ",o(b!==1?"inventory.matches":"inventory.match")]}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),a.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${f.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:f.connected?o("inventory.connected"):o("inventory.offline")})]}),x&&a.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:f.connected?b===0?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):y?a.jsxs(a.Fragment,{children:[S.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),a.jsx("div",{className:"space-y-2",children:S.map(A=>h(f,A))})]}),N.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),a.jsx("div",{className:"space-y-2",children:N.map(A=>h(f,A))})]})]}):a.jsx("div",{className:"space-y-2",children:v.map(A=>h(f,A))}):a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},f.id)})}),n.size>0&&a.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function AJe(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const TJe={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function EJe({spoolId:t}){const{t:e}=Vt(),n=tn(),{showToast:r}=mn(),{data:i,isLoading:s}=tt({queryKey:["spool-usage",t],queryFn:()=>se.getSpoolUsageHistory(t)}),o=lt({mutationFn:()=>se.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(at,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?a.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[a.jsx(Qn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),a.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[a.jsx(en,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>a.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-bambu-gray",children:AJe(l.created_at)}),l.print_name&&a.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[a.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),a.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),a.jsx("span",{className:TJe[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function PJe({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[]}){const{t:i}=Vt(),s=tn(),{showToast:o}=mn(),l=!!n,[c,u]=w.useState(dK),[d,h]=w.useState({}),[f,p]=w.useState("filament"),[x,v]=w.useState(!1),[b,y]=w.useState(!1),[S,N]=w.useState(!1),[A,M]=w.useState([]),[T,k]=w.useState(""),[j,E]=w.useState([]),[P,U]=w.useState([]),[L,B]=w.useState([]),[R,V]=w.useState([]),[q,I]=w.useState([]),[K,Y]=w.useState(new Set),[le,H]=w.useState(new Set),X=r.length>0?r:q,te=w.useMemo(()=>K.size,[K]);w.useEffect(()=>{V(wJe())},[]),w.useEffect(()=>{t&&((async()=>{N(!0);try{const W=await se.getCloudStatus();if(y(W.is_authenticated),W.is_authenticated){const ue=await se.getFilamentPresets();M(ue)}}catch(W){console.error("Failed to fetch cloud presets:",W),y(!1)}finally{N(!1)}})(),se.getSpoolCatalog().then(E).catch(console.error),se.getColorCatalog().then(B).catch(console.error),se.getLocalPresets().then(W=>U(W.filament)).catch(console.error),r.length===0&&(async()=>{try{const W=await se.getPrinters(),ue=await Promise.all(W.map(oe=>se.getPrinterStatus(oe.id).catch(()=>null))),Z=[];for(let oe=0;oe({cali_idx:D.slot_id,filament_id:D.filament_id,setting_id:D.setting_id||"",name:D.name,k_value:parseFloat(D.k_value)||0,n_coef:parseFloat(D.n_coef)||0,extruder_id:D.extruder_id,nozzle_diameter:D.nozzle_diameter}))}catch{}Z.push({printer:{...Q,connected:be},calibrations:ee})}I(Z)}catch(W){console.error("Failed to fetch printer calibrations:",W)}})())},[t,r.length]);const J=w.useMemo(()=>yJe(A,new Set,P),[A,P]),Se=w.useMemo(()=>bJe(A,P),[A,P]),fe=w.useMemo(()=>vJe(c.slicer_filament,J),[c.slicer_filament,J]);w.useEffect(()=>{if(t){if(n)if(u({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||""}),k(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const $=new Set;for(const W of n.k_profiles)W.cali_idx!==null&&W.cali_idx!==void 0&&$.add(`${W.printer_id}:${W.cali_idx}:${W.extruder??"null"}`);Y($)}else Y(new Set);else u(dK),k(""),Y(new Set);h({}),p("filament"),v(!1)}},[t,n]),w.useEffect(()=>{t&&X.length>0&&H(new Set(X.map($=>String($.printer.id))))},[t,X]);const me=($,W)=>{u(ue=>({...ue,[$]:W})),$==="weight_used"&&v(!0),d[$]&&h(ue=>({...ue,[$]:void 0}))},De=$=>{V(W=>_Je($,W))},de=lt({mutationFn:$=>se.createSpool($),onSuccess:async $=>{K.size>0&&$?.id&&await Ne($.id),await s.invalidateQueries({queryKey:["inventory-spools"]}),o(i("inventory.spoolCreated"),"success"),e()},onError:$=>{o($.message,"error")}}),ce=lt({mutationFn:$=>se.updateSpool(n.id,$),onSuccess:async()=>{n?.id&&await Ne(n.id),await s.invalidateQueries({queryKey:["inventory-spools"]}),o(i("inventory.spoolUpdated"),"success"),e()},onError:$=>{o($.message,"error")}}),Ne=async $=>{if(K.size===0){try{await se.saveSpoolKProfiles($,[])}catch{}return}const W=[];for(const ue of K){const[Z,oe,Q]=ue.split(":"),he=parseInt(Z),be=parseInt(oe),ee=Q==="null"?0:parseInt(Q),z=X.find(D=>D.printer.id===he);if(z){const D=z.calibrations.find(G=>G.cali_idx===be);D&&W.push({printer_id:he,extruder:ee,nozzle_diameter:D.nozzle_diameter||"0.4",k_value:D.k_value,name:D.name||null,cali_idx:D.cali_idx,setting_id:D.setting_id||null})}}if(W.length>0)try{await se.saveSpoolKProfiles($,W)}catch(ue){console.error("Failed to save K-profiles:",ue)}};if(w.useEffect(()=>{if(!t)return;const $=W=>{W.key==="Escape"&&e()};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[t,e]),!t)return null;const ie=()=>{const $=dJe(c);if(!$.isValid){h($.errors),($.errors.slicer_filament||$.errors.material)&&p("filament");return}const W=fe?.displayName||T||null,ue={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,slicer_filament:c.slicer_filament||null,slicer_filament_name:W,nozzle_temp_min:null,nozzle_temp_max:null,note:c.note||null};(!l||x)&&(ue.weight_used=c.weight_used),l?ce.mutate(ue):de.mutate(ue)},Le=de.isPending||ce.isPending;return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.jsxs("div",{className:"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:i(l?"inventory.editSpool":"inventory.addSpool")}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Ft,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("button",{onClick:()=>p("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${f==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(iC,{className:"w-4 h-4"}),i("inventory.filamentInfoTab")]}),a.jsxs("button",{onClick:()=>p("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${f==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(_de,{className:"w-4 h-4"}),i("inventory.paProfileTab"),te>0&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:te})]})]}),a.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:f==="filament"?a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:i("inventory.filamentInfo")}),a.jsx(SJe,{formData:c,updateField:me,cloudAuthenticated:b,loadingCloudPresets:S,presetInputValue:T,setPresetInputValue:k,selectedPresetOption:fe,filamentOptions:J,availableBrands:Se}),d.slicer_filament&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:d.slicer_filament}),d.material&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:d.material})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:i("inventory.color")}),a.jsx(NJe,{formData:c,updateField:me,recentColors:R,onColorUsed:De,catalogColors:L})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:i("inventory.additional")}),a.jsx(CJe,{formData:c,updateField:me,spoolCatalog:j})]}),l&&n&&a.jsx("div",{children:a.jsx(EJe,{spoolId:n.id})})]}):a.jsx(MJe,{formData:c,updateField:me,printersWithCalibrations:X,selectedProfiles:K,setSelectedProfiles:Y,expandedPrinters:le,setExpandedPrinters:H})}),a.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx(Me,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Me,{onClick:ie,disabled:Le,children:Le?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),i("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(bs,{className:"w-4 h-4"}),i(l?"common.save":"inventory.addSpool")]})})]})]})]})}function jJe({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:i}){const{t:s}=Vt(),[o,l]=w.useState(n),[c,u]=w.useState(null),d=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(A=>({...A})))},[t,n]),w.useEffect(()=>{if(!t)return;const A=M=>{M.key==="Escape"&&e()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[t,e]),!t)return null;const h=A=>{l(M=>M.map((T,k)=>k===A?{...T,visible:!T.visible}:T))},f=(A,M)=>{M<0||M>=o.length||l(T=>{const k=[...T],[j]=k.splice(A,1);return k.splice(M,0,j),k})},p=(A,M)=>{d.current=M,u(M),A.dataTransfer.effectAllowed="move"},x=(A,M)=>{A.preventDefault(),A.dataTransfer.dropEffect="move";const T=d.current;T!==null&&T!==M&&(f(T,M),d.current=M,u(M))},v=A=>{A.preventDefault()},b=()=>{d.current=null,u(null)},y=()=>{l(r.map(A=>({...A})))},S=()=>{i(o),e()},N=o.filter(A=>A.visible).length;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsx(_t,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:A=>A.stopPropagation(),children:a.jsxs(Nt,{className:"p-6 flex flex-col min-h-0",children:[a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),a.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),a.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),a.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((A,M)=>a.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===M?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${A.visible?"":"opacity-50"}`,draggable:!0,onDragStart:T=>p(T,M),onDragOver:T=>x(T,M),onDrop:v,onDragEnd:b,children:[a.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:a.jsx(Ph,{className:"w-4 h-4"})}),a.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:A.label}),a.jsxs("div",{className:"flex items-center gap-0.5",children:[a.jsx("button",{onClick:()=>f(M,M-1),disabled:M===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:a.jsx(ql,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>f(M,M+1),disabled:M===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:a.jsx(nr,{className:"w-4 h-4"})})]}),a.jsx("button",{onClick:()=>h(M),className:`p-1.5 rounded transition-colors ${A.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:A.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:A.visible?a.jsx(Kl,{className:"w-4 h-4"}):a.jsx(gv,{className:"w-4 h-4"})})]},A.id))}),a.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs(Me,{variant:"secondary",onClick:y,className:"mr-auto",children:[a.jsx(Do,{className:"w-4 h-4"}),s("inventory.reset")]}),a.jsx(Me,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),a.jsx(Me,{onClick:S,children:s("inventory.applyChanges")})]})]})})})}const Zae="bambuddy-inventory-columns",S1=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"remaining",label:"Remaining",visible:!0}];function DJe(){try{const t=localStorage.getItem(Zae);if(t){const e=JSON.parse(t),n=new Set(S1.map(o=>o.id)),r=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=S1.filter(o=>!r.has(o.id));return[...i,...s]}}catch{}return S1.map(t=>({...t}))}function RJe(t){try{localStorage.setItem(Zae,JSON.stringify(t))}catch{}}function Fu(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const FJe={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function Kj(t){return t?new Date(t).toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"}):"-"}const LJe={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",remaining:t=>t("inventory.remaining")},OJe={id:({spool:t})=>a.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:Kj(t.created_at)}),encode_time:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:Kj(t.encode_time)}),last_used_time:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?Kj(t.last_used):"Never"}),rgba:({spool:t})=>a.jsx("div",{className:"flex items-center justify-center",children:a.jsx("span",{className:"w-5 h-5 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:pne(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,i=String.fromCharCode(65+n.ams_id),s=n.tray_id+1;return a.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[r," ",i,s]})},label_weight:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:Fu(t.label_weight)}),net:({remaining:t})=>a.jsx("span",{className:"text-sm text-white",children:Fu(t)}),gross:({spool:t,remaining:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:Fu(e+t.core_weight)}),added_full:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?Fu(t.weight_used):"-"}),printed_total:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?a.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),remaining:({remaining:t,pct:e})=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),a.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]})},Xj={id:t=>t.id,added_time:t=>t.created_at||"",encode_time:t=>t.encode_time||"",last_used_time:t=>t.last_used||"",material:t=>(t.material||"").toLowerCase(),subtype:t=>(t.subtype||"").toLowerCase(),color_name:t=>(t.color_name||"").toLowerCase(),brand:t=>(t.brand||"").toLowerCase(),slicer_filament:t=>(t.slicer_filament_name||t.slicer_filament||"").toLowerCase(),location:(t,e)=>{const n=e[t.id];return n?`${n.printer_name||""} ${String.fromCharCode(65+n.ams_id)}${n.tray_id+1}`:""},label_weight:t=>t.label_weight,net:t=>Math.max(0,t.label_weight-t.weight_used),gross:t=>Math.max(0,t.label_weight-t.weight_used)+t.core_weight,used:t=>t.weight_used,remaining:t=>t.label_weight>0?Math.max(0,t.label_weight-t.weight_used)/t.label_weight:0,note:t=>(t.note||"").toLowerCase(),data_origin:t=>(t.data_origin||"").toLowerCase(),tag_type:t=>(t.tag_type||"").toLowerCase()},pF="bambuddy-inventory-sort";function IJe(){try{const t=localStorage.getItem(pF);if(t)return JSON.parse(t)}catch{}return null}function zJe(t){try{t?localStorage.setItem(pF,JSON.stringify(t)):localStorage.removeItem(pF)}catch{}}function UJe(){const{t}=Vt(),e=tn(),{showToast:n}=mn(),[r,i]=w.useState(null),[s,o]=w.useState(null),[l,c]=w.useState("active"),[u,d]=w.useState("all"),[h,f]=w.useState(""),[p,x]=w.useState(""),[v,b]=w.useState(""),[y,S]=w.useState("table"),[N,A]=w.useState(IJe),[M,T]=w.useState(DJe),[k,j]=w.useState(!1),[E,P]=w.useState(0),[U,L]=w.useState(()=>{try{const Q=localStorage.getItem("bambuddy-inventory-pageSize");if(Q){const he=Number(Q);if([15,30,50,100,-1].includes(he))return he}}catch{}return 15}),{data:B,isLoading:R}=tt({queryKey:["inventory-spools"],queryFn:()=>se.getSpools(!0),refetchInterval:3e4}),{data:V}=tt({queryKey:["spool-assignments"],queryFn:()=>se.getAssignments(),refetchInterval:3e4}),q=lt({mutationFn:Q=>se.deleteSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolDeleted"),"success")}}),I=lt({mutationFn:Q=>se.archiveSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolArchived"),"success")}}),K=lt({mutationFn:Q=>se.restoreSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolRestored"),"success")}}),Y=w.useMemo(()=>{if(!B)return null;let Q=0,he=0,be=0,ee=0;const z={};for(const D of B){if(D.archived_at)continue;ee++;const G=Math.max(0,D.label_weight-D.weight_used);Q+=G,he+=D.weight_used,(D.label_weight>0?G/D.label_weight*100:0)<20&&be++;const ve=D.material||"Unknown";z[ve]||(z[ve]={count:0,weight:0}),z[ve].count++,z[ve].weight+=G}return{totalWeight:Q,totalConsumed:he,lowStock:be,byMaterial:z,totalSpools:ee}},[B]),le=V?.length??0,H=w.useMemo(()=>{const Q={};for(const he of V||[])Q[he.spool_id]=he;return Q},[V]),X=w.useMemo(()=>Y?Object.entries(Y.byMaterial).sort((Q,he)=>he[1].weight-Q[1].weight).slice(0,4):[],[Y]),te=w.useMemo(()=>{let Q=B||[];if(l==="active"?Q=Q.filter(he=>!he.archived_at):Q=Q.filter(he=>!!he.archived_at),u==="used"?Q=Q.filter(he=>he.weight_used>0):u==="new"&&(Q=Q.filter(he=>he.weight_used===0)),h&&(Q=Q.filter(he=>he.material===h)),p&&(Q=Q.filter(he=>he.brand===p)),v){const he=v.toLowerCase();Q=Q.filter(be=>be.brand?.toLowerCase().includes(he)||be.material.toLowerCase().includes(he)||be.color_name?.toLowerCase().includes(he)||be.subtype?.toLowerCase().includes(he)||be.note?.toLowerCase().includes(he)||be.slicer_filament_name?.toLowerCase().includes(he))}return Q},[B,l,u,h,p,v]),J=()=>P(0),Se=[...new Set(B?.map(Q=>Q.material)||[])].sort(),fe=[...new Set(B?.map(Q=>Q.brand).filter(Boolean)||[])].sort(),me=l!=="active"||u!=="all"||!!h||!!p||!!v,De=Q=>{T(Q),RJe(Q)},de=w.useMemo(()=>M.filter(Q=>Q.visible).map(Q=>Q.id),[M]),ce=Q=>{Xj[Q]&&(A(he=>{let be;return he?.column===Q?be=he.direction==="asc"?{column:Q,direction:"desc"}:null:be={column:Q,direction:"asc"},zJe(be),be}),J())},Ne=w.useMemo(()=>{if(!N)return te;const Q=Xj[N.column];return Q?[...te].sort((be,ee)=>{const z=Q(be,H),D=Q(ee,H);return zD?N.direction==="asc"?1:-1:0}):te},[te,N,H]),ie=U===-1,Le=ie?Ne.length||1:U,$=Math.max(1,Math.ceil(Ne.length/Le)),W=ie?0:Math.min(E,$-1),ue=ie?Ne:Ne.slice(W*Le,(W+1)*Le),Z=Q=>{L(Q),P(0);try{localStorage.setItem("bambuddy-inventory-pageSize",String(Q))}catch{}},oe=()=>{c("active"),d("all"),f(""),x(""),b(""),J()};return a.jsxs("div",{className:"p-4 md:p-6 space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(ma,{className:"w-6 h-6 text-bambu-green"}),a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("inventory.title")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-9",children:(t("inventory.noSpools").split(".")[0],"")})]}),a.jsxs(Me,{onClick:()=>i({spool:null}),children:[a.jsx(ar,{className:"w-4 h-4"}),t("inventory.addSpool")]})]}),Y&&!R&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3",children:[a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(ma,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalInventory")})]}),a.jsx("div",{className:"text-xl font-bold text-white",children:Fu(Y.totalWeight,!0)}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[Y.totalSpools," ",Y.totalSpools!==1?t("inventory.spools"):t("inventory.spool")]})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(zF,{className:"w-4 h-4 text-blue-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalConsumed")})]}),a.jsx("div",{className:"text-xl font-bold text-white",children:Fu(Y.totalConsumed,!0)}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.sinceTracking")})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(rs,{className:"w-4 h-4 text-green-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.byMaterial")})]}),a.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:X.map(([Q,he])=>a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${FJe[Q]||"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Q," ",a.jsx("span",{className:"opacity-70",children:Fu(he.weight,!0)})]},Q))})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(Cr,{className:"w-4 h-4 text-purple-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.inPrinter")})]}),a.jsx("div",{className:"text-xl font-bold text-white",children:le}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.loadedInAms")})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(Cn,{className:"w-4 h-4 text-yellow-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.lowStock")})]}),a.jsx("div",{className:`text-xl font-bold ${Y.lowStock>0?"text-yellow-400":"text-white"}`,children:Y.lowStock}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.lowStockThreshold")})]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between",children:[a.jsxs("div",{className:"relative flex-1 max-w-md",children:[a.jsx(Or,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),a.jsx("input",{type:"text",value:v,onChange:Q=>{b(Q.target.value),J()},placeholder:t("inventory.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),v&&a.jsx("button",{onClick:()=>{b(""),J()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Ft,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[y==="table"&&a.jsxs("button",{onClick:()=>j(!0),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-bambu-gray border border-bambu-dark-tertiary rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t("inventory.configureColumns"),children:[a.jsx(vhe,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.columns")})]}),a.jsxs("div",{className:"flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>S("table"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${y==="table"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(npe,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.table")})]}),a.jsxs("button",{onClick:()=>S("cards"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${y==="cards"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(xv,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.cards")})]})]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsxs("button",{onClick:()=>{c("active"),J()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="active"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(ma,{className:"w-3.5 h-3.5"}),t("inventory.active")]}),a.jsxs("button",{onClick:()=>{c("archived"),J()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="archived"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(Rs,{className:"w-3.5 h-3.5"}),t("inventory.archived")]})]}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),a.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsx("button",{onClick:()=>{d("all"),J()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),a.jsxs("button",{onClick:()=>{d("used"),J()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${u==="used"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(Qn,{className:"w-3.5 h-3.5"}),t("inventory.used")]}),a.jsx("button",{onClick:()=>{d("new"),J()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="new"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.new")})]}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),a.jsxs("select",{value:h,onChange:Q=>{f(Q.target.value),J()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${h?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[a.jsx("option",{value:"",children:t("inventory.material")}),Se.map(Q=>a.jsx("option",{value:Q,children:Q},Q))]}),a.jsxs("select",{value:p,onChange:Q=>{x(Q.target.value),J()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${p?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[a.jsx("option",{value:"",children:t("inventory.brand")}),fe.map(Q=>a.jsx("option",{value:Q,children:Q},Q))]}),me&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),a.jsxs("button",{onClick:oe,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:[a.jsx(Ft,{className:"w-3.5 h-3.5"}),t("inventory.clearFilters")]})]}),a.jsxs("span",{className:"ml-auto text-xs text-bambu-gray",children:[Ne.length," ",Ne.length!==1?t("inventory.spools"):t("inventory.spool")]})]}),R?a.jsx("div",{className:"flex justify-center py-16",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})}):y==="cards"?ue.length>0?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:ue.map(Q=>{const he=Math.max(0,Q.label_weight-Q.weight_used),be=Q.label_weight>0?he/Q.label_weight*100:0,ee=Q.rgba?`#${Q.rgba.substring(0,6)}`:"#808080";return a.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors cursor-pointer ${Q.archived_at?"opacity-50":""}`,onClick:()=>i({spool:Q}),children:[a.jsx("div",{className:"h-14 flex items-center justify-center",style:{backgroundColor:ee},children:a.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:pne(Q.color_name,Q.rgba)||"-"})}),a.jsxs("div",{className:"p-4 space-y-3",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{children:[a.jsxs("h3",{className:"font-semibold text-white",children:[Q.material,Q.subtype?` ${Q.subtype}`:""]}),a.jsx("p",{className:"text-sm text-bambu-gray",children:Q.brand||"-"})]}),a.jsxs("span",{className:"text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:["#",Q.id]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[a.jsx("span",{children:t("inventory.remaining")}),a.jsxs("span",{children:[Math.round(be),"%"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full ${be>50?"bg-bambu-green":be>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(be,100)}%`}})}),a.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(he),"g"]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[a.jsxs("div",{children:[a.jsxs("span",{className:"text-bambu-gray/60",children:[t("inventory.labelWeight"),": "]}),a.jsx("span",{className:"text-bambu-gray",children:Fu(Q.label_weight)})]}),a.jsxs("div",{children:[a.jsxs("span",{className:"text-bambu-gray/60",children:[t("inventory.weightUsed"),": "]}),a.jsx("span",{className:"text-bambu-gray",children:Q.weight_used>0?Fu(Q.weight_used):"-"})]})]}),Q.note&&a.jsx("div",{className:"text-xs text-bambu-gray/60 pt-2 border-t border-bambu-dark-tertiary truncate",title:Q.note,children:Q.note})]})]},Q.id)})}),a.jsx(BJe,{pageIndex:W,pageSize:U,totalRows:Ne.length,totalPages:$,onPageChange:P,onPageSizeChange:Z,t})]}):a.jsx(mK,{hasFilters:me,onAddSpool:()=>i({spool:null}),t}):ue.length>0?a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[de.map(Q=>{const he=!!Xj[Q],be=N?.column===Q;return a.jsx("th",{className:`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${Q==="remaining"?"min-w-[150px]":""} ${he?"cursor-pointer hover:text-bambu-green transition-colors":""} ${be?"text-bambu-green":"text-bambu-gray"}`,onClick:he?()=>ce(Q):void 0,children:a.jsxs("span",{className:"inline-flex items-center gap-1",children:[LJe[Q]?.(t)??Q,he&&(be?N.direction==="asc"?a.jsx(Ef,{className:"w-3 h-3"}):a.jsx(hb,{className:"w-3 h-3"}):a.jsx(DF,{className:"w-3 h-3 opacity-30"}))]})},Q)}),a.jsx("th",{className:"text-right py-3 px-4 text-xs font-medium text-bambu-gray uppercase tracking-wide",children:t("common.actions")})]})}),a.jsx("tbody",{children:ue.map(Q=>{const he=Math.max(0,Q.label_weight-Q.weight_used),be=Q.label_weight>0?he/Q.label_weight*100:0;return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer ${Q.archived_at?"opacity-50":""}`,onClick:()=>i({spool:Q}),children:[de.map(ee=>a.jsx("td",{className:"py-3 px-4",children:OJe[ee]?.({spool:Q,remaining:he,pct:be,assignmentMap:H})},ee)),a.jsx("td",{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-center justify-end gap-1",onClick:ee=>ee.stopPropagation(),children:[a.jsx("button",{onClick:()=>i({spool:Q}),className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:t("inventory.editSpool"),children:a.jsx(rf,{className:"w-4 h-4"})}),Q.archived_at?a.jsx("button",{onClick:()=>K.mutate(Q.id),className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:t("inventory.restore"),children:a.jsx(Do,{className:"w-4 h-4"})}):a.jsx("button",{onClick:()=>o({type:"archive",spoolId:Q.id}),className:"p-1.5 text-bambu-gray hover:text-yellow-400 rounded transition-colors",title:t("inventory.archive"),children:a.jsx(Rs,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>o({type:"delete",spoolId:Q.id}),className:"p-1.5 text-bambu-gray hover:text-red-400 rounded transition-colors",title:t("common.delete"),children:a.jsx(en,{className:"w-4 h-4"})})]})})]},Q.id)})})]})}),a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-bambu-dark-tertiary/50 border-t border-bambu-dark-tertiary text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:ie?`${Ne.length} ${Ne.length!==1?t("inventory.spools"):t("inventory.spool")}`:a.jsxs(a.Fragment,{children:[t("inventory.showing")," ",W*Le+1," ",t("inventory.to")," ",Math.min((W+1)*Le,Ne.length)," ",t("inventory.of")," ",Ne.length," ",t("inventory.spools")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-gray",children:t("inventory.show")}),a.jsxs("select",{value:U,onChange:Q=>Z(Number(Q.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(Q=>a.jsx("option",{value:Q,children:Q},Q)),a.jsx("option",{value:-1,children:t("inventory.all")})]}),!ie&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>P(0),disabled:W===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"First page",children:a.jsx(lX,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>P(Q=>Math.max(0,Q-1)),disabled:W===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(Gl,{className:"w-4 h-4"})}),a.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[t("inventory.page")," ",W+1," ",t("inventory.of")," ",$]}),a.jsx("button",{onClick:()=>P(Q=>Math.min($-1,Q+1)),disabled:W>=$-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(fa,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>P($-1),disabled:W>=$-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Last page",children:a.jsx(cX,{className:"w-4 h-4"})})]})]})]})]}):a.jsx(mK,{hasFilters:me,onAddSpool:()=>i({spool:null}),t}),r!==null&&a.jsx(PJe,{isOpen:!0,onClose:()=>i(null),spool:r.spool}),s&&a.jsx(kn,{title:s.type==="delete"?t("common.delete"):t("inventory.archive"),message:s.type==="delete"?t("inventory.deleteConfirm"):t("inventory.archiveConfirm"),confirmText:s.type==="delete"?t("common.delete"):t("inventory.archive"),variant:s.type==="delete"?"danger":"warning",onConfirm:()=>{s.type==="delete"?q.mutate(s.spoolId):I.mutate(s.spoolId),o(null)},onCancel:()=>o(null)}),a.jsx(jJe,{isOpen:k,onClose:()=>j(!1),columns:M,defaultColumns:S1,onSave:De})]})}function BJe({pageIndex:t,pageSize:e,totalRows:n,totalPages:r,onPageChange:i,onPageSizeChange:s,t:o}){const l=e===-1;if(r<=1&&!l)return null;const c=l?n||1:e;return a.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o(n!==1?"inventory.spools":"inventory.spool")}`:a.jsxs(a.Fragment,{children:[o("inventory.showing")," ",t*c+1," ",o("inventory.to")," ",Math.min((t+1)*c,n)," ",o("inventory.of")," ",n," ",o("inventory.spools")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-gray",children:o("inventory.show")}),a.jsxs("select",{value:e,onChange:u=>s(Number(u.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(u=>a.jsx("option",{value:u,children:u},u)),a.jsx("option",{value:-1,children:o("inventory.all")})]}),!l&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>i(0),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(lX,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>i(Math.max(0,t-1)),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(Gl,{className:"w-4 h-4"})}),a.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("inventory.page")," ",t+1," ",o("inventory.of")," ",r]}),a.jsx("button",{onClick:()=>i(Math.min(r-1,t+1)),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(fa,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>i(r-1),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(cX,{className:"w-4 h-4"})})]})]})]})}function mK({hasFilters:t,onAddSpool:e,t:n}){return a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[a.jsxs("div",{className:"relative mb-6",children:[a.jsx("div",{className:"absolute inset-0 -m-4 bg-bambu-green/5 rounded-full blur-2xl"}),a.jsxs("div",{className:"relative flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-bambu-dark-secondary to-bambu-dark-tertiary border border-bambu-dark-tertiary shadow-lg",children:[a.jsx("div",{className:"absolute -top-1 -right-1 w-3 h-3 rounded-full bg-bambu-green/30"}),a.jsx("div",{className:"absolute -bottom-2 -left-2 w-2 h-2 rounded-full bg-bambu-green/20"}),t?a.jsx(Or,{className:"w-10 h-10 text-bambu-gray/40",strokeWidth:1.5}):a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-14 h-14 rounded-full border-4 border-bambu-gray/20 flex items-center justify-center",children:a.jsx("div",{className:"w-6 h-6 rounded-full bg-bambu-gray/10 border-2 border-bambu-gray/20"})}),a.jsx("div",{className:"absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-bambu-green flex items-center justify-center shadow-md",children:a.jsx("span",{className:"text-white text-lg font-bold leading-none",children:"+"})})]})]})]}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2 text-center",children:t?n("inventory.noSpoolsMatch"):n("inventory.noSpools").split(".")[0]}),a.jsx("p",{className:"text-sm text-bambu-gray text-center max-w-sm mb-6",children:n(t?"inventory.noSpoolsMatchDesc":"inventory.noSpools")}),!t&&a.jsxs(Me,{onClick:e,children:[a.jsx(ma,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})}const fK=["DEBUG","INFO","WARNING","ERROR"],Yj={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},HJe={DEBUG:Zk,INFO:Zs,WARNING:Cn,ERROR:Bi};function $Je(){const t=tn(),[e,n]=w.useState(!0),[r,i]=w.useState(new Set),[s,o]=w.useState(""),[l,c]=w.useState("ALL"),[u,d]=w.useState(!1),[h,f]=w.useState(!1),p=w.useRef(null),{data:x,isLoading:v,refetch:b}=tt({queryKey:["application-logs",l,s],queryFn:()=>Zg.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:h?2e3:!1,enabled:u});w.useEffect(()=>{u||f(!1)},[u]);const y=lt({mutationFn:()=>Zg.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});w.useEffect(()=>{e&&p.current&&x?.entries&&(p.current.scrollTop=p.current.scrollHeight)},[x?.entries,e]);const S=k=>{i(j=>{const E=new Set(j);return E.has(k)?E.delete(k):E.add(k),E})},N=k=>{const j=k.split(" ");return j.length>=2?j[1]:k},A=w.useMemo(()=>x?.entries??[],[x?.entries]),M=w.useMemo(()=>[...A].reverse(),[A]),T=({level:k})=>{const j=HJe[k]||Zs;return a.jsx(j,{className:`w-3.5 h-3.5 ${Yj[k]||"text-gray-400"}`})};return a.jsxs("div",{className:"bg-bambu-dark rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>d(!u),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/50 transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${h?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:a.jsx(Zk,{className:"w-5 h-5"})}),a.jsxs("div",{className:"text-left",children:[a.jsx("p",{className:"font-medium text-white",children:"Application Logs"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:h?`Live streaming - ${x?.filtered_count??0} entries`:"View and filter application logs"})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[h&&a.jsxs("span",{className:"flex items-center gap-1.5 px-2 py-1 bg-bambu-green/20 rounded text-bambu-green text-xs",children:[a.jsx("span",{className:"w-1.5 h-1.5 bg-bambu-green rounded-full animate-pulse"}),"Live"]}),u?a.jsx(ql,{className:"w-5 h-5 text-bambu-gray"}):a.jsx(nr,{className:"w-5 h-5 text-bambu-gray"})]})]}),u&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h?a.jsxs("button",{onClick:k=>{k.stopPropagation(),f(!1)},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded transition-colors",children:[a.jsx(gl,{className:"w-4 h-4"}),"Stop"]}):a.jsxs("button",{onClick:k=>{k.stopPropagation(),f(!0),b()},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 rounded transition-colors",children:[a.jsx(jo,{className:"w-4 h-4"}),"Start"]}),a.jsxs("button",{onClick:()=>y.mutate(),disabled:y.isPending||A.length===0,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:[a.jsx(en,{className:"w-4 h-4"}),"Clear"]}),a.jsx("button",{onClick:()=>b(),disabled:v,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:a.jsx(kr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),a.jsx("div",{className:"flex-1"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:e,onChange:k=>n(k.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark-tertiary"}),"Auto-scroll"]}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[x?.filtered_count??0,"/",x?.total_in_file??0]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Or,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:"Search message or logger name...",value:s,onChange:k=>o(k.target.value),className:"w-full pl-8 pr-8 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),s&&a.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Ft,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark-secondary rounded border border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>c("ALL"),className:`px-2 py-1.5 text-xs rounded-l transition-colors ${l==="ALL"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"All"}),fK.map((k,j)=>a.jsx("button",{onClick:()=>c(k),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${j===fK.length-1?"rounded-r":""} ${l===k?`${Yj[k]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:k},k))]})]})]}),a.jsx("div",{ref:p,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:A.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-[300px] text-bambu-gray",children:[a.jsx("p",{className:"mb-2",children:"No log entries found"}),a.jsx("p",{className:"text-sm",children:"Log file may be empty or cleared"})]}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary/30",children:M.map((k,j)=>{const E=r.has(j),P=k.message.includes(` `);return a.jsx("div",{className:`p-2 cursor-pointer hover:bg-bambu-dark-secondary/50 transition-colors ${E?"bg-bambu-dark-secondary/30":""}`,onClick:()=>P&&S(j),children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx("span",{className:"text-bambu-gray/70 shrink-0 w-20",children:N(k.timestamp)}),a.jsx("span",{className:"shrink-0",children:a.jsx(T,{level:k.level})}),a.jsxs("span",{className:"text-purple-400/80 shrink-0 max-w-[200px] truncate",title:k.logger_name,children:["[",k.logger_name,"]"]}),a.jsx("span",{className:`flex-1 ${Yj[k.level]||"text-white/80"} ${!E&&P?"truncate":""}`,children:E?a.jsx("pre",{className:"whitespace-pre-wrap break-all",children:k.message}):k.message.split(` `)[0]}),P&&a.jsx("span",{className:"text-bambu-gray/50 shrink-0",children:E?a.jsx(ql,{className:"w-3.5 h-3.5"}):a.jsx(nr,{className:"w-3.5 h-3.5"})})]})},j)})})}),a.jsx("div",{className:"flex items-center justify-between p-3 border-t border-bambu-dark-tertiary text-sm text-bambu-gray",children:h?a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),"Auto-refreshing every 2 seconds"]}):a.jsx("span",{children:"Click Start to enable live log streaming"})})]})]})}function VJe(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(2)} GB`}function Mi({icon:t,label:e,value:n,subValue:r,color:i="text-bambu-green"}){return a.jsxs("div",{className:"flex items-start gap-3 p-4 bg-bambu-dark rounded-lg",children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark-tertiary ${i}`,children:a.jsx(t,{className:"w-5 h-5"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:e}),a.jsx("p",{className:"text-lg font-semibold text-white truncate",children:n}),r&&a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:r})]})]})}function pK({percent:t,color:e="bg-bambu-green"}){return a.jsx("div",{className:"w-full h-2 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full ${e} transition-all duration-300`,style:{width:`${Math.min(100,t)}%`}})})}function ah({title:t,icon:e,children:n}){return a.jsxs(_t,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[a.jsx(e,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t})]}),n]})}function GJe(){const{t}=Vt(),e=tn(),[n,r]=w.useState(null),[i,s]=w.useState(!1),[o,l]=w.useState(!1),{data:c,isLoading:u,refetch:d,isFetching:h}=tt({queryKey:["systemInfo"],queryFn:se.getSystemInfo,refetchInterval:3e4}),{data:f}=tt({queryKey:["debugLogging"],queryFn:Zg.getDebugLoggingState,staleTime:10*1e3,refetchInterval:10*1e3}),{data:p}=tt({queryKey:["settings"],queryFn:se.getSettings}),{data:x}=tt({queryKey:["library-stats"],queryFn:se.getLibraryStats}),v=p?.time_format||"system",b=async()=>{l(!0);try{const A=await Zg.setDebugLogging(!f?.enabled);e.setQueryData(["debugLogging"],A)}catch(A){console.error("Failed to toggle debug logging:",A)}finally{l(!1)}},y=async()=>{r(null),s(!0);try{await Zg.downloadSupportBundle()}catch(A){r(A instanceof Error?A.message:"Failed to download support bundle")}finally{s(!1)}};if(u)return a.jsx("div",{className:"flex items-center justify-center h-64",children:a.jsx(at,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(!c)return a.jsx("div",{className:"p-6 text-center text-bambu-gray",children:t("system.failedToLoad","Failed to load system information")});const S=c.storage.disk_percent_used>90?"bg-red-500":c.storage.disk_percent_used>75?"bg-yellow-500":"bg-bambu-green",N=c.memory.percent_used>90?"bg-red-500":c.memory.percent_used>75?"bg-yellow-500":"bg-bambu-green";return a.jsxs("div",{className:"p-6 space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("system.title","System Information")}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("system.subtitle","Monitor system resources and database statistics")})]}),a.jsxs("button",{onClick:()=>d(),disabled:h,className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary rounded-lg transition-colors disabled:opacity-50",children:[a.jsx(kr,{className:`w-4 h-4 ${h?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),a.jsx(ah,{title:t("system.application","Application"),icon:$m,children:a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[a.jsx(Mi,{icon:$m,label:t("system.version","Version"),value:`v${c.app.version}`}),a.jsx(Mi,{icon:Qn,label:t("system.uptime","System Uptime"),value:c.system.uptime_formatted}),a.jsx(Mi,{icon:$m,label:t("system.hostname","Hostname"),value:c.system.hostname})]})}),a.jsx(ah,{title:t("support.title","Support & Troubleshooting"),icon:xme,children:a.jsxs("div",{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.description","Enable debug logging to capture detailed information, then download a support bundle to share when reporting issues.")}),a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${f?.enabled?"bg-amber-500/20 text-amber-500":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:a.jsx(Zk,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium text-white",children:t("support.debugLogging","Debug Logging")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[f?.enabled?t("support.debugLoggingEnabled","Capturing detailed logs"):t("support.debugLoggingDisabled","Normal logging level"),f?.enabled&&f.duration_seconds!==null&&a.jsxs("span",{className:"text-amber-400 ml-2",children:["(",Math.floor(f.duration_seconds/60),"m ",f.duration_seconds%60,"s)"]})]})]})]}),a.jsxs("button",{onClick:b,disabled:o,className:`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${f?.enabled?"bg-amber-500/20 text-amber-400 hover:bg-amber-500/30":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30"} disabled:opacity-50`,children:[o&&a.jsx(at,{className:"w-4 h-4 animate-spin"}),f?.enabled?t("support.disableDebug","Disable"):t("support.enableDebug","Enable")]})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-green",children:a.jsx(di,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium text-white",children:t("support.supportBundle","Support Bundle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.supportBundleDescription","Download system info and logs as a ZIP file")})]})]}),a.jsxs("button",{onClick:y,disabled:i||!f?.enabled,className:"px-4 py-2 rounded-lg font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",title:f?.enabled?void 0:t("support.enableDebugFirst","Enable debug logging first"),children:[i&&a.jsx(at,{className:"w-4 h-4 animate-spin"}),t("common.download","Download")]})]}),n&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/30 rounded-lg text-red-400 text-sm",children:n}),!f?.enabled&&a.jsx("div",{className:"p-4 bg-bambu-dark-tertiary/50 rounded-lg",children:a.jsxs("p",{className:"text-sm text-bambu-gray",children:[a.jsx("span",{className:"text-amber-400 font-medium",children:t("support.instructions","To report an issue:")}),a.jsx("br",{}),"1. ",t("support.step1","Enable debug logging"),a.jsx("br",{}),"2. ",t("support.step2","Reproduce the issue"),a.jsx("br",{}),"3. ",t("support.step3","Download the support bundle"),a.jsx("br",{}),"4. ",t("support.step4","Attach the ZIP file to your issue report")]})}),a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg space-y-3",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:t("support.privacyTitle","What's in the support bundle?")}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-sm",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-bambu-green font-medium mb-1",children:t("support.collected","Collected:")}),a.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[a.jsxs("li",{children:["• ",t("support.collectItem1","App version and debug mode")]}),a.jsxs("li",{children:["• ",t("support.collectItem2","OS, architecture, Python version")]}),a.jsxs("li",{children:["• ",t("support.collectItem3","Database statistics (counts only)")]}),a.jsxs("li",{children:["• ",t("support.collectItem4","Printer models and nozzle counts")]}),a.jsxs("li",{children:["• ",t("support.collectItem5","Non-sensitive settings (themes, formats)")]}),a.jsxs("li",{children:["• ",t("support.collectItem6","Debug logs (sanitized)")]}),a.jsxs("li",{children:["• ",t("support.collectItem7","Printer connectivity and firmware versions")]}),a.jsxs("li",{children:["• ",t("support.collectItem8","Integration status (Spoolman, MQTT, HA)")]}),a.jsxs("li",{children:["• ",t("support.collectItem9","Network interfaces (subnets only)")]}),a.jsxs("li",{children:["• ",t("support.collectItem10","Python package versions")]}),a.jsxs("li",{children:["• ",t("support.collectItem11","Database health checks")]}),a.jsxs("li",{children:["• ",t("support.collectItem12","Docker environment details")]})]})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-red-400 font-medium mb-1",children:t("support.notCollected","NOT collected:")}),a.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[a.jsxs("li",{children:["• ",t("support.notItem1","Printer names, IPs, serial numbers")]}),a.jsxs("li",{children:["• ",t("support.notItem2","Access codes and passwords")]}),a.jsxs("li",{children:["• ",t("support.notItem3","Email addresses")]}),a.jsxs("li",{children:["• ",t("support.notItem4","API keys and tokens")]}),a.jsxs("li",{children:["• ",t("support.notItem5","Webhook URLs")]}),a.jsxs("li",{children:["• ",t("support.notItem6","Your hostname or username")]})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray/70",children:t("support.privacyNote","IP addresses in logs are replaced with [IP] and email addresses with [EMAIL].")})]}),a.jsx($Je,{})]})}),a.jsxs(ah,{title:t("system.database","Database"),icon:Ac,children:[a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[a.jsx(Mi,{icon:Rs,label:t("system.totalArchives","Total Archives"),value:c.database.archives}),a.jsx(Mi,{icon:fb,label:t("system.completed","Completed"),value:c.database.archives_completed,color:"text-green-500"}),a.jsx(Mi,{icon:ha,label:t("system.failed","Failed"),value:c.database.archives_failed,color:"text-red-500"}),a.jsx(Mi,{icon:at,label:t("system.printing","Printing"),value:c.database.archives_printing,color:"text-yellow-500"})]}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(Mi,{icon:Cr,label:t("system.printers","Printers"),value:c.database.printers}),a.jsx(Mi,{icon:iC,label:t("system.filaments","Filaments"),value:c.database.filaments}),a.jsx(Mi,{icon:xs,label:t("system.projects","Projects"),value:c.database.projects}),a.jsx(Mi,{icon:dl,label:t("system.smartPlugs","Smart Plugs"),value:c.database.smart_plugs})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[a.jsx(Mi,{icon:Qn,label:t("system.totalPrintTime","Total Print Time"),value:c.database.total_print_time_formatted}),a.jsx(Mi,{icon:Rs,label:t("system.totalFilament","Total Filament Used"),value:`${c.database.total_filament_kg} kg`,subValue:`${c.database.total_filament_grams.toLocaleString()} g`})]})]}),a.jsxs(ah,{title:t("system.connectedPrinters","Connected Printers"),icon:Cr,children:[a.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[a.jsx("div",{className:"text-3xl font-bold text-bambu-green",children:c.printers.connected}),a.jsx("div",{className:"text-bambu-gray",children:t("system.ofTotal","of {{total}} printers connected",{total:c.printers.total})})]}),c.printers.connected_list.length>0?a.jsx("div",{className:"space-y-2",children:c.printers.connected_list.map(A=>a.jsxs("div",{className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green"}),a.jsx("span",{className:"font-medium text-white",children:A.name})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[a.jsx("span",{children:A.model}),a.jsx("span",{className:`px-2 py-0.5 rounded ${A.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":A.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:A.state})]})]},A.id))}):a.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),a.jsx(ah,{title:t("system.storage","Storage"),icon:qb,children:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:t("system.diskUsage","Disk Usage")}),a.jsxs("span",{className:"text-white",children:[c.storage.disk_used_formatted," / ",c.storage.disk_total_formatted]})]}),a.jsx(pK,{percent:c.storage.disk_percent_used,color:S}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.storage.disk_free_formatted," ",t("system.free","free")," (",(100-c.storage.disk_percent_used).toFixed(1),"%)"]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[a.jsx(Mi,{icon:Rs,label:t("system.archiveStorage","Archive Storage"),value:c.storage.archive_size_formatted}),a.jsx(Mi,{icon:Ac,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),x&&a.jsx(Mi,{icon:Xl,label:t("system.fileManagerStorage","File Manager"),value:VJe(x.total_size_bytes),subValue:`${x.total_files} files, ${x.total_folders} folders`})]})]})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[a.jsx(ah,{title:t("system.memory","Memory"),icon:Yme,children:a.jsx("div",{className:"space-y-4",children:a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:t("system.memoryUsage","Memory Usage")}),a.jsxs("span",{className:"text-white",children:[c.memory.used_formatted," / ",c.memory.total_formatted]})]}),a.jsx(pK,{percent:c.memory.percent_used,color:N}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.memory.available_formatted," ",t("system.available","available")]})]})})}),a.jsx(ah,{title:t("system.cpu","CPU"),icon:h_,children:a.jsx("div",{className:"space-y-4",children:a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsx(Mi,{icon:h_,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),a.jsx(Mi,{icon:h_,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),a.jsx(ah,{title:t("system.systemDetails","System Details"),icon:$m,children:a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(Mi,{icon:$m,label:t("system.os","Operating System"),value:c.system.platform,subValue:c.system.platform_release}),a.jsx(Mi,{icon:h_,label:t("system.architecture","Architecture"),value:c.system.architecture}),a.jsx(Mi,{icon:$m,label:t("system.python","Python"),value:c.system.python_version}),a.jsx(Mi,{icon:Qn,label:t("system.bootTime","Boot Time"),value:Ff(c.system.boot_time,v)})]})})]})}function qJe(){const t=Hc(),{t:e}=Vt(),{login:n}=Ir(),{showToast:r}=mn(),{mode:i}=np(),[s,o]=w.useState(""),[l,c]=w.useState(""),[u,d]=w.useState(!1),[h,f]=w.useState(""),{data:p}=tt({queryKey:["advancedAuthStatus"],queryFn:()=>se.getAdvancedAuthStatus()}),x=lt({mutationFn:()=>n(s,l),onSuccess:()=>{r(e("login.loginSuccess")),t("/")},onError:S=>{r(S.message||e("login.loginFailed"),"error")}}),v=lt({mutationFn:S=>se.forgotPassword({email:S}),onSuccess:S=>{r(S.message,"success"),d(!1),f("")},onError:S=>{r(S.message,"error")}}),b=S=>{if(S.preventDefault(),!s||!l){r(e("login.enterCredentials"),"error");return}x.mutate()},y=S=>{if(S.preventDefault(),!h){r("Please enter your email address","error");return}v.mutate(h)};return a.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:[a.jsxs("div",{className:"max-w-md w-full space-y-8 p-8 bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary shadow-lg",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("div",{className:"flex items-center justify-center mb-6",children:a.jsx("img",{src:i==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),a.jsx("h2",{className:"text-3xl font-bold text-white",children:e("login.title")}),a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("login.subtitle")})]}),a.jsxs("form",{className:"mt-8 space-y-6",onSubmit:b,children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{htmlFor:"username",className:"block text-sm font-medium text-white mb-2",children:p?.advanced_auth_enabled?e("login.usernameOrEmail")||"Username or Email":e("login.username")}),a.jsx("input",{id:"username",type:"text",required:!0,value:s,onChange:S=>o(S.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:p?.advanced_auth_enabled?e("login.usernameOrEmailPlaceholder")||"Enter your username or email":e("login.usernamePlaceholder"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-white mb-2",children:e("login.password")}),a.jsx("input",{id:"password",type:"password",required:!0,value:l,onChange:S=>c(S.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("login.passwordPlaceholder"),autoComplete:"current-password"})]})]}),a.jsx("div",{children:a.jsx("button",{type:"submit",disabled:x.isPending,className:"w-full flex justify-center py-3 px-4 bg-bambu-green hover:bg-bambu-green-light text-white font-medium rounded-lg shadow-lg shadow-bambu-green/20 hover:shadow-bambu-green/30 focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:ring-offset-2 focus:ring-offset-bambu-dark-secondary transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-bambu-green",children:x.isPending?e("login.signingIn"):e("login.signIn")})}),p?.advanced_auth_enabled&&a.jsx("div",{className:"text-center",children:a.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:e("login.forgotPassword")})})]})]}),u&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>d(!1),children:a.jsxs(_t,{className:"w-full max-w-md",onClick:S=>S.stopPropagation(),children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(k0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:e("login.forgotPasswordTitle")})]}),a.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>{d(!1),f("")},children:a.jsx(Ft,{className:"w-5 h-5"})})]})}),a.jsx(Nt,{children:p?.advanced_auth_enabled?a.jsxs("form",{onSubmit:y,className:"space-y-4",children:[a.jsx("p",{className:"text-bambu-gray text-sm",children:e("login.forgotPasswordEmailMessage")||"Enter your email address and we'll send you a new password."}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"forgot-email",className:"block text-sm font-medium text-white mb-2",children:e("login.emailAddress")||"Email Address"}),a.jsx("input",{id:"forgot-email",type:"email",required:!0,value:h,onChange:S=>f(S.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("login.emailPlaceholder")||"your.email@example.com"})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Me,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{d(!1),f("")},children:e("login.cancel")||"Cancel"}),a.jsx(Me,{type:"submit",className:"flex-1",disabled:v.isPending,children:v.isPending?e("login.sending")||"Sending...":e("login.sendResetEmail")||"Send Reset Email"})]})]}):a.jsxs("div",{className:"space-y-4",children:[a.jsx("p",{className:"text-bambu-gray",children:e("login.forgotPasswordMessage")}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4 space-y-2",children:[a.jsx("p",{className:"text-sm text-white font-medium",children:e("login.howToReset")}),a.jsxs("ol",{className:"text-sm text-bambu-gray space-y-1 list-decimal list-inside",children:[a.jsx("li",{children:e("login.resetStep1")}),a.jsx("li",{children:e("login.resetStep2")}),a.jsx("li",{children:e("login.resetStep3")}),a.jsx("li",{children:e("login.resetStep4")})]})]}),a.jsx(Me,{variant:"secondary",className:"w-full",onClick:()=>d(!1),children:e("login.gotIt")})]})})]})})]})}function WJe(){const t=Hc(),{t:e}=Vt(),{showToast:n}=mn(),{mode:r}=np(),{refreshAuth:i}=Ir(),[s,o]=w.useState(!1),[l,c]=w.useState(""),[u,d]=w.useState(""),[h,f]=w.useState(""),p=lt({mutationFn:()=>se.setupAuth({auth_enabled:s,admin_username:s?l:void 0,admin_password:s?u:void 0}),onSuccess:async v=>{await i(),v.auth_enabled?v.admin_created?(n(e("setup.toast.authEnabledAdminCreated")),t("/login")):(n(e("setup.toast.authEnabledExistingAdmins")),t("/login")):(n(e("setup.toast.setupCompleted")),t("/"))},onError:v=>{n(v.message,"error")}}),x=v=>{if(v.preventDefault(),s&&(l||u)){if(!l||!u){n(e("setup.toast.enterBothCredentials"),"error");return}if(u!==h){n(e("setup.toast.passwordsDoNotMatch"),"error");return}if(u.length<6){n(e("setup.toast.passwordTooShort"),"error");return}}p.mutate()};return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:a.jsxs("div",{className:"max-w-md w-full space-y-8 p-8 bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary shadow-lg",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("div",{className:"flex items-center justify-center mb-6",children:a.jsx("img",{src:r==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),a.jsx("h2",{className:"text-3xl font-bold text-white",children:e("setup.title")}),a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("setup.subtitle")})]}),a.jsxs("form",{className:"mt-8 space-y-6",onSubmit:x,children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center p-4 bg-bambu-dark-secondary/50 rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("input",{id:"auth-enabled",type:"checkbox",checked:s,onChange:v=>o(v.target.checked),className:"h-4 w-4 text-bambu-green focus:ring-bambu-green border-bambu-dark-tertiary rounded bg-bambu-dark-secondary"}),a.jsx("label",{htmlFor:"auth-enabled",className:"ml-3 block text-sm font-medium text-white",children:e("setup.enableAuth")})]}),s&&a.jsxs("div",{className:"space-y-4 mt-4",children:[a.jsx("div",{className:"p-3 bg-bambu-dark-secondary/50 border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Zs,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"text-sm text-bambu-gray",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:e("setup.adminAccount")}),a.jsx("p",{children:e("setup.adminAccountDesc")})]})]})}),a.jsxs("div",{children:[a.jsxs("label",{htmlFor:"admin-username",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminUsername")," ",a.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),a.jsx("input",{id:"admin-username",type:"text",value:l,onChange:v=>c(v.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("setup.adminUsernamePlaceholder"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsxs("label",{htmlFor:"admin-password",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminPassword")," ",a.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),a.jsx("input",{id:"admin-password",type:"password",value:u,onChange:v=>d(v.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("setup.adminPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]}),u&&a.jsxs("div",{children:[a.jsx("label",{htmlFor:"confirm-password",className:"block text-sm font-medium text-white mb-2",children:e("setup.confirmPassword")}),a.jsx("input",{id:"confirm-password",type:"password",value:h,onChange:v=>f(v.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("setup.confirmPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]})]})]}),a.jsx("div",{children:a.jsx("button",{type:"submit",disabled:p.isPending,className:"w-full flex justify-center py-3 px-4 bg-bambu-green hover:bg-bambu-green-light text-white font-medium rounded-lg shadow-lg shadow-bambu-green/20 hover:shadow-bambu-green/30 focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:ring-offset-2 focus:ring-offset-bambu-dark-secondary transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-bambu-green",children:p.isPending?e("setup.settingUp"):e("setup.completeSetup")})})]})]})})}function KJe(){const t=w.useRef(null),e=w.useRef(null),n=tn(),[r,i]=w.useState(!1),s=w.useRef(new Set),o=w.useRef(null),l=w.useRef(new Map),c=w.useRef(null),u=w.useRef([]),d=w.useRef(!1),h=w.useRef(()=>{}),f=w.useCallback(()=>{if(d.current||u.current.length===0)return;d.current=!0;const S=()=>{const N=u.current.shift();N?requestAnimationFrame(()=>{h.current(N),u.current.length>0?setTimeout(S,16):d.current=!1}):d.current=!1};S()},[]),p=w.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const N=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,A=new WebSocket(N);let M=null;A.onopen=()=>{console.log("[WebSocket] Connected"),i(!0),M=window.setInterval(()=>{A.readyState===WebSocket.OPEN&&A.send(JSON.stringify({type:"ping"}))},3e4)},A.onmessage=T=>{try{const k=JSON.parse(T.data);k.type==="printer_status"&&k.printer_id!==void 0&&k.data?h.current(k):(u.current.push(k),f())}catch{}},A.onclose=T=>{console.log("[WebSocket] Closed",T.code,T.reason),M&&(clearInterval(M),M=null),i(!1),t.current=null,e.current=window.setTimeout(()=>{p()},3e3)},A.onerror=T=>{console.error("[WebSocket] Error",T),A.close()},t.current=A},[f]),x=w.useCallback((S,N)=>{const A=l.current.get(S)||{};l.current.set(S,{...A,...N}),c.current||(c.current=window.setTimeout(()=>{const M=new Map(l.current);l.current.clear(),c.current=null,requestAnimationFrame(()=>{M.forEach((T,k)=>{n.setQueryData(["printerStatus",k],j=>{const E={...j,...T};return E.wifi_signal==null&&j?.wifi_signal!=null&&(E.wifi_signal=j.wifi_signal),E})})})},100))},[n]),v=w.useCallback(S=>{s.current.add(S),o.current&&clearTimeout(o.current),o.current=window.setTimeout(()=>{const N=Array.from(s.current);s.current.clear(),o.current=null;let A=0;N.forEach(M=>{setTimeout(()=>{requestAnimationFrame(()=>{n.invalidateQueries({queryKey:[M]})})},A),A+=500})},3e3)},[n]),b=w.useCallback(S=>{switch(S.type){case"printer_status":S.printer_id!==void 0&&S.data&&x(S.printer_id,S.data);break;case"print_start":S.printer_id!==void 0&&n.invalidateQueries({queryKey:["printerStatus",S.printer_id]});break;case"print_complete":v("archives"),v("archiveStats");break;case"archive_created":v("archives"),v("archiveStats");break;case"archive_updated":v("archives");break;case"pong":break;case"plate_not_empty":window.dispatchEvent(new CustomEvent("plate-not-empty",{detail:{printer_id:S.printer_id,printer_name:S.printer_name,message:S.message}}));break;case"spool_auto_assigned":v("inventory-spools"),v("spool-assignments");break;case"spool_usage_logged":v("inventory-spools");break;case"unknown_tag":window.dispatchEvent(new CustomEvent("unknown-tag",{detail:{printer_id:S.printer_id,ams_id:S.ams_id,tray_id:S.tray_id,tag_uid:S.tag_uid,tray_uuid:S.tray_uuid}}));break}},[n,v,x]);w.useEffect(()=>{h.current=b},[b]),w.useEffect(()=>(p(),()=>{e.current&&clearTimeout(e.current),o.current&&clearTimeout(o.current),c.current&&clearTimeout(c.current),t.current&&t.current.close()}),[p]);const y=w.useCallback(S=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(S))},[]);return{isConnected:r,sendMessage:y}}const XJe=new Que({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function YJe({children:t}){return KJe(),a.jsx(a.Fragment,{children:t})}function QJe({children:t}){const{authEnabled:e,loading:n,user:r}=Ir();return n?a.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!r?a.jsx(db,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function ZJe({children:t}){const{authEnabled:e,loading:n,user:r,isAdmin:i}=Ir();return n?a.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?r?i?a.jsx(a.Fragment,{children:t}):a.jsx(db,{to:"/",replace:!0}):a.jsx(db,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function JJe({children:t}){const{authEnabled:e,loading:n}=Ir();return n?a.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?a.jsx(db,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function eet(){return a.jsx(zpe,{children:a.jsx(Kpe,{children:a.jsx(Zue,{client:XJe,children:a.jsx(Gpe,{children:a.jsx(bue,{children:a.jsxs(qce,{children:[a.jsx(zi,{path:"/setup",element:a.jsx(JJe,{children:a.jsx(WJe,{})})}),a.jsx(zi,{path:"/login",element:a.jsx(qJe,{})}),a.jsx(zi,{path:"/camera/:printerId",element:a.jsx(rJe,{})}),a.jsx(zi,{path:"/overlay/:printerId",element:a.jsx(cJe,{})}),a.jsxs(zi,{element:a.jsx(QJe,{children:a.jsx(YJe,{children:a.jsx(Zpe,{})})}),children:[a.jsx(zi,{index:!0,element:a.jsx(e$e,{})}),a.jsx(zi,{path:"archives",element:a.jsx(HXe,{})}),a.jsx(zi,{path:"queue",element:a.jsx(MQe,{})}),a.jsx(zi,{path:"stats",element:a.jsx($Qe,{})}),a.jsx(zi,{path:"profiles",element:a.jsx(PZe,{})}),a.jsx(zi,{path:"maintenance",element:a.jsx(LZe,{})}),a.jsx(zi,{path:"projects",element:a.jsx(IZe,{})}),a.jsx(zi,{path:"projects/:id",element:a.jsx(GZe,{})}),a.jsx(zi,{path:"inventory",element:a.jsx(UJe,{})}),a.jsx(zi,{path:"files",element:a.jsx(JZe,{})}),a.jsx(zi,{path:"settings",element:a.jsx(ZJe,{children:a.jsx(gZe,{})})}),a.jsx(zi,{path:"users",element:a.jsx(db,{to:"/settings?tab=users",replace:!0})}),a.jsx(zi,{path:"groups",element:a.jsx(db,{to:"/settings?tab=users",replace:!0})}),a.jsx(zi,{path:"system",element:a.jsx(GJe,{})}),a.jsx(zi,{path:"external/:id",element:a.jsx(uJe,{})})]})]})})})})})})}Boe.createRoot(document.getElementById("root")).render(a.jsx(w.StrictMode,{children:a.jsx(eet,{})})); diff --git a/static/index.html b/static/index.html index fe5a9df55..05f5cbcde 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - + From 8b7a1697a8eacc2dbc85ca1e31d3faadcd283594 Mon Sep 17 00:00:00 2001 From: maziggy Date: Mon, 16 Feb 2026 08:31:56 +0100 Subject: [PATCH 6/7] feat: add thumbnail images to Telegram and ntfy notifications (#372) Pushover and Discord already received print thumbnails, but Telegram and ntfy only got text. Telegram now uses sendPhoto with the image as a caption attachment. ntfy sends the image as a binary PUT with Filename/Message headers. No config changes needed. --- CHANGELOG.md | 1 + backend/app/services/notification_service.py | 45 ++++++++++++++------ 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97c65386c..5121b1a8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ All notable changes to Bambuddy will be documented in this file. - **K-Profiles View — Accurate Filament Name Resolution** — K-profile filament names are now resolved from builtin filament tables and user cloud presets (via new `/cloud/filament-id-map` endpoint) instead of showing raw IDs like "GFU99" or "P4d64437". Falls back to extracting names from the profile name field. - **Print Log** — New view mode on the Archives page showing a chronological table of all print activity. Columns include date/time, print name, printer, user, status, duration, and filament. Supports filtering by search text, printer, user, status, and date range. Pagination with configurable page size. A dedicated clear button deletes only log entries without affecting archives. Data is stored in a separate `print_log_entries` database table. - **Sync Spool Weights from AMS** — New button in Settings → Filament Tracking (built-in inventory mode) to force-sync all inventory spool weights from the live AMS remain% values of connected printers. Overwrites the database weight data with current sensor readings. Useful for recovering from corrupted weight data (e.g., after a power-off event zeroed all fill levels). Requires printers to be online. Includes a confirmation modal. +- **Notification Thumbnails for Telegram & ntfy** ([#372](https://github.com/maziggy/bambuddy/issues/372)) — Print thumbnail images are now attached to Telegram and ntfy notifications (previously only Pushover and Discord). Telegram uses the `sendPhoto` API with the image as caption attachment. ntfy sends the image as a binary PUT with `Filename` and `Message` headers. No configuration needed — images are sent automatically when available. ### Fixed - **Firmware Upload Uses Wrong Filename on Cache Hit** — The firmware update uploader cached downloaded firmware files under a mangled name (e.g., `X1C_01_09_00_10.bin`) instead of the original filename from Bambu Lab's CDN. On the first download the correct filename was uploaded to the SD card, but on subsequent attempts the cached file with the wrong name was used — causing the printer to not recognize the firmware file. Now caches using the original filename so the SD card always receives the correct file. diff --git a/backend/app/services/notification_service.py b/backend/app/services/notification_service.py index 646394ca2..9f98c3010 100644 --- a/backend/app/services/notification_service.py +++ b/backend/app/services/notification_service.py @@ -188,7 +188,9 @@ class NotificationService: else: return False, f"HTTP {response.status_code}: {response.text[:200]}" - async def _send_ntfy(self, config: dict, title: str, message: str) -> tuple[bool, str]: + async def _send_ntfy( + self, config: dict, title: str, message: str, image_data: bytes | None = None + ) -> tuple[bool, str]: """Send notification via ntfy.""" server = config.get("server", "https://ntfy.sh").rstrip("/") topic = config.get("topic", "").strip() @@ -204,7 +206,14 @@ class NotificationService: headers["Authorization"] = f"Bearer {auth_token}" client = await self._get_client() - response = await client.post(url, content=message, headers=headers) + + if image_data: + # ntfy supports image attachments via multipart form-data + headers["Filename"] = "photo.jpg" + headers["Message"] = message + response = await client.put(url, content=image_data, headers=headers) + else: + response = await client.post(url, content=message, headers=headers) if response.status_code in (200, 204): return True, "Message sent successfully" @@ -257,7 +266,7 @@ class NotificationService: except Exception: return False, f"HTTP {response.status_code}: {response.text[:200]}" - async def _send_telegram(self, config: dict, message: str) -> tuple[bool, str]: + async def _send_telegram(self, config: dict, message: str, image_data: bytes | None = None) -> tuple[bool, str]: """Send notification via Telegram bot.""" bot_token = config.get("bot_token", "").strip() chat_id = config.get("chat_id", "").strip() @@ -265,8 +274,6 @@ class NotificationService: if not bot_token or not chat_id: return False, "Bot token and chat ID are required" - url = f"https://api.telegram.org/bot{bot_token}/sendMessage" - # Escape underscores in the message body so Telegram Markdown # parsing doesn't break on job names like "A1_plate_8" or error # codes like "0300_0001". The title is already wrapped in *bold* @@ -276,14 +283,24 @@ class NotificationService: body_part = body_part.replace("_", "\\_") message = f"{title_part}\n{body_part}" - data = { - "chat_id": chat_id, - "text": message, - "parse_mode": "Markdown", - } - client = await self._get_client() - response = await client.post(url, json=data) + + if image_data: + # Use sendPhoto to attach the thumbnail with the caption + url = f"https://api.telegram.org/bot{bot_token}/sendPhoto" + response = await client.post( + url, + data={"chat_id": chat_id, "caption": message, "parse_mode": "Markdown"}, + files={"photo": ("photo.jpg", image_data, "image/jpeg")}, + ) + else: + url = f"https://api.telegram.org/bot{bot_token}/sendMessage" + data = { + "chat_id": chat_id, + "text": message, + "parse_mode": "Markdown", + } + response = await client.post(url, json=data) if response.status_code == 200: result = response.json() @@ -451,11 +468,11 @@ class NotificationService: if provider.provider_type == "callmebot": return await self._send_callmebot(config, f"{title}\n{message}") elif provider.provider_type == "ntfy": - return await self._send_ntfy(config, title, message) + return await self._send_ntfy(config, title, message, image_data=image_data) elif provider.provider_type == "pushover": return await self._send_pushover(config, title, message, image_data=image_data) elif provider.provider_type == "telegram": - return await self._send_telegram(config, f"*{title}*\n{message}") + return await self._send_telegram(config, f"*{title}*\n{message}", image_data=image_data) elif provider.provider_type == "email": return await self._send_email(config, title, message) elif provider.provider_type == "discord": From bd9821d39c46d079b1c6b304247f05f4067f906f Mon Sep 17 00:00:00 2001 From: maziggy Date: Mon, 16 Feb 2026 08:35:10 +0100 Subject: [PATCH 7/7] The only-labels: 'feedback' parameter tells the stale bot to only process issues that have the feedback label. All other issues (feature requests with future, bug reports, etc.) will be left alone. --- .github/workflows/stale.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 03e2b7824..7bdc599d8 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -18,3 +18,4 @@ jobs: days-before-stale: 21 days-before-close: 7 stale-issue-label: 'stale' + only-labels: 'feedback'