diff --git a/CHANGELOG.md b/CHANGELOG.md index 37a4cc709..087c3ad61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ All notable changes to Bambuddy will be documented in this file. - **External Camera Not Used for Snapshot + Stream Dropping** ([#325](https://github.com/maziggy/bambuddy/issues/325)) — The snapshot endpoint (`/camera/snapshot`) always used the internal printer camera even when an external camera was configured. Now checks for external camera first, matching the existing stream endpoint behavior. Also fixed external MJPEG and RTSP streams silently dropping every ~60 seconds due to missing reconnect logic — the underlying stream generators exit on read timeout, and the caller now retries up to 3 times with a 2-second delay instead of ending the stream. - **H2C Nozzle Rack Text Unreadable on Light Filament Colors** ([#300](https://github.com/maziggy/bambuddy/issues/300)) — Nozzle rack slots use the loaded filament color as background, but white/light filaments made the white "0.4" text nearly invisible. Now uses a luminance check to switch to dark text on light backgrounds. +### Improved +- **Additional Currency Options** ([#329](https://github.com/maziggy/bambuddy/issues/329)) — Added 16 additional currencies to the cost tracking dropdown: HKD, INR, KRW, SEK, NOK, DKK, PLN, BRL, TWD, SGD, NZD, MXN, CZK, THB, ZAR. + ## [0.1.9] - 2026-02-10 ### New Features diff --git a/frontend/src/pages/SettingsPage.tsx b/frontend/src/pages/SettingsPage.tsx index 438425b7a..e971414e9 100644 --- a/frontend/src/pages/SettingsPage.tsx +++ b/frontend/src/pages/SettingsPage.tsx @@ -1587,6 +1587,21 @@ export function SettingsPage() { + + + + + + + + + + + + + + +
diff --git a/static/assets/index-GkrFU7v8.js b/static/assets/index-Co9UeRtt.js similarity index 94% rename from static/assets/index-GkrFU7v8.js rename to static/assets/index-Co9UeRtt.js index bc654a7d3..942eb933b 100644 --- a/static/assets/index-GkrFU7v8.js +++ b/static/assets/index-Co9UeRtt.js @@ -8449,9 +8449,9 @@ void main() { `);if(r>0){var{circleTangency:N,lineTangency:T,theta:M}=Y_({cx:e,cy:n,radius:r,angle:c,sign:d,isExternal:!0,cornerRadius:s,cornerIsExternal:l}),{circleTangency:A,lineTangency:k,theta:R}=Y_({cx:e,cy:n,radius:r,angle:u,sign:-d,isExternal:!0,cornerRadius:s,cornerIsExternal:l}),C=l?Math.abs(c-u):Math.abs(c-u)-M-R;if(C<0&&s===0)return"".concat(S,"L").concat(e,",").concat(n,"Z");S+="L".concat(k.x,",").concat(k.y,` A`).concat(s,",").concat(s,",0,0,").concat(+(d<0),",").concat(A.x,",").concat(A.y,` A`).concat(r,",").concat(r,",0,").concat(+(C>180),",").concat(+(d>0),",").concat(N.x,",").concat(N.y,` - A`).concat(s,",").concat(s,",0,0,").concat(+(d<0),",").concat(T.x,",").concat(T.y,"Z")}else S+="L".concat(e,",").concat(n,"Z");return S},iPe={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},mQ=t=>{var e=ci(t,iPe),{cx:n,cy:r,innerRadius:i,outerRadius:s,cornerRadius:o,forceCornerRadius:l,cornerIsExternal:c,startAngle:u,endAngle:d,className:h}=e;if(s0&&Math.abs(u-d)<360?y=rPe({cx:n,cy:r,innerRadius:i,outerRadius:s,cornerRadius:Math.min(b,m/2),forceCornerRadius:l,cornerIsExternal:c,startAngle:u,endAngle:d}):y=fQ({cx:n,cy:r,innerRadius:i,outerRadius:s,startAngle:u,endAngle:d}),_.createElement("path",mD({},Ga(e),{className:p,d:y}))};function aPe(t,e,n){if(t==="horizontal")return[{x:e.x,y:n.top},{x:e.x,y:n.top+n.height}];if(t==="vertical")return[{x:n.left,y:e.y},{x:n.left+n.width,y:e.y}];if(GX(e)){if(t==="centric"){var{cx:r,cy:i,innerRadius:s,outerRadius:o,angle:l}=e,c=Bi(r,i,s,l),u=Bi(r,i,o,l);return[{x:c.x,y:c.y},{x:u.x,y:u.y}]}return hQ(e)}}var zC={},UC={},BC={},hV;function sPe(){return hV||(hV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=iY();function n(r){return e.isSymbol(r)?NaN:Number(r)}t.toNumber=n})(BC)),BC}var fV;function oPe(){return fV||(fV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=sPe();function n(r){return r?(r=e.toNumber(r),r===1/0||r===-1/0?(r<0?-1:1)*Number.MAX_VALUE:r===r?r:0):r===0?r:0}t.toFinite=n})(UC)),UC}var mV;function lPe(){return mV||(mV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=aY(),n=oPe();function r(i,s,o){o&&typeof o!="number"&&e.isIterateeCall(i,s,o)&&(s=o=void 0),i=n.toFinite(i),s===void 0?(s=i,i=0):s=n.toFinite(s),o=o===void 0?ie?1:t>=e?0:NaN}function dPe(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}function tL(t){let e,n,r;t.length!==2?(e=_h,n=(l,c)=>_h(t(l),c),r=(l,c)=>t(l)-c):(e=t===_h||t===dPe?t:hPe,n=t,r=t);function i(l,c,u=0,d=l.length){if(u>>1;n(l[h],c)<0?u=h+1:d=h}while(u>>1;n(l[h],c)<=0?u=h+1:d=h}while(uu&&r(l[h-1],c)>-r(l[h],c)?h-1:h}return{left:i,center:o,right:s}}function hPe(){return 0}function gQ(t){return t===null?NaN:+t}function*fPe(t,e){for(let n of t)n!=null&&(n=+n)>=n&&(yield n)}const mPe=tL(_h),rv=mPe.right;tL(gQ).center;class gV extends Map{constructor(e,n=bPe){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),e!=null)for(const[r,i]of e)this.set(r,i)}get(e){return super.get(bV(this,e))}has(e){return super.has(bV(this,e))}set(e,n){return super.set(pPe(this,e),n)}delete(e){return super.delete(gPe(this,e))}}function bV({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):n}function pPe({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}function gPe({_intern:t,_key:e},n){const r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}function bPe(t){return t!==null&&typeof t=="object"?t.valueOf():t}function xPe(t=_h){if(t===_h)return bQ;if(typeof t!="function")throw new TypeError("compare is not a function");return(e,n)=>{const r=t(e,n);return r||r===0?r:(t(n,n)===0)-(t(e,e)===0)}}function bQ(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(te?1:0)}const yPe=Math.sqrt(50),vPe=Math.sqrt(10),wPe=Math.sqrt(2);function US(t,e,n){const r=(e-t)/Math.max(0,n),i=Math.floor(Math.log10(r)),s=r/Math.pow(10,i),o=s>=yPe?10:s>=vPe?5:s>=wPe?2:1;let l,c,u;return i<0?(u=Math.pow(10,-i)/o,l=Math.round(t*u),c=Math.round(e*u),l/ue&&--c,u=-u):(u=Math.pow(10,i)*o,l=Math.round(t/u),c=Math.round(e/u),l*ue&&--c),c0))return[];if(t===e)return[t];const r=e=i))return[];const l=s-i+1,c=new Array(l);if(r)if(o<0)for(let u=0;u=r)&&(n=r);return n}function yV(t,e){let n;for(const r of t)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function xQ(t,e,n=0,r=1/0,i){if(e=Math.floor(e),n=Math.floor(Math.max(0,n)),r=Math.floor(Math.min(t.length-1,r)),!(n<=e&&e<=r))return t;for(i=i===void 0?bQ:xPe(i);r>n;){if(r-n>600){const c=r-n+1,u=e-n+1,d=Math.log(c),h=.5*Math.exp(2*d/3),p=.5*Math.sqrt(d*h*(c-h)/c)*(u-c/2<0?-1:1),m=Math.max(n,Math.floor(e-u*h/c+p)),b=Math.min(r,Math.floor(e+(c-u)*h/c+p));xQ(t,e,m,b,i)}const s=t[e];let o=n,l=r;for(Jx(t,n,e),i(t[r],s)>0&&Jx(t,n,r);o0;)--l}i(t[n],s)===0?Jx(t,n,l):(++l,Jx(t,l,r)),l<=e&&(n=l+1),e<=l&&(r=l-1)}return t}function Jx(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}function _Pe(t,e,n){if(t=Float64Array.from(fPe(t)),!(!(r=t.length)||isNaN(e=+e))){if(e<=0||r<2)return yV(t);if(e>=1)return xV(t);var r,i=(r-1)*e,s=Math.floor(i),o=xV(xQ(t,s).subarray(0,s+1)),l=yV(t.subarray(s+1));return o+(l-o)*(i-s)}}function SPe(t,e,n=gQ){if(!(!(r=t.length)||isNaN(e=+e))){if(e<=0||r<2)return+n(t[0],0,t);if(e>=1)return+n(t[r-1],r-1,t);var r,i=(r-1)*e,s=Math.floor(i),o=+n(t[s],s,t),l=+n(t[s+1],s+1,t);return o+(l-o)*(i-s)}}function NPe(t,e,n){t=+t,e=+e,n=(i=arguments.length)<2?(e=t,t=0,1):i<3?1:+n;for(var r=-1,i=Math.max(0,Math.ceil((e-t)/n))|0,s=new Array(i);++r>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):n===8?Q_(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):n===4?Q_(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=EPe.exec(t))?new Vs(e[1],e[2],e[3],1):(e=TPe.exec(t))?new Vs(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=APe.exec(t))?Q_(e[1],e[2],e[3],e[4]):(e=CPe.exec(t))?Q_(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=PPe.exec(t))?MV(e[1],e[2]/100,e[3]/100,1):(e=jPe.exec(t))?MV(e[1],e[2]/100,e[3]/100,e[4]):vV.hasOwnProperty(t)?SV(vV[t]):t==="transparent"?new Vs(NaN,NaN,NaN,0):null}function SV(t){return new Vs(t>>16&255,t>>8&255,t&255,1)}function Q_(t,e,n,r){return r<=0&&(t=e=n=NaN),new Vs(t,e,n,r)}function OPe(t){return t instanceof iv||(t=vy(t)),t?(t=t.rgb(),new Vs(t.r,t.g,t.b,t.opacity)):new Vs}function yD(t,e,n,r){return arguments.length===1?OPe(t):new Vs(t,e,n,r??1)}function Vs(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}iL(Vs,yD,vQ(iv,{brighter(t){return t=t==null?BS:Math.pow(BS,t),new Vs(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?xy:Math.pow(xy,t),new Vs(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new Vs(em(this.r),em(this.g),em(this.b),HS(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:NV,formatHex:NV,formatHex8:LPe,formatRgb:kV,toString:kV}));function NV(){return`#${Bf(this.r)}${Bf(this.g)}${Bf(this.b)}`}function LPe(){return`#${Bf(this.r)}${Bf(this.g)}${Bf(this.b)}${Bf((isNaN(this.opacity)?1:this.opacity)*255)}`}function kV(){const t=HS(this.opacity);return`${t===1?"rgb(":"rgba("}${em(this.r)}, ${em(this.g)}, ${em(this.b)}${t===1?")":`, ${t})`}`}function HS(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function em(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Bf(t){return t=em(t),(t<16?"0":"")+t.toString(16)}function MV(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new Dl(t,e,n,r)}function wQ(t){if(t instanceof Dl)return new Dl(t.h,t.s,t.l,t.opacity);if(t instanceof iv||(t=vy(t)),!t)return new Dl;if(t instanceof Dl)return t;t=t.rgb();var e=t.r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),s=Math.max(e,n,r),o=NaN,l=s-i,c=(s+i)/2;return l?(e===s?o=(n-r)/l+(n0&&c<1?0:o,new Dl(o,l,c,t.opacity)}function FPe(t,e,n,r){return arguments.length===1?wQ(t):new Dl(t,e,n,r??1)}function Dl(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}iL(Dl,FPe,vQ(iv,{brighter(t){return t=t==null?BS:Math.pow(BS,t),new Dl(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?xy:Math.pow(xy,t),new Dl(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,i=2*n-r;return new Vs($C(t>=240?t-240:t+120,i,r),$C(t,i,r),$C(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new Dl(EV(this.h),Z_(this.s),Z_(this.l),HS(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=HS(this.opacity);return`${t===1?"hsl(":"hsla("}${EV(this.h)}, ${Z_(this.s)*100}%, ${Z_(this.l)*100}%${t===1?")":`, ${t})`}`}}));function EV(t){return t=(t||0)%360,t<0?t+360:t}function Z_(t){return Math.max(0,Math.min(1,t||0))}function $C(t,e,n){return(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)*255}const aL=t=>()=>t;function IPe(t,e){return function(n){return t+n*e}}function zPe(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}function UPe(t){return(t=+t)==1?_Q:function(e,n){return n-e?zPe(e,n,t):aL(isNaN(e)?n:e)}}function _Q(t,e){var n=e-t;return n?IPe(t,n):aL(isNaN(t)?e:t)}const TV=(function t(e){var n=UPe(e);function r(i,s){var o=n((i=yD(i)).r,(s=yD(s)).r),l=n(i.g,s.g),c=n(i.b,s.b),u=_Q(i.opacity,s.opacity);return function(d){return i.r=o(d),i.g=l(d),i.b=c(d),i.opacity=u(d),i+""}}return r.gamma=t,r})(1);function BPe(t,e){e||(e=[]);var n=t?Math.min(e.length,t.length):0,r=e.slice(),i;return function(s){for(i=0;in&&(s=e.slice(n,s),l[o]?l[o]+=s:l[++o]=s),(r=r[0])===(i=i[0])?l[o]?l[o]+=i:l[++o]=i:(l[++o]=null,c.push({i:o,x:$S(r,i)})),n=VC.lastIndex;return ne&&(n=t,t=e,e=n),function(r){return Math.max(t,Math.min(e,r))}}function ZPe(t,e,n){var r=t[0],i=t[1],s=e[0],o=e[1];return i2?JPe:ZPe,c=u=null,h}function h(p){return p==null||isNaN(p=+p)?s:(c||(c=l(t.map(r),e,n)))(r(o(p)))}return h.invert=function(p){return o(i((u||(u=l(e,t.map(r),$S)))(p)))},h.domain=function(p){return arguments.length?(t=Array.from(p,VS),d()):t.slice()},h.range=function(p){return arguments.length?(e=Array.from(p),d()):e.slice()},h.rangeRound=function(p){return e=Array.from(p),n=sL,d()},h.clamp=function(p){return arguments.length?(o=p?!0:ws,d()):o!==ws},h.interpolate=function(p){return arguments.length?(n=p,d()):n},h.unknown=function(p){return arguments.length?(s=p,h):s},function(p,m){return r=p,i=m,d()}}function oL(){return sM()(ws,ws)}function eje(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function GS(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}function ob(t){return t=GS(Math.abs(t)),t?t[1]:NaN}function tje(t,e){return function(n,r){for(var i=n.length,s=[],o=0,l=t[0],c=0;i>0&&l>0&&(c+l+1>r&&(l=Math.max(1,r-c)),s.push(n.substring(i-=l,i+l)),!((c+=l+1)>r));)l=t[o=(o+1)%t.length];return s.reverse().join(e)}}function nje(t){return function(e){return e.replace(/[0-9]/g,function(n){return t[+n]})}}var rje=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function wy(t){if(!(e=rje.exec(t)))throw new Error("invalid format: "+t);var e;return new lL({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}wy.prototype=lL.prototype;function lL(t){this.fill=t.fill===void 0?" ":t.fill+"",this.align=t.align===void 0?">":t.align+"",this.sign=t.sign===void 0?"-":t.sign+"",this.symbol=t.symbol===void 0?"":t.symbol+"",this.zero=!!t.zero,this.width=t.width===void 0?void 0:+t.width,this.comma=!!t.comma,this.precision=t.precision===void 0?void 0:+t.precision,this.trim=!!t.trim,this.type=t.type===void 0?"":t.type+""}lL.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function ije(t){e:for(var e=t.length,n=1,r=-1,i;n0&&(r=0);break}return r>0?t.slice(0,r)+t.slice(i+1):t}var SQ;function aje(t,e){var n=GS(t,e);if(!n)return t+"";var r=n[0],i=n[1],s=i-(SQ=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,o=r.length;return s===o?r:s>o?r+new Array(s-o+1).join("0"):s>0?r.slice(0,s)+"."+r.slice(s):"0."+new Array(1-s).join("0")+GS(t,Math.max(0,e+s-1))[0]}function CV(t,e){var n=GS(t,e);if(!n)return t+"";var r=n[0],i=n[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}const PV={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:eje,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>CV(t*100,e),r:CV,s:aje,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function jV(t){return t}var DV=Array.prototype.map,RV=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function sje(t){var e=t.grouping===void 0||t.thousands===void 0?jV:tje(DV.call(t.grouping,Number),t.thousands+""),n=t.currency===void 0?"":t.currency[0]+"",r=t.currency===void 0?"":t.currency[1]+"",i=t.decimal===void 0?".":t.decimal+"",s=t.numerals===void 0?jV:nje(DV.call(t.numerals,String)),o=t.percent===void 0?"%":t.percent+"",l=t.minus===void 0?"−":t.minus+"",c=t.nan===void 0?"NaN":t.nan+"";function u(h){h=wy(h);var p=h.fill,m=h.align,b=h.sign,y=h.symbol,x=h.zero,v=h.width,S=h.comma,N=h.precision,T=h.trim,M=h.type;M==="n"?(S=!0,M="g"):PV[M]||(N===void 0&&(N=12),T=!0,M="g"),(x||p==="0"&&m==="=")&&(x=!0,p="0",m="=");var A=y==="$"?n:y==="#"&&/[boxX]/.test(M)?"0"+M.toLowerCase():"",k=y==="$"?r:/[%p]/.test(M)?o:"",R=PV[M],C=/[defgprs%]/.test(M);N=N===void 0?6:/[gprs]/.test(M)?Math.max(1,Math.min(21,N)):Math.max(0,Math.min(20,N));function P(U){var F=A,H=k,D,$,G;if(M==="c")H=R(U)+H,U="";else{U=+U;var I=U<0||1/U<0;if(U=isNaN(U)?c:R(Math.abs(U),N),T&&(U=ije(U)),I&&+U==0&&b!=="+"&&(I=!1),F=(I?b==="("?b:l:b==="-"||b==="("?"":b)+F,H=(M==="s"?RV[8+SQ/3]:"")+H+(I&&b==="("?")":""),C){for(D=-1,$=U.length;++D<$;)if(G=U.charCodeAt(D),48>G||G>57){H=(G===46?i+U.slice(D+1):U.slice(D))+H,U=U.slice(0,D);break}}}S&&!x&&(U=e(U,1/0));var K=F.length+U.length+H.length,Q=K>1)+F+U+H+Q.slice(K);break;default:U=Q+F+U+H;break}return s(U)}return P.toString=function(){return h+""},P}function d(h,p){var m=u((h=wy(h),h.type="f",h)),b=Math.max(-8,Math.min(8,Math.floor(ob(p)/3)))*3,y=Math.pow(10,-b),x=RV[8+b/3];return function(v){return m(y*v)+x}}return{format:u,formatPrefix:d}}var J_,cL,NQ;oje({thousands:",",grouping:[3],currency:["$",""]});function oje(t){return J_=sje(t),cL=J_.format,NQ=J_.formatPrefix,J_}function lje(t){return Math.max(0,-ob(Math.abs(t)))}function cje(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(ob(e)/3)))*3-ob(Math.abs(t)))}function uje(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,ob(e)-ob(t))+1}function kQ(t,e,n,r){var i=bD(t,e,n),s;switch(r=wy(r??",f"),r.type){case"s":{var o=Math.max(Math.abs(t),Math.abs(e));return r.precision==null&&!isNaN(s=cje(i,o))&&(r.precision=s),NQ(r,o)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(s=uje(i,Math.max(Math.abs(t),Math.abs(e))))&&(r.precision=s-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(s=lje(i))&&(r.precision=s-(r.type==="%")*2);break}}return cL(r)}function $h(t){var e=t.domain;return t.ticks=function(n){var r=e();return pD(r[0],r[r.length-1],n??10)},t.tickFormat=function(n,r){var i=e();return kQ(i[0],i[i.length-1],n??10,r)},t.nice=function(n){n==null&&(n=10);var r=e(),i=0,s=r.length-1,o=r[i],l=r[s],c,u,d=10;for(l0;){if(u=gD(o,l,n),u===c)return r[i]=o,r[s]=l,e(r);if(u>0)o=Math.floor(o/u)*u,l=Math.ceil(l/u)*u;else if(u<0)o=Math.ceil(o*u)/u,l=Math.floor(l*u)/u;else break;c=u}return t},t}function MQ(){var t=oL();return t.copy=function(){return av(t,MQ())},xl.apply(t,arguments),$h(t)}function EQ(t){var e;function n(r){return r==null||isNaN(r=+r)?e:r}return n.invert=n,n.domain=n.range=function(r){return arguments.length?(t=Array.from(r,VS),n):t.slice()},n.unknown=function(r){return arguments.length?(e=r,n):e},n.copy=function(){return EQ(t).unknown(e)},t=arguments.length?Array.from(t,VS):[0,1],$h(n)}function TQ(t,e){t=t.slice();var n=0,r=t.length-1,i=t[n],s=t[r],o;return sMath.pow(t,e)}function pje(t){return t===Math.E?Math.log:t===10&&Math.log10||t===2&&Math.log2||(t=Math.log(t),e=>Math.log(e)/t)}function FV(t){return(e,n)=>-t(-e,n)}function uL(t){const e=t(OV,LV),n=e.domain;let r=10,i,s;function o(){return i=pje(r),s=mje(r),n()[0]<0?(i=FV(i),s=FV(s),t(dje,hje)):t(OV,LV),e}return e.base=function(l){return arguments.length?(r=+l,o()):r},e.domain=function(l){return arguments.length?(n(l),o()):n()},e.ticks=l=>{const c=n();let u=c[0],d=c[c.length-1];const h=d0){for(;p<=m;++p)for(b=1;bd)break;v.push(y)}}else for(;p<=m;++p)for(b=r-1;b>=1;--b)if(y=p>0?b/s(-p):b*s(p),!(yd)break;v.push(y)}v.length*2{if(l==null&&(l=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=wy(c)).precision==null&&(c.trim=!0),c=cL(c)),l===1/0)return c;const u=Math.max(1,r*l/e.ticks().length);return d=>{let h=d/s(Math.round(i(d)));return h*rn(TQ(n(),{floor:l=>s(Math.floor(i(l))),ceil:l=>s(Math.ceil(i(l)))})),e}function AQ(){const t=uL(sM()).domain([1,10]);return t.copy=()=>av(t,AQ()).base(t.base()),xl.apply(t,arguments),t}function IV(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function zV(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function dL(t){var e=1,n=t(IV(e),zV(e));return n.constant=function(r){return arguments.length?t(IV(e=+r),zV(e)):e},$h(n)}function CQ(){var t=dL(sM());return t.copy=function(){return av(t,CQ()).constant(t.constant())},xl.apply(t,arguments)}function UV(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function gje(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function bje(t){return t<0?-t*t:t*t}function hL(t){var e=t(ws,ws),n=1;function r(){return n===1?t(ws,ws):n===.5?t(gje,bje):t(UV(n),UV(1/n))}return e.exponent=function(i){return arguments.length?(n=+i,r()):n},$h(e)}function fL(){var t=hL(sM());return t.copy=function(){return av(t,fL()).exponent(t.exponent())},xl.apply(t,arguments),t}function xje(){return fL.apply(null,arguments).exponent(.5)}function BV(t){return Math.sign(t)*t*t}function yje(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function PQ(){var t=oL(),e=[0,1],n=!1,r;function i(s){var o=yje(t(s));return isNaN(o)?r:n?Math.round(o):o}return i.invert=function(s){return t.invert(BV(s))},i.domain=function(s){return arguments.length?(t.domain(s),i):t.domain()},i.range=function(s){return arguments.length?(t.range((e=Array.from(s,VS)).map(BV)),i):e.slice()},i.rangeRound=function(s){return i.range(s).round(!0)},i.round=function(s){return arguments.length?(n=!!s,i):n},i.clamp=function(s){return arguments.length?(t.clamp(s),i):t.clamp()},i.unknown=function(s){return arguments.length?(r=s,i):r},i.copy=function(){return PQ(t.domain(),e).round(n).clamp(t.clamp()).unknown(r)},xl.apply(i,arguments),$h(i)}function jQ(){var t=[],e=[],n=[],r;function i(){var o=0,l=Math.max(1,e.length);for(n=new Array(l-1);++o0?n[l-1]:t[0],l=n?[r[n-1],e]:[r[u-1],r[u]]},o.unknown=function(c){return arguments.length&&(s=c),o},o.thresholds=function(){return r.slice()},o.copy=function(){return DQ().domain([t,e]).range(i).unknown(s)},xl.apply($h(o),arguments)}function RQ(){var t=[.5],e=[0,1],n,r=1;function i(s){return s!=null&&s<=s?e[rv(t,s,0,r)]:n}return i.domain=function(s){return arguments.length?(t=Array.from(s),r=Math.min(t.length,e.length-1),i):t.slice()},i.range=function(s){return arguments.length?(e=Array.from(s),r=Math.min(t.length,e.length-1),i):e.slice()},i.invertExtent=function(s){var o=e.indexOf(s);return[t[o-1],t[o]]},i.unknown=function(s){return arguments.length?(n=s,i):n},i.copy=function(){return RQ().domain(t).range(e).unknown(n)},xl.apply(i,arguments)}const GC=new Date,qC=new Date;function sa(t,e,n,r){function i(s){return t(s=arguments.length===0?new Date:new Date(+s)),s}return i.floor=s=>(t(s=new Date(+s)),s),i.ceil=s=>(t(s=new Date(s-1)),e(s,1),t(s),s),i.round=s=>{const o=i(s),l=i.ceil(s);return s-o(e(s=new Date(+s),o==null?1:Math.floor(o)),s),i.range=(s,o,l)=>{const c=[];if(s=i.ceil(s),l=l==null?1:Math.floor(l),!(s0))return c;let u;do c.push(u=new Date(+s)),e(s,l),t(s);while(usa(o=>{if(o>=o)for(;t(o),!s(o);)o.setTime(o-1)},(o,l)=>{if(o>=o)if(l<0)for(;++l<=0;)for(;e(o,-1),!s(o););else for(;--l>=0;)for(;e(o,1),!s(o););}),n&&(i.count=(s,o)=>(GC.setTime(+s),qC.setTime(+o),t(GC),t(qC),Math.floor(n(GC,qC))),i.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?i.filter(r?o=>r(o)%s===0:o=>i.count(0,o)%s===0):i)),i}const qS=sa(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);qS.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?sa(e=>{e.setTime(Math.floor(e/t)*t)},(e,n)=>{e.setTime(+e+n*t)},(e,n)=>(n-e)/t):qS);qS.range;const ku=1e3,al=ku*60,Mu=al*60,Ku=Mu*24,mL=Ku*7,HV=Ku*30,WC=Ku*365,Hf=sa(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*ku)},(t,e)=>(e-t)/ku,t=>t.getUTCSeconds());Hf.range;const pL=sa(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*ku)},(t,e)=>{t.setTime(+t+e*al)},(t,e)=>(e-t)/al,t=>t.getMinutes());pL.range;const gL=sa(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*al)},(t,e)=>(e-t)/al,t=>t.getUTCMinutes());gL.range;const bL=sa(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*ku-t.getMinutes()*al)},(t,e)=>{t.setTime(+t+e*Mu)},(t,e)=>(e-t)/Mu,t=>t.getHours());bL.range;const xL=sa(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*Mu)},(t,e)=>(e-t)/Mu,t=>t.getUTCHours());xL.range;const sv=sa(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*al)/Ku,t=>t.getDate()-1);sv.range;const oM=sa(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Ku,t=>t.getUTCDate()-1);oM.range;const OQ=sa(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Ku,t=>Math.floor(t/Ku));OQ.range;function Fm(t){return sa(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(e,n)=>{e.setDate(e.getDate()+n*7)},(e,n)=>(n-e-(n.getTimezoneOffset()-e.getTimezoneOffset())*al)/mL)}const lM=Fm(0),WS=Fm(1),vje=Fm(2),wje=Fm(3),lb=Fm(4),_je=Fm(5),Sje=Fm(6);lM.range;WS.range;vje.range;wje.range;lb.range;_je.range;Sje.range;function Im(t){return sa(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(e,n)=>{e.setUTCDate(e.getUTCDate()+n*7)},(e,n)=>(n-e)/mL)}const cM=Im(0),KS=Im(1),Nje=Im(2),kje=Im(3),cb=Im(4),Mje=Im(5),Eje=Im(6);cM.range;KS.range;Nje.range;kje.range;cb.range;Mje.range;Eje.range;const yL=sa(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth());yL.range;const vL=sa(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth());vL.range;const Xu=sa(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());Xu.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:sa(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,n)=>{e.setFullYear(e.getFullYear()+n*t)});Xu.range;const Yu=sa(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());Yu.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:sa(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,n)=>{e.setUTCFullYear(e.getUTCFullYear()+n*t)});Yu.range;function LQ(t,e,n,r,i,s){const o=[[Hf,1,ku],[Hf,5,5*ku],[Hf,15,15*ku],[Hf,30,30*ku],[s,1,al],[s,5,5*al],[s,15,15*al],[s,30,30*al],[i,1,Mu],[i,3,3*Mu],[i,6,6*Mu],[i,12,12*Mu],[r,1,Ku],[r,2,2*Ku],[n,1,mL],[e,1,HV],[e,3,3*HV],[t,1,WC]];function l(u,d,h){const p=dx).right(o,p);if(m===o.length)return t.every(bD(u/WC,d/WC,h));if(m===0)return qS.every(Math.max(bD(u,d,h),1));const[b,y]=o[p/o[m-1][2]53)return null;"w"in ce||(ce.w=1),"Z"in ce?(V=XC(e0(ce.y,0,1)),Y=V.getUTCDay(),V=Y>4||Y===0?KS.ceil(V):KS(V),V=oM.offset(V,(ce.V-1)*7),ce.y=V.getUTCFullYear(),ce.m=V.getUTCMonth(),ce.d=V.getUTCDate()+(ce.w+6)%7):(V=KC(e0(ce.y,0,1)),Y=V.getDay(),V=Y>4||Y===0?WS.ceil(V):WS(V),V=sv.offset(V,(ce.V-1)*7),ce.y=V.getFullYear(),ce.m=V.getMonth(),ce.d=V.getDate()+(ce.w+6)%7)}else("W"in ce||"U"in ce)&&("w"in ce||(ce.w="u"in ce?ce.u%7:"W"in ce?1:0),Y="Z"in ce?XC(e0(ce.y,0,1)).getUTCDay():KC(e0(ce.y,0,1)).getDay(),ce.m=0,ce.d="W"in ce?(ce.w+6)%7+ce.W*7-(Y+5)%7:ce.w+ce.U*7-(Y+6)%7);return"Z"in ce?(ce.H+=ce.Z/100|0,ce.M+=ce.Z%100,XC(ce)):KC(ce)}}function R(se,ke,Fe,ce){for(var Ve=0,V=ke.length,Y=Fe.length,ue,q;Ve=Y)return-1;if(ue=ke.charCodeAt(Ve++),ue===37){if(ue=ke.charAt(Ve++),q=M[ue in $V?ke.charAt(Ve++):ue],!q||(ce=q(se,Fe,ce))<0)return-1}else if(ue!=Fe.charCodeAt(ce++))return-1}return ce}function C(se,ke,Fe){var ce=u.exec(ke.slice(Fe));return ce?(se.p=d.get(ce[0].toLowerCase()),Fe+ce[0].length):-1}function P(se,ke,Fe){var ce=m.exec(ke.slice(Fe));return ce?(se.w=b.get(ce[0].toLowerCase()),Fe+ce[0].length):-1}function U(se,ke,Fe){var ce=h.exec(ke.slice(Fe));return ce?(se.w=p.get(ce[0].toLowerCase()),Fe+ce[0].length):-1}function F(se,ke,Fe){var ce=v.exec(ke.slice(Fe));return ce?(se.m=S.get(ce[0].toLowerCase()),Fe+ce[0].length):-1}function H(se,ke,Fe){var ce=y.exec(ke.slice(Fe));return ce?(se.m=x.get(ce[0].toLowerCase()),Fe+ce[0].length):-1}function D(se,ke,Fe){return R(se,e,ke,Fe)}function $(se,ke,Fe){return R(se,n,ke,Fe)}function G(se,ke,Fe){return R(se,r,ke,Fe)}function I(se){return o[se.getDay()]}function K(se){return s[se.getDay()]}function Q(se){return c[se.getMonth()]}function oe(se){return l[se.getMonth()]}function B(se){return i[+(se.getHours()>=12)]}function W(se){return 1+~~(se.getMonth()/3)}function J(se){return o[se.getUTCDay()]}function ne(se){return s[se.getUTCDay()]}function me(se){return c[se.getUTCMonth()]}function fe(se){return l[se.getUTCMonth()]}function de(se){return i[+(se.getUTCHours()>=12)]}function Re(se){return 1+~~(se.getUTCMonth()/3)}return{format:function(se){var ke=A(se+="",N);return ke.toString=function(){return se},ke},parse:function(se){var ke=k(se+="",!1);return ke.toString=function(){return se},ke},utcFormat:function(se){var ke=A(se+="",T);return ke.toString=function(){return se},ke},utcParse:function(se){var ke=k(se+="",!0);return ke.toString=function(){return se},ke}}}var $V={"-":"",_:" ",0:"0"},ka=/^\s*\d+/,Dje=/^%/,Rje=/[\\^$*+?|[\]().{}]/g;function ur(t,e,n){var r=t<0?"-":"",i=(r?-t:t)+"",s=i.length;return r+(s[e.toLowerCase(),n]))}function Lje(t,e,n){var r=ka.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function Fje(t,e,n){var r=ka.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function Ije(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function zje(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function Uje(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function VV(t,e,n){var r=ka.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function GV(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function Bje(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function Hje(t,e,n){var r=ka.exec(e.slice(n,n+1));return r?(t.q=r[0]*3-3,n+r[0].length):-1}function $je(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function qV(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function Vje(t,e,n){var r=ka.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function WV(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function Gje(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function qje(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function Wje(t,e,n){var r=ka.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function Kje(t,e,n){var r=ka.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function Xje(t,e,n){var r=Dje.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function Yje(t,e,n){var r=ka.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function Qje(t,e,n){var r=ka.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function KV(t,e){return ur(t.getDate(),e,2)}function Zje(t,e){return ur(t.getHours(),e,2)}function Jje(t,e){return ur(t.getHours()%12||12,e,2)}function e3e(t,e){return ur(1+sv.count(Xu(t),t),e,3)}function FQ(t,e){return ur(t.getMilliseconds(),e,3)}function t3e(t,e){return FQ(t,e)+"000"}function n3e(t,e){return ur(t.getMonth()+1,e,2)}function r3e(t,e){return ur(t.getMinutes(),e,2)}function i3e(t,e){return ur(t.getSeconds(),e,2)}function a3e(t){var e=t.getDay();return e===0?7:e}function s3e(t,e){return ur(lM.count(Xu(t)-1,t),e,2)}function IQ(t){var e=t.getDay();return e>=4||e===0?lb(t):lb.ceil(t)}function o3e(t,e){return t=IQ(t),ur(lb.count(Xu(t),t)+(Xu(t).getDay()===4),e,2)}function l3e(t){return t.getDay()}function c3e(t,e){return ur(WS.count(Xu(t)-1,t),e,2)}function u3e(t,e){return ur(t.getFullYear()%100,e,2)}function d3e(t,e){return t=IQ(t),ur(t.getFullYear()%100,e,2)}function h3e(t,e){return ur(t.getFullYear()%1e4,e,4)}function f3e(t,e){var n=t.getDay();return t=n>=4||n===0?lb(t):lb.ceil(t),ur(t.getFullYear()%1e4,e,4)}function m3e(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+ur(e/60|0,"0",2)+ur(e%60,"0",2)}function XV(t,e){return ur(t.getUTCDate(),e,2)}function p3e(t,e){return ur(t.getUTCHours(),e,2)}function g3e(t,e){return ur(t.getUTCHours()%12||12,e,2)}function b3e(t,e){return ur(1+oM.count(Yu(t),t),e,3)}function zQ(t,e){return ur(t.getUTCMilliseconds(),e,3)}function x3e(t,e){return zQ(t,e)+"000"}function y3e(t,e){return ur(t.getUTCMonth()+1,e,2)}function v3e(t,e){return ur(t.getUTCMinutes(),e,2)}function w3e(t,e){return ur(t.getUTCSeconds(),e,2)}function _3e(t){var e=t.getUTCDay();return e===0?7:e}function S3e(t,e){return ur(cM.count(Yu(t)-1,t),e,2)}function UQ(t){var e=t.getUTCDay();return e>=4||e===0?cb(t):cb.ceil(t)}function N3e(t,e){return t=UQ(t),ur(cb.count(Yu(t),t)+(Yu(t).getUTCDay()===4),e,2)}function k3e(t){return t.getUTCDay()}function M3e(t,e){return ur(KS.count(Yu(t)-1,t),e,2)}function E3e(t,e){return ur(t.getUTCFullYear()%100,e,2)}function T3e(t,e){return t=UQ(t),ur(t.getUTCFullYear()%100,e,2)}function A3e(t,e){return ur(t.getUTCFullYear()%1e4,e,4)}function C3e(t,e){var n=t.getUTCDay();return t=n>=4||n===0?cb(t):cb.ceil(t),ur(t.getUTCFullYear()%1e4,e,4)}function P3e(){return"+0000"}function YV(){return"%"}function QV(t){return+t}function ZV(t){return Math.floor(+t/1e3)}var eg,BQ,HQ;j3e({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function j3e(t){return eg=jje(t),BQ=eg.format,eg.parse,HQ=eg.utcFormat,eg.utcParse,eg}function D3e(t){return new Date(t)}function R3e(t){return t instanceof Date?+t:+new Date(+t)}function wL(t,e,n,r,i,s,o,l,c,u){var d=oL(),h=d.invert,p=d.domain,m=u(".%L"),b=u(":%S"),y=u("%I:%M"),x=u("%I %p"),v=u("%a %d"),S=u("%b %d"),N=u("%B"),T=u("%Y");function M(A){return(c(A)e(i/(t.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(i,s)=>_Pe(t,s/r))},n.copy=function(){return qQ(e).domain(t)},nd.apply(n,arguments)}function dM(){var t=0,e=.5,n=1,r=1,i,s,o,l,c,u=ws,d,h=!1,p;function m(y){return isNaN(y=+y)?p:(y=.5+((y=+d(y))-s)*(r*yt.chartData,NL=st([Gh],t=>{var e=t.chartData!=null?t.chartData.length-1:0;return{chartData:t.chartData,computedData:t.computedData,dataEndIndex:e,dataStartIndex:0}}),ov=(t,e,n,r)=>r?NL(t):Gh(t);function Lh(t){if(Array.isArray(t)&&t.length===2){var[e,n]=t;if(wr(e)&&wr(n))return!0}return!1}function JV(t,e,n){return n?t:[Math.min(t[0],e[0]),Math.max(t[1],e[1])]}function YQ(t,e){if(e&&typeof t!="function"&&Array.isArray(t)&&t.length===2){var[n,r]=t,i,s;if(wr(n))i=n;else if(typeof n=="function")return;if(wr(r))s=r;else if(typeof r=="function")return;var o=[i,s];if(Lh(o))return o}}function z3e(t,e,n){if(!(!n&&e==null)){if(typeof t=="function"&&e!=null)try{var r=t(e,n);if(Lh(r))return JV(r,e,n)}catch{}if(Array.isArray(t)&&t.length===2){var[i,s]=t,o,l;if(i==="auto")e!=null&&(o=Math.min(...e));else if(Vt(i))o=i;else if(typeof i=="function")try{e!=null&&(o=i(e?.[0]))}catch{}else if(typeof i=="string"&&E$.test(i)){var c=E$.exec(i);if(c==null||e==null)o=void 0;else{var u=+c[1];o=e[0]-u}}else o=e?.[0];if(s==="auto")e!=null&&(l=Math.max(...e));else if(Vt(s))l=s;else if(typeof s=="function")try{e!=null&&(l=s(e?.[1]))}catch{}else if(typeof s=="string"&&T$.test(s)){var d=T$.exec(s);if(d==null||e==null)l=void 0;else{var h=+d[1];l=e[1]+h}}else l=e?.[1];var p=[o,l];if(Lh(p))return e==null?p:JV(p,e,n)}}}var Db=1e9,U3e={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},ML,ni=!0,pl="[DecimalError] ",tm=pl+"Invalid argument: ",kL=pl+"Exponent out of range: ",Rb=Math.floor,Cf=Math.pow,B3e=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,go,xa=1e7,Kr=7,QQ=9007199254740991,XS=Rb(QQ/Kr),qt={};qt.absoluteValue=qt.abs=function(){var t=new this.constructor(this);return t.s&&(t.s=1),t};qt.comparedTo=qt.cmp=function(t){var e,n,r,i,s=this;if(t=new s.constructor(t),s.s!==t.s)return s.s||-t.s;if(s.e!==t.e)return s.e>t.e^s.s<0?1:-1;for(r=s.d.length,i=t.d.length,e=0,n=rt.d[e]^s.s<0?1:-1;return r===i?0:r>i^s.s<0?1:-1};qt.decimalPlaces=qt.dp=function(){var t=this,e=t.d.length-1,n=(e-t.e)*Kr;if(e=t.d[e],e)for(;e%10==0;e/=10)n--;return n<0?0:n};qt.dividedBy=qt.div=function(t){return Du(this,new this.constructor(t))};qt.dividedToIntegerBy=qt.idiv=function(t){var e=this,n=e.constructor;return Fr(Du(e,new n(t),0,1),n.precision)};qt.equals=qt.eq=function(t){return!this.cmp(t)};qt.exponent=function(){return Gi(this)};qt.greaterThan=qt.gt=function(t){return this.cmp(t)>0};qt.greaterThanOrEqualTo=qt.gte=function(t){return this.cmp(t)>=0};qt.isInteger=qt.isint=function(){return this.e>this.d.length-2};qt.isNegative=qt.isneg=function(){return this.s<0};qt.isPositive=qt.ispos=function(){return this.s>0};qt.isZero=function(){return this.s===0};qt.lessThan=qt.lt=function(t){return this.cmp(t)<0};qt.lessThanOrEqualTo=qt.lte=function(t){return this.cmp(t)<1};qt.logarithm=qt.log=function(t){var e,n=this,r=n.constructor,i=r.precision,s=i+5;if(t===void 0)t=new r(10);else if(t=new r(t),t.s<1||t.eq(go))throw Error(pl+"NaN");if(n.s<1)throw Error(pl+(n.s?"NaN":"-Infinity"));return n.eq(go)?new r(0):(ni=!1,e=Du(_y(n,s),_y(t,s),s),ni=!0,Fr(e,i))};qt.minus=qt.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?eZ(e,t):ZQ(e,(t.s=-t.s,t))};qt.modulo=qt.mod=function(t){var e,n=this,r=n.constructor,i=r.precision;if(t=new r(t),!t.s)throw Error(pl+"NaN");return n.s?(ni=!1,e=Du(n,t,0,1).times(t),ni=!0,n.minus(e)):Fr(new r(n),i)};qt.naturalExponential=qt.exp=function(){return JQ(this)};qt.naturalLogarithm=qt.ln=function(){return _y(this)};qt.negated=qt.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};qt.plus=qt.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?ZQ(e,t):eZ(e,(t.s=-t.s,t))};qt.precision=qt.sd=function(t){var e,n,r,i=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(tm+t);if(e=Gi(i)+1,r=i.d.length-1,n=r*Kr+1,r=i.d[r],r){for(;r%10==0;r/=10)n--;for(r=i.d[0];r>=10;r/=10)n++}return t&&e>n?e:n};qt.squareRoot=qt.sqrt=function(){var t,e,n,r,i,s,o,l=this,c=l.constructor;if(l.s<1){if(!l.s)return new c(0);throw Error(pl+"NaN")}for(t=Gi(l),ni=!1,i=Math.sqrt(+l),i==0||i==1/0?(e=uc(l.d),(e.length+t)%2==0&&(e+="0"),i=Math.sqrt(e),t=Rb((t+1)/2)-(t<0||t%2),i==1/0?e="5e"+t:(e=i.toExponential(),e=e.slice(0,e.indexOf("e")+1)+t),r=new c(e)):r=new c(i.toString()),n=c.precision,i=o=n+3;;)if(s=r,r=s.plus(Du(l,s,o+2)).times(.5),uc(s.d).slice(0,o)===(e=uc(r.d)).slice(0,o)){if(e=e.slice(o-3,o+1),i==o&&e=="4999"){if(Fr(s,n+1,0),s.times(s).eq(l)){r=s;break}}else if(e!="9999")break;o+=4}return ni=!0,Fr(r,n)};qt.times=qt.mul=function(t){var e,n,r,i,s,o,l,c,u,d=this,h=d.constructor,p=d.d,m=(t=new h(t)).d;if(!d.s||!t.s)return new h(0);for(t.s*=d.s,n=d.e+t.e,c=p.length,u=m.length,c=0;){for(e=0,i=c+r;i>r;)l=s[i]+m[r]*p[i-r-1]+e,s[i--]=l%xa|0,e=l/xa|0;s[i]=(s[i]+e)%xa|0}for(;!s[--o];)s.pop();return e?++n:s.shift(),t.d=s,t.e=n,ni?Fr(t,h.precision):t};qt.toDecimalPlaces=qt.todp=function(t,e){var n=this,r=n.constructor;return n=new r(n),t===void 0?n:(vc(t,0,Db),e===void 0?e=r.rounding:vc(e,0,8),Fr(n,t+Gi(n)+1,e))};qt.toExponential=function(t,e){var n,r=this,i=r.constructor;return t===void 0?n=Nm(r,!0):(vc(t,0,Db),e===void 0?e=i.rounding:vc(e,0,8),r=Fr(new i(r),t+1,e),n=Nm(r,!0,t+1)),n};qt.toFixed=function(t,e){var n,r,i=this,s=i.constructor;return t===void 0?Nm(i):(vc(t,0,Db),e===void 0?e=s.rounding:vc(e,0,8),r=Fr(new s(i),t+Gi(i)+1,e),n=Nm(r.abs(),!1,t+Gi(r)+1),i.isneg()&&!i.isZero()?"-"+n:n)};qt.toInteger=qt.toint=function(){var t=this,e=t.constructor;return Fr(new e(t),Gi(t)+1,e.rounding)};qt.toNumber=function(){return+this};qt.toPower=qt.pow=function(t){var e,n,r,i,s,o,l=this,c=l.constructor,u=12,d=+(t=new c(t));if(!t.s)return new c(go);if(l=new c(l),!l.s){if(t.s<1)throw Error(pl+"Infinity");return l}if(l.eq(go))return l;if(r=c.precision,t.eq(go))return Fr(l,r);if(e=t.e,n=t.d.length-1,o=e>=n,s=l.s,o){if((n=d<0?-d:d)<=QQ){for(i=new c(go),e=Math.ceil(r/Kr+4),ni=!1;n%2&&(i=i.times(l),tG(i.d,e)),n=Rb(n/2),n!==0;)l=l.times(l),tG(l.d,e);return ni=!0,t.s<0?new c(go).div(i):Fr(i,r)}}else if(s<0)throw Error(pl+"NaN");return s=s<0&&t.d[Math.max(e,n)]&1?-1:1,l.s=1,ni=!1,i=t.times(_y(l,r+u)),ni=!0,i=JQ(i),i.s=s,i};qt.toPrecision=function(t,e){var n,r,i=this,s=i.constructor;return t===void 0?(n=Gi(i),r=Nm(i,n<=s.toExpNeg||n>=s.toExpPos)):(vc(t,1,Db),e===void 0?e=s.rounding:vc(e,0,8),i=Fr(new s(i),t,e),n=Gi(i),r=Nm(i,t<=n||n<=s.toExpNeg,t)),r};qt.toSignificantDigits=qt.tosd=function(t,e){var n=this,r=n.constructor;return t===void 0?(t=r.precision,e=r.rounding):(vc(t,1,Db),e===void 0?e=r.rounding:vc(e,0,8)),Fr(new r(n),t,e)};qt.toString=qt.valueOf=qt.val=qt.toJSON=qt[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=Gi(t),n=t.constructor;return Nm(t,e<=n.toExpNeg||e>=n.toExpPos)};function ZQ(t,e){var n,r,i,s,o,l,c,u,d=t.constructor,h=d.precision;if(!t.s||!e.s)return e.s||(e=new d(t)),ni?Fr(e,h):e;if(c=t.d,u=e.d,o=t.e,i=e.e,c=c.slice(),s=o-i,s){for(s<0?(r=c,s=-s,l=u.length):(r=u,i=o,l=c.length),o=Math.ceil(h/Kr),l=o>l?o+1:l+1,s>l&&(s=l,r.length=1),r.reverse();s--;)r.push(0);r.reverse()}for(l=c.length,s=u.length,l-s<0&&(s=l,r=u,u=c,c=r),n=0;s;)n=(c[--s]=c[s]+u[s]+n)/xa|0,c[s]%=xa;for(n&&(c.unshift(n),++i),l=c.length;c[--l]==0;)c.pop();return e.d=c,e.e=i,ni?Fr(e,h):e}function vc(t,e,n){if(t!==~~t||tn)throw Error(tm+t)}function uc(t){var e,n,r,i=t.length-1,s="",o=t[0];if(i>0){for(s+=o,e=1;eo?1:-1;else for(l=c=0;li[l]?1:-1;break}return c}function n(r,i,s){for(var o=0;s--;)r[s]-=o,o=r[s]1;)r.shift()}return function(r,i,s,o){var l,c,u,d,h,p,m,b,y,x,v,S,N,T,M,A,k,R,C=r.constructor,P=r.s==i.s?1:-1,U=r.d,F=i.d;if(!r.s)return new C(r);if(!i.s)throw Error(pl+"Division by zero");for(c=r.e-i.e,k=F.length,M=U.length,m=new C(P),b=m.d=[],u=0;F[u]==(U[u]||0);)++u;if(F[u]>(U[u]||0)&&--c,s==null?S=s=C.precision:o?S=s+(Gi(r)-Gi(i))+1:S=s,S<0)return new C(0);if(S=S/Kr+2|0,u=0,k==1)for(d=0,F=F[0],S++;(u1&&(F=t(F,d),U=t(U,d),k=F.length,M=U.length),T=k,y=U.slice(0,k),x=y.length;x=xa/2&&++A;do d=0,l=e(F,y,k,x),l<0?(v=y[0],k!=x&&(v=v*xa+(y[1]||0)),d=v/A|0,d>1?(d>=xa&&(d=xa-1),h=t(F,d),p=h.length,x=y.length,l=e(h,y,p,x),l==1&&(d--,n(h,k16)throw Error(kL+Gi(t));if(!t.s)return new d(go);for(ni=!1,l=h,o=new d(.03125);t.abs().gte(.1);)t=t.times(o),u+=5;for(r=Math.log(Cf(2,u))/Math.LN10*2+5|0,l+=r,n=i=s=new d(go),d.precision=l;;){if(i=Fr(i.times(t),l),n=n.times(++c),o=s.plus(Du(i,n,l)),uc(o.d).slice(0,l)===uc(s.d).slice(0,l)){for(;u--;)s=Fr(s.times(s),l);return d.precision=h,e==null?(ni=!0,Fr(s,h)):s}s=o}}function Gi(t){for(var e=t.e*Kr,n=t.d[0];n>=10;n/=10)e++;return e}function YC(t,e,n){if(e>t.LN10.sd())throw ni=!0,n&&(t.precision=n),Error(pl+"LN10 precision limit exceeded");return Fr(new t(t.LN10),e)}function Qd(t){for(var e="";t--;)e+="0";return e}function _y(t,e){var n,r,i,s,o,l,c,u,d,h=1,p=10,m=t,b=m.d,y=m.constructor,x=y.precision;if(m.s<1)throw Error(pl+(m.s?"NaN":"-Infinity"));if(m.eq(go))return new y(0);if(e==null?(ni=!1,u=x):u=e,m.eq(10))return e==null&&(ni=!0),YC(y,u);if(u+=p,y.precision=u,n=uc(b),r=n.charAt(0),s=Gi(m),Math.abs(s)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)m=m.times(t),n=uc(m.d),r=n.charAt(0),h++;s=Gi(m),r>1?(m=new y("0."+n),s++):m=new y(r+"."+n.slice(1))}else return c=YC(y,u+2,x).times(s+""),m=_y(new y(r+"."+n.slice(1)),u-p).plus(c),y.precision=x,e==null?(ni=!0,Fr(m,x)):m;for(l=o=m=Du(m.minus(go),m.plus(go),u),d=Fr(m.times(m),u),i=3;;){if(o=Fr(o.times(d),u),c=l.plus(Du(o,new y(i),u)),uc(c.d).slice(0,u)===uc(l.d).slice(0,u))return l=l.times(2),s!==0&&(l=l.plus(YC(y,u+2,x).times(s+""))),l=Du(l,new y(h),u),y.precision=x,e==null?(ni=!0,Fr(l,x)):l;l=c,i+=2}}function eG(t,e){var n,r,i;for((n=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(n<0&&(n=r),n+=+e.slice(r+1),e=e.substring(0,r)):n<0&&(n=e.length),r=0;e.charCodeAt(r)===48;)++r;for(i=e.length;e.charCodeAt(i-1)===48;)--i;if(e=e.slice(r,i),e){if(i-=r,n=n-r-1,t.e=Rb(n/Kr),t.d=[],r=(n+1)%Kr,n<0&&(r+=Kr),rXS||t.e<-XS))throw Error(kL+n)}else t.s=0,t.e=0,t.d=[0];return t}function Fr(t,e,n){var r,i,s,o,l,c,u,d,h=t.d;for(o=1,s=h[0];s>=10;s/=10)o++;if(r=e-o,r<0)r+=Kr,i=e,u=h[d=0];else{if(d=Math.ceil((r+1)/Kr),s=h.length,d>=s)return t;for(u=s=h[d],o=1;s>=10;s/=10)o++;r%=Kr,i=r-Kr+o}if(n!==void 0&&(s=Cf(10,o-i-1),l=u/s%10|0,c=e<0||h[d+1]!==void 0||u%s,c=n<4?(l||c)&&(n==0||n==(t.s<0?3:2)):l>5||l==5&&(n==4||c||n==6&&(r>0?i>0?u/Cf(10,o-i):0:h[d-1])%10&1||n==(t.s<0?8:7))),e<1||!h[0])return c?(s=Gi(t),h.length=1,e=e-s-1,h[0]=Cf(10,(Kr-e%Kr)%Kr),t.e=Rb(-e/Kr)||0):(h.length=1,h[0]=t.e=t.s=0),t;if(r==0?(h.length=d,s=1,d--):(h.length=d+1,s=Cf(10,Kr-r),h[d]=i>0?(u/Cf(10,o-i)%Cf(10,i)|0)*s:0),c)for(;;)if(d==0){(h[0]+=s)==xa&&(h[0]=1,++t.e);break}else{if(h[d]+=s,h[d]!=xa)break;h[d--]=0,s=1}for(r=h.length;h[--r]===0;)h.pop();if(ni&&(t.e>XS||t.e<-XS))throw Error(kL+Gi(t));return t}function eZ(t,e){var n,r,i,s,o,l,c,u,d,h,p=t.constructor,m=p.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new p(t),ni?Fr(e,m):e;if(c=t.d,h=e.d,r=e.e,u=t.e,c=c.slice(),o=u-r,o){for(d=o<0,d?(n=c,o=-o,l=h.length):(n=h,r=u,l=c.length),i=Math.max(Math.ceil(m/Kr),l)+2,o>i&&(o=i,n.length=1),n.reverse(),i=o;i--;)n.push(0);n.reverse()}else{for(i=c.length,l=h.length,d=i0;--i)c[l++]=0;for(i=h.length;i>o;){if(c[--i]0?s=s.charAt(0)+"."+s.slice(1)+Qd(r):o>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(i<0?"e":"e+")+i):i<0?(s="0."+Qd(-i-1)+s,n&&(r=n-o)>0&&(s+=Qd(r))):i>=o?(s+=Qd(i+1-o),n&&(r=n-i-1)>0&&(s=s+"."+Qd(r))):((r=i+1)0&&(i+1===o&&(s+="."),s+=Qd(r))),t.s<0?"-"+s:s}function tG(t,e){if(t.length>e)return t.length=e,!0}function tZ(t){var e,n,r;function i(s){var o=this;if(!(o instanceof i))return new i(s);if(o.constructor=i,s instanceof i){o.s=s.s,o.e=s.e,o.d=(s=s.d)?s.slice():s;return}if(typeof s=="number"){if(s*0!==0)throw Error(tm+s);if(s>0)o.s=1;else if(s<0)s=-s,o.s=-1;else{o.s=0,o.e=0,o.d=[0];return}if(s===~~s&&s<1e7){o.e=0,o.d=[s];return}return eG(o,s.toString())}else if(typeof s!="string")throw Error(tm+s);if(s.charCodeAt(0)===45?(s=s.slice(1),o.s=-1):o.s=1,B3e.test(s))eG(o,s);else throw Error(tm+s)}if(i.prototype=qt,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=tZ,i.config=i.set=H3e,t===void 0&&(t={}),t)for(r=["precision","rounding","toExpNeg","toExpPos","LN10"],e=0;e=i[e+1]&&r<=i[e+2])this[n]=r;else throw Error(tm+n+": "+r);if((r=t[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(tm+n+": "+r);return this}var ML=tZ(U3e);go=new ML(1);const yr=ML;var $3e=t=>t,nZ={},rZ=t=>t===nZ,nG=t=>function e(){return arguments.length===0||arguments.length===1&&rZ(arguments.length<=0?void 0:arguments[0])?e:t(...arguments)},iZ=(t,e)=>t===1?e:nG(function(){for(var n=arguments.length,r=new Array(n),i=0;io!==nZ).length;return s>=t?e(...r):iZ(t-s,nG(function(){for(var o=arguments.length,l=new Array(o),c=0;crZ(d)?l.shift():d);return e(...u,...l)}))}),V3e=t=>iZ(t.length,t),_D=(t,e)=>{for(var n=[],r=t;rArray.isArray(e)?e.map(t):Object.keys(e).map(n=>e[n]).map(t)),q3e=function(){for(var e=arguments.length,n=new Array(e),r=0;rc(l),s(...arguments))}},SD=t=>Array.isArray(t)?t.reverse():t.split("").reverse().join("");function aZ(t){var e;return t===0?e=1:e=Math.floor(new yr(t).abs().log(10).toNumber())+1,e}function sZ(t,e,n){for(var r=new yr(t),i=0,s=[];r.lt(e)&&i<1e5;)s.push(r.toNumber()),r=r.add(n),i++;return s}var oZ=t=>{var[e,n]=t,[r,i]=[e,n];return e>n&&([r,i]=[n,e]),[r,i]},lZ=(t,e,n)=>{if(t.lte(0))return new yr(0);var r=aZ(t.toNumber()),i=new yr(10).pow(r),s=t.div(i),o=r!==1?.05:.1,l=new yr(Math.ceil(s.div(o).toNumber())).add(n).mul(o),c=l.mul(i);return e?new yr(c.toNumber()):new yr(Math.ceil(c.toNumber()))},W3e=(t,e,n)=>{var r=new yr(1),i=new yr(t);if(!i.isint()&&n){var s=Math.abs(t);s<1?(r=new yr(10).pow(aZ(t)-1),i=new yr(Math.floor(i.div(r).toNumber())).mul(r)):s>1&&(i=new yr(Math.floor(t)))}else t===0?i=new yr(Math.floor((e-1)/2)):n||(i=new yr(Math.floor(t)));var o=Math.floor((e-1)/2),l=q3e(G3e(c=>i.add(new yr(c-o).mul(r)).toNumber()),_D);return l(0,e)},cZ=function(e,n,r,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((n-e)/(r-1)))return{step:new yr(0),tickMin:new yr(0),tickMax:new yr(0)};var o=lZ(new yr(n).sub(e).div(r-1),i,s),l;e<=0&&n>=0?l=new yr(0):(l=new yr(e).add(n).div(2),l=l.sub(new yr(l).mod(o)));var c=Math.ceil(l.sub(e).div(o).toNumber()),u=Math.ceil(new yr(n).sub(l).div(o).toNumber()),d=c+u+1;return d>r?cZ(e,n,r,i,s+1):(d0?u+(r-d):u,c=n>0?c:c+(r-d)),{step:o,tickMin:l.sub(new yr(c).mul(o)),tickMax:l.add(new yr(u).mul(o))})},K3e=function(e){var[n,r]=e,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=Math.max(i,2),[l,c]=oZ([n,r]);if(l===-1/0||c===1/0){var u=c===1/0?[l,..._D(0,i-1).map(()=>1/0)]:[..._D(0,i-1).map(()=>-1/0),c];return n>r?SD(u):u}if(l===c)return W3e(l,i,s);var{step:d,tickMin:h,tickMax:p}=cZ(l,c,o,s,0),m=sZ(h,p.add(new yr(.1).mul(d)),d);return n>r?SD(m):m},X3e=function(e,n){var[r,i]=e,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,[o,l]=oZ([r,i]);if(o===-1/0||l===1/0)return[r,i];if(o===l)return[o];var c=Math.max(n,2),u=lZ(new yr(l).sub(o).div(c-1),s,0),d=[...sZ(new yr(o),new yr(l),u),l];return s===!1&&(d=d.map(h=>Math.round(h))),r>i?SD(d):d},uZ=t=>t.rootProps.maxBarSize,Y3e=t=>t.rootProps.barGap,dZ=t=>t.rootProps.barCategoryGap,Q3e=t=>t.rootProps.barSize,lv=t=>t.rootProps.stackOffset,hZ=t=>t.rootProps.reverseStackOrder,EL=t=>t.options.chartName,TL=t=>t.rootProps.syncId,fZ=t=>t.rootProps.syncMethod,AL=t=>t.options.eventEmitter,Z3e=t=>t.rootProps.baseValue,vi={grid:-100,barBackground:-50,area:100,cursorRectangle:200,bar:300,line:400,axis:500,scatter:600,activeBar:1e3,cursorLine:1100,activeDot:1200,label:2e3},xu={allowDuplicatedCategory:!0,angleAxisId:0,reversed:!1,scale:"auto",tick:!0,type:"category"},mo={allowDataOverflow:!1,allowDuplicatedCategory:!0,radiusAxisId:0,scale:"auto",tick:!0,tickCount:5,type:"number"},hM=(t,e)=>{if(!(!t||!e))return t!=null&&t.reversed?[e[1],e[0]]:e},J3e={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:!1,dataKey:void 0,domain:void 0,id:xu.angleAxisId,includeHidden:!1,name:void 0,reversed:xu.reversed,scale:xu.scale,tick:xu.tick,tickCount:void 0,ticks:void 0,type:xu.type,unit:void 0},eDe={allowDataOverflow:mo.allowDataOverflow,allowDecimals:!1,allowDuplicatedCategory:mo.allowDuplicatedCategory,dataKey:void 0,domain:void 0,id:mo.radiusAxisId,includeHidden:!1,name:void 0,reversed:!1,scale:mo.scale,tick:mo.tick,tickCount:mo.tickCount,ticks:void 0,type:mo.type,unit:void 0},tDe={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:xu.allowDuplicatedCategory,dataKey:void 0,domain:void 0,id:xu.angleAxisId,includeHidden:!1,name:void 0,reversed:!1,scale:xu.scale,tick:xu.tick,tickCount:void 0,ticks:void 0,type:"number",unit:void 0},nDe={allowDataOverflow:mo.allowDataOverflow,allowDecimals:!1,allowDuplicatedCategory:mo.allowDuplicatedCategory,dataKey:void 0,domain:void 0,id:mo.radiusAxisId,includeHidden:!1,name:void 0,reversed:!1,scale:mo.scale,tick:mo.tick,tickCount:mo.tickCount,ticks:void 0,type:"category",unit:void 0},CL=(t,e)=>t.polarAxis.angleAxis[e]!=null?t.polarAxis.angleAxis[e]:t.layout.layoutType==="radial"?tDe:J3e,PL=(t,e)=>t.polarAxis.radiusAxis[e]!=null?t.polarAxis.radiusAxis[e]:t.layout.layoutType==="radial"?nDe:eDe,fM=t=>t.polarOptions,jL=st([ed,td,ia],dQ),mZ=st([fM,jL],(t,e)=>{if(t!=null)return as(t.innerRadius,e,0)}),pZ=st([fM,jL],(t,e)=>{if(t!=null)return as(t.outerRadius,e,e*.8)}),rDe=t=>{if(t==null)return[0,0];var{startAngle:e,endAngle:n}=t;return[e,n]},gZ=st([fM],rDe);st([CL,gZ],hM);var bZ=st([jL,mZ,pZ],(t,e,n)=>{if(!(t==null||e==null||n==null))return[e,n]});st([PL,bZ],hM);var xZ=st([Kn,fM,mZ,pZ,ed,td],(t,e,n,r,i,s)=>{if(!(t!=="centric"&&t!=="radial"||e==null||n==null||r==null)){var{cx:o,cy:l,startAngle:c,endAngle:u}=e;return{cx:as(o,i,i/2),cy:as(l,s,s/2),innerRadius:n,outerRadius:r,startAngle:c,endAngle:u,clockWise:!1}}}),ii=(t,e)=>e,cv=(t,e,n)=>n;function mM(t){return t?.id}function yZ(t,e,n){var{chartData:r=[]}=e,{allowDuplicatedCategory:i,dataKey:s}=n,o=new Map;return t.forEach(l=>{var c,u=(c=l.data)!==null&&c!==void 0?c:r;if(!(u==null||u.length===0)){var d=mM(l);u.forEach((h,p)=>{var m=s==null||i?p:String(vr(h,s,null)),b=vr(h,l.dataKey,0),y;o.has(m)?y=o.get(m):y={},Object.assign(y,{[d]:b}),o.set(m,y)})}}),Array.from(o.values())}function pM(t){return t.stackId!=null&&t.dataKey!=null}var gM=(t,e)=>t===e?!0:t==null||e==null?!1:t[0]===e[0]&&t[1]===e[1];function bM(t,e){return Array.isArray(t)&&Array.isArray(e)&&t.length===0&&e.length===0?!0:t===e}function iDe(t,e){if(t.length===e.length){for(var n=0;n{var e=Kn(t);return e==="horizontal"?"xAxis":e==="vertical"?"yAxis":e==="centric"?"angleAxis":"radiusAxis"},Ob=t=>t.tooltip.settings.axisId;function rG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function YS(t){for(var e=1;et.cartesianAxis.xAxis[e],Ac=(t,e)=>{var n=vZ(t,e);return n??ga},ba={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:ND,hide:!0,id:0,includeHidden:!1,interval:"preserveEnd",minTickGap:5,mirror:!1,name:void 0,orientation:"left",padding:{top:0,bottom:0},reversed:!1,scale:"auto",tick:!0,tickCount:5,tickFormatter:void 0,ticks:void 0,type:"number",unit:void 0,width:ev},wZ=(t,e)=>t.cartesianAxis.yAxis[e],Cc=(t,e)=>{var n=wZ(t,e);return n??ba},lDe={domain:[0,"auto"],includeHidden:!1,reversed:!1,allowDataOverflow:!1,allowDuplicatedCategory:!1,dataKey:void 0,id:0,name:"",range:[64,64],scale:"auto",type:"number",unit:""},DL=(t,e)=>{var n=t.cartesianAxis.zAxis[e];return n??lDe},ui=(t,e,n)=>{switch(e){case"xAxis":return Ac(t,n);case"yAxis":return Cc(t,n);case"zAxis":return DL(t,n);case"angleAxis":return CL(t,n);case"radiusAxis":return PL(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},cDe=(t,e,n)=>{switch(e){case"xAxis":return Ac(t,n);case"yAxis":return Cc(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},uv=(t,e,n)=>{switch(e){case"xAxis":return Ac(t,n);case"yAxis":return Cc(t,n);case"angleAxis":return CL(t,n);case"radiusAxis":return PL(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},_Z=t=>t.graphicalItems.cartesianItems.some(e=>e.type==="bar")||t.graphicalItems.polarItems.some(e=>e.type==="radialBar");function RL(t,e){return n=>{switch(t){case"xAxis":return"xAxisId"in n&&n.xAxisId===e;case"yAxis":return"yAxisId"in n&&n.yAxisId===e;case"zAxis":return"zAxisId"in n&&n.zAxisId===e;case"angleAxis":return"angleAxisId"in n&&n.angleAxisId===e;case"radiusAxis":return"radiusAxisId"in n&&n.radiusAxisId===e;default:return!1}}}var dv=t=>t.graphicalItems.cartesianItems,uDe=st([ii,cv],RL),OL=(t,e,n)=>t.filter(n).filter(r=>e?.includeHidden===!0?!0:!r.hide),hv=st([dv,ui,uDe],OL,{memoizeOptions:{resultEqualityCheck:bM}}),SZ=st([hv],t=>t.filter(e=>e.type==="area"||e.type==="bar").filter(pM)),NZ=t=>t.filter(e=>!("stackId"in e)||e.stackId===void 0),dDe=st([hv],NZ),LL=t=>t.map(e=>e.data).filter(Boolean).flat(1),hDe=st([hv],LL,{memoizeOptions:{resultEqualityCheck:bM}}),FL=(t,e)=>{var{chartData:n=[],dataStartIndex:r,dataEndIndex:i}=e;return t.length>0?t:n.slice(r,i+1)},IL=st([hDe,ov],FL),zL=(t,e,n)=>e?.dataKey!=null?t.map(r=>({value:vr(r,e.dataKey)})):n.length>0?n.map(r=>r.dataKey).flatMap(r=>t.map(i=>({value:vr(i,r)}))):t.map(r=>({value:r})),xM=st([IL,ui,hv],zL);function kZ(t,e){switch(t){case"xAxis":return e.direction==="x";case"yAxis":return e.direction==="y";default:return!1}}function I1(t){if(fl(t)||t instanceof Date){var e=Number(t);if(wr(e))return e}}function iG(t){if(Array.isArray(t)){var e=[I1(t[0]),I1(t[1])];return Lh(e)?e:void 0}var n=I1(t);if(n!=null)return[n,n]}function Qu(t){return t.map(I1).filter(c2e)}function fDe(t,e,n){return!n||typeof e!="number"||Ys(e)?[]:n.length?Qu(n.flatMap(r=>{var i=vr(t,r.dataKey),s,o;if(Array.isArray(i)?[s,o]=i:s=o=i,!(!wr(s)||!wr(o)))return[e-s,e+o]})):[]}var la=t=>{var e=oa(t),n=Ob(t);return uv(t,e,n)},fv=st([la],t=>t?.dataKey),mDe=st([SZ,ov,la],yZ),MZ=(t,e,n,r)=>{var i={},s=e.reduce((o,l)=>(l.stackId==null||(o[l.stackId]==null&&(o[l.stackId]=[]),o[l.stackId].push(l)),o),i);return Object.fromEntries(Object.entries(s).map(o=>{var[l,c]=o,u=r?[...c].reverse():c,d=u.map(mM);return[l,{stackedData:DTe(t,d,n),graphicalItems:u}]}))},Sy=st([mDe,SZ,lv,hZ],MZ),EZ=(t,e,n,r)=>{var{dataStartIndex:i,dataEndIndex:s}=e;if(r==null&&n!=="zAxis"){var o=FTe(t,i,s);if(!(o!=null&&o[0]===0&&o[1]===0))return o}},pDe=st([ui],t=>t.allowDataOverflow),UL=t=>{var e;if(t==null||!("domain"in t))return ND;if(t.domain!=null)return t.domain;if(t.ticks!=null){if(t.type==="number"){var n=Qu(t.ticks);return[Math.min(...n),Math.max(...n)]}if(t.type==="category")return t.ticks.map(String)}return(e=t?.domain)!==null&&e!==void 0?e:ND},BL=st([ui],UL),HL=st([BL,pDe],YQ),gDe=st([Sy,Gh,ii,HL],EZ,{memoizeOptions:{resultEqualityCheck:gM}}),yM=t=>t.errorBars,bDe=(t,e,n)=>t.flatMap(r=>e[r.id]).filter(Boolean).filter(r=>kZ(n,r)),QS=function(){for(var e=arguments.length,n=new Array(e),r=0;r{var s,o;if(n.length>0&&t.forEach(l=>{n.forEach(c=>{var u,d,h=(u=r[c.id])===null||u===void 0?void 0:u.filter(v=>kZ(i,v)),p=vr(l,(d=e.dataKey)!==null&&d!==void 0?d:c.dataKey),m=fDe(l,p,h);if(m.length>=2){var b=Math.min(...m),y=Math.max(...m);(s==null||bo)&&(o=y)}var x=iG(p);x!=null&&(s=s==null?x[0]:Math.min(s,x[0]),o=o==null?x[1]:Math.max(o,x[1]))})}),e?.dataKey!=null&&t.forEach(l=>{var c=iG(vr(l,e.dataKey));c!=null&&(s=s==null?c[0]:Math.min(s,c[0]),o=o==null?c[1]:Math.max(o,c[1]))}),wr(s)&&wr(o))return[s,o]},xDe=st([IL,ui,dDe,yM,ii],$L,{memoizeOptions:{resultEqualityCheck:gM}});function yDe(t){var{value:e}=t;if(fl(e)||e instanceof Date)return e}var vDe=(t,e,n)=>{var r=t.map(yDe).filter(i=>i!=null);return n&&(e.dataKey==null||e.allowDuplicatedCategory&&HX(r))?pQ(0,t.length):e.allowDuplicatedCategory?r:Array.from(new Set(r))},TZ=t=>t.referenceElements.dots,Lb=(t,e,n)=>t.filter(r=>r.ifOverflow==="extendDomain").filter(r=>e==="xAxis"?r.xAxisId===n:r.yAxisId===n),wDe=st([TZ,ii,cv],Lb),AZ=t=>t.referenceElements.areas,_De=st([AZ,ii,cv],Lb),CZ=t=>t.referenceElements.lines,SDe=st([CZ,ii,cv],Lb),PZ=(t,e)=>{var n=Qu(t.map(r=>e==="xAxis"?r.x:r.y));if(n.length!==0)return[Math.min(...n),Math.max(...n)]},NDe=st(wDe,ii,PZ),jZ=(t,e)=>{var n=Qu(t.flatMap(r=>[e==="xAxis"?r.x1:r.y1,e==="xAxis"?r.x2:r.y2]));if(n.length!==0)return[Math.min(...n),Math.max(...n)]},kDe=st([_De,ii],jZ);function MDe(t){var e;if(t.x!=null)return Qu([t.x]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.x);return n==null||n.length===0?[]:Qu(n)}function EDe(t){var e;if(t.y!=null)return Qu([t.y]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.y);return n==null||n.length===0?[]:Qu(n)}var DZ=(t,e)=>{var n=t.flatMap(r=>e==="xAxis"?MDe(r):EDe(r));if(n.length!==0)return[Math.min(...n),Math.max(...n)]},TDe=st([SDe,ii],DZ),ADe=st(NDe,TDe,kDe,(t,e,n)=>QS(t,n,e)),VL=(t,e,n,r,i,s,o,l)=>{if(n!=null)return n;var c=o==="vertical"&&l==="xAxis"||o==="horizontal"&&l==="yAxis",u=c?QS(r,s,i):QS(s,i);return z3e(e,u,t.allowDataOverflow)},CDe=st([ui,BL,HL,gDe,xDe,ADe,Kn,ii],VL,{memoizeOptions:{resultEqualityCheck:gM}}),PDe=[0,1],GL=(t,e,n,r,i,s,o)=>{if(!((t==null||n==null||n.length===0)&&o===void 0)){var{dataKey:l,type:c}=t,u=Tc(e,s);if(u&&l==null){var d;return pQ(0,(d=n?.length)!==null&&d!==void 0?d:0)}return c==="category"?vDe(r,t,u):i==="expand"?PDe:o}},qL=st([ui,Kn,IL,xM,lv,ii,CDe],GL),RZ=(t,e,n,r,i)=>{if(t!=null){var{scale:s,type:o}=t;if(s==="auto")return e==="radial"&&i==="radiusAxis"?"band":e==="radial"&&i==="angleAxis"?"linear":o==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?"point":o==="category"?"band":"linear";if(typeof s=="string"){var l="scale".concat(Ky(s));return l in f0?l:"point"}}},Fb=st([ui,Kn,_Z,EL,ii],RZ);function jDe(t){if(t!=null){if(t in f0)return f0[t]();var e="scale".concat(Ky(t));if(e in f0)return f0[e]()}}function WL(t,e,n,r){if(!(n==null||r==null)){if(typeof t.scale=="function")return t.scale.copy().domain(n).range(r);var i=jDe(e);if(i!=null){var s=i.domain(n).range(r);return TTe(s),s}}}var KL=(t,e,n)=>{var r=UL(e);if(!(n!=="auto"&&n!=="linear")){if(e!=null&&e.tickCount&&Array.isArray(r)&&(r[0]==="auto"||r[1]==="auto")&&Lh(t))return K3e(t,e.tickCount,e.allowDecimals);if(e!=null&&e.tickCount&&e.type==="number"&&Lh(t))return X3e(t,e.tickCount,e.allowDecimals)}},XL=st([qL,uv,Fb],KL),YL=(t,e,n,r)=>{if(r!=="angleAxis"&&t?.type==="number"&&Lh(e)&&Array.isArray(n)&&n.length>0){var i=e[0],s=n[0],o=e[1],l=n[n.length-1];return[Math.min(i,s),Math.max(o,l)]}return e},DDe=st([ui,qL,XL,ii],YL),RDe=st(xM,ui,(t,e)=>{if(!(!e||e.type!=="number")){var n=1/0,r=Array.from(Qu(t.map(l=>l.value))).sort((l,c)=>l-c);if(r.length<2)return 1/0;var i=r[r.length-1]-r[0];if(i===0)return 1/0;for(var s=0;sr,(t,e,n,r,i)=>{if(!wr(t))return 0;var s=e==="vertical"?r.height:r.width;if(i==="gap")return t*s/2;if(i==="no-gap"){var o=as(n,t*s),l=t*s/2;return l-o-(l-o)/s*o}return 0}),ODe=(t,e)=>{var n=Ac(t,e);return n==null||typeof n.padding!="string"?0:OZ(t,"xAxis",e,n.padding)},LDe=(t,e)=>{var n=Cc(t,e);return n==null||typeof n.padding!="string"?0:OZ(t,"yAxis",e,n.padding)},FDe=st(Ac,ODe,(t,e)=>{var n,r;if(t==null)return{left:0,right:0};var{padding:i}=t;return typeof i=="string"?{left:e,right:e}:{left:((n=i.left)!==null&&n!==void 0?n:0)+e,right:((r=i.right)!==null&&r!==void 0?r:0)+e}}),IDe=st(Cc,LDe,(t,e)=>{var n,r;if(t==null)return{top:0,bottom:0};var{padding:i}=t;return typeof i=="string"?{top:e,bottom:e}:{top:((n=i.top)!==null&&n!==void 0?n:0)+e,bottom:((r=i.bottom)!==null&&r!==void 0?r:0)+e}}),zDe=st([ia,FDe,tM,eM,(t,e,n)=>n],(t,e,n,r,i)=>{var{padding:s}=r;return i?[s.left,n.width-s.right]:[t.left+e.left,t.left+t.width-e.right]}),UDe=st([ia,Kn,IDe,tM,eM,(t,e,n)=>n],(t,e,n,r,i,s)=>{var{padding:o}=i;return s?[r.height-o.bottom,o.top]:e==="horizontal"?[t.top+t.height-n.bottom,t.top+n.top]:[t.top+n.top,t.top+t.height-n.bottom]}),mv=(t,e,n,r)=>{var i;switch(e){case"xAxis":return zDe(t,n,r);case"yAxis":return UDe(t,n,r);case"zAxis":return(i=DL(t,n))===null||i===void 0?void 0:i.range;case"angleAxis":return gZ(t);case"radiusAxis":return bZ(t,n);default:return}},LZ=st([ui,mv],hM),Fh=st([ui,Fb,DDe,LZ],WL);st([hv,yM,ii],bDe);function FZ(t,e){return t.ide.id?1:0}var vM=(t,e)=>e,wM=(t,e,n)=>n,BDe=st(Zk,vM,wM,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(FZ)),HDe=st(Jk,vM,wM,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(FZ)),IZ=(t,e)=>({width:t.width,height:e.height}),$De=(t,e)=>{var n=typeof e.width=="number"?e.width:ev;return{width:n,height:t.height}},zZ=st(ia,Ac,IZ),VDe=(t,e,n)=>{switch(e){case"top":return t.top;case"bottom":return n-t.bottom;default:return 0}},GDe=(t,e,n)=>{switch(e){case"left":return t.left;case"right":return n-t.right;default:return 0}},qDe=st(td,ia,BDe,vM,wM,(t,e,n,r,i)=>{var s={},o;return n.forEach(l=>{var c=IZ(e,l);o==null&&(o=VDe(e,r,t));var u=r==="top"&&!i||r==="bottom"&&i;s[l.id]=o-Number(u)*c.height,o+=(u?-1:1)*c.height}),s}),WDe=st(ed,ia,HDe,vM,wM,(t,e,n,r,i)=>{var s={},o;return n.forEach(l=>{var c=$De(e,l);o==null&&(o=GDe(e,r,t));var u=r==="left"&&!i||r==="right"&&i;s[l.id]=o-Number(u)*c.width,o+=(u?-1:1)*c.width}),s}),KDe=(t,e)=>{var n=Ac(t,e);if(n!=null)return qDe(t,n.orientation,n.mirror)},XDe=st([ia,Ac,KDe,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var i=n?.[r];return i==null?{x:t.left,y:0}:{x:t.left,y:i}}}),YDe=(t,e)=>{var n=Cc(t,e);if(n!=null)return WDe(t,n.orientation,n.mirror)},QDe=st([ia,Cc,YDe,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var i=n?.[r];return i==null?{x:0,y:t.top}:{x:i,y:t.top}}}),UZ=st(ia,Cc,(t,e)=>{var n=typeof e.width=="number"?e.width:ev;return{width:n,height:t.height}}),aG=(t,e,n)=>{switch(e){case"xAxis":return zZ(t,n).width;case"yAxis":return UZ(t,n).height;default:return}},BZ=(t,e,n,r)=>{if(n!=null){var{allowDuplicatedCategory:i,type:s,dataKey:o}=n,l=Tc(t,r),c=e.map(u=>u.value);if(o&&l&&s==="category"&&i&&HX(c))return c}},QL=st([Kn,xM,ui,ii],BZ),HZ=(t,e,n,r)=>{if(!(n==null||n.dataKey==null)){var{type:i,scale:s}=n,o=Tc(t,r);if(o&&(i==="number"||s!=="auto"))return e.map(l=>l.value)}},ZL=st([Kn,xM,uv,ii],HZ),sG=st([Kn,cDe,Fb,Fh,QL,ZL,mv,XL,ii],(t,e,n,r,i,s,o,l,c)=>{if(e!=null){var u=Tc(t,c);return{angle:e.angle,interval:e.interval,minTickGap:e.minTickGap,orientation:e.orientation,tick:e.tick,tickCount:e.tickCount,tickFormatter:e.tickFormatter,ticks:e.ticks,type:e.type,unit:e.unit,axisType:c,categoricalDomain:s,duplicateDomain:i,isCategorical:u,niceTicks:l,range:o,realScaleType:n,scale:r}}}),ZDe=(t,e,n,r,i,s,o,l,c)=>{if(!(e==null||r==null)){var u=Tc(t,c),{type:d,ticks:h,tickCount:p}=e,m=n==="scaleBand"&&typeof r.bandwidth=="function"?r.bandwidth()/2:2,b=d==="category"&&r.bandwidth?r.bandwidth()/m:0;b=c==="angleAxis"&&s!=null&&s.length>=2?wa(s[0]-s[1])*2*b:b;var y=h||i;if(y){var x=y.map((v,S)=>{var N=o?o.indexOf(v):v;return{index:S,coordinate:r(N)+b,value:v,offset:b}});return x.filter(v=>wr(v.coordinate))}return u&&l?l.map((v,S)=>({coordinate:r(v)+b,value:v,index:S,offset:b})).filter(v=>wr(v.coordinate)):r.ticks?r.ticks(p).map(v=>({coordinate:r(v)+b,value:v,offset:b})):r.domain().map((v,S)=>({coordinate:r(v)+b,value:o?o[v]:v,index:S,offset:b}))}},$Z=st([Kn,uv,Fb,Fh,XL,mv,QL,ZL,ii],ZDe),JDe=(t,e,n,r,i,s,o)=>{if(!(e==null||n==null||r==null||r[0]===r[1])){var l=Tc(t,o),{tickCount:c}=e,u=0;return u=o==="angleAxis"&&r?.length>=2?wa(r[0]-r[1])*2*u:u,l&&s?s.map((d,h)=>({coordinate:n(d)+u,value:d,index:h,offset:u})):n.ticks?n.ticks(c).map(d=>({coordinate:n(d)+u,value:d,offset:u})):n.domain().map((d,h)=>({coordinate:n(d)+u,value:i?i[d]:d,index:h,offset:u}))}},wc=st([Kn,uv,Fh,mv,QL,ZL,ii],JDe),_c=st(ui,Fh,(t,e)=>{if(!(t==null||e==null))return YS(YS({},t),{},{scale:e})}),eRe=st([ui,Fb,qL,LZ],WL);st((t,e,n)=>DL(t,n),eRe,(t,e)=>{if(!(t==null||e==null))return YS(YS({},t),{},{scale:e})});var tRe=st([Kn,Zk,Jk],(t,e,n)=>{switch(t){case"horizontal":return e.some(r=>r.reversed)?"right-to-left":"left-to-right";case"vertical":return n.some(r=>r.reversed)?"bottom-to-top":"top-to-bottom";case"centric":case"radial":return"left-to-right";default:return}}),VZ=t=>t.options.defaultTooltipEventType,GZ=t=>t.options.validateTooltipEventTypes;function qZ(t,e,n){if(t==null)return e;var r=t?"axis":"item";return n==null?e:n.includes(r)?r:e}function JL(t,e){var n=VZ(t),r=GZ(t);return qZ(e,n,r)}function nRe(t){return Ht(e=>JL(e,t))}var WZ=(t,e)=>{var n,r=Number(e);if(!(Ys(r)||e==null))return r>=0?t==null||(n=t[r])===null||n===void 0?void 0:n.value:void 0},rRe=t=>t.tooltip.settings,ih={active:!1,index:null,dataKey:void 0,graphicalItemId:void 0,coordinate:void 0},iRe={itemInteraction:{click:ih,hover:ih},axisInteraction:{click:ih,hover:ih},keyboardInteraction:ih,syncInteraction:{active:!1,index:null,dataKey:void 0,label:void 0,coordinate:void 0,sourceViewBox:void 0,graphicalItemId:void 0},tooltipItemPayloads:[],settings:{shared:void 0,trigger:"hover",axisId:0,active:!1,defaultIndex:void 0}},KZ=Qs({name:"tooltip",initialState:iRe,reducers:{addTooltipEntrySettings:{reducer(t,e){t.tooltipItemPayloads.push(e.payload)},prepare:Jr()},replaceTooltipEntrySettings:{reducer(t,e){var{prev:n,next:r}=e.payload,i=Il(t).tooltipItemPayloads.indexOf(n);i>-1&&(t.tooltipItemPayloads[i]=r)},prepare:Jr()},removeTooltipEntrySettings:{reducer(t,e){var n=Il(t).tooltipItemPayloads.indexOf(e.payload);n>-1&&t.tooltipItemPayloads.splice(n,1)},prepare:Jr()},setTooltipSettingsState(t,e){t.settings=e.payload},setActiveMouseOverItemIndex(t,e){t.syncInteraction.active=!1,t.keyboardInteraction.active=!1,t.itemInteraction.hover.active=!0,t.itemInteraction.hover.index=e.payload.activeIndex,t.itemInteraction.hover.dataKey=e.payload.activeDataKey,t.itemInteraction.hover.graphicalItemId=e.payload.activeGraphicalItemId,t.itemInteraction.hover.coordinate=e.payload.activeCoordinate},mouseLeaveChart(t){t.itemInteraction.hover.active=!1,t.axisInteraction.hover.active=!1},mouseLeaveItem(t){t.itemInteraction.hover.active=!1},setActiveClickItemIndex(t,e){t.syncInteraction.active=!1,t.itemInteraction.click.active=!0,t.keyboardInteraction.active=!1,t.itemInteraction.click.index=e.payload.activeIndex,t.itemInteraction.click.dataKey=e.payload.activeDataKey,t.itemInteraction.click.graphicalItemId=e.payload.activeGraphicalItemId,t.itemInteraction.click.coordinate=e.payload.activeCoordinate},setMouseOverAxisIndex(t,e){t.syncInteraction.active=!1,t.axisInteraction.hover.active=!0,t.keyboardInteraction.active=!1,t.axisInteraction.hover.index=e.payload.activeIndex,t.axisInteraction.hover.dataKey=e.payload.activeDataKey,t.axisInteraction.hover.coordinate=e.payload.activeCoordinate},setMouseClickAxisIndex(t,e){t.syncInteraction.active=!1,t.keyboardInteraction.active=!1,t.axisInteraction.click.active=!0,t.axisInteraction.click.index=e.payload.activeIndex,t.axisInteraction.click.dataKey=e.payload.activeDataKey,t.axisInteraction.click.coordinate=e.payload.activeCoordinate},setSyncInteraction(t,e){t.syncInteraction=e.payload},setKeyboardInteraction(t,e){t.keyboardInteraction.active=e.payload.active,t.keyboardInteraction.index=e.payload.activeIndex,t.keyboardInteraction.coordinate=e.payload.activeCoordinate,t.keyboardInteraction.dataKey=e.payload.activeDataKey}}}),{addTooltipEntrySettings:aRe,replaceTooltipEntrySettings:sRe,removeTooltipEntrySettings:oRe,setTooltipSettingsState:lRe,setActiveMouseOverItemIndex:XZ,mouseLeaveItem:cRe,mouseLeaveChart:YZ,setActiveClickItemIndex:uRe,setMouseOverAxisIndex:QZ,setMouseClickAxisIndex:dRe,setSyncInteraction:kD,setKeyboardInteraction:MD}=KZ.actions,hRe=KZ.reducer;function oG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function e1(t){for(var e=1;e{if(e==null)return ih;var i=gRe(t,e,n);if(i==null)return ih;if(i.active)return i;if(t.keyboardInteraction.active)return t.keyboardInteraction;if(t.syncInteraction.active&&t.syncInteraction.index!=null)return t.syncInteraction;var s=t.settings.active===!0;if(bRe(i)){if(s)return e1(e1({},i),{},{active:!0})}else if(r!=null)return{active:!0,coordinate:void 0,dataKey:void 0,index:r,graphicalItemId:void 0};return e1(e1({},ih),{},{coordinate:i.coordinate})};function xRe(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(t instanceof Date){var e=t.valueOf();return Number.isFinite(e)?e:void 0}var n=Number(t);return Number.isFinite(n)?n:void 0}function yRe(t,e){var n=xRe(t),r=e[0],i=e[1];if(n===void 0)return!1;var s=Math.min(r,i),o=Math.max(r,i);return n>=s&&n<=o}function vRe(t,e,n){if(n==null||e==null)return!0;var r=vr(t,e);return r==null||!Lh(n)?!0:yRe(r,n)}var e4=(t,e,n,r)=>{var i=t?.index;if(i==null)return null;var s=Number(i);if(!wr(s))return i;var o=0,l=1/0;e.length>0&&(l=e.length-1);var c=Math.max(o,Math.min(s,l)),u=e[c];return u==null||vRe(u,n,r)?String(c):null},JZ=(t,e,n,r,i,s,o,l)=>{if(!(s==null||l==null)){var c=o[0],u=c==null?void 0:l(c.positions,s);if(u!=null)return u;var d=i?.[Number(s)];if(d)switch(n){case"horizontal":return{x:d.coordinate,y:(r.top+e)/2};default:return{x:(r.left+t)/2,y:d.coordinate}}}},eJ=(t,e,n,r)=>{if(e==="axis")return t.tooltipItemPayloads;if(t.tooltipItemPayloads.length===0)return[];var i;return n==="hover"?i=t.itemInteraction.hover.dataKey:i=t.itemInteraction.click.dataKey,i==null&&r!=null?[t.tooltipItemPayloads[0]]:t.tooltipItemPayloads.filter(s=>{var o;return((o=s.settings)===null||o===void 0?void 0:o.dataKey)===i})},pv=t=>t.options.tooltipPayloadSearcher,Ib=t=>t.tooltip;function lG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function cG(t){for(var e=1;e{if(!(e==null||s==null)){var{chartData:l,computedData:c,dataStartIndex:u,dataEndIndex:d}=n,h=[];return t.reduce((p,m)=>{var b,{dataDefinedOnItem:y,settings:x}=m,v=NRe(y,l),S=Array.isArray(v)?FY(v,u,d):v,N=(b=x?.dataKey)!==null&&b!==void 0?b:r,T=x?.nameKey,M;if(r&&Array.isArray(S)&&!Array.isArray(S[0])&&o==="axis"?M=$X(S,r,i):M=s(S,e,c,T),Array.isArray(M))M.forEach(k=>{var R=cG(cG({},x),{},{name:k.name,unit:k.unit,color:void 0,fill:void 0});p.push(A$({tooltipEntrySettings:R,dataKey:k.dataKey,payload:k.payload,value:vr(k.payload,k.dataKey),name:k.name}))});else{var A;p.push(A$({tooltipEntrySettings:x,dataKey:N,payload:M,value:vr(M,N),name:(A=vr(M,T))!==null&&A!==void 0?A:x?.name}))}return p},h)}},t4=st([la,Kn,_Z,EL,oa],RZ),kRe=st([t=>t.graphicalItems.cartesianItems,t=>t.graphicalItems.polarItems],(t,e)=>[...t,...e]),MRe=st([oa,Ob],RL),gv=st([kRe,la,MRe],OL,{memoizeOptions:{resultEqualityCheck:bM}}),ERe=st([gv],t=>t.filter(pM)),TRe=st([gv],LL,{memoizeOptions:{resultEqualityCheck:bM}}),zb=st([TRe,Gh],FL),ARe=st([ERe,Gh,la],yZ),n4=st([zb,la,gv],zL),nJ=st([la],UL),CRe=st([la],t=>t.allowDataOverflow),rJ=st([nJ,CRe],YQ),PRe=st([gv],t=>t.filter(pM)),jRe=st([ARe,PRe,lv,hZ],MZ),DRe=st([jRe,Gh,oa,rJ],EZ),RRe=st([gv],NZ),ORe=st([zb,la,RRe,yM,oa],$L,{memoizeOptions:{resultEqualityCheck:gM}}),LRe=st([TZ,oa,Ob],Lb),FRe=st([LRe,oa],PZ),IRe=st([AZ,oa,Ob],Lb),zRe=st([IRe,oa],jZ),URe=st([CZ,oa,Ob],Lb),BRe=st([URe,oa],DZ),HRe=st([FRe,BRe,zRe],QS),$Re=st([la,nJ,rJ,DRe,ORe,HRe,Kn,oa],VL),bv=st([la,Kn,zb,n4,lv,oa,$Re],GL),VRe=st([bv,la,t4],KL),GRe=st([la,bv,VRe,oa],YL),iJ=t=>{var e=oa(t),n=Ob(t),r=!1;return mv(t,e,n,r)},aJ=st([la,iJ],hM),sJ=st([la,t4,GRe,aJ],WL),qRe=st([Kn,n4,la,oa],BZ),WRe=st([Kn,n4,la,oa],HZ),KRe=(t,e,n,r,i,s,o,l)=>{if(e){var{type:c}=e,u=Tc(t,l);if(r){var d=n==="scaleBand"&&r.bandwidth?r.bandwidth()/2:2,h=c==="category"&&r.bandwidth?r.bandwidth()/d:0;return h=l==="angleAxis"&&i!=null&&i?.length>=2?wa(i[0]-i[1])*2*h:h,u&&o?o.map((p,m)=>({coordinate:r(p)+h,value:p,index:m,offset:h})):r.domain().map((p,m)=>({coordinate:r(p)+h,value:s?s[p]:p,index:m,offset:h}))}}},rd=st([Kn,la,t4,sJ,iJ,qRe,WRe,oa],KRe),r4=st([VZ,GZ,rRe],(t,e,n)=>qZ(n.shared,t,e)),oJ=t=>t.tooltip.settings.trigger,i4=t=>t.tooltip.settings.defaultIndex,xv=st([Ib,r4,oJ,i4],ZZ),Ih=st([xv,zb,fv,bv],e4),lJ=st([rd,Ih],WZ),a4=st([xv],t=>{if(t)return t.dataKey}),XRe=st([xv],t=>{if(t)return t.graphicalItemId}),cJ=st([Ib,r4,oJ,i4],eJ),YRe=st([ed,td,Kn,ia,rd,i4,cJ,pv],JZ),QRe=st([xv,YRe],(t,e)=>t!=null&&t.coordinate?t.coordinate:e),ZRe=st([xv],t=>t.active),JRe=st([cJ,Ih,Gh,fv,lJ,pv,r4],tJ),eOe=st([JRe],t=>{if(t!=null){var e=t.map(n=>n.payload).filter(n=>n!=null);return Array.from(new Set(e))}});function uG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function dG(t){for(var e=1;eHt(la),aOe=()=>{var t=iOe(),e=Ht(rd),n=Ht(sJ);return Oh(!t||!n?void 0:dG(dG({},t),{},{scale:n}),e)};function hG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function tg(t){for(var e=1;e{var i=e.find(s=>s&&s.index===n);if(i){if(t==="horizontal")return{x:i.coordinate,y:r.chartY};if(t==="vertical")return{x:r.chartX,y:i.coordinate}}return{x:0,y:0}},uOe=(t,e,n,r)=>{var i=e.find(u=>u&&u.index===n);if(i){if(t==="centric"){var s=i.coordinate,{radius:o}=r;return tg(tg(tg({},r),Bi(r.cx,r.cy,o,s)),{},{angle:s,radius:o})}var l=i.coordinate,{angle:c}=r;return tg(tg(tg({},r),Bi(r.cx,r.cy,l,c)),{},{angle:c,radius:l})}return{angle:0,clockWise:!1,cx:0,cy:0,endAngle:0,innerRadius:0,outerRadius:0,radius:0,startAngle:0,x:0,y:0}};function dOe(t,e){var{chartX:n,chartY:r}=t;return n>=e.left&&n<=e.left+e.width&&r>=e.top&&r<=e.top+e.height}var uJ=(t,e,n,r,i)=>{var s,o=-1,l=(s=e?.length)!==null&&s!==void 0?s:0;if(l<=1||t==null)return 0;if(r==="angleAxis"&&i!=null&&Math.abs(Math.abs(i[1]-i[0])-360)<=1e-6)for(var c=0;c0?n[c-1].coordinate:n[l-1].coordinate,d=n[c].coordinate,h=c>=l-1?n[0].coordinate:n[c+1].coordinate,p=void 0;if(wa(d-u)!==wa(h-d)){var m=[];if(wa(h-d)===wa(i[1]-i[0])){p=h;var b=d+i[1]-i[0];m[0]=Math.min(b,(b+u)/2),m[1]=Math.max(b,(b+u)/2)}else{p=u;var y=h+i[1]-i[0];m[0]=Math.min(d,(y+d)/2),m[1]=Math.max(d,(y+d)/2)}var x=[Math.min(d,(p+d)/2),Math.max(d,(p+d)/2)];if(t>x[0]&&t<=x[1]||t>=m[0]&&t<=m[1]){({index:o}=n[c]);break}}else{var v=Math.min(u,h),S=Math.max(u,h);if(t>(v+d)/2&&t<=(S+d)/2){({index:o}=n[c]);break}}}else if(e){for(var N=0;N0&&N(e[N].coordinate+e[N-1].coordinate)/2&&t<=(e[N].coordinate+e[N+1].coordinate)/2||N===l-1&&t>(e[N].coordinate+e[N-1].coordinate)/2){({index:o}=e[N]);break}}return o},dJ=()=>Ht(EL),s4=(t,e)=>e,hJ=(t,e,n)=>n,o4=(t,e,n,r)=>r,hOe=st(rd,t=>$k(t,e=>e.coordinate)),l4=st([Ib,s4,hJ,o4],ZZ),c4=st([l4,zb,fv,bv],e4),fOe=(t,e,n)=>{if(e!=null){var r=Ib(t);return e==="axis"?n==="hover"?r.axisInteraction.hover.dataKey:r.axisInteraction.click.dataKey:n==="hover"?r.itemInteraction.hover.dataKey:r.itemInteraction.click.dataKey}},fJ=st([Ib,s4,hJ,o4],eJ),ZS=st([ed,td,Kn,ia,rd,o4,fJ,pv],JZ),mOe=st([l4,ZS],(t,e)=>{var n;return(n=t.coordinate)!==null&&n!==void 0?n:e}),mJ=st([rd,c4],WZ),pOe=st([fJ,c4,Gh,fv,mJ,pv,s4],tJ),gOe=st([l4,c4],(t,e)=>({isActive:t.active&&e!=null,activeIndex:e})),bOe=(t,e,n,r,i,s,o)=>{if(!(!t||!n||!r||!i)&&dOe(t,o)){var l=ITe(t,e),c=uJ(l,s,i,n,r),u=cOe(e,i,c,t);return{activeIndex:String(c),activeCoordinate:u}}},xOe=(t,e,n,r,i,s,o)=>{if(!(!t||!r||!i||!s||!n)){var l=tPe(t,n);if(l){var c=zTe(l,e),u=uJ(c,o,s,r,i),d=uOe(e,s,u,l);return{activeIndex:String(u),activeCoordinate:d}}}},yOe=(t,e,n,r,i,s,o,l)=>{if(!(!t||!e||!r||!i||!s))return e==="horizontal"||e==="vertical"?bOe(t,e,r,i,s,o,l):xOe(t,e,n,r,i,s,o)},vOe=st(t=>t.zIndex.zIndexMap,(t,e)=>e,(t,e,n)=>n,(t,e,n)=>{if(e!=null){var r=t[e];if(r!=null)return n?r.panoramaElementId:r.elementId}}),wOe=st(t=>t.zIndex.zIndexMap,t=>{var e=Object.keys(t).map(r=>parseInt(r,10)).concat(Object.values(vi)),n=Array.from(new Set(e));return n.sort((r,i)=>r-i)},{memoizeOptions:{resultEqualityCheck:iDe}});function fG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function mG(t){for(var e=1;emG(mG({},t),{},{[e]:{elementId:void 0,panoramaElementId:void 0,consumers:0}}),kOe)},EOe=new Set(Object.values(vi));function TOe(t){return EOe.has(t)}var pJ=Qs({name:"zIndex",initialState:MOe,reducers:{registerZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]?t.zIndexMap[n].consumers+=1:t.zIndexMap[n]={consumers:1,elementId:void 0,panoramaElementId:void 0}},prepare:Jr()},unregisterZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(t.zIndexMap[n].consumers-=1,t.zIndexMap[n].consumers<=0&&!TOe(n)&&delete t.zIndexMap[n])},prepare:Jr()},registerZIndexPortalId:{reducer:(t,e)=>{var{zIndex:n,elementId:r,isPanorama:i}=e.payload;t.zIndexMap[n]?i?t.zIndexMap[n].panoramaElementId=r:t.zIndexMap[n].elementId=r:t.zIndexMap[n]={consumers:0,elementId:i?void 0:r,panoramaElementId:i?r:void 0}},prepare:Jr()},unregisterZIndexPortalId:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(e.payload.isPanorama?t.zIndexMap[n].panoramaElementId=void 0:t.zIndexMap[n].elementId=void 0)},prepare:Jr()}}}),{registerZIndexPortal:AOe,unregisterZIndexPortal:COe,registerZIndexPortalId:POe,unregisterZIndexPortalId:jOe}=pJ.actions,DOe=pJ.reducer;function ls(t){var{zIndex:e,children:n}=t,r=bAe(),i=r&&e!==void 0&&e!==0,s=aa(),o=zr();_.useLayoutEffect(()=>i?(o(AOe({zIndex:e})),()=>{o(COe({zIndex:e}))}):Xy,[o,e,i]);var l=Ht(u=>vOe(u,e,s));if(!i)return n;if(!l)return null;var c=document.getElementById(l);return c?vu.createPortal(n,c):null}function ED(){return ED=Object.assign?Object.assign.bind():function(t){for(var e=1;e_.useContext(gJ),QC={exports:{}},gG;function BOe(){return gG||(gG=1,(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(c,u,d){this.fn=c,this.context=u,this.once=d||!1}function s(c,u,d,h,p){if(typeof d!="function")throw new TypeError("The listener must be a function");var m=new i(d,h||c,p),b=n?n+u:u;return c._events[b]?c._events[b].fn?c._events[b]=[c._events[b],m]:c._events[b].push(m):(c._events[b]=m,c._eventsCount++),c}function o(c,u){--c._eventsCount===0?c._events=new r:delete c._events[u]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var u=[],d,h;if(this._eventsCount===0)return u;for(h in d=this._events)e.call(d,h)&&u.push(n?h.slice(1):h);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},l.prototype.listeners=function(u){var d=n?n+u:u,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,m=h.length,b=new Array(m);p{t.eventEmitter==null&&(t.eventEmitter=Symbol("rechartsEventEmitter"))}}}),GOe=bJ.reducer,{createEventEmitter:qOe}=bJ.actions;function WOe(t){return t.tooltip.syncInteraction}var KOe={chartData:void 0,computedData:void 0,dataStartIndex:0,dataEndIndex:0},xJ=Qs({name:"chartData",initialState:KOe,reducers:{setChartData(t,e){if(t.chartData=e.payload,e.payload==null){t.dataStartIndex=0,t.dataEndIndex=0;return}e.payload.length>0&&t.dataEndIndex!==e.payload.length-1&&(t.dataEndIndex=e.payload.length-1)},setComputedData(t,e){t.computedData=e.payload},setDataStartEndIndexes(t,e){var{startIndex:n,endIndex:r}=e.payload;n!=null&&(t.dataStartIndex=n),r!=null&&(t.dataEndIndex=r)}}}),{setChartData:xG,setDataStartEndIndexes:XOe,setComputedData:mQe}=xJ.actions,YOe=xJ.reducer,QOe=["x","y"];function yG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function ng(t){for(var e=1;ec.rootProps.className);_.useEffect(()=>{if(t==null)return Xy;var c=(u,d,h)=>{if(e!==h&&t===u){if(r==="index"){var p;if(o&&d!==null&&d!==void 0&&(p=d.payload)!==null&&p!==void 0&&p.coordinate&&d.payload.sourceViewBox){var m=d.payload.coordinate,{x:b,y}=m,x=tLe(m,QOe),{x:v,y:S,width:N,height:T}=d.payload.sourceViewBox,M=ng(ng({},x),{},{x:o.x+(N?(b-v)/N:0)*o.width,y:o.y+(T?(y-S)/T:0)*o.height});n(ng(ng({},d),{},{payload:ng(ng({},d.payload),{},{coordinate:M})}))}else n(d);return}if(i!=null){var A;if(typeof r=="function"){var k={activeTooltipIndex:d.payload.index==null?void 0:Number(d.payload.index),isTooltipActive:d.payload.active,activeIndex:d.payload.index==null?void 0:Number(d.payload.index),activeLabel:d.payload.label,activeDataKey:d.payload.dataKey,activeCoordinate:d.payload.coordinate},R=r(i,k);A=i[R]}else r==="value"&&(A=i.find(G=>String(G.value)===d.payload.label));var{coordinate:C}=d.payload;if(A==null||d.payload.active===!1||C==null||o==null){n(kD({active:!1,coordinate:void 0,dataKey:void 0,index:null,label:void 0,sourceViewBox:void 0,graphicalItemId:void 0}));return}var{x:P,y:U}=C,F=Math.min(P,o.x+o.width),H=Math.min(U,o.y+o.height),D={x:s==="horizontal"?A.coordinate:F,y:s==="horizontal"?H:A.coordinate},$=kD({active:d.payload.active,coordinate:D,dataKey:d.payload.dataKey,index:String(A.index),label:d.payload.label,sourceViewBox:d.payload.sourceViewBox,graphicalItemId:d.payload.graphicalItemId});n($)}}};return Ny.on(TD,c),()=>{Ny.off(TD,c)}},[l,n,e,t,r,i,s,o])}function iLe(){var t=Ht(TL),e=Ht(AL),n=zr();_.useEffect(()=>{if(t==null)return Xy;var r=(i,s,o)=>{e!==o&&t===i&&n(XOe(s))};return Ny.on(bG,r),()=>{Ny.off(bG,r)}},[n,e,t])}function aLe(){var t=zr();_.useEffect(()=>{t(qOe())},[t]),rLe(),iLe()}function sLe(t,e,n,r,i,s){var o=Ht(m=>fOe(m,t,e)),l=Ht(AL),c=Ht(TL),u=Ht(fZ),d=Ht(WOe),h=d?.active,p=tv();_.useEffect(()=>{if(!h&&c!=null&&l!=null){var m=kD({active:s,coordinate:n,dataKey:o,index:i,label:typeof r=="number"?String(r):r,sourceViewBox:p,graphicalItemId:void 0});Ny.emit(TD,c,m,l)}},[h,n,o,i,r,l,c,u,s,p])}function vG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function wG(t){for(var e=1;e{k(lRe({shared:S,trigger:N,axisId:A,active:i,defaultIndex:R}))},[k,S,N,A,i,R]);var C=tv(),P=aQ(),U=nRe(S),{activeIndex:F,isActive:H}=(e=Ht(de=>gOe(de,U,N,R)))!==null&&e!==void 0?e:{},D=Ht(de=>pOe(de,U,N,R)),$=Ht(de=>mJ(de,U,N,R)),G=Ht(de=>mOe(de,U,N,R)),I=D,K=UOe(),Q=(n=i??H)!==null&&n!==void 0?n:!1,[oe,B]=oY([I,Q]),W=U==="axis"?$:void 0;sLe(U,N,G,W,F,Q);var J=M??K;if(J==null||C==null||U==null)return null;var ne=I??_G;Q||(ne=_G),u&&ne.length&&(ne=tY(ne.filter(de=>de.value!=null&&(de.hide!==!0||r.includeHidden)),p,uLe));var me=ne.length>0,fe=_.createElement(nCe,{allowEscapeViewBox:s,animationDuration:o,animationEasing:l,isAnimationActive:d,active:Q,coordinate:G,hasPayload:me,offset:h,position:m,reverseDirection:b,useTranslate3d:y,viewBox:C,wrapperStyle:x,lastBoundingBox:oe,innerRef:B,hasPortalFromProps:!!M},dLe(c,wG(wG({},r),{},{payload:ne,label:W,active:Q,activeIndex:F,coordinate:G,accessibilityLayer:P})));return _.createElement(_.Fragment,null,vu.createPortal(fe,J),Q&&_.createElement(zOe,{cursor:v,tooltipEventType:U,coordinate:G,payload:ne,index:F}))}var yv=t=>null;yv.displayName="Cell";function fLe(t,e,n){return(e=mLe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mLe(t){var e=pLe(t,"string");return typeof e=="symbol"?e:e+""}function pLe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}class gLe{constructor(e){fLe(this,"cache",new Map),this.maxSize=e}get(e){var n=this.cache.get(e);return n!==void 0&&(this.cache.delete(e),this.cache.set(e,n)),n}set(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){var r=this.cache.keys().next().value;r!=null&&this.cache.delete(r)}this.cache.set(e,n)}clear(){this.cache.clear()}size(){return this.cache.size}}function SG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function bLe(t){for(var e=1;e{try{var n=document.getElementById(kG);n||(n=document.createElement("span"),n.setAttribute("id",kG),n.setAttribute("aria-hidden","true"),document.body.appendChild(n)),Object.assign(n.style,_Le,e),n.textContent="".concat(t);var r=n.getBoundingClientRect();return{width:r.width,height:r.height}}catch{return{width:0,height:0}}},A0=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||Ab.isSsr)return{width:0,height:0};if(!yJ.enableCache)return MG(e,n);var r=SLe(e,n),i=NG.get(r);if(i)return i;var s=MG(e,n);return NG.set(r,s),s},EG=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,TG=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,NLe=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,kLe=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,vJ={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},MLe=Object.keys(vJ),_g="NaN";function ELe(t,e){return t*vJ[e]}class Us{static parse(e){var n,[,r,i]=(n=kLe.exec(e))!==null&&n!==void 0?n:[];return new Us(parseFloat(r),i??"")}constructor(e,n){this.num=e,this.unit=n,this.num=e,this.unit=n,Ys(e)&&(this.unit=""),n!==""&&!NLe.test(n)&&(this.num=NaN,this.unit=""),MLe.includes(n)&&(this.num=ELe(e,n),this.unit="px")}add(e){return this.unit!==e.unit?new Us(NaN,""):new Us(this.num+e.num,this.unit)}subtract(e){return this.unit!==e.unit?new Us(NaN,""):new Us(this.num-e.num,this.unit)}multiply(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new Us(NaN,""):new Us(this.num*e.num,this.unit||e.unit)}divide(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new Us(NaN,""):new Us(this.num/e.num,this.unit||e.unit)}toString(){return"".concat(this.num).concat(this.unit)}isNaN(){return Ys(this.num)}}function wJ(t){if(t.includes(_g))return _g;for(var e=t;e.includes("*")||e.includes("/");){var n,[,r,i,s]=(n=EG.exec(e))!==null&&n!==void 0?n:[],o=Us.parse(r??""),l=Us.parse(s??""),c=i==="*"?o.multiply(l):o.divide(l);if(c.isNaN())return _g;e=e.replace(EG,c.toString())}for(;e.includes("+")||/.-\d+(?:\.\d+)?/.test(e);){var u,[,d,h,p]=(u=TG.exec(e))!==null&&u!==void 0?u:[],m=Us.parse(d??""),b=Us.parse(p??""),y=h==="+"?m.add(b):m.subtract(b);if(y.isNaN())return _g;e=e.replace(TG,y.toString())}return e}var AG=/\(([^()]*)\)/;function TLe(t){for(var e=t,n;(n=AG.exec(e))!=null;){var[,r]=n;e=e.replace(AG,wJ(r))}return e}function ALe(t){var e=t.replace(/\s+/g,"");return e=TLe(e),e=wJ(e),e}function CLe(t){try{return ALe(t)}catch{return _g}}function ZC(t){var e=CLe(t.slice(5,-1));return e===_g?"":e}var PLe=["x","y","lineHeight","capHeight","fill","scaleToFit","textAnchor","verticalAnchor"],jLe=["dx","dy","angle","className","breakAll"];function AD(){return AD=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{children:e,breakAll:n,style:r}=t;try{var i=[];Yr(e)||(n?i=e.toString().split(""):i=e.toString().split(_J));var s=i.map(l=>({word:l,width:A0(l,r).width})),o=n?0:A0(" ",r).width;return{wordsWithComputedWidth:s,spaceWidth:o}}catch{return null}};function RLe(t){return t==="start"||t==="middle"||t==="end"||t==="inherit"}var NJ=(t,e,n,r)=>t.reduce((i,s)=>{var{word:o,width:l}=s,c=i[i.length-1];if(c&&l!=null&&(e==null||r||c.width+l+nt.reduce((e,n)=>e.width>n.width?e:n),OLe="…",PG=(t,e,n,r,i,s,o,l)=>{var c=t.slice(0,e),u=SJ({breakAll:n,style:r,children:c+OLe});if(!u)return[!1,[]];var d=NJ(u.wordsWithComputedWidth,s,o,l),h=d.length>i||kJ(d).width>Number(s);return[h,d]},LLe=(t,e,n,r,i)=>{var{maxLines:s,children:o,style:l,breakAll:c}=t,u=Vt(s),d=String(o),h=NJ(e,r,n,i);if(!u||i)return h;var p=h.length>s||kJ(h).width>Number(r);if(!p)return h;for(var m=0,b=d.length-1,y=0,x;m<=b&&y<=d.length-1;){var v=Math.floor((m+b)/2),S=v-1,[N,T]=PG(d,S,c,l,s,r,n,i),[M]=PG(d,v,c,l,s,r,n,i);if(!N&&!M&&(m=v+1),N&&M&&(b=v-1),!N&&M){x=T;break}y++}return x||h},jG=t=>{var e=Yr(t)?[]:t.toString().split(_J);return[{words:e,width:void 0}]},FLe=t=>{var{width:e,scaleToFit:n,children:r,style:i,breakAll:s,maxLines:o}=t;if((e||n)&&!Ab.isSsr){var l,c,u=SJ({breakAll:s,children:r,style:i});if(u){var{wordsWithComputedWidth:d,spaceWidth:h}=u;l=d,c=h}else return jG(r);return LLe({breakAll:s,children:r,maxLines:o,style:i},l,c,e,!!n)}return jG(r)},MJ="#808080",ILe={angle:0,breakAll:!1,capHeight:"0.71em",fill:MJ,lineHeight:"1em",scaleToFit:!1,textAnchor:"start",verticalAnchor:"end",x:0,y:0},SM=_.forwardRef((t,e)=>{var n=ci(t,ILe),{x:r,y:i,lineHeight:s,capHeight:o,fill:l,scaleToFit:c,textAnchor:u,verticalAnchor:d}=n,h=CG(n,PLe),p=_.useMemo(()=>FLe({breakAll:h.breakAll,children:h.children,maxLines:h.maxLines,scaleToFit:c,style:h.style,width:h.width}),[h.breakAll,h.children,h.maxLines,c,h.style,h.width]),{dx:m,dy:b,angle:y,className:x,breakAll:v}=h,S=CG(h,jLe);if(!fl(r)||!fl(i)||p.length===0)return null;var N=Number(r)+(Vt(m)?m:0),T=Number(i)+(Vt(b)?b:0);if(!wr(N)||!wr(T))return null;var M;switch(d){case"start":M=ZC("calc(".concat(o,")"));break;case"middle":M=ZC("calc(".concat((p.length-1)/2," * -").concat(s," + (").concat(o," / 2))"));break;default:M=ZC("calc(".concat(p.length-1," * -").concat(s,")"));break}var A=[];if(c){var k=p[0].width,{width:R}=h;A.push("scale(".concat(Vt(R)&&Vt(k)?R/k:1,")"))}return y&&A.push("rotate(".concat(y,", ").concat(N,", ").concat(T,")")),A.length&&(S.transform=A.join(" ")),_.createElement("text",AD({},Ga(S),{ref:e,x:N,y:T,className:nr("recharts-text",x),textAnchor:u,fill:l.includes("url")?MJ:l}),p.map((C,P)=>{var U=C.words.join(v?"":" ");return _.createElement("tspan",{x:N,dy:P===0?M:s,key:"".concat(U,"-").concat(P)},U)}))});SM.displayName="Text";var zLe=["labelRef"];function ULe(t,e){if(t==null)return{};var n,r,i=BLe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var{x:e,y:n,upperWidth:r,lowerWidth:i,width:s,height:o,children:l}=t,c=_.useMemo(()=>({x:e,y:n,upperWidth:r,lowerWidth:i,width:s,height:o}),[e,n,r,i,s,o]);return _.createElement(EJ.Provider,{value:c},l)},AJ=()=>{var t=_.useContext(EJ),e=tv();return t||WY(e)},GLe=_.createContext(null),qLe=()=>{var t=_.useContext(GLe),e=Ht(xZ);return t||e},WLe=t=>{var{value:e,formatter:n}=t,r=Yr(t.children)?e:t.children;return typeof n=="function"?n(r):r},u4=t=>t!=null&&typeof t=="function",KLe=(t,e)=>{var n=wa(e-t),r=Math.min(Math.abs(e-t),360);return n*r},XLe=(t,e,n,r,i)=>{var{offset:s,className:o}=t,{cx:l,cy:c,innerRadius:u,outerRadius:d,startAngle:h,endAngle:p,clockWise:m}=i,b=(u+d)/2,y=KLe(h,p),x=y>=0?1:-1,v,S;switch(e){case"insideStart":v=h+x*s,S=m;break;case"insideEnd":v=p-x*s,S=!m;break;case"end":v=p+x*s,S=m;break;default:throw new Error("Unsupported position ".concat(e))}S=y<=0?S:!S;var N=Bi(l,c,b,v),T=Bi(l,c,b,v+(S?1:-1)*359),M="M".concat(N.x,",").concat(N.y,` + A`).concat(s,",").concat(s,",0,0,").concat(+(d<0),",").concat(T.x,",").concat(T.y,"Z")}else S+="L".concat(e,",").concat(n,"Z");return S},iPe={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},mQ=t=>{var e=ci(t,iPe),{cx:n,cy:r,innerRadius:i,outerRadius:s,cornerRadius:o,forceCornerRadius:l,cornerIsExternal:c,startAngle:u,endAngle:d,className:h}=e;if(s0&&Math.abs(u-d)<360?y=rPe({cx:n,cy:r,innerRadius:i,outerRadius:s,cornerRadius:Math.min(b,m/2),forceCornerRadius:l,cornerIsExternal:c,startAngle:u,endAngle:d}):y=fQ({cx:n,cy:r,innerRadius:i,outerRadius:s,startAngle:u,endAngle:d}),_.createElement("path",mD({},Ga(e),{className:p,d:y}))};function aPe(t,e,n){if(t==="horizontal")return[{x:e.x,y:n.top},{x:e.x,y:n.top+n.height}];if(t==="vertical")return[{x:n.left,y:e.y},{x:n.left+n.width,y:e.y}];if(GX(e)){if(t==="centric"){var{cx:r,cy:i,innerRadius:s,outerRadius:o,angle:l}=e,c=Bi(r,i,s,l),u=Bi(r,i,o,l);return[{x:c.x,y:c.y},{x:u.x,y:u.y}]}return hQ(e)}}var zC={},UC={},BC={},hV;function sPe(){return hV||(hV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=iY();function n(r){return e.isSymbol(r)?NaN:Number(r)}t.toNumber=n})(BC)),BC}var fV;function oPe(){return fV||(fV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=sPe();function n(r){return r?(r=e.toNumber(r),r===1/0||r===-1/0?(r<0?-1:1)*Number.MAX_VALUE:r===r?r:0):r===0?r:0}t.toFinite=n})(UC)),UC}var mV;function lPe(){return mV||(mV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=aY(),n=oPe();function r(i,s,o){o&&typeof o!="number"&&e.isIterateeCall(i,s,o)&&(s=o=void 0),i=n.toFinite(i),s===void 0?(s=i,i=0):s=n.toFinite(s),o=o===void 0?ie?1:t>=e?0:NaN}function dPe(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}function tL(t){let e,n,r;t.length!==2?(e=_h,n=(l,c)=>_h(t(l),c),r=(l,c)=>t(l)-c):(e=t===_h||t===dPe?t:hPe,n=t,r=t);function i(l,c,u=0,d=l.length){if(u>>1;n(l[h],c)<0?u=h+1:d=h}while(u>>1;n(l[h],c)<=0?u=h+1:d=h}while(uu&&r(l[h-1],c)>-r(l[h],c)?h-1:h}return{left:i,center:o,right:s}}function hPe(){return 0}function gQ(t){return t===null?NaN:+t}function*fPe(t,e){for(let n of t)n!=null&&(n=+n)>=n&&(yield n)}const mPe=tL(_h),rv=mPe.right;tL(gQ).center;class gV extends Map{constructor(e,n=bPe){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),e!=null)for(const[r,i]of e)this.set(r,i)}get(e){return super.get(bV(this,e))}has(e){return super.has(bV(this,e))}set(e,n){return super.set(pPe(this,e),n)}delete(e){return super.delete(gPe(this,e))}}function bV({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):n}function pPe({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}function gPe({_intern:t,_key:e},n){const r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}function bPe(t){return t!==null&&typeof t=="object"?t.valueOf():t}function xPe(t=_h){if(t===_h)return bQ;if(typeof t!="function")throw new TypeError("compare is not a function");return(e,n)=>{const r=t(e,n);return r||r===0?r:(t(n,n)===0)-(t(e,e)===0)}}function bQ(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(te?1:0)}const yPe=Math.sqrt(50),vPe=Math.sqrt(10),wPe=Math.sqrt(2);function US(t,e,n){const r=(e-t)/Math.max(0,n),i=Math.floor(Math.log10(r)),s=r/Math.pow(10,i),o=s>=yPe?10:s>=vPe?5:s>=wPe?2:1;let l,c,u;return i<0?(u=Math.pow(10,-i)/o,l=Math.round(t*u),c=Math.round(e*u),l/ue&&--c,u=-u):(u=Math.pow(10,i)*o,l=Math.round(t/u),c=Math.round(e/u),l*ue&&--c),c0))return[];if(t===e)return[t];const r=e=i))return[];const l=s-i+1,c=new Array(l);if(r)if(o<0)for(let u=0;u=r)&&(n=r);return n}function yV(t,e){let n;for(const r of t)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function xQ(t,e,n=0,r=1/0,i){if(e=Math.floor(e),n=Math.floor(Math.max(0,n)),r=Math.floor(Math.min(t.length-1,r)),!(n<=e&&e<=r))return t;for(i=i===void 0?bQ:xPe(i);r>n;){if(r-n>600){const c=r-n+1,u=e-n+1,d=Math.log(c),h=.5*Math.exp(2*d/3),p=.5*Math.sqrt(d*h*(c-h)/c)*(u-c/2<0?-1:1),m=Math.max(n,Math.floor(e-u*h/c+p)),b=Math.min(r,Math.floor(e+(c-u)*h/c+p));xQ(t,e,m,b,i)}const s=t[e];let o=n,l=r;for(Jx(t,n,e),i(t[r],s)>0&&Jx(t,n,r);o0;)--l}i(t[n],s)===0?Jx(t,n,l):(++l,Jx(t,l,r)),l<=e&&(n=l+1),e<=l&&(r=l-1)}return t}function Jx(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}function _Pe(t,e,n){if(t=Float64Array.from(fPe(t)),!(!(r=t.length)||isNaN(e=+e))){if(e<=0||r<2)return yV(t);if(e>=1)return xV(t);var r,i=(r-1)*e,s=Math.floor(i),o=xV(xQ(t,s).subarray(0,s+1)),l=yV(t.subarray(s+1));return o+(l-o)*(i-s)}}function SPe(t,e,n=gQ){if(!(!(r=t.length)||isNaN(e=+e))){if(e<=0||r<2)return+n(t[0],0,t);if(e>=1)return+n(t[r-1],r-1,t);var r,i=(r-1)*e,s=Math.floor(i),o=+n(t[s],s,t),l=+n(t[s+1],s+1,t);return o+(l-o)*(i-s)}}function NPe(t,e,n){t=+t,e=+e,n=(i=arguments.length)<2?(e=t,t=0,1):i<3?1:+n;for(var r=-1,i=Math.max(0,Math.ceil((e-t)/n))|0,s=new Array(i);++r>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):n===8?Q_(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):n===4?Q_(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=EPe.exec(t))?new Vs(e[1],e[2],e[3],1):(e=TPe.exec(t))?new Vs(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=APe.exec(t))?Q_(e[1],e[2],e[3],e[4]):(e=CPe.exec(t))?Q_(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=PPe.exec(t))?MV(e[1],e[2]/100,e[3]/100,1):(e=jPe.exec(t))?MV(e[1],e[2]/100,e[3]/100,e[4]):vV.hasOwnProperty(t)?SV(vV[t]):t==="transparent"?new Vs(NaN,NaN,NaN,0):null}function SV(t){return new Vs(t>>16&255,t>>8&255,t&255,1)}function Q_(t,e,n,r){return r<=0&&(t=e=n=NaN),new Vs(t,e,n,r)}function OPe(t){return t instanceof iv||(t=vy(t)),t?(t=t.rgb(),new Vs(t.r,t.g,t.b,t.opacity)):new Vs}function yD(t,e,n,r){return arguments.length===1?OPe(t):new Vs(t,e,n,r??1)}function Vs(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}iL(Vs,yD,vQ(iv,{brighter(t){return t=t==null?BS:Math.pow(BS,t),new Vs(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?xy:Math.pow(xy,t),new Vs(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new Vs(em(this.r),em(this.g),em(this.b),HS(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:NV,formatHex:NV,formatHex8:LPe,formatRgb:kV,toString:kV}));function NV(){return`#${Bf(this.r)}${Bf(this.g)}${Bf(this.b)}`}function LPe(){return`#${Bf(this.r)}${Bf(this.g)}${Bf(this.b)}${Bf((isNaN(this.opacity)?1:this.opacity)*255)}`}function kV(){const t=HS(this.opacity);return`${t===1?"rgb(":"rgba("}${em(this.r)}, ${em(this.g)}, ${em(this.b)}${t===1?")":`, ${t})`}`}function HS(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function em(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Bf(t){return t=em(t),(t<16?"0":"")+t.toString(16)}function MV(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new Dl(t,e,n,r)}function wQ(t){if(t instanceof Dl)return new Dl(t.h,t.s,t.l,t.opacity);if(t instanceof iv||(t=vy(t)),!t)return new Dl;if(t instanceof Dl)return t;t=t.rgb();var e=t.r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),s=Math.max(e,n,r),o=NaN,l=s-i,c=(s+i)/2;return l?(e===s?o=(n-r)/l+(n0&&c<1?0:o,new Dl(o,l,c,t.opacity)}function FPe(t,e,n,r){return arguments.length===1?wQ(t):new Dl(t,e,n,r??1)}function Dl(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}iL(Dl,FPe,vQ(iv,{brighter(t){return t=t==null?BS:Math.pow(BS,t),new Dl(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?xy:Math.pow(xy,t),new Dl(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,i=2*n-r;return new Vs($C(t>=240?t-240:t+120,i,r),$C(t,i,r),$C(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new Dl(EV(this.h),Z_(this.s),Z_(this.l),HS(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=HS(this.opacity);return`${t===1?"hsl(":"hsla("}${EV(this.h)}, ${Z_(this.s)*100}%, ${Z_(this.l)*100}%${t===1?")":`, ${t})`}`}}));function EV(t){return t=(t||0)%360,t<0?t+360:t}function Z_(t){return Math.max(0,Math.min(1,t||0))}function $C(t,e,n){return(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)*255}const aL=t=>()=>t;function IPe(t,e){return function(n){return t+n*e}}function zPe(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}function UPe(t){return(t=+t)==1?_Q:function(e,n){return n-e?zPe(e,n,t):aL(isNaN(e)?n:e)}}function _Q(t,e){var n=e-t;return n?IPe(t,n):aL(isNaN(t)?e:t)}const TV=(function t(e){var n=UPe(e);function r(i,s){var o=n((i=yD(i)).r,(s=yD(s)).r),l=n(i.g,s.g),c=n(i.b,s.b),u=_Q(i.opacity,s.opacity);return function(d){return i.r=o(d),i.g=l(d),i.b=c(d),i.opacity=u(d),i+""}}return r.gamma=t,r})(1);function BPe(t,e){e||(e=[]);var n=t?Math.min(e.length,t.length):0,r=e.slice(),i;return function(s){for(i=0;in&&(s=e.slice(n,s),l[o]?l[o]+=s:l[++o]=s),(r=r[0])===(i=i[0])?l[o]?l[o]+=i:l[++o]=i:(l[++o]=null,c.push({i:o,x:$S(r,i)})),n=VC.lastIndex;return ne&&(n=t,t=e,e=n),function(r){return Math.max(t,Math.min(e,r))}}function ZPe(t,e,n){var r=t[0],i=t[1],s=e[0],o=e[1];return i2?JPe:ZPe,c=u=null,h}function h(p){return p==null||isNaN(p=+p)?s:(c||(c=l(t.map(r),e,n)))(r(o(p)))}return h.invert=function(p){return o(i((u||(u=l(e,t.map(r),$S)))(p)))},h.domain=function(p){return arguments.length?(t=Array.from(p,VS),d()):t.slice()},h.range=function(p){return arguments.length?(e=Array.from(p),d()):e.slice()},h.rangeRound=function(p){return e=Array.from(p),n=sL,d()},h.clamp=function(p){return arguments.length?(o=p?!0:ws,d()):o!==ws},h.interpolate=function(p){return arguments.length?(n=p,d()):n},h.unknown=function(p){return arguments.length?(s=p,h):s},function(p,m){return r=p,i=m,d()}}function oL(){return sM()(ws,ws)}function eje(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function GS(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}function ob(t){return t=GS(Math.abs(t)),t?t[1]:NaN}function tje(t,e){return function(n,r){for(var i=n.length,s=[],o=0,l=t[0],c=0;i>0&&l>0&&(c+l+1>r&&(l=Math.max(1,r-c)),s.push(n.substring(i-=l,i+l)),!((c+=l+1)>r));)l=t[o=(o+1)%t.length];return s.reverse().join(e)}}function nje(t){return function(e){return e.replace(/[0-9]/g,function(n){return t[+n]})}}var rje=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function wy(t){if(!(e=rje.exec(t)))throw new Error("invalid format: "+t);var e;return new lL({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}wy.prototype=lL.prototype;function lL(t){this.fill=t.fill===void 0?" ":t.fill+"",this.align=t.align===void 0?">":t.align+"",this.sign=t.sign===void 0?"-":t.sign+"",this.symbol=t.symbol===void 0?"":t.symbol+"",this.zero=!!t.zero,this.width=t.width===void 0?void 0:+t.width,this.comma=!!t.comma,this.precision=t.precision===void 0?void 0:+t.precision,this.trim=!!t.trim,this.type=t.type===void 0?"":t.type+""}lL.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function ije(t){e:for(var e=t.length,n=1,r=-1,i;n0&&(r=0);break}return r>0?t.slice(0,r)+t.slice(i+1):t}var SQ;function aje(t,e){var n=GS(t,e);if(!n)return t+"";var r=n[0],i=n[1],s=i-(SQ=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,o=r.length;return s===o?r:s>o?r+new Array(s-o+1).join("0"):s>0?r.slice(0,s)+"."+r.slice(s):"0."+new Array(1-s).join("0")+GS(t,Math.max(0,e+s-1))[0]}function CV(t,e){var n=GS(t,e);if(!n)return t+"";var r=n[0],i=n[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}const PV={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:eje,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>CV(t*100,e),r:CV,s:aje,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function jV(t){return t}var DV=Array.prototype.map,RV=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function sje(t){var e=t.grouping===void 0||t.thousands===void 0?jV:tje(DV.call(t.grouping,Number),t.thousands+""),n=t.currency===void 0?"":t.currency[0]+"",r=t.currency===void 0?"":t.currency[1]+"",i=t.decimal===void 0?".":t.decimal+"",s=t.numerals===void 0?jV:nje(DV.call(t.numerals,String)),o=t.percent===void 0?"%":t.percent+"",l=t.minus===void 0?"−":t.minus+"",c=t.nan===void 0?"NaN":t.nan+"";function u(h){h=wy(h);var p=h.fill,m=h.align,b=h.sign,y=h.symbol,x=h.zero,v=h.width,S=h.comma,N=h.precision,T=h.trim,M=h.type;M==="n"?(S=!0,M="g"):PV[M]||(N===void 0&&(N=12),T=!0,M="g"),(x||p==="0"&&m==="=")&&(x=!0,p="0",m="=");var A=y==="$"?n:y==="#"&&/[boxX]/.test(M)?"0"+M.toLowerCase():"",k=y==="$"?r:/[%p]/.test(M)?o:"",R=PV[M],C=/[defgprs%]/.test(M);N=N===void 0?6:/[gprs]/.test(M)?Math.max(1,Math.min(21,N)):Math.max(0,Math.min(20,N));function P(U){var F=A,H=k,D,$,G;if(M==="c")H=R(U)+H,U="";else{U=+U;var I=U<0||1/U<0;if(U=isNaN(U)?c:R(Math.abs(U),N),T&&(U=ije(U)),I&&+U==0&&b!=="+"&&(I=!1),F=(I?b==="("?b:l:b==="-"||b==="("?"":b)+F,H=(M==="s"?RV[8+SQ/3]:"")+H+(I&&b==="("?")":""),C){for(D=-1,$=U.length;++D<$;)if(G=U.charCodeAt(D),48>G||G>57){H=(G===46?i+U.slice(D+1):U.slice(D))+H,U=U.slice(0,D);break}}}S&&!x&&(U=e(U,1/0));var K=F.length+U.length+H.length,Q=K>1)+F+U+H+Q.slice(K);break;default:U=Q+F+U+H;break}return s(U)}return P.toString=function(){return h+""},P}function d(h,p){var m=u((h=wy(h),h.type="f",h)),b=Math.max(-8,Math.min(8,Math.floor(ob(p)/3)))*3,y=Math.pow(10,-b),x=RV[8+b/3];return function(v){return m(y*v)+x}}return{format:u,formatPrefix:d}}var J_,cL,NQ;oje({thousands:",",grouping:[3],currency:["$",""]});function oje(t){return J_=sje(t),cL=J_.format,NQ=J_.formatPrefix,J_}function lje(t){return Math.max(0,-ob(Math.abs(t)))}function cje(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(ob(e)/3)))*3-ob(Math.abs(t)))}function uje(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,ob(e)-ob(t))+1}function kQ(t,e,n,r){var i=bD(t,e,n),s;switch(r=wy(r??",f"),r.type){case"s":{var o=Math.max(Math.abs(t),Math.abs(e));return r.precision==null&&!isNaN(s=cje(i,o))&&(r.precision=s),NQ(r,o)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(s=uje(i,Math.max(Math.abs(t),Math.abs(e))))&&(r.precision=s-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(s=lje(i))&&(r.precision=s-(r.type==="%")*2);break}}return cL(r)}function $h(t){var e=t.domain;return t.ticks=function(n){var r=e();return pD(r[0],r[r.length-1],n??10)},t.tickFormat=function(n,r){var i=e();return kQ(i[0],i[i.length-1],n??10,r)},t.nice=function(n){n==null&&(n=10);var r=e(),i=0,s=r.length-1,o=r[i],l=r[s],c,u,d=10;for(l0;){if(u=gD(o,l,n),u===c)return r[i]=o,r[s]=l,e(r);if(u>0)o=Math.floor(o/u)*u,l=Math.ceil(l/u)*u;else if(u<0)o=Math.ceil(o*u)/u,l=Math.floor(l*u)/u;else break;c=u}return t},t}function MQ(){var t=oL();return t.copy=function(){return av(t,MQ())},xl.apply(t,arguments),$h(t)}function EQ(t){var e;function n(r){return r==null||isNaN(r=+r)?e:r}return n.invert=n,n.domain=n.range=function(r){return arguments.length?(t=Array.from(r,VS),n):t.slice()},n.unknown=function(r){return arguments.length?(e=r,n):e},n.copy=function(){return EQ(t).unknown(e)},t=arguments.length?Array.from(t,VS):[0,1],$h(n)}function TQ(t,e){t=t.slice();var n=0,r=t.length-1,i=t[n],s=t[r],o;return sMath.pow(t,e)}function pje(t){return t===Math.E?Math.log:t===10&&Math.log10||t===2&&Math.log2||(t=Math.log(t),e=>Math.log(e)/t)}function FV(t){return(e,n)=>-t(-e,n)}function uL(t){const e=t(OV,LV),n=e.domain;let r=10,i,s;function o(){return i=pje(r),s=mje(r),n()[0]<0?(i=FV(i),s=FV(s),t(dje,hje)):t(OV,LV),e}return e.base=function(l){return arguments.length?(r=+l,o()):r},e.domain=function(l){return arguments.length?(n(l),o()):n()},e.ticks=l=>{const c=n();let u=c[0],d=c[c.length-1];const h=d0){for(;p<=m;++p)for(b=1;bd)break;v.push(y)}}else for(;p<=m;++p)for(b=r-1;b>=1;--b)if(y=p>0?b/s(-p):b*s(p),!(yd)break;v.push(y)}v.length*2{if(l==null&&(l=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=wy(c)).precision==null&&(c.trim=!0),c=cL(c)),l===1/0)return c;const u=Math.max(1,r*l/e.ticks().length);return d=>{let h=d/s(Math.round(i(d)));return h*rn(TQ(n(),{floor:l=>s(Math.floor(i(l))),ceil:l=>s(Math.ceil(i(l)))})),e}function AQ(){const t=uL(sM()).domain([1,10]);return t.copy=()=>av(t,AQ()).base(t.base()),xl.apply(t,arguments),t}function IV(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function zV(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function dL(t){var e=1,n=t(IV(e),zV(e));return n.constant=function(r){return arguments.length?t(IV(e=+r),zV(e)):e},$h(n)}function CQ(){var t=dL(sM());return t.copy=function(){return av(t,CQ()).constant(t.constant())},xl.apply(t,arguments)}function UV(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function gje(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function bje(t){return t<0?-t*t:t*t}function hL(t){var e=t(ws,ws),n=1;function r(){return n===1?t(ws,ws):n===.5?t(gje,bje):t(UV(n),UV(1/n))}return e.exponent=function(i){return arguments.length?(n=+i,r()):n},$h(e)}function fL(){var t=hL(sM());return t.copy=function(){return av(t,fL()).exponent(t.exponent())},xl.apply(t,arguments),t}function xje(){return fL.apply(null,arguments).exponent(.5)}function BV(t){return Math.sign(t)*t*t}function yje(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function PQ(){var t=oL(),e=[0,1],n=!1,r;function i(s){var o=yje(t(s));return isNaN(o)?r:n?Math.round(o):o}return i.invert=function(s){return t.invert(BV(s))},i.domain=function(s){return arguments.length?(t.domain(s),i):t.domain()},i.range=function(s){return arguments.length?(t.range((e=Array.from(s,VS)).map(BV)),i):e.slice()},i.rangeRound=function(s){return i.range(s).round(!0)},i.round=function(s){return arguments.length?(n=!!s,i):n},i.clamp=function(s){return arguments.length?(t.clamp(s),i):t.clamp()},i.unknown=function(s){return arguments.length?(r=s,i):r},i.copy=function(){return PQ(t.domain(),e).round(n).clamp(t.clamp()).unknown(r)},xl.apply(i,arguments),$h(i)}function jQ(){var t=[],e=[],n=[],r;function i(){var o=0,l=Math.max(1,e.length);for(n=new Array(l-1);++o0?n[l-1]:t[0],l=n?[r[n-1],e]:[r[u-1],r[u]]},o.unknown=function(c){return arguments.length&&(s=c),o},o.thresholds=function(){return r.slice()},o.copy=function(){return DQ().domain([t,e]).range(i).unknown(s)},xl.apply($h(o),arguments)}function RQ(){var t=[.5],e=[0,1],n,r=1;function i(s){return s!=null&&s<=s?e[rv(t,s,0,r)]:n}return i.domain=function(s){return arguments.length?(t=Array.from(s),r=Math.min(t.length,e.length-1),i):t.slice()},i.range=function(s){return arguments.length?(e=Array.from(s),r=Math.min(t.length,e.length-1),i):e.slice()},i.invertExtent=function(s){var o=e.indexOf(s);return[t[o-1],t[o]]},i.unknown=function(s){return arguments.length?(n=s,i):n},i.copy=function(){return RQ().domain(t).range(e).unknown(n)},xl.apply(i,arguments)}const GC=new Date,qC=new Date;function sa(t,e,n,r){function i(s){return t(s=arguments.length===0?new Date:new Date(+s)),s}return i.floor=s=>(t(s=new Date(+s)),s),i.ceil=s=>(t(s=new Date(s-1)),e(s,1),t(s),s),i.round=s=>{const o=i(s),l=i.ceil(s);return s-o(e(s=new Date(+s),o==null?1:Math.floor(o)),s),i.range=(s,o,l)=>{const c=[];if(s=i.ceil(s),l=l==null?1:Math.floor(l),!(s0))return c;let u;do c.push(u=new Date(+s)),e(s,l),t(s);while(usa(o=>{if(o>=o)for(;t(o),!s(o);)o.setTime(o-1)},(o,l)=>{if(o>=o)if(l<0)for(;++l<=0;)for(;e(o,-1),!s(o););else for(;--l>=0;)for(;e(o,1),!s(o););}),n&&(i.count=(s,o)=>(GC.setTime(+s),qC.setTime(+o),t(GC),t(qC),Math.floor(n(GC,qC))),i.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?i.filter(r?o=>r(o)%s===0:o=>i.count(0,o)%s===0):i)),i}const qS=sa(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);qS.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?sa(e=>{e.setTime(Math.floor(e/t)*t)},(e,n)=>{e.setTime(+e+n*t)},(e,n)=>(n-e)/t):qS);qS.range;const ku=1e3,al=ku*60,Mu=al*60,Ku=Mu*24,mL=Ku*7,HV=Ku*30,WC=Ku*365,Hf=sa(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*ku)},(t,e)=>(e-t)/ku,t=>t.getUTCSeconds());Hf.range;const pL=sa(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*ku)},(t,e)=>{t.setTime(+t+e*al)},(t,e)=>(e-t)/al,t=>t.getMinutes());pL.range;const gL=sa(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*al)},(t,e)=>(e-t)/al,t=>t.getUTCMinutes());gL.range;const bL=sa(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*ku-t.getMinutes()*al)},(t,e)=>{t.setTime(+t+e*Mu)},(t,e)=>(e-t)/Mu,t=>t.getHours());bL.range;const xL=sa(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*Mu)},(t,e)=>(e-t)/Mu,t=>t.getUTCHours());xL.range;const sv=sa(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*al)/Ku,t=>t.getDate()-1);sv.range;const oM=sa(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Ku,t=>t.getUTCDate()-1);oM.range;const OQ=sa(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Ku,t=>Math.floor(t/Ku));OQ.range;function Fm(t){return sa(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(e,n)=>{e.setDate(e.getDate()+n*7)},(e,n)=>(n-e-(n.getTimezoneOffset()-e.getTimezoneOffset())*al)/mL)}const lM=Fm(0),WS=Fm(1),vje=Fm(2),wje=Fm(3),lb=Fm(4),_je=Fm(5),Sje=Fm(6);lM.range;WS.range;vje.range;wje.range;lb.range;_je.range;Sje.range;function Im(t){return sa(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(e,n)=>{e.setUTCDate(e.getUTCDate()+n*7)},(e,n)=>(n-e)/mL)}const cM=Im(0),KS=Im(1),Nje=Im(2),kje=Im(3),cb=Im(4),Mje=Im(5),Eje=Im(6);cM.range;KS.range;Nje.range;kje.range;cb.range;Mje.range;Eje.range;const yL=sa(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth());yL.range;const vL=sa(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth());vL.range;const Xu=sa(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());Xu.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:sa(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,n)=>{e.setFullYear(e.getFullYear()+n*t)});Xu.range;const Yu=sa(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());Yu.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:sa(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,n)=>{e.setUTCFullYear(e.getUTCFullYear()+n*t)});Yu.range;function LQ(t,e,n,r,i,s){const o=[[Hf,1,ku],[Hf,5,5*ku],[Hf,15,15*ku],[Hf,30,30*ku],[s,1,al],[s,5,5*al],[s,15,15*al],[s,30,30*al],[i,1,Mu],[i,3,3*Mu],[i,6,6*Mu],[i,12,12*Mu],[r,1,Ku],[r,2,2*Ku],[n,1,mL],[e,1,HV],[e,3,3*HV],[t,1,WC]];function l(u,d,h){const p=dx).right(o,p);if(m===o.length)return t.every(bD(u/WC,d/WC,h));if(m===0)return qS.every(Math.max(bD(u,d,h),1));const[b,y]=o[p/o[m-1][2]53)return null;"w"in ce||(ce.w=1),"Z"in ce?(V=XC(e0(ce.y,0,1)),Y=V.getUTCDay(),V=Y>4||Y===0?KS.ceil(V):KS(V),V=oM.offset(V,(ce.V-1)*7),ce.y=V.getUTCFullYear(),ce.m=V.getUTCMonth(),ce.d=V.getUTCDate()+(ce.w+6)%7):(V=KC(e0(ce.y,0,1)),Y=V.getDay(),V=Y>4||Y===0?WS.ceil(V):WS(V),V=sv.offset(V,(ce.V-1)*7),ce.y=V.getFullYear(),ce.m=V.getMonth(),ce.d=V.getDate()+(ce.w+6)%7)}else("W"in ce||"U"in ce)&&("w"in ce||(ce.w="u"in ce?ce.u%7:"W"in ce?1:0),Y="Z"in ce?XC(e0(ce.y,0,1)).getUTCDay():KC(e0(ce.y,0,1)).getDay(),ce.m=0,ce.d="W"in ce?(ce.w+6)%7+ce.W*7-(Y+5)%7:ce.w+ce.U*7-(Y+6)%7);return"Z"in ce?(ce.H+=ce.Z/100|0,ce.M+=ce.Z%100,XC(ce)):KC(ce)}}function R(se,ke,Fe,ce){for(var Ve=0,V=ke.length,Y=Fe.length,ue,q;Ve=Y)return-1;if(ue=ke.charCodeAt(Ve++),ue===37){if(ue=ke.charAt(Ve++),q=M[ue in $V?ke.charAt(Ve++):ue],!q||(ce=q(se,Fe,ce))<0)return-1}else if(ue!=Fe.charCodeAt(ce++))return-1}return ce}function C(se,ke,Fe){var ce=u.exec(ke.slice(Fe));return ce?(se.p=d.get(ce[0].toLowerCase()),Fe+ce[0].length):-1}function P(se,ke,Fe){var ce=m.exec(ke.slice(Fe));return ce?(se.w=b.get(ce[0].toLowerCase()),Fe+ce[0].length):-1}function U(se,ke,Fe){var ce=h.exec(ke.slice(Fe));return ce?(se.w=p.get(ce[0].toLowerCase()),Fe+ce[0].length):-1}function F(se,ke,Fe){var ce=v.exec(ke.slice(Fe));return ce?(se.m=S.get(ce[0].toLowerCase()),Fe+ce[0].length):-1}function H(se,ke,Fe){var ce=y.exec(ke.slice(Fe));return ce?(se.m=x.get(ce[0].toLowerCase()),Fe+ce[0].length):-1}function D(se,ke,Fe){return R(se,e,ke,Fe)}function $(se,ke,Fe){return R(se,n,ke,Fe)}function G(se,ke,Fe){return R(se,r,ke,Fe)}function I(se){return o[se.getDay()]}function K(se){return s[se.getDay()]}function Q(se){return c[se.getMonth()]}function oe(se){return l[se.getMonth()]}function B(se){return i[+(se.getHours()>=12)]}function W(se){return 1+~~(se.getMonth()/3)}function J(se){return o[se.getUTCDay()]}function ne(se){return s[se.getUTCDay()]}function me(se){return c[se.getUTCMonth()]}function fe(se){return l[se.getUTCMonth()]}function de(se){return i[+(se.getUTCHours()>=12)]}function Re(se){return 1+~~(se.getUTCMonth()/3)}return{format:function(se){var ke=A(se+="",N);return ke.toString=function(){return se},ke},parse:function(se){var ke=k(se+="",!1);return ke.toString=function(){return se},ke},utcFormat:function(se){var ke=A(se+="",T);return ke.toString=function(){return se},ke},utcParse:function(se){var ke=k(se+="",!0);return ke.toString=function(){return se},ke}}}var $V={"-":"",_:" ",0:"0"},ka=/^\s*\d+/,Dje=/^%/,Rje=/[\\^$*+?|[\]().{}]/g;function ur(t,e,n){var r=t<0?"-":"",i=(r?-t:t)+"",s=i.length;return r+(s[e.toLowerCase(),n]))}function Lje(t,e,n){var r=ka.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function Fje(t,e,n){var r=ka.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function Ije(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function zje(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function Uje(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function VV(t,e,n){var r=ka.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function GV(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function Bje(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function Hje(t,e,n){var r=ka.exec(e.slice(n,n+1));return r?(t.q=r[0]*3-3,n+r[0].length):-1}function $je(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function qV(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function Vje(t,e,n){var r=ka.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function WV(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function Gje(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function qje(t,e,n){var r=ka.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function Wje(t,e,n){var r=ka.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function Kje(t,e,n){var r=ka.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function Xje(t,e,n){var r=Dje.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function Yje(t,e,n){var r=ka.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function Qje(t,e,n){var r=ka.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function KV(t,e){return ur(t.getDate(),e,2)}function Zje(t,e){return ur(t.getHours(),e,2)}function Jje(t,e){return ur(t.getHours()%12||12,e,2)}function e3e(t,e){return ur(1+sv.count(Xu(t),t),e,3)}function FQ(t,e){return ur(t.getMilliseconds(),e,3)}function t3e(t,e){return FQ(t,e)+"000"}function n3e(t,e){return ur(t.getMonth()+1,e,2)}function r3e(t,e){return ur(t.getMinutes(),e,2)}function i3e(t,e){return ur(t.getSeconds(),e,2)}function a3e(t){var e=t.getDay();return e===0?7:e}function s3e(t,e){return ur(lM.count(Xu(t)-1,t),e,2)}function IQ(t){var e=t.getDay();return e>=4||e===0?lb(t):lb.ceil(t)}function o3e(t,e){return t=IQ(t),ur(lb.count(Xu(t),t)+(Xu(t).getDay()===4),e,2)}function l3e(t){return t.getDay()}function c3e(t,e){return ur(WS.count(Xu(t)-1,t),e,2)}function u3e(t,e){return ur(t.getFullYear()%100,e,2)}function d3e(t,e){return t=IQ(t),ur(t.getFullYear()%100,e,2)}function h3e(t,e){return ur(t.getFullYear()%1e4,e,4)}function f3e(t,e){var n=t.getDay();return t=n>=4||n===0?lb(t):lb.ceil(t),ur(t.getFullYear()%1e4,e,4)}function m3e(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+ur(e/60|0,"0",2)+ur(e%60,"0",2)}function XV(t,e){return ur(t.getUTCDate(),e,2)}function p3e(t,e){return ur(t.getUTCHours(),e,2)}function g3e(t,e){return ur(t.getUTCHours()%12||12,e,2)}function b3e(t,e){return ur(1+oM.count(Yu(t),t),e,3)}function zQ(t,e){return ur(t.getUTCMilliseconds(),e,3)}function x3e(t,e){return zQ(t,e)+"000"}function y3e(t,e){return ur(t.getUTCMonth()+1,e,2)}function v3e(t,e){return ur(t.getUTCMinutes(),e,2)}function w3e(t,e){return ur(t.getUTCSeconds(),e,2)}function _3e(t){var e=t.getUTCDay();return e===0?7:e}function S3e(t,e){return ur(cM.count(Yu(t)-1,t),e,2)}function UQ(t){var e=t.getUTCDay();return e>=4||e===0?cb(t):cb.ceil(t)}function N3e(t,e){return t=UQ(t),ur(cb.count(Yu(t),t)+(Yu(t).getUTCDay()===4),e,2)}function k3e(t){return t.getUTCDay()}function M3e(t,e){return ur(KS.count(Yu(t)-1,t),e,2)}function E3e(t,e){return ur(t.getUTCFullYear()%100,e,2)}function T3e(t,e){return t=UQ(t),ur(t.getUTCFullYear()%100,e,2)}function A3e(t,e){return ur(t.getUTCFullYear()%1e4,e,4)}function C3e(t,e){var n=t.getUTCDay();return t=n>=4||n===0?cb(t):cb.ceil(t),ur(t.getUTCFullYear()%1e4,e,4)}function P3e(){return"+0000"}function YV(){return"%"}function QV(t){return+t}function ZV(t){return Math.floor(+t/1e3)}var eg,BQ,HQ;j3e({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function j3e(t){return eg=jje(t),BQ=eg.format,eg.parse,HQ=eg.utcFormat,eg.utcParse,eg}function D3e(t){return new Date(t)}function R3e(t){return t instanceof Date?+t:+new Date(+t)}function wL(t,e,n,r,i,s,o,l,c,u){var d=oL(),h=d.invert,p=d.domain,m=u(".%L"),b=u(":%S"),y=u("%I:%M"),x=u("%I %p"),v=u("%a %d"),S=u("%b %d"),N=u("%B"),T=u("%Y");function M(A){return(c(A)e(i/(t.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(i,s)=>_Pe(t,s/r))},n.copy=function(){return qQ(e).domain(t)},nd.apply(n,arguments)}function dM(){var t=0,e=.5,n=1,r=1,i,s,o,l,c,u=ws,d,h=!1,p;function m(y){return isNaN(y=+y)?p:(y=.5+((y=+d(y))-s)*(r*yt.chartData,NL=st([Gh],t=>{var e=t.chartData!=null?t.chartData.length-1:0;return{chartData:t.chartData,computedData:t.computedData,dataEndIndex:e,dataStartIndex:0}}),ov=(t,e,n,r)=>r?NL(t):Gh(t);function Lh(t){if(Array.isArray(t)&&t.length===2){var[e,n]=t;if(wr(e)&&wr(n))return!0}return!1}function JV(t,e,n){return n?t:[Math.min(t[0],e[0]),Math.max(t[1],e[1])]}function YQ(t,e){if(e&&typeof t!="function"&&Array.isArray(t)&&t.length===2){var[n,r]=t,i,s;if(wr(n))i=n;else if(typeof n=="function")return;if(wr(r))s=r;else if(typeof r=="function")return;var o=[i,s];if(Lh(o))return o}}function z3e(t,e,n){if(!(!n&&e==null)){if(typeof t=="function"&&e!=null)try{var r=t(e,n);if(Lh(r))return JV(r,e,n)}catch{}if(Array.isArray(t)&&t.length===2){var[i,s]=t,o,l;if(i==="auto")e!=null&&(o=Math.min(...e));else if(Vt(i))o=i;else if(typeof i=="function")try{e!=null&&(o=i(e?.[0]))}catch{}else if(typeof i=="string"&&E$.test(i)){var c=E$.exec(i);if(c==null||e==null)o=void 0;else{var u=+c[1];o=e[0]-u}}else o=e?.[0];if(s==="auto")e!=null&&(l=Math.max(...e));else if(Vt(s))l=s;else if(typeof s=="function")try{e!=null&&(l=s(e?.[1]))}catch{}else if(typeof s=="string"&&T$.test(s)){var d=T$.exec(s);if(d==null||e==null)l=void 0;else{var h=+d[1];l=e[1]+h}}else l=e?.[1];var p=[o,l];if(Lh(p))return e==null?p:JV(p,e,n)}}}var Db=1e9,U3e={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},ML,ni=!0,pl="[DecimalError] ",tm=pl+"Invalid argument: ",kL=pl+"Exponent out of range: ",Rb=Math.floor,Cf=Math.pow,B3e=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,go,xa=1e7,Kr=7,QQ=9007199254740991,XS=Rb(QQ/Kr),qt={};qt.absoluteValue=qt.abs=function(){var t=new this.constructor(this);return t.s&&(t.s=1),t};qt.comparedTo=qt.cmp=function(t){var e,n,r,i,s=this;if(t=new s.constructor(t),s.s!==t.s)return s.s||-t.s;if(s.e!==t.e)return s.e>t.e^s.s<0?1:-1;for(r=s.d.length,i=t.d.length,e=0,n=rt.d[e]^s.s<0?1:-1;return r===i?0:r>i^s.s<0?1:-1};qt.decimalPlaces=qt.dp=function(){var t=this,e=t.d.length-1,n=(e-t.e)*Kr;if(e=t.d[e],e)for(;e%10==0;e/=10)n--;return n<0?0:n};qt.dividedBy=qt.div=function(t){return Du(this,new this.constructor(t))};qt.dividedToIntegerBy=qt.idiv=function(t){var e=this,n=e.constructor;return Fr(Du(e,new n(t),0,1),n.precision)};qt.equals=qt.eq=function(t){return!this.cmp(t)};qt.exponent=function(){return Gi(this)};qt.greaterThan=qt.gt=function(t){return this.cmp(t)>0};qt.greaterThanOrEqualTo=qt.gte=function(t){return this.cmp(t)>=0};qt.isInteger=qt.isint=function(){return this.e>this.d.length-2};qt.isNegative=qt.isneg=function(){return this.s<0};qt.isPositive=qt.ispos=function(){return this.s>0};qt.isZero=function(){return this.s===0};qt.lessThan=qt.lt=function(t){return this.cmp(t)<0};qt.lessThanOrEqualTo=qt.lte=function(t){return this.cmp(t)<1};qt.logarithm=qt.log=function(t){var e,n=this,r=n.constructor,i=r.precision,s=i+5;if(t===void 0)t=new r(10);else if(t=new r(t),t.s<1||t.eq(go))throw Error(pl+"NaN");if(n.s<1)throw Error(pl+(n.s?"NaN":"-Infinity"));return n.eq(go)?new r(0):(ni=!1,e=Du(_y(n,s),_y(t,s),s),ni=!0,Fr(e,i))};qt.minus=qt.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?eZ(e,t):ZQ(e,(t.s=-t.s,t))};qt.modulo=qt.mod=function(t){var e,n=this,r=n.constructor,i=r.precision;if(t=new r(t),!t.s)throw Error(pl+"NaN");return n.s?(ni=!1,e=Du(n,t,0,1).times(t),ni=!0,n.minus(e)):Fr(new r(n),i)};qt.naturalExponential=qt.exp=function(){return JQ(this)};qt.naturalLogarithm=qt.ln=function(){return _y(this)};qt.negated=qt.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};qt.plus=qt.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?ZQ(e,t):eZ(e,(t.s=-t.s,t))};qt.precision=qt.sd=function(t){var e,n,r,i=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(tm+t);if(e=Gi(i)+1,r=i.d.length-1,n=r*Kr+1,r=i.d[r],r){for(;r%10==0;r/=10)n--;for(r=i.d[0];r>=10;r/=10)n++}return t&&e>n?e:n};qt.squareRoot=qt.sqrt=function(){var t,e,n,r,i,s,o,l=this,c=l.constructor;if(l.s<1){if(!l.s)return new c(0);throw Error(pl+"NaN")}for(t=Gi(l),ni=!1,i=Math.sqrt(+l),i==0||i==1/0?(e=uc(l.d),(e.length+t)%2==0&&(e+="0"),i=Math.sqrt(e),t=Rb((t+1)/2)-(t<0||t%2),i==1/0?e="5e"+t:(e=i.toExponential(),e=e.slice(0,e.indexOf("e")+1)+t),r=new c(e)):r=new c(i.toString()),n=c.precision,i=o=n+3;;)if(s=r,r=s.plus(Du(l,s,o+2)).times(.5),uc(s.d).slice(0,o)===(e=uc(r.d)).slice(0,o)){if(e=e.slice(o-3,o+1),i==o&&e=="4999"){if(Fr(s,n+1,0),s.times(s).eq(l)){r=s;break}}else if(e!="9999")break;o+=4}return ni=!0,Fr(r,n)};qt.times=qt.mul=function(t){var e,n,r,i,s,o,l,c,u,d=this,h=d.constructor,p=d.d,m=(t=new h(t)).d;if(!d.s||!t.s)return new h(0);for(t.s*=d.s,n=d.e+t.e,c=p.length,u=m.length,c=0;){for(e=0,i=c+r;i>r;)l=s[i]+m[r]*p[i-r-1]+e,s[i--]=l%xa|0,e=l/xa|0;s[i]=(s[i]+e)%xa|0}for(;!s[--o];)s.pop();return e?++n:s.shift(),t.d=s,t.e=n,ni?Fr(t,h.precision):t};qt.toDecimalPlaces=qt.todp=function(t,e){var n=this,r=n.constructor;return n=new r(n),t===void 0?n:(vc(t,0,Db),e===void 0?e=r.rounding:vc(e,0,8),Fr(n,t+Gi(n)+1,e))};qt.toExponential=function(t,e){var n,r=this,i=r.constructor;return t===void 0?n=Nm(r,!0):(vc(t,0,Db),e===void 0?e=i.rounding:vc(e,0,8),r=Fr(new i(r),t+1,e),n=Nm(r,!0,t+1)),n};qt.toFixed=function(t,e){var n,r,i=this,s=i.constructor;return t===void 0?Nm(i):(vc(t,0,Db),e===void 0?e=s.rounding:vc(e,0,8),r=Fr(new s(i),t+Gi(i)+1,e),n=Nm(r.abs(),!1,t+Gi(r)+1),i.isneg()&&!i.isZero()?"-"+n:n)};qt.toInteger=qt.toint=function(){var t=this,e=t.constructor;return Fr(new e(t),Gi(t)+1,e.rounding)};qt.toNumber=function(){return+this};qt.toPower=qt.pow=function(t){var e,n,r,i,s,o,l=this,c=l.constructor,u=12,d=+(t=new c(t));if(!t.s)return new c(go);if(l=new c(l),!l.s){if(t.s<1)throw Error(pl+"Infinity");return l}if(l.eq(go))return l;if(r=c.precision,t.eq(go))return Fr(l,r);if(e=t.e,n=t.d.length-1,o=e>=n,s=l.s,o){if((n=d<0?-d:d)<=QQ){for(i=new c(go),e=Math.ceil(r/Kr+4),ni=!1;n%2&&(i=i.times(l),tG(i.d,e)),n=Rb(n/2),n!==0;)l=l.times(l),tG(l.d,e);return ni=!0,t.s<0?new c(go).div(i):Fr(i,r)}}else if(s<0)throw Error(pl+"NaN");return s=s<0&&t.d[Math.max(e,n)]&1?-1:1,l.s=1,ni=!1,i=t.times(_y(l,r+u)),ni=!0,i=JQ(i),i.s=s,i};qt.toPrecision=function(t,e){var n,r,i=this,s=i.constructor;return t===void 0?(n=Gi(i),r=Nm(i,n<=s.toExpNeg||n>=s.toExpPos)):(vc(t,1,Db),e===void 0?e=s.rounding:vc(e,0,8),i=Fr(new s(i),t,e),n=Gi(i),r=Nm(i,t<=n||n<=s.toExpNeg,t)),r};qt.toSignificantDigits=qt.tosd=function(t,e){var n=this,r=n.constructor;return t===void 0?(t=r.precision,e=r.rounding):(vc(t,1,Db),e===void 0?e=r.rounding:vc(e,0,8)),Fr(new r(n),t,e)};qt.toString=qt.valueOf=qt.val=qt.toJSON=qt[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=Gi(t),n=t.constructor;return Nm(t,e<=n.toExpNeg||e>=n.toExpPos)};function ZQ(t,e){var n,r,i,s,o,l,c,u,d=t.constructor,h=d.precision;if(!t.s||!e.s)return e.s||(e=new d(t)),ni?Fr(e,h):e;if(c=t.d,u=e.d,o=t.e,i=e.e,c=c.slice(),s=o-i,s){for(s<0?(r=c,s=-s,l=u.length):(r=u,i=o,l=c.length),o=Math.ceil(h/Kr),l=o>l?o+1:l+1,s>l&&(s=l,r.length=1),r.reverse();s--;)r.push(0);r.reverse()}for(l=c.length,s=u.length,l-s<0&&(s=l,r=u,u=c,c=r),n=0;s;)n=(c[--s]=c[s]+u[s]+n)/xa|0,c[s]%=xa;for(n&&(c.unshift(n),++i),l=c.length;c[--l]==0;)c.pop();return e.d=c,e.e=i,ni?Fr(e,h):e}function vc(t,e,n){if(t!==~~t||tn)throw Error(tm+t)}function uc(t){var e,n,r,i=t.length-1,s="",o=t[0];if(i>0){for(s+=o,e=1;eo?1:-1;else for(l=c=0;li[l]?1:-1;break}return c}function n(r,i,s){for(var o=0;s--;)r[s]-=o,o=r[s]1;)r.shift()}return function(r,i,s,o){var l,c,u,d,h,p,m,b,y,x,v,S,N,T,M,A,k,R,C=r.constructor,P=r.s==i.s?1:-1,U=r.d,F=i.d;if(!r.s)return new C(r);if(!i.s)throw Error(pl+"Division by zero");for(c=r.e-i.e,k=F.length,M=U.length,m=new C(P),b=m.d=[],u=0;F[u]==(U[u]||0);)++u;if(F[u]>(U[u]||0)&&--c,s==null?S=s=C.precision:o?S=s+(Gi(r)-Gi(i))+1:S=s,S<0)return new C(0);if(S=S/Kr+2|0,u=0,k==1)for(d=0,F=F[0],S++;(u1&&(F=t(F,d),U=t(U,d),k=F.length,M=U.length),T=k,y=U.slice(0,k),x=y.length;x=xa/2&&++A;do d=0,l=e(F,y,k,x),l<0?(v=y[0],k!=x&&(v=v*xa+(y[1]||0)),d=v/A|0,d>1?(d>=xa&&(d=xa-1),h=t(F,d),p=h.length,x=y.length,l=e(h,y,p,x),l==1&&(d--,n(h,k16)throw Error(kL+Gi(t));if(!t.s)return new d(go);for(ni=!1,l=h,o=new d(.03125);t.abs().gte(.1);)t=t.times(o),u+=5;for(r=Math.log(Cf(2,u))/Math.LN10*2+5|0,l+=r,n=i=s=new d(go),d.precision=l;;){if(i=Fr(i.times(t),l),n=n.times(++c),o=s.plus(Du(i,n,l)),uc(o.d).slice(0,l)===uc(s.d).slice(0,l)){for(;u--;)s=Fr(s.times(s),l);return d.precision=h,e==null?(ni=!0,Fr(s,h)):s}s=o}}function Gi(t){for(var e=t.e*Kr,n=t.d[0];n>=10;n/=10)e++;return e}function YC(t,e,n){if(e>t.LN10.sd())throw ni=!0,n&&(t.precision=n),Error(pl+"LN10 precision limit exceeded");return Fr(new t(t.LN10),e)}function Qd(t){for(var e="";t--;)e+="0";return e}function _y(t,e){var n,r,i,s,o,l,c,u,d,h=1,p=10,m=t,b=m.d,y=m.constructor,x=y.precision;if(m.s<1)throw Error(pl+(m.s?"NaN":"-Infinity"));if(m.eq(go))return new y(0);if(e==null?(ni=!1,u=x):u=e,m.eq(10))return e==null&&(ni=!0),YC(y,u);if(u+=p,y.precision=u,n=uc(b),r=n.charAt(0),s=Gi(m),Math.abs(s)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)m=m.times(t),n=uc(m.d),r=n.charAt(0),h++;s=Gi(m),r>1?(m=new y("0."+n),s++):m=new y(r+"."+n.slice(1))}else return c=YC(y,u+2,x).times(s+""),m=_y(new y(r+"."+n.slice(1)),u-p).plus(c),y.precision=x,e==null?(ni=!0,Fr(m,x)):m;for(l=o=m=Du(m.minus(go),m.plus(go),u),d=Fr(m.times(m),u),i=3;;){if(o=Fr(o.times(d),u),c=l.plus(Du(o,new y(i),u)),uc(c.d).slice(0,u)===uc(l.d).slice(0,u))return l=l.times(2),s!==0&&(l=l.plus(YC(y,u+2,x).times(s+""))),l=Du(l,new y(h),u),y.precision=x,e==null?(ni=!0,Fr(l,x)):l;l=c,i+=2}}function eG(t,e){var n,r,i;for((n=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(n<0&&(n=r),n+=+e.slice(r+1),e=e.substring(0,r)):n<0&&(n=e.length),r=0;e.charCodeAt(r)===48;)++r;for(i=e.length;e.charCodeAt(i-1)===48;)--i;if(e=e.slice(r,i),e){if(i-=r,n=n-r-1,t.e=Rb(n/Kr),t.d=[],r=(n+1)%Kr,n<0&&(r+=Kr),rXS||t.e<-XS))throw Error(kL+n)}else t.s=0,t.e=0,t.d=[0];return t}function Fr(t,e,n){var r,i,s,o,l,c,u,d,h=t.d;for(o=1,s=h[0];s>=10;s/=10)o++;if(r=e-o,r<0)r+=Kr,i=e,u=h[d=0];else{if(d=Math.ceil((r+1)/Kr),s=h.length,d>=s)return t;for(u=s=h[d],o=1;s>=10;s/=10)o++;r%=Kr,i=r-Kr+o}if(n!==void 0&&(s=Cf(10,o-i-1),l=u/s%10|0,c=e<0||h[d+1]!==void 0||u%s,c=n<4?(l||c)&&(n==0||n==(t.s<0?3:2)):l>5||l==5&&(n==4||c||n==6&&(r>0?i>0?u/Cf(10,o-i):0:h[d-1])%10&1||n==(t.s<0?8:7))),e<1||!h[0])return c?(s=Gi(t),h.length=1,e=e-s-1,h[0]=Cf(10,(Kr-e%Kr)%Kr),t.e=Rb(-e/Kr)||0):(h.length=1,h[0]=t.e=t.s=0),t;if(r==0?(h.length=d,s=1,d--):(h.length=d+1,s=Cf(10,Kr-r),h[d]=i>0?(u/Cf(10,o-i)%Cf(10,i)|0)*s:0),c)for(;;)if(d==0){(h[0]+=s)==xa&&(h[0]=1,++t.e);break}else{if(h[d]+=s,h[d]!=xa)break;h[d--]=0,s=1}for(r=h.length;h[--r]===0;)h.pop();if(ni&&(t.e>XS||t.e<-XS))throw Error(kL+Gi(t));return t}function eZ(t,e){var n,r,i,s,o,l,c,u,d,h,p=t.constructor,m=p.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new p(t),ni?Fr(e,m):e;if(c=t.d,h=e.d,r=e.e,u=t.e,c=c.slice(),o=u-r,o){for(d=o<0,d?(n=c,o=-o,l=h.length):(n=h,r=u,l=c.length),i=Math.max(Math.ceil(m/Kr),l)+2,o>i&&(o=i,n.length=1),n.reverse(),i=o;i--;)n.push(0);n.reverse()}else{for(i=c.length,l=h.length,d=i0;--i)c[l++]=0;for(i=h.length;i>o;){if(c[--i]0?s=s.charAt(0)+"."+s.slice(1)+Qd(r):o>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(i<0?"e":"e+")+i):i<0?(s="0."+Qd(-i-1)+s,n&&(r=n-o)>0&&(s+=Qd(r))):i>=o?(s+=Qd(i+1-o),n&&(r=n-i-1)>0&&(s=s+"."+Qd(r))):((r=i+1)0&&(i+1===o&&(s+="."),s+=Qd(r))),t.s<0?"-"+s:s}function tG(t,e){if(t.length>e)return t.length=e,!0}function tZ(t){var e,n,r;function i(s){var o=this;if(!(o instanceof i))return new i(s);if(o.constructor=i,s instanceof i){o.s=s.s,o.e=s.e,o.d=(s=s.d)?s.slice():s;return}if(typeof s=="number"){if(s*0!==0)throw Error(tm+s);if(s>0)o.s=1;else if(s<0)s=-s,o.s=-1;else{o.s=0,o.e=0,o.d=[0];return}if(s===~~s&&s<1e7){o.e=0,o.d=[s];return}return eG(o,s.toString())}else if(typeof s!="string")throw Error(tm+s);if(s.charCodeAt(0)===45?(s=s.slice(1),o.s=-1):o.s=1,B3e.test(s))eG(o,s);else throw Error(tm+s)}if(i.prototype=qt,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=tZ,i.config=i.set=H3e,t===void 0&&(t={}),t)for(r=["precision","rounding","toExpNeg","toExpPos","LN10"],e=0;e=i[e+1]&&r<=i[e+2])this[n]=r;else throw Error(tm+n+": "+r);if((r=t[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(tm+n+": "+r);return this}var ML=tZ(U3e);go=new ML(1);const yr=ML;var $3e=t=>t,nZ={},rZ=t=>t===nZ,nG=t=>function e(){return arguments.length===0||arguments.length===1&&rZ(arguments.length<=0?void 0:arguments[0])?e:t(...arguments)},iZ=(t,e)=>t===1?e:nG(function(){for(var n=arguments.length,r=new Array(n),i=0;io!==nZ).length;return s>=t?e(...r):iZ(t-s,nG(function(){for(var o=arguments.length,l=new Array(o),c=0;crZ(d)?l.shift():d);return e(...u,...l)}))}),V3e=t=>iZ(t.length,t),_D=(t,e)=>{for(var n=[],r=t;rArray.isArray(e)?e.map(t):Object.keys(e).map(n=>e[n]).map(t)),q3e=function(){for(var e=arguments.length,n=new Array(e),r=0;rc(l),s(...arguments))}},SD=t=>Array.isArray(t)?t.reverse():t.split("").reverse().join("");function aZ(t){var e;return t===0?e=1:e=Math.floor(new yr(t).abs().log(10).toNumber())+1,e}function sZ(t,e,n){for(var r=new yr(t),i=0,s=[];r.lt(e)&&i<1e5;)s.push(r.toNumber()),r=r.add(n),i++;return s}var oZ=t=>{var[e,n]=t,[r,i]=[e,n];return e>n&&([r,i]=[n,e]),[r,i]},lZ=(t,e,n)=>{if(t.lte(0))return new yr(0);var r=aZ(t.toNumber()),i=new yr(10).pow(r),s=t.div(i),o=r!==1?.05:.1,l=new yr(Math.ceil(s.div(o).toNumber())).add(n).mul(o),c=l.mul(i);return e?new yr(c.toNumber()):new yr(Math.ceil(c.toNumber()))},W3e=(t,e,n)=>{var r=new yr(1),i=new yr(t);if(!i.isint()&&n){var s=Math.abs(t);s<1?(r=new yr(10).pow(aZ(t)-1),i=new yr(Math.floor(i.div(r).toNumber())).mul(r)):s>1&&(i=new yr(Math.floor(t)))}else t===0?i=new yr(Math.floor((e-1)/2)):n||(i=new yr(Math.floor(t)));var o=Math.floor((e-1)/2),l=q3e(G3e(c=>i.add(new yr(c-o).mul(r)).toNumber()),_D);return l(0,e)},cZ=function(e,n,r,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((n-e)/(r-1)))return{step:new yr(0),tickMin:new yr(0),tickMax:new yr(0)};var o=lZ(new yr(n).sub(e).div(r-1),i,s),l;e<=0&&n>=0?l=new yr(0):(l=new yr(e).add(n).div(2),l=l.sub(new yr(l).mod(o)));var c=Math.ceil(l.sub(e).div(o).toNumber()),u=Math.ceil(new yr(n).sub(l).div(o).toNumber()),d=c+u+1;return d>r?cZ(e,n,r,i,s+1):(d0?u+(r-d):u,c=n>0?c:c+(r-d)),{step:o,tickMin:l.sub(new yr(c).mul(o)),tickMax:l.add(new yr(u).mul(o))})},K3e=function(e){var[n,r]=e,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=Math.max(i,2),[l,c]=oZ([n,r]);if(l===-1/0||c===1/0){var u=c===1/0?[l,..._D(0,i-1).map(()=>1/0)]:[..._D(0,i-1).map(()=>-1/0),c];return n>r?SD(u):u}if(l===c)return W3e(l,i,s);var{step:d,tickMin:h,tickMax:p}=cZ(l,c,o,s,0),m=sZ(h,p.add(new yr(.1).mul(d)),d);return n>r?SD(m):m},X3e=function(e,n){var[r,i]=e,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,[o,l]=oZ([r,i]);if(o===-1/0||l===1/0)return[r,i];if(o===l)return[o];var c=Math.max(n,2),u=lZ(new yr(l).sub(o).div(c-1),s,0),d=[...sZ(new yr(o),new yr(l),u),l];return s===!1&&(d=d.map(h=>Math.round(h))),r>i?SD(d):d},uZ=t=>t.rootProps.maxBarSize,Y3e=t=>t.rootProps.barGap,dZ=t=>t.rootProps.barCategoryGap,Q3e=t=>t.rootProps.barSize,lv=t=>t.rootProps.stackOffset,hZ=t=>t.rootProps.reverseStackOrder,EL=t=>t.options.chartName,TL=t=>t.rootProps.syncId,fZ=t=>t.rootProps.syncMethod,AL=t=>t.options.eventEmitter,Z3e=t=>t.rootProps.baseValue,vi={grid:-100,barBackground:-50,area:100,cursorRectangle:200,bar:300,line:400,axis:500,scatter:600,activeBar:1e3,cursorLine:1100,activeDot:1200,label:2e3},xu={allowDuplicatedCategory:!0,angleAxisId:0,reversed:!1,scale:"auto",tick:!0,type:"category"},mo={allowDataOverflow:!1,allowDuplicatedCategory:!0,radiusAxisId:0,scale:"auto",tick:!0,tickCount:5,type:"number"},hM=(t,e)=>{if(!(!t||!e))return t!=null&&t.reversed?[e[1],e[0]]:e},J3e={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:!1,dataKey:void 0,domain:void 0,id:xu.angleAxisId,includeHidden:!1,name:void 0,reversed:xu.reversed,scale:xu.scale,tick:xu.tick,tickCount:void 0,ticks:void 0,type:xu.type,unit:void 0},eDe={allowDataOverflow:mo.allowDataOverflow,allowDecimals:!1,allowDuplicatedCategory:mo.allowDuplicatedCategory,dataKey:void 0,domain:void 0,id:mo.radiusAxisId,includeHidden:!1,name:void 0,reversed:!1,scale:mo.scale,tick:mo.tick,tickCount:mo.tickCount,ticks:void 0,type:mo.type,unit:void 0},tDe={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:xu.allowDuplicatedCategory,dataKey:void 0,domain:void 0,id:xu.angleAxisId,includeHidden:!1,name:void 0,reversed:!1,scale:xu.scale,tick:xu.tick,tickCount:void 0,ticks:void 0,type:"number",unit:void 0},nDe={allowDataOverflow:mo.allowDataOverflow,allowDecimals:!1,allowDuplicatedCategory:mo.allowDuplicatedCategory,dataKey:void 0,domain:void 0,id:mo.radiusAxisId,includeHidden:!1,name:void 0,reversed:!1,scale:mo.scale,tick:mo.tick,tickCount:mo.tickCount,ticks:void 0,type:"category",unit:void 0},CL=(t,e)=>t.polarAxis.angleAxis[e]!=null?t.polarAxis.angleAxis[e]:t.layout.layoutType==="radial"?tDe:J3e,PL=(t,e)=>t.polarAxis.radiusAxis[e]!=null?t.polarAxis.radiusAxis[e]:t.layout.layoutType==="radial"?nDe:eDe,fM=t=>t.polarOptions,jL=st([ed,td,ia],dQ),mZ=st([fM,jL],(t,e)=>{if(t!=null)return as(t.innerRadius,e,0)}),pZ=st([fM,jL],(t,e)=>{if(t!=null)return as(t.outerRadius,e,e*.8)}),rDe=t=>{if(t==null)return[0,0];var{startAngle:e,endAngle:n}=t;return[e,n]},gZ=st([fM],rDe);st([CL,gZ],hM);var bZ=st([jL,mZ,pZ],(t,e,n)=>{if(!(t==null||e==null||n==null))return[e,n]});st([PL,bZ],hM);var xZ=st([Kn,fM,mZ,pZ,ed,td],(t,e,n,r,i,s)=>{if(!(t!=="centric"&&t!=="radial"||e==null||n==null||r==null)){var{cx:o,cy:l,startAngle:c,endAngle:u}=e;return{cx:as(o,i,i/2),cy:as(l,s,s/2),innerRadius:n,outerRadius:r,startAngle:c,endAngle:u,clockWise:!1}}}),ii=(t,e)=>e,cv=(t,e,n)=>n;function mM(t){return t?.id}function yZ(t,e,n){var{chartData:r=[]}=e,{allowDuplicatedCategory:i,dataKey:s}=n,o=new Map;return t.forEach(l=>{var c,u=(c=l.data)!==null&&c!==void 0?c:r;if(!(u==null||u.length===0)){var d=mM(l);u.forEach((h,p)=>{var m=s==null||i?p:String(vr(h,s,null)),b=vr(h,l.dataKey,0),y;o.has(m)?y=o.get(m):y={},Object.assign(y,{[d]:b}),o.set(m,y)})}}),Array.from(o.values())}function pM(t){return t.stackId!=null&&t.dataKey!=null}var gM=(t,e)=>t===e?!0:t==null||e==null?!1:t[0]===e[0]&&t[1]===e[1];function bM(t,e){return Array.isArray(t)&&Array.isArray(e)&&t.length===0&&e.length===0?!0:t===e}function iDe(t,e){if(t.length===e.length){for(var n=0;n{var e=Kn(t);return e==="horizontal"?"xAxis":e==="vertical"?"yAxis":e==="centric"?"angleAxis":"radiusAxis"},Ob=t=>t.tooltip.settings.axisId;function rG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function YS(t){for(var e=1;et.cartesianAxis.xAxis[e],Ac=(t,e)=>{var n=vZ(t,e);return n??ga},ba={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:ND,hide:!0,id:0,includeHidden:!1,interval:"preserveEnd",minTickGap:5,mirror:!1,name:void 0,orientation:"left",padding:{top:0,bottom:0},reversed:!1,scale:"auto",tick:!0,tickCount:5,tickFormatter:void 0,ticks:void 0,type:"number",unit:void 0,width:ev},wZ=(t,e)=>t.cartesianAxis.yAxis[e],Cc=(t,e)=>{var n=wZ(t,e);return n??ba},lDe={domain:[0,"auto"],includeHidden:!1,reversed:!1,allowDataOverflow:!1,allowDuplicatedCategory:!1,dataKey:void 0,id:0,name:"",range:[64,64],scale:"auto",type:"number",unit:""},DL=(t,e)=>{var n=t.cartesianAxis.zAxis[e];return n??lDe},ui=(t,e,n)=>{switch(e){case"xAxis":return Ac(t,n);case"yAxis":return Cc(t,n);case"zAxis":return DL(t,n);case"angleAxis":return CL(t,n);case"radiusAxis":return PL(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},cDe=(t,e,n)=>{switch(e){case"xAxis":return Ac(t,n);case"yAxis":return Cc(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},uv=(t,e,n)=>{switch(e){case"xAxis":return Ac(t,n);case"yAxis":return Cc(t,n);case"angleAxis":return CL(t,n);case"radiusAxis":return PL(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},_Z=t=>t.graphicalItems.cartesianItems.some(e=>e.type==="bar")||t.graphicalItems.polarItems.some(e=>e.type==="radialBar");function RL(t,e){return n=>{switch(t){case"xAxis":return"xAxisId"in n&&n.xAxisId===e;case"yAxis":return"yAxisId"in n&&n.yAxisId===e;case"zAxis":return"zAxisId"in n&&n.zAxisId===e;case"angleAxis":return"angleAxisId"in n&&n.angleAxisId===e;case"radiusAxis":return"radiusAxisId"in n&&n.radiusAxisId===e;default:return!1}}}var dv=t=>t.graphicalItems.cartesianItems,uDe=st([ii,cv],RL),OL=(t,e,n)=>t.filter(n).filter(r=>e?.includeHidden===!0?!0:!r.hide),hv=st([dv,ui,uDe],OL,{memoizeOptions:{resultEqualityCheck:bM}}),SZ=st([hv],t=>t.filter(e=>e.type==="area"||e.type==="bar").filter(pM)),NZ=t=>t.filter(e=>!("stackId"in e)||e.stackId===void 0),dDe=st([hv],NZ),LL=t=>t.map(e=>e.data).filter(Boolean).flat(1),hDe=st([hv],LL,{memoizeOptions:{resultEqualityCheck:bM}}),FL=(t,e)=>{var{chartData:n=[],dataStartIndex:r,dataEndIndex:i}=e;return t.length>0?t:n.slice(r,i+1)},IL=st([hDe,ov],FL),zL=(t,e,n)=>e?.dataKey!=null?t.map(r=>({value:vr(r,e.dataKey)})):n.length>0?n.map(r=>r.dataKey).flatMap(r=>t.map(i=>({value:vr(i,r)}))):t.map(r=>({value:r})),xM=st([IL,ui,hv],zL);function kZ(t,e){switch(t){case"xAxis":return e.direction==="x";case"yAxis":return e.direction==="y";default:return!1}}function I1(t){if(fl(t)||t instanceof Date){var e=Number(t);if(wr(e))return e}}function iG(t){if(Array.isArray(t)){var e=[I1(t[0]),I1(t[1])];return Lh(e)?e:void 0}var n=I1(t);if(n!=null)return[n,n]}function Qu(t){return t.map(I1).filter(c2e)}function fDe(t,e,n){return!n||typeof e!="number"||Ys(e)?[]:n.length?Qu(n.flatMap(r=>{var i=vr(t,r.dataKey),s,o;if(Array.isArray(i)?[s,o]=i:s=o=i,!(!wr(s)||!wr(o)))return[e-s,e+o]})):[]}var la=t=>{var e=oa(t),n=Ob(t);return uv(t,e,n)},fv=st([la],t=>t?.dataKey),mDe=st([SZ,ov,la],yZ),MZ=(t,e,n,r)=>{var i={},s=e.reduce((o,l)=>(l.stackId==null||(o[l.stackId]==null&&(o[l.stackId]=[]),o[l.stackId].push(l)),o),i);return Object.fromEntries(Object.entries(s).map(o=>{var[l,c]=o,u=r?[...c].reverse():c,d=u.map(mM);return[l,{stackedData:DTe(t,d,n),graphicalItems:u}]}))},Sy=st([mDe,SZ,lv,hZ],MZ),EZ=(t,e,n,r)=>{var{dataStartIndex:i,dataEndIndex:s}=e;if(r==null&&n!=="zAxis"){var o=FTe(t,i,s);if(!(o!=null&&o[0]===0&&o[1]===0))return o}},pDe=st([ui],t=>t.allowDataOverflow),UL=t=>{var e;if(t==null||!("domain"in t))return ND;if(t.domain!=null)return t.domain;if(t.ticks!=null){if(t.type==="number"){var n=Qu(t.ticks);return[Math.min(...n),Math.max(...n)]}if(t.type==="category")return t.ticks.map(String)}return(e=t?.domain)!==null&&e!==void 0?e:ND},BL=st([ui],UL),HL=st([BL,pDe],YQ),gDe=st([Sy,Gh,ii,HL],EZ,{memoizeOptions:{resultEqualityCheck:gM}}),yM=t=>t.errorBars,bDe=(t,e,n)=>t.flatMap(r=>e[r.id]).filter(Boolean).filter(r=>kZ(n,r)),QS=function(){for(var e=arguments.length,n=new Array(e),r=0;r{var s,o;if(n.length>0&&t.forEach(l=>{n.forEach(c=>{var u,d,h=(u=r[c.id])===null||u===void 0?void 0:u.filter(v=>kZ(i,v)),p=vr(l,(d=e.dataKey)!==null&&d!==void 0?d:c.dataKey),m=fDe(l,p,h);if(m.length>=2){var b=Math.min(...m),y=Math.max(...m);(s==null||bo)&&(o=y)}var x=iG(p);x!=null&&(s=s==null?x[0]:Math.min(s,x[0]),o=o==null?x[1]:Math.max(o,x[1]))})}),e?.dataKey!=null&&t.forEach(l=>{var c=iG(vr(l,e.dataKey));c!=null&&(s=s==null?c[0]:Math.min(s,c[0]),o=o==null?c[1]:Math.max(o,c[1]))}),wr(s)&&wr(o))return[s,o]},xDe=st([IL,ui,dDe,yM,ii],$L,{memoizeOptions:{resultEqualityCheck:gM}});function yDe(t){var{value:e}=t;if(fl(e)||e instanceof Date)return e}var vDe=(t,e,n)=>{var r=t.map(yDe).filter(i=>i!=null);return n&&(e.dataKey==null||e.allowDuplicatedCategory&&HX(r))?pQ(0,t.length):e.allowDuplicatedCategory?r:Array.from(new Set(r))},TZ=t=>t.referenceElements.dots,Lb=(t,e,n)=>t.filter(r=>r.ifOverflow==="extendDomain").filter(r=>e==="xAxis"?r.xAxisId===n:r.yAxisId===n),wDe=st([TZ,ii,cv],Lb),AZ=t=>t.referenceElements.areas,_De=st([AZ,ii,cv],Lb),CZ=t=>t.referenceElements.lines,SDe=st([CZ,ii,cv],Lb),PZ=(t,e)=>{var n=Qu(t.map(r=>e==="xAxis"?r.x:r.y));if(n.length!==0)return[Math.min(...n),Math.max(...n)]},NDe=st(wDe,ii,PZ),jZ=(t,e)=>{var n=Qu(t.flatMap(r=>[e==="xAxis"?r.x1:r.y1,e==="xAxis"?r.x2:r.y2]));if(n.length!==0)return[Math.min(...n),Math.max(...n)]},kDe=st([_De,ii],jZ);function MDe(t){var e;if(t.x!=null)return Qu([t.x]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.x);return n==null||n.length===0?[]:Qu(n)}function EDe(t){var e;if(t.y!=null)return Qu([t.y]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.y);return n==null||n.length===0?[]:Qu(n)}var DZ=(t,e)=>{var n=t.flatMap(r=>e==="xAxis"?MDe(r):EDe(r));if(n.length!==0)return[Math.min(...n),Math.max(...n)]},TDe=st([SDe,ii],DZ),ADe=st(NDe,TDe,kDe,(t,e,n)=>QS(t,n,e)),VL=(t,e,n,r,i,s,o,l)=>{if(n!=null)return n;var c=o==="vertical"&&l==="xAxis"||o==="horizontal"&&l==="yAxis",u=c?QS(r,s,i):QS(s,i);return z3e(e,u,t.allowDataOverflow)},CDe=st([ui,BL,HL,gDe,xDe,ADe,Kn,ii],VL,{memoizeOptions:{resultEqualityCheck:gM}}),PDe=[0,1],GL=(t,e,n,r,i,s,o)=>{if(!((t==null||n==null||n.length===0)&&o===void 0)){var{dataKey:l,type:c}=t,u=Tc(e,s);if(u&&l==null){var d;return pQ(0,(d=n?.length)!==null&&d!==void 0?d:0)}return c==="category"?vDe(r,t,u):i==="expand"?PDe:o}},qL=st([ui,Kn,IL,xM,lv,ii,CDe],GL),RZ=(t,e,n,r,i)=>{if(t!=null){var{scale:s,type:o}=t;if(s==="auto")return e==="radial"&&i==="radiusAxis"?"band":e==="radial"&&i==="angleAxis"?"linear":o==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?"point":o==="category"?"band":"linear";if(typeof s=="string"){var l="scale".concat(Ky(s));return l in f0?l:"point"}}},Fb=st([ui,Kn,_Z,EL,ii],RZ);function jDe(t){if(t!=null){if(t in f0)return f0[t]();var e="scale".concat(Ky(t));if(e in f0)return f0[e]()}}function WL(t,e,n,r){if(!(n==null||r==null)){if(typeof t.scale=="function")return t.scale.copy().domain(n).range(r);var i=jDe(e);if(i!=null){var s=i.domain(n).range(r);return TTe(s),s}}}var KL=(t,e,n)=>{var r=UL(e);if(!(n!=="auto"&&n!=="linear")){if(e!=null&&e.tickCount&&Array.isArray(r)&&(r[0]==="auto"||r[1]==="auto")&&Lh(t))return K3e(t,e.tickCount,e.allowDecimals);if(e!=null&&e.tickCount&&e.type==="number"&&Lh(t))return X3e(t,e.tickCount,e.allowDecimals)}},XL=st([qL,uv,Fb],KL),YL=(t,e,n,r)=>{if(r!=="angleAxis"&&t?.type==="number"&&Lh(e)&&Array.isArray(n)&&n.length>0){var i=e[0],s=n[0],o=e[1],l=n[n.length-1];return[Math.min(i,s),Math.max(o,l)]}return e},DDe=st([ui,qL,XL,ii],YL),RDe=st(xM,ui,(t,e)=>{if(!(!e||e.type!=="number")){var n=1/0,r=Array.from(Qu(t.map(l=>l.value))).sort((l,c)=>l-c);if(r.length<2)return 1/0;var i=r[r.length-1]-r[0];if(i===0)return 1/0;for(var s=0;sr,(t,e,n,r,i)=>{if(!wr(t))return 0;var s=e==="vertical"?r.height:r.width;if(i==="gap")return t*s/2;if(i==="no-gap"){var o=as(n,t*s),l=t*s/2;return l-o-(l-o)/s*o}return 0}),ODe=(t,e)=>{var n=Ac(t,e);return n==null||typeof n.padding!="string"?0:OZ(t,"xAxis",e,n.padding)},LDe=(t,e)=>{var n=Cc(t,e);return n==null||typeof n.padding!="string"?0:OZ(t,"yAxis",e,n.padding)},FDe=st(Ac,ODe,(t,e)=>{var n,r;if(t==null)return{left:0,right:0};var{padding:i}=t;return typeof i=="string"?{left:e,right:e}:{left:((n=i.left)!==null&&n!==void 0?n:0)+e,right:((r=i.right)!==null&&r!==void 0?r:0)+e}}),IDe=st(Cc,LDe,(t,e)=>{var n,r;if(t==null)return{top:0,bottom:0};var{padding:i}=t;return typeof i=="string"?{top:e,bottom:e}:{top:((n=i.top)!==null&&n!==void 0?n:0)+e,bottom:((r=i.bottom)!==null&&r!==void 0?r:0)+e}}),zDe=st([ia,FDe,tM,eM,(t,e,n)=>n],(t,e,n,r,i)=>{var{padding:s}=r;return i?[s.left,n.width-s.right]:[t.left+e.left,t.left+t.width-e.right]}),UDe=st([ia,Kn,IDe,tM,eM,(t,e,n)=>n],(t,e,n,r,i,s)=>{var{padding:o}=i;return s?[r.height-o.bottom,o.top]:e==="horizontal"?[t.top+t.height-n.bottom,t.top+n.top]:[t.top+n.top,t.top+t.height-n.bottom]}),mv=(t,e,n,r)=>{var i;switch(e){case"xAxis":return zDe(t,n,r);case"yAxis":return UDe(t,n,r);case"zAxis":return(i=DL(t,n))===null||i===void 0?void 0:i.range;case"angleAxis":return gZ(t);case"radiusAxis":return bZ(t,n);default:return}},LZ=st([ui,mv],hM),Fh=st([ui,Fb,DDe,LZ],WL);st([hv,yM,ii],bDe);function FZ(t,e){return t.ide.id?1:0}var vM=(t,e)=>e,wM=(t,e,n)=>n,BDe=st(Zk,vM,wM,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(FZ)),HDe=st(Jk,vM,wM,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(FZ)),IZ=(t,e)=>({width:t.width,height:e.height}),$De=(t,e)=>{var n=typeof e.width=="number"?e.width:ev;return{width:n,height:t.height}},zZ=st(ia,Ac,IZ),VDe=(t,e,n)=>{switch(e){case"top":return t.top;case"bottom":return n-t.bottom;default:return 0}},GDe=(t,e,n)=>{switch(e){case"left":return t.left;case"right":return n-t.right;default:return 0}},qDe=st(td,ia,BDe,vM,wM,(t,e,n,r,i)=>{var s={},o;return n.forEach(l=>{var c=IZ(e,l);o==null&&(o=VDe(e,r,t));var u=r==="top"&&!i||r==="bottom"&&i;s[l.id]=o-Number(u)*c.height,o+=(u?-1:1)*c.height}),s}),WDe=st(ed,ia,HDe,vM,wM,(t,e,n,r,i)=>{var s={},o;return n.forEach(l=>{var c=$De(e,l);o==null&&(o=GDe(e,r,t));var u=r==="left"&&!i||r==="right"&&i;s[l.id]=o-Number(u)*c.width,o+=(u?-1:1)*c.width}),s}),KDe=(t,e)=>{var n=Ac(t,e);if(n!=null)return qDe(t,n.orientation,n.mirror)},XDe=st([ia,Ac,KDe,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var i=n?.[r];return i==null?{x:t.left,y:0}:{x:t.left,y:i}}}),YDe=(t,e)=>{var n=Cc(t,e);if(n!=null)return WDe(t,n.orientation,n.mirror)},QDe=st([ia,Cc,YDe,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var i=n?.[r];return i==null?{x:0,y:t.top}:{x:i,y:t.top}}}),UZ=st(ia,Cc,(t,e)=>{var n=typeof e.width=="number"?e.width:ev;return{width:n,height:t.height}}),aG=(t,e,n)=>{switch(e){case"xAxis":return zZ(t,n).width;case"yAxis":return UZ(t,n).height;default:return}},BZ=(t,e,n,r)=>{if(n!=null){var{allowDuplicatedCategory:i,type:s,dataKey:o}=n,l=Tc(t,r),c=e.map(u=>u.value);if(o&&l&&s==="category"&&i&&HX(c))return c}},QL=st([Kn,xM,ui,ii],BZ),HZ=(t,e,n,r)=>{if(!(n==null||n.dataKey==null)){var{type:i,scale:s}=n,o=Tc(t,r);if(o&&(i==="number"||s!=="auto"))return e.map(l=>l.value)}},ZL=st([Kn,xM,uv,ii],HZ),sG=st([Kn,cDe,Fb,Fh,QL,ZL,mv,XL,ii],(t,e,n,r,i,s,o,l,c)=>{if(e!=null){var u=Tc(t,c);return{angle:e.angle,interval:e.interval,minTickGap:e.minTickGap,orientation:e.orientation,tick:e.tick,tickCount:e.tickCount,tickFormatter:e.tickFormatter,ticks:e.ticks,type:e.type,unit:e.unit,axisType:c,categoricalDomain:s,duplicateDomain:i,isCategorical:u,niceTicks:l,range:o,realScaleType:n,scale:r}}}),ZDe=(t,e,n,r,i,s,o,l,c)=>{if(!(e==null||r==null)){var u=Tc(t,c),{type:d,ticks:h,tickCount:p}=e,m=n==="scaleBand"&&typeof r.bandwidth=="function"?r.bandwidth()/2:2,b=d==="category"&&r.bandwidth?r.bandwidth()/m:0;b=c==="angleAxis"&&s!=null&&s.length>=2?wa(s[0]-s[1])*2*b:b;var y=h||i;if(y){var x=y.map((v,S)=>{var N=o?o.indexOf(v):v;return{index:S,coordinate:r(N)+b,value:v,offset:b}});return x.filter(v=>wr(v.coordinate))}return u&&l?l.map((v,S)=>({coordinate:r(v)+b,value:v,index:S,offset:b})).filter(v=>wr(v.coordinate)):r.ticks?r.ticks(p).map(v=>({coordinate:r(v)+b,value:v,offset:b})):r.domain().map((v,S)=>({coordinate:r(v)+b,value:o?o[v]:v,index:S,offset:b}))}},$Z=st([Kn,uv,Fb,Fh,XL,mv,QL,ZL,ii],ZDe),JDe=(t,e,n,r,i,s,o)=>{if(!(e==null||n==null||r==null||r[0]===r[1])){var l=Tc(t,o),{tickCount:c}=e,u=0;return u=o==="angleAxis"&&r?.length>=2?wa(r[0]-r[1])*2*u:u,l&&s?s.map((d,h)=>({coordinate:n(d)+u,value:d,index:h,offset:u})):n.ticks?n.ticks(c).map(d=>({coordinate:n(d)+u,value:d,offset:u})):n.domain().map((d,h)=>({coordinate:n(d)+u,value:i?i[d]:d,index:h,offset:u}))}},wc=st([Kn,uv,Fh,mv,QL,ZL,ii],JDe),_c=st(ui,Fh,(t,e)=>{if(!(t==null||e==null))return YS(YS({},t),{},{scale:e})}),eRe=st([ui,Fb,qL,LZ],WL);st((t,e,n)=>DL(t,n),eRe,(t,e)=>{if(!(t==null||e==null))return YS(YS({},t),{},{scale:e})});var tRe=st([Kn,Zk,Jk],(t,e,n)=>{switch(t){case"horizontal":return e.some(r=>r.reversed)?"right-to-left":"left-to-right";case"vertical":return n.some(r=>r.reversed)?"bottom-to-top":"top-to-bottom";case"centric":case"radial":return"left-to-right";default:return}}),VZ=t=>t.options.defaultTooltipEventType,GZ=t=>t.options.validateTooltipEventTypes;function qZ(t,e,n){if(t==null)return e;var r=t?"axis":"item";return n==null?e:n.includes(r)?r:e}function JL(t,e){var n=VZ(t),r=GZ(t);return qZ(e,n,r)}function nRe(t){return Ht(e=>JL(e,t))}var WZ=(t,e)=>{var n,r=Number(e);if(!(Ys(r)||e==null))return r>=0?t==null||(n=t[r])===null||n===void 0?void 0:n.value:void 0},rRe=t=>t.tooltip.settings,ih={active:!1,index:null,dataKey:void 0,graphicalItemId:void 0,coordinate:void 0},iRe={itemInteraction:{click:ih,hover:ih},axisInteraction:{click:ih,hover:ih},keyboardInteraction:ih,syncInteraction:{active:!1,index:null,dataKey:void 0,label:void 0,coordinate:void 0,sourceViewBox:void 0,graphicalItemId:void 0},tooltipItemPayloads:[],settings:{shared:void 0,trigger:"hover",axisId:0,active:!1,defaultIndex:void 0}},KZ=Qs({name:"tooltip",initialState:iRe,reducers:{addTooltipEntrySettings:{reducer(t,e){t.tooltipItemPayloads.push(e.payload)},prepare:Jr()},replaceTooltipEntrySettings:{reducer(t,e){var{prev:n,next:r}=e.payload,i=Il(t).tooltipItemPayloads.indexOf(n);i>-1&&(t.tooltipItemPayloads[i]=r)},prepare:Jr()},removeTooltipEntrySettings:{reducer(t,e){var n=Il(t).tooltipItemPayloads.indexOf(e.payload);n>-1&&t.tooltipItemPayloads.splice(n,1)},prepare:Jr()},setTooltipSettingsState(t,e){t.settings=e.payload},setActiveMouseOverItemIndex(t,e){t.syncInteraction.active=!1,t.keyboardInteraction.active=!1,t.itemInteraction.hover.active=!0,t.itemInteraction.hover.index=e.payload.activeIndex,t.itemInteraction.hover.dataKey=e.payload.activeDataKey,t.itemInteraction.hover.graphicalItemId=e.payload.activeGraphicalItemId,t.itemInteraction.hover.coordinate=e.payload.activeCoordinate},mouseLeaveChart(t){t.itemInteraction.hover.active=!1,t.axisInteraction.hover.active=!1},mouseLeaveItem(t){t.itemInteraction.hover.active=!1},setActiveClickItemIndex(t,e){t.syncInteraction.active=!1,t.itemInteraction.click.active=!0,t.keyboardInteraction.active=!1,t.itemInteraction.click.index=e.payload.activeIndex,t.itemInteraction.click.dataKey=e.payload.activeDataKey,t.itemInteraction.click.graphicalItemId=e.payload.activeGraphicalItemId,t.itemInteraction.click.coordinate=e.payload.activeCoordinate},setMouseOverAxisIndex(t,e){t.syncInteraction.active=!1,t.axisInteraction.hover.active=!0,t.keyboardInteraction.active=!1,t.axisInteraction.hover.index=e.payload.activeIndex,t.axisInteraction.hover.dataKey=e.payload.activeDataKey,t.axisInteraction.hover.coordinate=e.payload.activeCoordinate},setMouseClickAxisIndex(t,e){t.syncInteraction.active=!1,t.keyboardInteraction.active=!1,t.axisInteraction.click.active=!0,t.axisInteraction.click.index=e.payload.activeIndex,t.axisInteraction.click.dataKey=e.payload.activeDataKey,t.axisInteraction.click.coordinate=e.payload.activeCoordinate},setSyncInteraction(t,e){t.syncInteraction=e.payload},setKeyboardInteraction(t,e){t.keyboardInteraction.active=e.payload.active,t.keyboardInteraction.index=e.payload.activeIndex,t.keyboardInteraction.coordinate=e.payload.activeCoordinate,t.keyboardInteraction.dataKey=e.payload.activeDataKey}}}),{addTooltipEntrySettings:aRe,replaceTooltipEntrySettings:sRe,removeTooltipEntrySettings:oRe,setTooltipSettingsState:lRe,setActiveMouseOverItemIndex:XZ,mouseLeaveItem:cRe,mouseLeaveChart:YZ,setActiveClickItemIndex:uRe,setMouseOverAxisIndex:QZ,setMouseClickAxisIndex:dRe,setSyncInteraction:kD,setKeyboardInteraction:MD}=KZ.actions,hRe=KZ.reducer;function oG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function e1(t){for(var e=1;e{if(e==null)return ih;var i=gRe(t,e,n);if(i==null)return ih;if(i.active)return i;if(t.keyboardInteraction.active)return t.keyboardInteraction;if(t.syncInteraction.active&&t.syncInteraction.index!=null)return t.syncInteraction;var s=t.settings.active===!0;if(bRe(i)){if(s)return e1(e1({},i),{},{active:!0})}else if(r!=null)return{active:!0,coordinate:void 0,dataKey:void 0,index:r,graphicalItemId:void 0};return e1(e1({},ih),{},{coordinate:i.coordinate})};function xRe(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(t instanceof Date){var e=t.valueOf();return Number.isFinite(e)?e:void 0}var n=Number(t);return Number.isFinite(n)?n:void 0}function yRe(t,e){var n=xRe(t),r=e[0],i=e[1];if(n===void 0)return!1;var s=Math.min(r,i),o=Math.max(r,i);return n>=s&&n<=o}function vRe(t,e,n){if(n==null||e==null)return!0;var r=vr(t,e);return r==null||!Lh(n)?!0:yRe(r,n)}var e4=(t,e,n,r)=>{var i=t?.index;if(i==null)return null;var s=Number(i);if(!wr(s))return i;var o=0,l=1/0;e.length>0&&(l=e.length-1);var c=Math.max(o,Math.min(s,l)),u=e[c];return u==null||vRe(u,n,r)?String(c):null},JZ=(t,e,n,r,i,s,o,l)=>{if(!(s==null||l==null)){var c=o[0],u=c==null?void 0:l(c.positions,s);if(u!=null)return u;var d=i?.[Number(s)];if(d)switch(n){case"horizontal":return{x:d.coordinate,y:(r.top+e)/2};default:return{x:(r.left+t)/2,y:d.coordinate}}}},eJ=(t,e,n,r)=>{if(e==="axis")return t.tooltipItemPayloads;if(t.tooltipItemPayloads.length===0)return[];var i;return n==="hover"?i=t.itemInteraction.hover.dataKey:i=t.itemInteraction.click.dataKey,i==null&&r!=null?[t.tooltipItemPayloads[0]]:t.tooltipItemPayloads.filter(s=>{var o;return((o=s.settings)===null||o===void 0?void 0:o.dataKey)===i})},pv=t=>t.options.tooltipPayloadSearcher,Ib=t=>t.tooltip;function lG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function cG(t){for(var e=1;e{if(!(e==null||s==null)){var{chartData:l,computedData:c,dataStartIndex:u,dataEndIndex:d}=n,h=[];return t.reduce((p,m)=>{var b,{dataDefinedOnItem:y,settings:x}=m,v=NRe(y,l),S=Array.isArray(v)?FY(v,u,d):v,N=(b=x?.dataKey)!==null&&b!==void 0?b:r,T=x?.nameKey,M;if(r&&Array.isArray(S)&&!Array.isArray(S[0])&&o==="axis"?M=$X(S,r,i):M=s(S,e,c,T),Array.isArray(M))M.forEach(k=>{var R=cG(cG({},x),{},{name:k.name,unit:k.unit,color:void 0,fill:void 0});p.push(A$({tooltipEntrySettings:R,dataKey:k.dataKey,payload:k.payload,value:vr(k.payload,k.dataKey),name:k.name}))});else{var A;p.push(A$({tooltipEntrySettings:x,dataKey:N,payload:M,value:vr(M,N),name:(A=vr(M,T))!==null&&A!==void 0?A:x?.name}))}return p},h)}},t4=st([la,Kn,_Z,EL,oa],RZ),kRe=st([t=>t.graphicalItems.cartesianItems,t=>t.graphicalItems.polarItems],(t,e)=>[...t,...e]),MRe=st([oa,Ob],RL),gv=st([kRe,la,MRe],OL,{memoizeOptions:{resultEqualityCheck:bM}}),ERe=st([gv],t=>t.filter(pM)),TRe=st([gv],LL,{memoizeOptions:{resultEqualityCheck:bM}}),zb=st([TRe,Gh],FL),ARe=st([ERe,Gh,la],yZ),n4=st([zb,la,gv],zL),nJ=st([la],UL),CRe=st([la],t=>t.allowDataOverflow),rJ=st([nJ,CRe],YQ),PRe=st([gv],t=>t.filter(pM)),jRe=st([ARe,PRe,lv,hZ],MZ),DRe=st([jRe,Gh,oa,rJ],EZ),RRe=st([gv],NZ),ORe=st([zb,la,RRe,yM,oa],$L,{memoizeOptions:{resultEqualityCheck:gM}}),LRe=st([TZ,oa,Ob],Lb),FRe=st([LRe,oa],PZ),IRe=st([AZ,oa,Ob],Lb),zRe=st([IRe,oa],jZ),URe=st([CZ,oa,Ob],Lb),BRe=st([URe,oa],DZ),HRe=st([FRe,BRe,zRe],QS),$Re=st([la,nJ,rJ,DRe,ORe,HRe,Kn,oa],VL),bv=st([la,Kn,zb,n4,lv,oa,$Re],GL),VRe=st([bv,la,t4],KL),GRe=st([la,bv,VRe,oa],YL),iJ=t=>{var e=oa(t),n=Ob(t),r=!1;return mv(t,e,n,r)},aJ=st([la,iJ],hM),sJ=st([la,t4,GRe,aJ],WL),qRe=st([Kn,n4,la,oa],BZ),WRe=st([Kn,n4,la,oa],HZ),KRe=(t,e,n,r,i,s,o,l)=>{if(e){var{type:c}=e,u=Tc(t,l);if(r){var d=n==="scaleBand"&&r.bandwidth?r.bandwidth()/2:2,h=c==="category"&&r.bandwidth?r.bandwidth()/d:0;return h=l==="angleAxis"&&i!=null&&i?.length>=2?wa(i[0]-i[1])*2*h:h,u&&o?o.map((p,m)=>({coordinate:r(p)+h,value:p,index:m,offset:h})):r.domain().map((p,m)=>({coordinate:r(p)+h,value:s?s[p]:p,index:m,offset:h}))}}},rd=st([Kn,la,t4,sJ,iJ,qRe,WRe,oa],KRe),r4=st([VZ,GZ,rRe],(t,e,n)=>qZ(n.shared,t,e)),oJ=t=>t.tooltip.settings.trigger,i4=t=>t.tooltip.settings.defaultIndex,xv=st([Ib,r4,oJ,i4],ZZ),Ih=st([xv,zb,fv,bv],e4),lJ=st([rd,Ih],WZ),a4=st([xv],t=>{if(t)return t.dataKey}),XRe=st([xv],t=>{if(t)return t.graphicalItemId}),cJ=st([Ib,r4,oJ,i4],eJ),YRe=st([ed,td,Kn,ia,rd,i4,cJ,pv],JZ),QRe=st([xv,YRe],(t,e)=>t!=null&&t.coordinate?t.coordinate:e),ZRe=st([xv],t=>t.active),JRe=st([cJ,Ih,Gh,fv,lJ,pv,r4],tJ),eOe=st([JRe],t=>{if(t!=null){var e=t.map(n=>n.payload).filter(n=>n!=null);return Array.from(new Set(e))}});function uG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function dG(t){for(var e=1;eHt(la),aOe=()=>{var t=iOe(),e=Ht(rd),n=Ht(sJ);return Oh(!t||!n?void 0:dG(dG({},t),{},{scale:n}),e)};function hG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function tg(t){for(var e=1;e{var i=e.find(s=>s&&s.index===n);if(i){if(t==="horizontal")return{x:i.coordinate,y:r.chartY};if(t==="vertical")return{x:r.chartX,y:i.coordinate}}return{x:0,y:0}},uOe=(t,e,n,r)=>{var i=e.find(u=>u&&u.index===n);if(i){if(t==="centric"){var s=i.coordinate,{radius:o}=r;return tg(tg(tg({},r),Bi(r.cx,r.cy,o,s)),{},{angle:s,radius:o})}var l=i.coordinate,{angle:c}=r;return tg(tg(tg({},r),Bi(r.cx,r.cy,l,c)),{},{angle:c,radius:l})}return{angle:0,clockWise:!1,cx:0,cy:0,endAngle:0,innerRadius:0,outerRadius:0,radius:0,startAngle:0,x:0,y:0}};function dOe(t,e){var{chartX:n,chartY:r}=t;return n>=e.left&&n<=e.left+e.width&&r>=e.top&&r<=e.top+e.height}var uJ=(t,e,n,r,i)=>{var s,o=-1,l=(s=e?.length)!==null&&s!==void 0?s:0;if(l<=1||t==null)return 0;if(r==="angleAxis"&&i!=null&&Math.abs(Math.abs(i[1]-i[0])-360)<=1e-6)for(var c=0;c0?n[c-1].coordinate:n[l-1].coordinate,d=n[c].coordinate,h=c>=l-1?n[0].coordinate:n[c+1].coordinate,p=void 0;if(wa(d-u)!==wa(h-d)){var m=[];if(wa(h-d)===wa(i[1]-i[0])){p=h;var b=d+i[1]-i[0];m[0]=Math.min(b,(b+u)/2),m[1]=Math.max(b,(b+u)/2)}else{p=u;var y=h+i[1]-i[0];m[0]=Math.min(d,(y+d)/2),m[1]=Math.max(d,(y+d)/2)}var x=[Math.min(d,(p+d)/2),Math.max(d,(p+d)/2)];if(t>x[0]&&t<=x[1]||t>=m[0]&&t<=m[1]){({index:o}=n[c]);break}}else{var v=Math.min(u,h),S=Math.max(u,h);if(t>(v+d)/2&&t<=(S+d)/2){({index:o}=n[c]);break}}}else if(e){for(var N=0;N0&&N(e[N].coordinate+e[N-1].coordinate)/2&&t<=(e[N].coordinate+e[N+1].coordinate)/2||N===l-1&&t>(e[N].coordinate+e[N-1].coordinate)/2){({index:o}=e[N]);break}}return o},dJ=()=>Ht(EL),s4=(t,e)=>e,hJ=(t,e,n)=>n,o4=(t,e,n,r)=>r,hOe=st(rd,t=>$k(t,e=>e.coordinate)),l4=st([Ib,s4,hJ,o4],ZZ),c4=st([l4,zb,fv,bv],e4),fOe=(t,e,n)=>{if(e!=null){var r=Ib(t);return e==="axis"?n==="hover"?r.axisInteraction.hover.dataKey:r.axisInteraction.click.dataKey:n==="hover"?r.itemInteraction.hover.dataKey:r.itemInteraction.click.dataKey}},fJ=st([Ib,s4,hJ,o4],eJ),ZS=st([ed,td,Kn,ia,rd,o4,fJ,pv],JZ),mOe=st([l4,ZS],(t,e)=>{var n;return(n=t.coordinate)!==null&&n!==void 0?n:e}),mJ=st([rd,c4],WZ),pOe=st([fJ,c4,Gh,fv,mJ,pv,s4],tJ),gOe=st([l4,c4],(t,e)=>({isActive:t.active&&e!=null,activeIndex:e})),bOe=(t,e,n,r,i,s,o)=>{if(!(!t||!n||!r||!i)&&dOe(t,o)){var l=ITe(t,e),c=uJ(l,s,i,n,r),u=cOe(e,i,c,t);return{activeIndex:String(c),activeCoordinate:u}}},xOe=(t,e,n,r,i,s,o)=>{if(!(!t||!r||!i||!s||!n)){var l=tPe(t,n);if(l){var c=zTe(l,e),u=uJ(c,o,s,r,i),d=uOe(e,s,u,l);return{activeIndex:String(u),activeCoordinate:d}}}},yOe=(t,e,n,r,i,s,o,l)=>{if(!(!t||!e||!r||!i||!s))return e==="horizontal"||e==="vertical"?bOe(t,e,r,i,s,o,l):xOe(t,e,n,r,i,s,o)},vOe=st(t=>t.zIndex.zIndexMap,(t,e)=>e,(t,e,n)=>n,(t,e,n)=>{if(e!=null){var r=t[e];if(r!=null)return n?r.panoramaElementId:r.elementId}}),wOe=st(t=>t.zIndex.zIndexMap,t=>{var e=Object.keys(t).map(r=>parseInt(r,10)).concat(Object.values(vi)),n=Array.from(new Set(e));return n.sort((r,i)=>r-i)},{memoizeOptions:{resultEqualityCheck:iDe}});function fG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function mG(t){for(var e=1;emG(mG({},t),{},{[e]:{elementId:void 0,panoramaElementId:void 0,consumers:0}}),kOe)},EOe=new Set(Object.values(vi));function TOe(t){return EOe.has(t)}var pJ=Qs({name:"zIndex",initialState:MOe,reducers:{registerZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]?t.zIndexMap[n].consumers+=1:t.zIndexMap[n]={consumers:1,elementId:void 0,panoramaElementId:void 0}},prepare:Jr()},unregisterZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(t.zIndexMap[n].consumers-=1,t.zIndexMap[n].consumers<=0&&!TOe(n)&&delete t.zIndexMap[n])},prepare:Jr()},registerZIndexPortalId:{reducer:(t,e)=>{var{zIndex:n,elementId:r,isPanorama:i}=e.payload;t.zIndexMap[n]?i?t.zIndexMap[n].panoramaElementId=r:t.zIndexMap[n].elementId=r:t.zIndexMap[n]={consumers:0,elementId:i?void 0:r,panoramaElementId:i?r:void 0}},prepare:Jr()},unregisterZIndexPortalId:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(e.payload.isPanorama?t.zIndexMap[n].panoramaElementId=void 0:t.zIndexMap[n].elementId=void 0)},prepare:Jr()}}}),{registerZIndexPortal:AOe,unregisterZIndexPortal:COe,registerZIndexPortalId:POe,unregisterZIndexPortalId:jOe}=pJ.actions,DOe=pJ.reducer;function ls(t){var{zIndex:e,children:n}=t,r=bAe(),i=r&&e!==void 0&&e!==0,s=aa(),o=zr();_.useLayoutEffect(()=>i?(o(AOe({zIndex:e})),()=>{o(COe({zIndex:e}))}):Xy,[o,e,i]);var l=Ht(u=>vOe(u,e,s));if(!i)return n;if(!l)return null;var c=document.getElementById(l);return c?vu.createPortal(n,c):null}function ED(){return ED=Object.assign?Object.assign.bind():function(t){for(var e=1;e_.useContext(gJ),QC={exports:{}},gG;function BOe(){return gG||(gG=1,(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(c,u,d){this.fn=c,this.context=u,this.once=d||!1}function s(c,u,d,h,p){if(typeof d!="function")throw new TypeError("The listener must be a function");var m=new i(d,h||c,p),b=n?n+u:u;return c._events[b]?c._events[b].fn?c._events[b]=[c._events[b],m]:c._events[b].push(m):(c._events[b]=m,c._eventsCount++),c}function o(c,u){--c._eventsCount===0?c._events=new r:delete c._events[u]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var u=[],d,h;if(this._eventsCount===0)return u;for(h in d=this._events)e.call(d,h)&&u.push(n?h.slice(1):h);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},l.prototype.listeners=function(u){var d=n?n+u:u,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,m=h.length,b=new Array(m);p{t.eventEmitter==null&&(t.eventEmitter=Symbol("rechartsEventEmitter"))}}}),GOe=bJ.reducer,{createEventEmitter:qOe}=bJ.actions;function WOe(t){return t.tooltip.syncInteraction}var KOe={chartData:void 0,computedData:void 0,dataStartIndex:0,dataEndIndex:0},xJ=Qs({name:"chartData",initialState:KOe,reducers:{setChartData(t,e){if(t.chartData=e.payload,e.payload==null){t.dataStartIndex=0,t.dataEndIndex=0;return}e.payload.length>0&&t.dataEndIndex!==e.payload.length-1&&(t.dataEndIndex=e.payload.length-1)},setComputedData(t,e){t.computedData=e.payload},setDataStartEndIndexes(t,e){var{startIndex:n,endIndex:r}=e.payload;n!=null&&(t.dataStartIndex=n),r!=null&&(t.dataEndIndex=r)}}}),{setChartData:xG,setDataStartEndIndexes:XOe,setComputedData:pQe}=xJ.actions,YOe=xJ.reducer,QOe=["x","y"];function yG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function ng(t){for(var e=1;ec.rootProps.className);_.useEffect(()=>{if(t==null)return Xy;var c=(u,d,h)=>{if(e!==h&&t===u){if(r==="index"){var p;if(o&&d!==null&&d!==void 0&&(p=d.payload)!==null&&p!==void 0&&p.coordinate&&d.payload.sourceViewBox){var m=d.payload.coordinate,{x:b,y}=m,x=tLe(m,QOe),{x:v,y:S,width:N,height:T}=d.payload.sourceViewBox,M=ng(ng({},x),{},{x:o.x+(N?(b-v)/N:0)*o.width,y:o.y+(T?(y-S)/T:0)*o.height});n(ng(ng({},d),{},{payload:ng(ng({},d.payload),{},{coordinate:M})}))}else n(d);return}if(i!=null){var A;if(typeof r=="function"){var k={activeTooltipIndex:d.payload.index==null?void 0:Number(d.payload.index),isTooltipActive:d.payload.active,activeIndex:d.payload.index==null?void 0:Number(d.payload.index),activeLabel:d.payload.label,activeDataKey:d.payload.dataKey,activeCoordinate:d.payload.coordinate},R=r(i,k);A=i[R]}else r==="value"&&(A=i.find(G=>String(G.value)===d.payload.label));var{coordinate:C}=d.payload;if(A==null||d.payload.active===!1||C==null||o==null){n(kD({active:!1,coordinate:void 0,dataKey:void 0,index:null,label:void 0,sourceViewBox:void 0,graphicalItemId:void 0}));return}var{x:P,y:U}=C,F=Math.min(P,o.x+o.width),H=Math.min(U,o.y+o.height),D={x:s==="horizontal"?A.coordinate:F,y:s==="horizontal"?H:A.coordinate},$=kD({active:d.payload.active,coordinate:D,dataKey:d.payload.dataKey,index:String(A.index),label:d.payload.label,sourceViewBox:d.payload.sourceViewBox,graphicalItemId:d.payload.graphicalItemId});n($)}}};return Ny.on(TD,c),()=>{Ny.off(TD,c)}},[l,n,e,t,r,i,s,o])}function iLe(){var t=Ht(TL),e=Ht(AL),n=zr();_.useEffect(()=>{if(t==null)return Xy;var r=(i,s,o)=>{e!==o&&t===i&&n(XOe(s))};return Ny.on(bG,r),()=>{Ny.off(bG,r)}},[n,e,t])}function aLe(){var t=zr();_.useEffect(()=>{t(qOe())},[t]),rLe(),iLe()}function sLe(t,e,n,r,i,s){var o=Ht(m=>fOe(m,t,e)),l=Ht(AL),c=Ht(TL),u=Ht(fZ),d=Ht(WOe),h=d?.active,p=tv();_.useEffect(()=>{if(!h&&c!=null&&l!=null){var m=kD({active:s,coordinate:n,dataKey:o,index:i,label:typeof r=="number"?String(r):r,sourceViewBox:p,graphicalItemId:void 0});Ny.emit(TD,c,m,l)}},[h,n,o,i,r,l,c,u,s,p])}function vG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function wG(t){for(var e=1;e{k(lRe({shared:S,trigger:N,axisId:A,active:i,defaultIndex:R}))},[k,S,N,A,i,R]);var C=tv(),P=aQ(),U=nRe(S),{activeIndex:F,isActive:H}=(e=Ht(de=>gOe(de,U,N,R)))!==null&&e!==void 0?e:{},D=Ht(de=>pOe(de,U,N,R)),$=Ht(de=>mJ(de,U,N,R)),G=Ht(de=>mOe(de,U,N,R)),I=D,K=UOe(),Q=(n=i??H)!==null&&n!==void 0?n:!1,[oe,B]=oY([I,Q]),W=U==="axis"?$:void 0;sLe(U,N,G,W,F,Q);var J=M??K;if(J==null||C==null||U==null)return null;var ne=I??_G;Q||(ne=_G),u&&ne.length&&(ne=tY(ne.filter(de=>de.value!=null&&(de.hide!==!0||r.includeHidden)),p,uLe));var me=ne.length>0,fe=_.createElement(nCe,{allowEscapeViewBox:s,animationDuration:o,animationEasing:l,isAnimationActive:d,active:Q,coordinate:G,hasPayload:me,offset:h,position:m,reverseDirection:b,useTranslate3d:y,viewBox:C,wrapperStyle:x,lastBoundingBox:oe,innerRef:B,hasPortalFromProps:!!M},dLe(c,wG(wG({},r),{},{payload:ne,label:W,active:Q,activeIndex:F,coordinate:G,accessibilityLayer:P})));return _.createElement(_.Fragment,null,vu.createPortal(fe,J),Q&&_.createElement(zOe,{cursor:v,tooltipEventType:U,coordinate:G,payload:ne,index:F}))}var yv=t=>null;yv.displayName="Cell";function fLe(t,e,n){return(e=mLe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mLe(t){var e=pLe(t,"string");return typeof e=="symbol"?e:e+""}function pLe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}class gLe{constructor(e){fLe(this,"cache",new Map),this.maxSize=e}get(e){var n=this.cache.get(e);return n!==void 0&&(this.cache.delete(e),this.cache.set(e,n)),n}set(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){var r=this.cache.keys().next().value;r!=null&&this.cache.delete(r)}this.cache.set(e,n)}clear(){this.cache.clear()}size(){return this.cache.size}}function SG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function bLe(t){for(var e=1;e{try{var n=document.getElementById(kG);n||(n=document.createElement("span"),n.setAttribute("id",kG),n.setAttribute("aria-hidden","true"),document.body.appendChild(n)),Object.assign(n.style,_Le,e),n.textContent="".concat(t);var r=n.getBoundingClientRect();return{width:r.width,height:r.height}}catch{return{width:0,height:0}}},A0=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||Ab.isSsr)return{width:0,height:0};if(!yJ.enableCache)return MG(e,n);var r=SLe(e,n),i=NG.get(r);if(i)return i;var s=MG(e,n);return NG.set(r,s),s},EG=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,TG=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,NLe=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,kLe=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,vJ={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},MLe=Object.keys(vJ),_g="NaN";function ELe(t,e){return t*vJ[e]}class Us{static parse(e){var n,[,r,i]=(n=kLe.exec(e))!==null&&n!==void 0?n:[];return new Us(parseFloat(r),i??"")}constructor(e,n){this.num=e,this.unit=n,this.num=e,this.unit=n,Ys(e)&&(this.unit=""),n!==""&&!NLe.test(n)&&(this.num=NaN,this.unit=""),MLe.includes(n)&&(this.num=ELe(e,n),this.unit="px")}add(e){return this.unit!==e.unit?new Us(NaN,""):new Us(this.num+e.num,this.unit)}subtract(e){return this.unit!==e.unit?new Us(NaN,""):new Us(this.num-e.num,this.unit)}multiply(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new Us(NaN,""):new Us(this.num*e.num,this.unit||e.unit)}divide(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new Us(NaN,""):new Us(this.num/e.num,this.unit||e.unit)}toString(){return"".concat(this.num).concat(this.unit)}isNaN(){return Ys(this.num)}}function wJ(t){if(t.includes(_g))return _g;for(var e=t;e.includes("*")||e.includes("/");){var n,[,r,i,s]=(n=EG.exec(e))!==null&&n!==void 0?n:[],o=Us.parse(r??""),l=Us.parse(s??""),c=i==="*"?o.multiply(l):o.divide(l);if(c.isNaN())return _g;e=e.replace(EG,c.toString())}for(;e.includes("+")||/.-\d+(?:\.\d+)?/.test(e);){var u,[,d,h,p]=(u=TG.exec(e))!==null&&u!==void 0?u:[],m=Us.parse(d??""),b=Us.parse(p??""),y=h==="+"?m.add(b):m.subtract(b);if(y.isNaN())return _g;e=e.replace(TG,y.toString())}return e}var AG=/\(([^()]*)\)/;function TLe(t){for(var e=t,n;(n=AG.exec(e))!=null;){var[,r]=n;e=e.replace(AG,wJ(r))}return e}function ALe(t){var e=t.replace(/\s+/g,"");return e=TLe(e),e=wJ(e),e}function CLe(t){try{return ALe(t)}catch{return _g}}function ZC(t){var e=CLe(t.slice(5,-1));return e===_g?"":e}var PLe=["x","y","lineHeight","capHeight","fill","scaleToFit","textAnchor","verticalAnchor"],jLe=["dx","dy","angle","className","breakAll"];function AD(){return AD=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{children:e,breakAll:n,style:r}=t;try{var i=[];Yr(e)||(n?i=e.toString().split(""):i=e.toString().split(_J));var s=i.map(l=>({word:l,width:A0(l,r).width})),o=n?0:A0(" ",r).width;return{wordsWithComputedWidth:s,spaceWidth:o}}catch{return null}};function RLe(t){return t==="start"||t==="middle"||t==="end"||t==="inherit"}var NJ=(t,e,n,r)=>t.reduce((i,s)=>{var{word:o,width:l}=s,c=i[i.length-1];if(c&&l!=null&&(e==null||r||c.width+l+nt.reduce((e,n)=>e.width>n.width?e:n),OLe="…",PG=(t,e,n,r,i,s,o,l)=>{var c=t.slice(0,e),u=SJ({breakAll:n,style:r,children:c+OLe});if(!u)return[!1,[]];var d=NJ(u.wordsWithComputedWidth,s,o,l),h=d.length>i||kJ(d).width>Number(s);return[h,d]},LLe=(t,e,n,r,i)=>{var{maxLines:s,children:o,style:l,breakAll:c}=t,u=Vt(s),d=String(o),h=NJ(e,r,n,i);if(!u||i)return h;var p=h.length>s||kJ(h).width>Number(r);if(!p)return h;for(var m=0,b=d.length-1,y=0,x;m<=b&&y<=d.length-1;){var v=Math.floor((m+b)/2),S=v-1,[N,T]=PG(d,S,c,l,s,r,n,i),[M]=PG(d,v,c,l,s,r,n,i);if(!N&&!M&&(m=v+1),N&&M&&(b=v-1),!N&&M){x=T;break}y++}return x||h},jG=t=>{var e=Yr(t)?[]:t.toString().split(_J);return[{words:e,width:void 0}]},FLe=t=>{var{width:e,scaleToFit:n,children:r,style:i,breakAll:s,maxLines:o}=t;if((e||n)&&!Ab.isSsr){var l,c,u=SJ({breakAll:s,children:r,style:i});if(u){var{wordsWithComputedWidth:d,spaceWidth:h}=u;l=d,c=h}else return jG(r);return LLe({breakAll:s,children:r,maxLines:o,style:i},l,c,e,!!n)}return jG(r)},MJ="#808080",ILe={angle:0,breakAll:!1,capHeight:"0.71em",fill:MJ,lineHeight:"1em",scaleToFit:!1,textAnchor:"start",verticalAnchor:"end",x:0,y:0},SM=_.forwardRef((t,e)=>{var n=ci(t,ILe),{x:r,y:i,lineHeight:s,capHeight:o,fill:l,scaleToFit:c,textAnchor:u,verticalAnchor:d}=n,h=CG(n,PLe),p=_.useMemo(()=>FLe({breakAll:h.breakAll,children:h.children,maxLines:h.maxLines,scaleToFit:c,style:h.style,width:h.width}),[h.breakAll,h.children,h.maxLines,c,h.style,h.width]),{dx:m,dy:b,angle:y,className:x,breakAll:v}=h,S=CG(h,jLe);if(!fl(r)||!fl(i)||p.length===0)return null;var N=Number(r)+(Vt(m)?m:0),T=Number(i)+(Vt(b)?b:0);if(!wr(N)||!wr(T))return null;var M;switch(d){case"start":M=ZC("calc(".concat(o,")"));break;case"middle":M=ZC("calc(".concat((p.length-1)/2," * -").concat(s," + (").concat(o," / 2))"));break;default:M=ZC("calc(".concat(p.length-1," * -").concat(s,")"));break}var A=[];if(c){var k=p[0].width,{width:R}=h;A.push("scale(".concat(Vt(R)&&Vt(k)?R/k:1,")"))}return y&&A.push("rotate(".concat(y,", ").concat(N,", ").concat(T,")")),A.length&&(S.transform=A.join(" ")),_.createElement("text",AD({},Ga(S),{ref:e,x:N,y:T,className:nr("recharts-text",x),textAnchor:u,fill:l.includes("url")?MJ:l}),p.map((C,P)=>{var U=C.words.join(v?"":" ");return _.createElement("tspan",{x:N,dy:P===0?M:s,key:"".concat(U,"-").concat(P)},U)}))});SM.displayName="Text";var zLe=["labelRef"];function ULe(t,e){if(t==null)return{};var n,r,i=BLe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var{x:e,y:n,upperWidth:r,lowerWidth:i,width:s,height:o,children:l}=t,c=_.useMemo(()=>({x:e,y:n,upperWidth:r,lowerWidth:i,width:s,height:o}),[e,n,r,i,s,o]);return _.createElement(EJ.Provider,{value:c},l)},AJ=()=>{var t=_.useContext(EJ),e=tv();return t||WY(e)},GLe=_.createContext(null),qLe=()=>{var t=_.useContext(GLe),e=Ht(xZ);return t||e},WLe=t=>{var{value:e,formatter:n}=t,r=Yr(t.children)?e:t.children;return typeof n=="function"?n(r):r},u4=t=>t!=null&&typeof t=="function",KLe=(t,e)=>{var n=wa(e-t),r=Math.min(Math.abs(e-t),360);return n*r},XLe=(t,e,n,r,i)=>{var{offset:s,className:o}=t,{cx:l,cy:c,innerRadius:u,outerRadius:d,startAngle:h,endAngle:p,clockWise:m}=i,b=(u+d)/2,y=KLe(h,p),x=y>=0?1:-1,v,S;switch(e){case"insideStart":v=h+x*s,S=m;break;case"insideEnd":v=p-x*s,S=!m;break;case"end":v=p+x*s,S=m;break;default:throw new Error("Unsupported position ".concat(e))}S=y<=0?S:!S;var N=Bi(l,c,b,v),T=Bi(l,c,b,v+(S?1:-1)*359),M="M".concat(N.x,",").concat(N.y,` A`).concat(b,",").concat(b,",0,1,").concat(S?0:1,`, - `).concat(T.x,",").concat(T.y),A=Yr(t.id)?uy("recharts-radial-line-"):t.id;return _.createElement("text",yu({},r,{dominantBaseline:"central",className:nr("recharts-radial-bar-label",o)}),_.createElement("defs",null,_.createElement("path",{id:A,d:M})),_.createElement("textPath",{xlinkHref:"#".concat(A)},n))},YLe=(t,e,n)=>{var{cx:r,cy:i,innerRadius:s,outerRadius:o,startAngle:l,endAngle:c}=t,u=(l+c)/2;if(n==="outside"){var{x:d,y:h}=Bi(r,i,o+e,u);return{x:d,y:h,textAnchor:d>=r?"start":"end",verticalAnchor:"middle"}}if(n==="center")return{x:r,y:i,textAnchor:"middle",verticalAnchor:"middle"};if(n==="centerTop")return{x:r,y:i,textAnchor:"middle",verticalAnchor:"start"};if(n==="centerBottom")return{x:r,y:i,textAnchor:"middle",verticalAnchor:"end"};var p=(s+o)/2,{x:m,y:b}=Bi(r,i,p,u);return{x:m,y:b,textAnchor:"middle",verticalAnchor:"middle"}},CD=t=>"cx"in t&&Vt(t.cx),QLe=(t,e)=>{var{parentViewBox:n,offset:r,position:i}=t,s;n!=null&&!CD(n)&&(s=n);var{x:o,y:l,upperWidth:c,lowerWidth:u,height:d}=e,h=o,p=o+(c-u)/2,m=(h+p)/2,b=(c+u)/2,y=h+c/2,x=d>=0?1:-1,v=x*r,S=x>0?"end":"start",N=x>0?"start":"end",T=c>=0?1:-1,M=T*r,A=T>0?"end":"start",k=T>0?"start":"end";if(i==="top"){var R={x:h+c/2,y:l-v,textAnchor:"middle",verticalAnchor:S};return Mi(Mi({},R),s?{height:Math.max(l-s.y,0),width:c}:{})}if(i==="bottom"){var C={x:p+u/2,y:l+d+v,textAnchor:"middle",verticalAnchor:N};return Mi(Mi({},C),s?{height:Math.max(s.y+s.height-(l+d),0),width:u}:{})}if(i==="left"){var P={x:m-M,y:l+d/2,textAnchor:A,verticalAnchor:"middle"};return Mi(Mi({},P),s?{width:Math.max(P.x-s.x,0),height:d}:{})}if(i==="right"){var U={x:m+b+M,y:l+d/2,textAnchor:k,verticalAnchor:"middle"};return Mi(Mi({},U),s?{width:Math.max(s.x+s.width-U.x,0),height:d}:{})}var F=s?{width:b,height:d}:{};return i==="insideLeft"?Mi({x:m+M,y:l+d/2,textAnchor:k,verticalAnchor:"middle"},F):i==="insideRight"?Mi({x:m+b-M,y:l+d/2,textAnchor:A,verticalAnchor:"middle"},F):i==="insideTop"?Mi({x:h+c/2,y:l+v,textAnchor:"middle",verticalAnchor:N},F):i==="insideBottom"?Mi({x:p+u/2,y:l+d-v,textAnchor:"middle",verticalAnchor:S},F):i==="insideTopLeft"?Mi({x:h+M,y:l+v,textAnchor:k,verticalAnchor:N},F):i==="insideTopRight"?Mi({x:h+c-M,y:l+v,textAnchor:A,verticalAnchor:N},F):i==="insideBottomLeft"?Mi({x:p+M,y:l+d-v,textAnchor:k,verticalAnchor:S},F):i==="insideBottomRight"?Mi({x:p+u-M,y:l+d-v,textAnchor:A,verticalAnchor:S},F):i&&typeof i=="object"&&(Vt(i.x)||qu(i.x))&&(Vt(i.y)||qu(i.y))?Mi({x:o+as(i.x,b),y:l+as(i.y,d),textAnchor:"end",verticalAnchor:"end"},F):Mi({x:y,y:l+d/2,textAnchor:"middle",verticalAnchor:"middle"},F)},ZLe={angle:0,offset:5,zIndex:vi.label,position:"middle",textBreakAll:!1};function Zd(t){var e=ci(t,ZLe),{viewBox:n,position:r,value:i,children:s,content:o,className:l="",textBreakAll:c,labelRef:u}=e,d=qLe(),h=AJ(),p=r==="center"?h:d??h,m,b,y;if(n==null?m=p:CD(n)?m=n:m=WY(n),!m||Yr(i)&&Yr(s)&&!_.isValidElement(o)&&typeof o!="function")return null;var x=Mi(Mi({},e),{},{viewBox:m});if(_.isValidElement(o)){var{labelRef:v}=x,S=ULe(x,zLe);return _.cloneElement(o,S)}if(typeof o=="function"){if(b=_.createElement(o,x),_.isValidElement(b))return b}else b=WLe(e);var N=Ga(e);if(CD(m)){if(r==="insideStart"||r==="insideEnd"||r==="end")return XLe(e,r,b,N,m);y=YLe(m,e.offset,e.position)}else y=QLe(e,m);return _.createElement(ls,{zIndex:e.zIndex},_.createElement(SM,yu({ref:u,className:nr("recharts-label",l)},N,y,{textAnchor:RLe(N.textAnchor)?N.textAnchor:y.textAnchor,breakAll:c}),b))}Zd.displayName="Label";var JLe=(t,e,n)=>{if(!t)return null;var r={viewBox:e,labelRef:n};return t===!0?_.createElement(Zd,yu({key:"label-implicit"},r)):fl(t)?_.createElement(Zd,yu({key:"label-implicit",value:t},r)):_.isValidElement(t)?t.type===Zd?_.cloneElement(t,Mi({key:"label-implicit"},r)):_.createElement(Zd,yu({key:"label-implicit",content:t},r)):u4(t)?_.createElement(Zd,yu({key:"label-implicit",content:t},r)):t&&typeof t=="object"?_.createElement(Zd,yu({},t,{key:"label-implicit"},r)):null};function CJ(t){var{label:e,labelRef:n}=t,r=AJ();return JLe(e,r,n)||null}var JC={},eP={},RG;function e4e(){return RG||(RG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n[n.length-1]}t.last=e})(eP)),eP}var tP={},OG;function t4e(){return OG||(OG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Array.isArray(n)?n:Array.from(n)}t.toArray=e})(tP)),tP}var LG;function n4e(){return LG||(LG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=e4e(),n=t4e(),r=IO();function i(s){if(r.isArrayLike(s))return e.last(n.toArray(s))}t.last=i})(JC)),JC}var nP,FG;function r4e(){return FG||(FG=1,nP=n4e().last),nP}var i4e=r4e();const a4e=gl(i4e);var s4e=["valueAccessor"],o4e=["dataKey","clockWise","id","textBreakAll","zIndex"];function JS(){return JS=Object.assign?Object.assign.bind():function(t){for(var e=1;eArray.isArray(t.value)?a4e(t.value):t.value,PJ=_.createContext(void 0),d4=PJ.Provider,jJ=_.createContext(void 0),u4e=jJ.Provider;function d4e(){return _.useContext(PJ)}function h4e(){return _.useContext(jJ)}function U1(t){var{valueAccessor:e=c4e}=t,n=IG(t,s4e),{dataKey:r,clockWise:i,id:s,textBreakAll:o,zIndex:l}=n,c=IG(n,o4e),u=d4e(),d=h4e(),h=u||d;return!h||!h.length?null:_.createElement(ls,{zIndex:l??vi.label},_.createElement(li,{className:"recharts-label-list"},h.map((p,m)=>{var b,y=Yr(r)?e(p,m):vr(p&&p.payload,r),x=Yr(s)?{}:{id:"".concat(s,"-").concat(m)};return _.createElement(Zd,JS({key:"label-".concat(m)},Ga(p),c,x,{fill:(b=n.fill)!==null&&b!==void 0?b:p.fill,parentViewBox:p.parentViewBox,value:y,textBreakAll:o,viewBox:p.viewBox,index:m,zIndex:0}))})))}U1.displayName="LabelList";function NM(t){var{label:e}=t;return e?e===!0?_.createElement(U1,{key:"labelList-implicit"}):_.isValidElement(e)||u4(e)?_.createElement(U1,{key:"labelList-implicit",content:e}):typeof e=="object"?_.createElement(U1,JS({key:"labelList-implicit"},e,{type:String(e.type)})):null:null}function PD(){return PD=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{cx:e,cy:n,r,className:i}=t,s=nr("recharts-dot",i);return Vt(e)&&Vt(n)&&Vt(r)?_.createElement("circle",PD({},Ms(t),FO(t),{className:s,cx:e,cy:n,r})):null},RJ=t=>t.graphicalItems.polarItems,f4e=st([ii,cv],RL),kM=st([RJ,ui,f4e],OL),m4e=st([kM],LL),MM=st([m4e,NL],FL),p4e=st([MM,ui,kM],zL);st([MM,ui,kM],(t,e,n)=>n.length>0?t.flatMap(r=>n.flatMap(i=>{var s,o=vr(r,(s=e.dataKey)!==null&&s!==void 0?s:i.dataKey);return{value:o,errorDomain:[]}})).filter(Boolean):e?.dataKey!=null?t.map(r=>({value:vr(r,e.dataKey),errorDomain:[]})):t.map(r=>({value:r,errorDomain:[]})));var zG=()=>{},g4e=st([MM,ui,kM,yM,ii],$L),b4e=st([ui,BL,HL,zG,g4e,zG,Kn,ii],VL),OJ=st([ui,Kn,MM,p4e,lv,ii,b4e],GL),x4e=st([OJ,ui,Fb],KL);st([ui,OJ,x4e,ii],YL);var y4e={radiusAxis:{},angleAxis:{}},LJ=Qs({name:"polarAxis",initialState:y4e,reducers:{addRadiusAxis(t,e){t.radiusAxis[e.payload.id]=e.payload},removeRadiusAxis(t,e){delete t.radiusAxis[e.payload.id]},addAngleAxis(t,e){t.angleAxis[e.payload.id]=e.payload},removeAngleAxis(t,e){delete t.angleAxis[e.payload.id]}}}),{addRadiusAxis:pQe,removeRadiusAxis:gQe,addAngleAxis:bQe,removeAngleAxis:xQe}=LJ.actions,v4e=LJ.reducer;function UG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function BG(t){for(var e=1;ee,h4=st([RJ,N4e],(t,e)=>t.filter(n=>n.type==="pie").find(n=>n.id===e)),k4e=[],f4=(t,e,n)=>n?.length===0?k4e:n,FJ=st([NL,h4,f4],(t,e,n)=>{var{chartData:r}=t;if(e!=null){var i;if(e?.data!=null&&e.data.length>0?i=e.data:i=r,(!i||!i.length)&&n!=null&&(i=n.map(s=>BG(BG({},e.presentationProps),s.props))),i!=null)return i}}),M4e=st([FJ,h4,f4],(t,e,n)=>{if(!(t==null||e==null))return t.map((r,i)=>{var s,o=vr(r,e.nameKey,e.name),l;return n!=null&&(s=n[i])!==null&&s!==void 0&&(s=s.props)!==null&&s!==void 0&&s.fill?l=n[i].props.fill:typeof r=="object"&&r!=null&&"fill"in r?l=r.fill:l=e.fill,{value:Hh(o,e.dataKey),color:l,payload:r,type:e.legendType}})}),E4e=st([FJ,h4,f4,ia],(t,e,n,r)=>{if(!(e==null||t==null))return TFe({offset:r,pieSettings:e,displayedData:t,cells:n})}),rP={exports:{}},Mr={};var HG;function T4e(){if(HG)return Mr;HG=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.suspense_list"),d=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),p=Symbol.for("react.view_transition"),m=Symbol.for("react.client.reference");function b(y){if(typeof y=="object"&&y!==null){var x=y.$$typeof;switch(x){case t:switch(y=y.type,y){case n:case i:case r:case c:case u:case p:return y;default:switch(y=y&&y.$$typeof,y){case o:case l:case h:case d:return y;case s:return y;default:return x}}case e:return x}}}return Mr.ContextConsumer=s,Mr.ContextProvider=o,Mr.Element=t,Mr.ForwardRef=l,Mr.Fragment=n,Mr.Lazy=h,Mr.Memo=d,Mr.Portal=e,Mr.Profiler=i,Mr.StrictMode=r,Mr.Suspense=c,Mr.SuspenseList=u,Mr.isContextConsumer=function(y){return b(y)===s},Mr.isContextProvider=function(y){return b(y)===o},Mr.isElement=function(y){return typeof y=="object"&&y!==null&&y.$$typeof===t},Mr.isForwardRef=function(y){return b(y)===l},Mr.isFragment=function(y){return b(y)===n},Mr.isLazy=function(y){return b(y)===h},Mr.isMemo=function(y){return b(y)===d},Mr.isPortal=function(y){return b(y)===e},Mr.isProfiler=function(y){return b(y)===i},Mr.isStrictMode=function(y){return b(y)===r},Mr.isSuspense=function(y){return b(y)===c},Mr.isSuspenseList=function(y){return b(y)===u},Mr.isValidElementType=function(y){return typeof y=="string"||typeof y=="function"||y===n||y===i||y===r||y===c||y===u||typeof y=="object"&&y!==null&&(y.$$typeof===h||y.$$typeof===d||y.$$typeof===o||y.$$typeof===s||y.$$typeof===l||y.$$typeof===m||y.getModuleId!==void 0)},Mr.typeOf=b,Mr}var $G;function A4e(){return $G||($G=1,rP.exports=T4e()),rP.exports}var C4e=A4e(),VG=t=>typeof t=="string"?t:t?t.displayName||t.name||"Component":"",GG=null,iP=null,IJ=t=>{if(t===GG&&Array.isArray(iP))return iP;var e=[];return _.Children.forEach(t,n=>{Yr(n)||(C4e.isFragment(n)?e=e.concat(IJ(n.props.children)):e.push(n))}),iP=e,GG=t,e};function m4(t,e){var n=[],r=[];return Array.isArray(e)?r=e.map(i=>VG(i)):r=[VG(e)],IJ(t).forEach(i=>{var s=wm(i,"type.displayName")||wm(i,"type.name");s&&r.indexOf(s)!==-1&&n.push(i)}),n}var p4=t=>t&&typeof t=="object"&&"clipDot"in t?!!t.clipDot:!0,aP={},qG;function P4e(){return qG||(qG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){if(typeof n!="object"||n==null)return!1;if(Object.getPrototypeOf(n)===null)return!0;if(Object.prototype.toString.call(n)!=="[object Object]"){const i=n[Symbol.toStringTag];return i==null||!Object.getOwnPropertyDescriptor(n,Symbol.toStringTag)?.writable?!1:n.toString()===`[object ${i}]`}let r=n;for(;Object.getPrototypeOf(r)!==null;)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(n)===r}t.isPlainObject=e})(aP)),aP}var sP,WG;function j4e(){return WG||(WG=1,sP=P4e().isPlainObject),sP}var D4e=j4e();const R4e=gl(D4e);function KG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function XG(t){for(var e=1;e{var s=n-r,o;return o="M ".concat(t,",").concat(e),o+="L ".concat(t+n,",").concat(e),o+="L ".concat(t+n-s/2,",").concat(e+i),o+="L ".concat(t+n-s/2-r,",").concat(e+i),o+="L ".concat(t,",").concat(e," Z"),o},I4e={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},z4e=t=>{var e=ci(t,I4e),{x:n,y:r,upperWidth:i,lowerWidth:s,height:o,className:l}=e,{animationEasing:c,animationDuration:u,animationBegin:d,isUpdateAnimationActive:h}=e,p=_.useRef(null),[m,b]=_.useState(-1),y=_.useRef(i),x=_.useRef(s),v=_.useRef(o),S=_.useRef(n),N=_.useRef(r),T=Pb(t,"trapezoid-");if(_.useEffect(()=>{if(p.current&&p.current.getTotalLength)try{var D=p.current.getTotalLength();D&&b(D)}catch{}},[]),n!==+n||r!==+r||i!==+i||s!==+s||o!==+o||i===0&&s===0||o===0)return null;var M=nr("recharts-trapezoid",l);if(!h)return _.createElement("g",null,_.createElement("path",eN({},Ga(e),{className:M,d:YG(n,r,i,s,o)})));var A=y.current,k=x.current,R=v.current,C=S.current,P=N.current,U="0px ".concat(m===-1?1:m,"px"),F="".concat(m,"px 0px"),H=sQ(["strokeDasharray"],u,c);return _.createElement(Cb,{animationId:T,key:T,canBegin:m>0,duration:u,easing:c,isActive:h,begin:d},D=>{var $=pr(A,i,D),G=pr(k,s,D),I=pr(R,o,D),K=pr(C,n,D),Q=pr(P,r,D);p.current&&(y.current=$,x.current=G,v.current=I,S.current=K,N.current=Q);var oe=D>0?{transition:H,strokeDasharray:F}:{strokeDasharray:U};return _.createElement("path",eN({},Ga(e),{className:M,d:YG(K,Q,$,G,I),ref:p,style:XG(XG({},oe),e.style)}))})},U4e=["option","shapeType","propTransformer","activeClassName"];function B4e(t,e){if(t==null)return{};var n,r,i=H4e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var r=zr();return(i,s)=>o=>{t?.(i,s,o),r(XZ({activeIndex:String(s),activeDataKey:e,activeCoordinate:i.tooltipPosition,activeGraphicalItemId:n}))}},x4=t=>{var e=zr();return(n,r)=>i=>{t?.(n,r,i),e(cRe())}},y4=(t,e,n)=>{var r=zr();return(i,s)=>o=>{t?.(i,s,o),r(uRe({activeIndex:String(s),activeDataKey:e,activeCoordinate:i.tooltipPosition,activeGraphicalItemId:n}))}};function EM(t){var{tooltipEntrySettings:e}=t,n=zr(),r=aa(),i=_.useRef(null);return _.useLayoutEffect(()=>{r||(i.current===null?n(aRe(e)):i.current!==e&&n(sRe({prev:i.current,next:e})),i.current=e)},[e,n,r]),_.useLayoutEffect(()=>()=>{i.current&&(n(oRe(i.current)),i.current=null)},[n]),null}function v4(t){var{legendPayload:e}=t,n=zr(),r=aa(),i=_.useRef(null);return _.useLayoutEffect(()=>{r||(i.current===null?n(nQ(e)):i.current!==e&&n(rQ({prev:i.current,next:e})),i.current=e)},[n,r,e]),_.useLayoutEffect(()=>()=>{i.current&&(n(iQ(i.current)),i.current=null)},[n]),null}function X4e(t){var{legendPayload:e}=t,n=zr(),r=Ht(Kn),i=_.useRef(null);return _.useLayoutEffect(()=>{r!=="centric"&&r!=="radial"||(i.current===null?n(nQ(e)):i.current!==e&&n(rQ({prev:i.current,next:e})),i.current=e)},[n,r,e]),_.useLayoutEffect(()=>()=>{i.current&&(n(iQ(i.current)),i.current=null)},[n]),null}var oP,Y4e=()=>{var[t]=_.useState(()=>uy("uid-"));return t},Q4e=(oP=tse.useId)!==null&&oP!==void 0?oP:Y4e;function zJ(t,e){var n=Q4e();return e||(t?"".concat(t,"-").concat(n):n)}var Z4e=_.createContext(void 0),TM=t=>{var{id:e,type:n,children:r}=t,i=zJ("recharts-".concat(n),e);return _.createElement(Z4e.Provider,{value:i},r(i))},J4e={cartesianItems:[],polarItems:[]},UJ=Qs({name:"graphicalItems",initialState:J4e,reducers:{addCartesianGraphicalItem:{reducer(t,e){t.cartesianItems.push(e.payload)},prepare:Jr()},replaceCartesianGraphicalItem:{reducer(t,e){var{prev:n,next:r}=e.payload,i=Il(t).cartesianItems.indexOf(n);i>-1&&(t.cartesianItems[i]=r)},prepare:Jr()},removeCartesianGraphicalItem:{reducer(t,e){var n=Il(t).cartesianItems.indexOf(e.payload);n>-1&&t.cartesianItems.splice(n,1)},prepare:Jr()},addPolarGraphicalItem:{reducer(t,e){t.polarItems.push(e.payload)},prepare:Jr()},removePolarGraphicalItem:{reducer(t,e){var n=Il(t).polarItems.indexOf(e.payload);n>-1&&t.polarItems.splice(n,1)},prepare:Jr()}}}),{addCartesianGraphicalItem:eFe,replaceCartesianGraphicalItem:tFe,removeCartesianGraphicalItem:nFe,addPolarGraphicalItem:rFe,removePolarGraphicalItem:iFe}=UJ.actions,aFe=UJ.reducer,sFe=t=>{var e=zr(),n=_.useRef(null);return _.useLayoutEffect(()=>{n.current===null?e(eFe(t)):n.current!==t&&e(tFe({prev:n.current,next:t})),n.current=t},[e,t]),_.useLayoutEffect(()=>()=>{n.current&&(e(nFe(n.current)),n.current=null)},[e]),null},w4=_.memo(sFe);function oFe(t){var e=zr();return _.useLayoutEffect(()=>(e(rFe(t)),()=>{e(iFe(t))}),[e,t]),null}var lFe=["key"],cFe=["onMouseEnter","onClick","onMouseLeave"],uFe=["id"],dFe=["id"];function JG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function gi(t){for(var e=1;em4(t.children,yv),[t.children]),n=Ht(r=>M4e(r,t.id,e));return n==null?null:_.createElement(X4e,{legendPayload:n})}var bFe=_.memo(t=>{var{dataKey:e,nameKey:n,sectors:r,stroke:i,strokeWidth:s,fill:o,name:l,hide:c,tooltipType:u}=t,d={dataDefinedOnItem:r.map(h=>h.tooltipPayload),positions:r.map(h=>h.tooltipPosition),settings:{stroke:i,strokeWidth:s,fill:o,dataKey:e,nameKey:n,name:Hh(l,e),hide:c,type:u,color:o,unit:""}};return _.createElement(EM,{tooltipEntrySettings:d})}),xFe=(t,e)=>t>e?"start":tas(typeof e=="function"?e(t):e,n,n*.8),vFe=(t,e,n)=>{var{top:r,left:i,width:s,height:o}=e,l=dQ(s,o),c=i+as(t.cx,s,s/2),u=r+as(t.cy,o,o/2),d=as(t.innerRadius,l,0),h=yFe(n,t.outerRadius,l),p=t.maxRadius||Math.sqrt(s*s+o*o)/2;return{cx:c,cy:u,innerRadius:d,outerRadius:h,maxRadius:p}},wFe=(t,e)=>{var n=wa(e-t),r=Math.min(Math.abs(e-t),360);return n*r};function _Fe(t){return t&&typeof t=="object"&&"className"in t&&typeof t.className=="string"?t.className:""}var SFe=(t,e)=>{if(_.isValidElement(t))return _.cloneElement(t,e);if(typeof t=="function")return t(e);var n=nr("recharts-pie-label-line",typeof t!="boolean"?t.className:""),{key:r}=e,i=AM(e,lFe);return _.createElement(Lg,zh({},i,{type:"linear",className:n}))},NFe=(t,e,n)=>{if(_.isValidElement(t))return _.cloneElement(t,e);var r=n;if(typeof t=="function"&&(r=t(e),_.isValidElement(r)))return r;var i=nr("recharts-pie-label-text",_Fe(t));return _.createElement(SM,zh({},e,{alignmentBaseline:"middle",className:i}),r)};function kFe(t){var{sectors:e,props:n,showLabels:r}=t,{label:i,labelLine:s,dataKey:o}=n;if(!r||!i||!e)return null;var l=Ms(n),c=vm(i),u=vm(s),d=typeof i=="object"&&"offsetRadius"in i&&typeof i.offsetRadius=="number"&&i.offsetRadius||20,h=e.map((p,m)=>{var b=(p.startAngle+p.endAngle)/2,y=Bi(p.cx,p.cy,p.outerRadius+d,b),x=gi(gi(gi(gi({},l),p),{},{stroke:"none"},c),{},{index:m,textAnchor:xFe(y.x,p.cx)},y),v=gi(gi(gi(gi({},l),p),{},{fill:"none",stroke:p.fill},u),{},{index:m,points:[Bi(p.cx,p.cy,p.outerRadius,b),y],key:"line"});return _.createElement(ls,{zIndex:vi.label,key:"label-".concat(p.startAngle,"-").concat(p.endAngle,"-").concat(p.midAngle,"-").concat(m)},_.createElement(li,null,s&&SFe(s,v),NFe(i,x,vr(p,o))))});return _.createElement(li,{className:"recharts-pie-labels"},h)}function MFe(t){var{sectors:e,props:n,showLabels:r}=t,{label:i}=n;return typeof i=="object"&&i!=null&&"position"in i?_.createElement(NM,{label:i}):_.createElement(kFe,{sectors:e,props:n,showLabels:r})}function EFe(t){var{sectors:e,activeShape:n,inactiveShape:r,allOtherPieProps:i,shape:s,id:o}=t,l=Ht(Ih),c=Ht(a4),u=Ht(XRe),{onMouseEnter:d,onClick:h,onMouseLeave:p}=i,m=AM(i,cFe),b=b4(d,i.dataKey,o),y=x4(p),x=y4(h,i.dataKey,o);return e==null||e.length===0?null:_.createElement(_.Fragment,null,e.map((v,S)=>{if(v?.startAngle===0&&v?.endAngle===0&&e.length!==1)return null;var N=u==null||u===o,T=String(S)===l&&(c==null||i.dataKey===c)&&N,M=l?r:null,A=n&&T?n:M,k=gi(gi({},v),{},{stroke:v.stroke,tabIndex:-1,[HY]:S,[$Y]:i.dataKey});return _.createElement(li,zh({key:"sector-".concat(v?.startAngle,"-").concat(v?.endAngle,"-").concat(v.midAngle,"-").concat(S),tabIndex:-1,className:"recharts-pie-sector"},Yy(m,v,S),{onMouseEnter:b(v,S),onMouseLeave:y(v,S),onClick:x(v,S)}),_.createElement(g4,zh({option:s??A,index:S,shapeType:"sector",isActive:T},k)))}))}function TFe(t){var e,{pieSettings:n,displayedData:r,cells:i,offset:s}=t,{cornerRadius:o,startAngle:l,endAngle:c,dataKey:u,nameKey:d,tooltipType:h}=n,p=Math.abs(n.minAngle),m=wFe(l,c),b=Math.abs(m),y=r.length<=1?0:(e=n.paddingAngle)!==null&&e!==void 0?e:0,x=r.filter(A=>vr(A,u,0)!==0).length,v=(b>=360?x:x-1)*y,S=b-x*p-v,N=r.reduce((A,k)=>{var R=vr(k,u,0);return A+(Vt(R)?R:0)},0),T;if(N>0){var M;T=r.map((A,k)=>{var R=vr(A,u,0),C=vr(A,d,k),P=vFe(n,s,A),U=(Vt(R)?R:0)/N,F,H=gi(gi({},A),i&&i[k]&&i[k].props);k?F=M.endAngle+wa(m)*y*(R!==0?1:0):F=l;var D=F+wa(m)*((R!==0?p:0)+U*S),$=(F+D)/2,G=(P.innerRadius+P.outerRadius)/2,I=[{name:C,value:R,payload:H,dataKey:u,type:h}],K=Bi(P.cx,P.cy,G,$);return M=gi(gi(gi(gi({},n.presentationProps),{},{percent:U,cornerRadius:typeof o=="string"?parseFloat(o):o,name:C,tooltipPayload:I,midAngle:$,middleRadius:G,tooltipPosition:K},H),P),{},{value:R,dataKey:u,startAngle:F,endAngle:D,payload:H,paddingAngle:wa(m)*y}),M})}return T}function AFe(t){var{showLabels:e,sectors:n,children:r}=t,i=_.useMemo(()=>!e||!n?[]:n.map(s=>({value:s.value,payload:s.payload,clockWise:!1,parentViewBox:void 0,viewBox:{cx:s.cx,cy:s.cy,innerRadius:s.innerRadius,outerRadius:s.outerRadius,startAngle:s.startAngle,endAngle:s.endAngle,clockWise:!1},fill:s.fill})),[n,e]);return _.createElement(u4e,{value:e?i:void 0},r)}function CFe(t){var{props:e,previousSectorsRef:n,id:r}=t,{sectors:i,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,activeShape:u,inactiveShape:d,onAnimationStart:h,onAnimationEnd:p}=e,m=Pb(e,"recharts-pie-"),b=n.current,[y,x]=_.useState(!1),v=_.useCallback(()=>{typeof p=="function"&&p(),x(!1)},[p]),S=_.useCallback(()=>{typeof h=="function"&&h(),x(!0)},[h]);return _.createElement(AFe,{showLabels:!y,sectors:i},_.createElement(Cb,{animationId:m,begin:o,duration:l,isActive:s,easing:c,onAnimationStart:S,onAnimationEnd:v,key:m},N=>{var T=[],M=i&&i[0],A=M?.startAngle;return i?.forEach((k,R)=>{var C=b&&b[R],P=R>0?wm(k,"paddingAngle",0):0;if(C){var U=pr(C.endAngle-C.startAngle,k.endAngle-k.startAngle,N),F=gi(gi({},k),{},{startAngle:A+P,endAngle:A+U+P});T.push(F),A=F.endAngle}else{var{endAngle:H,startAngle:D}=k,$=pr(0,H-D,N),G=gi(gi({},k),{},{startAngle:A+P,endAngle:A+$+P});T.push(G),A=G.endAngle}}),n.current=T,_.createElement(li,null,_.createElement(EFe,{sectors:T,activeShape:u,inactiveShape:d,allOtherPieProps:e,shape:e.shape,id:r}))}),_.createElement(MFe,{showLabels:!y,sectors:i,props:e}),e.children)}var PFe={animationBegin:400,animationDuration:1500,animationEasing:"ease",cx:"50%",cy:"50%",dataKey:"value",endAngle:360,fill:"#808080",hide:!1,innerRadius:0,isAnimationActive:"auto",label:!1,labelLine:!0,legendType:"rect",minAngle:0,nameKey:"name",outerRadius:"80%",paddingAngle:0,rootTabIndex:0,startAngle:0,stroke:"#fff",zIndex:vi.area};function jFe(t){var{id:e}=t,n=AM(t,uFe),{hide:r,className:i,rootTabIndex:s}=t,o=_.useMemo(()=>m4(t.children,yv),[t.children]),l=Ht(d=>E4e(d,e,o)),c=_.useRef(null),u=nr("recharts-pie",i);return r||l==null?(c.current=null,_.createElement(li,{tabIndex:s,className:u})):_.createElement(ls,{zIndex:t.zIndex},_.createElement(bFe,{dataKey:t.dataKey,nameKey:t.nameKey,sectors:l,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,tooltipType:t.tooltipType}),_.createElement(li,{tabIndex:s,className:u},_.createElement(CFe,{props:gi(gi({},n),{},{sectors:l}),previousSectorsRef:c,id:e})))}function BJ(t){var e=ci(t,PFe),{id:n}=e,r=AM(e,dFe),i=Ms(r);return _.createElement(TM,{id:n,type:"pie"},s=>_.createElement(_.Fragment,null,_.createElement(oFe,{type:"pie",id:s,data:r.data,dataKey:r.dataKey,hide:r.hide,angleAxisId:0,radiusAxisId:0,name:r.name,nameKey:r.nameKey,tooltipType:r.tooltipType,legendType:r.legendType,fill:r.fill,cx:r.cx,cy:r.cy,startAngle:r.startAngle,endAngle:r.endAngle,paddingAngle:r.paddingAngle,minAngle:r.minAngle,innerRadius:r.innerRadius,outerRadius:r.outerRadius,cornerRadius:r.cornerRadius,presentationProps:i,maxRadius:e.maxRadius}),_.createElement(gFe,zh({},r,{id:s})),_.createElement(jFe,zh({},r,{id:s}))))}BJ.displayName="Pie";var DFe=["points"];function eq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function lP(t){for(var e=1;e{var x,v,S=lP(lP(lP({r:3},o),h),{},{index:y,cx:(x=b.x)!==null&&x!==void 0?x:void 0,cy:(v=b.y)!==null&&v!==void 0?v:void 0,dataKey:s,value:b.value,payload:b.payload,points:e});return _.createElement(zFe,{key:"dot-".concat(y),option:n,dotProps:S,className:i})}),m={};return l&&c!=null&&(m.clipPath="url(#clipPath-".concat(d?"":"dots-").concat(c,")")),_.createElement(ls,{zIndex:u},_.createElement(li,nN({className:r},m),p))}function tq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function nq(t){for(var e=1;e({top:t.top,bottom:t.bottom,left:t.left,right:t.right})),eIe=st([JFe,ed,td],(t,e,n)=>{if(!(!t||e==null||n==null))return{x:t.left,y:t.top,width:Math.max(0,e-t.left-t.right),height:Math.max(0,n-t.top-t.bottom)}}),CM=()=>Ht(eIe),tIe=()=>Ht(eOe);function rq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function cP(t){for(var e=1;e{var{point:e,childIndex:n,mainColor:r,activeDot:i,dataKey:s,clipPath:o}=t;if(i===!1||e.x==null||e.y==null)return null;var l={index:n,dataKey:s,cx:e.x,cy:e.y,r:4,fill:r??"none",strokeWidth:2,stroke:"#fff",payload:e.payload,value:e.value},c=cP(cP(cP({},l),vm(i)),FO(i)),u;return _.isValidElement(i)?u=_.cloneElement(i,c):typeof i=="function"?u=i(c):u=_.createElement(DJ,c),_.createElement(li,{className:"recharts-active-dot",clipPath:o},u)};function jD(t){var{points:e,mainColor:n,activeDot:r,itemDataKey:i,clipPath:s,zIndex:o=vi.activeDot}=t,l=Ht(Ih),c=tIe();if(e==null||c==null)return null;var u=e.find(d=>c.includes(d.payload));return Yr(u)?null:_.createElement(ls,{zIndex:o},_.createElement(aIe,{point:u,childIndex:Number(l),mainColor:n,dataKey:i,activeDot:r,clipPath:s}))}var sIe="Invariant failed";function oIe(t,e){throw new Error(sIe)}var lIe=["x","y"];function DD(){return DD=Object.assign?Object.assign.bind():function(t){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:0;return(r,i)=>{if(Vt(e))return e;var s=Vt(r)||Yr(r);return s?e(r,i):(s||oIe(),n)}},gIe={},VJ=Qs({name:"errorBars",initialState:gIe,reducers:{addErrorBar:(t,e)=>{var{itemId:n,errorBar:r}=e.payload;t[n]||(t[n]=[]),t[n].push(r)},replaceErrorBar:(t,e)=>{var{itemId:n,prev:r,next:i}=e.payload;t[n]&&(t[n]=t[n].map(s=>s.dataKey===r.dataKey&&s.direction===r.direction?i:s))},removeErrorBar:(t,e)=>{var{itemId:n,errorBar:r}=e.payload;t[n]&&(t[n]=t[n].filter(i=>i.dataKey!==r.dataKey||i.direction!==r.direction))}}}),{addErrorBar:_Qe,replaceErrorBar:SQe,removeErrorBar:NQe}=VJ.actions,bIe=VJ.reducer,xIe=["children"];function yIe(t,e){if(t==null)return{};var n,r,i=vIe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r({x:0,y:0,value:0}),errorBarOffset:0},_Ie=_.createContext(wIe);function GJ(t){var{children:e}=t,n=yIe(t,xIe);return _.createElement(_Ie.Provider,{value:n},e)}function PM(t,e){var n,r,i=Ht(u=>Ac(u,t)),s=Ht(u=>Cc(u,e)),o=(n=i?.allowDataOverflow)!==null&&n!==void 0?n:ga.allowDataOverflow,l=(r=s?.allowDataOverflow)!==null&&r!==void 0?r:ba.allowDataOverflow,c=o||l;return{needClip:c,needClipX:o,needClipY:l}}function _4(t){var{xAxisId:e,yAxisId:n,clipPathId:r}=t,i=CM(),{needClipX:s,needClipY:o,needClip:l}=PM(e,n);if(!l||!i)return null;var{x:c,y:u,width:d,height:h}=i;return _.createElement("clipPath",{id:"clipPath-".concat(r)},_.createElement("rect",{x:s?c:c-d/2,y:o?u:u-h/2,width:s?d:d*2,height:o?h:h*2}))}function SIe(t,e){return t&&typeof t=="object"&&"zIndex"in t&&typeof t.zIndex=="number"&&wr(t.zIndex)?t.zIndex:e}var uP={exports:{}},dP={};var aq;function NIe(){if(aq)return dP;aq=1;var t=yb();function e(c,u){return c===u&&(c!==0||1/c===1/u)||c!==c&&u!==u}var n=typeof Object.is=="function"?Object.is:e,r=t.useSyncExternalStore,i=t.useRef,s=t.useEffect,o=t.useMemo,l=t.useDebugValue;return dP.useSyncExternalStoreWithSelector=function(c,u,d,h,p){var m=i(null);if(m.current===null){var b={hasValue:!1,value:null};m.current=b}else b=m.current;m=o(function(){function x(M){if(!v){if(v=!0,S=M,M=h(M),p!==void 0&&b.hasValue){var A=b.value;if(p(A,M))return N=A}return N=M}if(A=N,n(S,M))return A;var k=h(M);return p!==void 0&&p(A,k)?(S=M,A):(S=M,N=k)}var v=!1,S,N,T=d===void 0?null:d;return[function(){return x(u())},T===null?void 0:function(){return x(T())}]},[u,d,h,p]);var y=r(c,m[0],m[1]);return s(function(){b.hasValue=!0,b.value=y},[y]),l(y),y},dP}var sq;function kIe(){return sq||(sq=1,uP.exports=NIe()),uP.exports}kIe();function MIe(t){t()}function EIe(){let t=null,e=null;return{clear(){t=null,e=null},notify(){MIe(()=>{let n=t;for(;n;)n.callback(),n=n.next})},get(){const n=[];let r=t;for(;r;)n.push(r),r=r.next;return n},subscribe(n){let r=!0;const i=e={callback:n,next:null,prev:e};return i.prev?i.prev.next=i:t=i,function(){!r||t===null||(r=!1,i.next?i.next.prev=i.prev:e=i.prev,i.prev?i.prev.next=i.next:t=i.next)}}}}var oq={notify(){},get:()=>[]};function TIe(t,e){let n,r=oq,i=0,s=!1;function o(y){d();const x=r.subscribe(y);let v=!1;return()=>{v||(v=!0,x(),h())}}function l(){r.notify()}function c(){b.onStateChange&&b.onStateChange()}function u(){return s}function d(){i++,n||(n=t.subscribe(c),r=EIe())}function h(){i--,n&&i===0&&(n(),n=void 0,r.clear(),r=oq)}function p(){s||(s=!0,d())}function m(){s&&(s=!1,h())}const b={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:u,trySubscribe:p,tryUnsubscribe:m,getListeners:()=>r};return b}var AIe=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",CIe=AIe(),PIe=()=>typeof navigator<"u"&&navigator.product==="ReactNative",jIe=PIe(),DIe=()=>CIe||jIe?_.useLayoutEffect:_.useEffect,RIe=DIe();function lq(t,e){return t===e?t!==0||e!==0||1/t===1/e:t!==t&&e!==e}function OIe(t,e){if(lq(t,e))return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(let i=0;i{const c=TIe(i);return{store:i,subscription:c,getServerState:r?()=>r:void 0}},[i,r]),o=_.useMemo(()=>i.getState(),[i]);RIe(()=>{const{subscription:c}=s;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),o!==i.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[s,o]);const l=n||zIe;return _.createElement(l.Provider,{value:s},e)}var BIe=UIe,HIe=new Set(["axisLine","tickLine","activeBar","activeDot","activeLabel","activeShape","allowEscapeViewBox","background","cursor","dot","label","line","margin","padding","position","shape","style","tick","wrapperStyle"]);function $Ie(t,e){return t==null&&e==null?!0:typeof t=="number"&&typeof e=="number"?t===e||t!==t&&e!==e:t===e}function vv(t,e){var n=new Set([...Object.keys(t),...Object.keys(e)]);for(var r of n)if(HIe.has(r)){if(t[r]==null&&e[r]==null)continue;if(!OIe(t[r],e[r]))return!1}else if(!$Ie(t[r],e[r]))return!1;return!0}var VIe=["onMouseEnter","onMouseLeave","onClick"],GIe=["value","background","tooltipPosition"],qIe=["id"],WIe=["onMouseEnter","onClick","onMouseLeave"];function Zu(){return Zu=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{dataKey:e,name:n,fill:r,legendType:i,hide:s}=t;return[{inactive:s,dataKey:e,type:i,color:r,value:Hh(n,e),payload:t}]},JIe=_.memo(t=>{var{dataKey:e,stroke:n,strokeWidth:r,fill:i,name:s,hide:o,unit:l,tooltipType:c}=t,u={dataDefinedOnItem:void 0,positions:void 0,settings:{stroke:n,strokeWidth:r,fill:i,dataKey:e,nameKey:void 0,name:Hh(s,e),hide:o,type:c,color:i,unit:l}};return _.createElement(EM,{tooltipEntrySettings:u})});function e5e(t){var e=Ht(Ih),{data:n,dataKey:r,background:i,allOtherBarProps:s}=t,{onMouseEnter:o,onMouseLeave:l,onClick:c}=s,u=iN(s,VIe),d=b4(o,r),h=x4(l),p=y4(c,r);if(!i||n==null)return null;var m=vm(i);return _.createElement(ls,{zIndex:SIe(i,vi.barBackground)},n.map((b,y)=>{var{value:x,background:v,tooltipPosition:S}=b,N=iN(b,GIe);if(!v)return null;var T=d(b,y),M=h(b,y),A=p(b,y),k=xs(xs(xs(xs(xs({option:i,isActive:String(y)===e},N),{},{fill:"#eee"},v),m),Yy(u,b,y)),{},{onMouseEnter:T,onMouseLeave:M,onClick:A,dataKey:r,index:y,className:"recharts-bar-background-rectangle"});return _.createElement(rN,Zu({key:"background-bar-".concat(y)},k))}))}function t5e(t){var{showLabels:e,children:n,rects:r}=t,i=r?.map(s=>{var o={x:s.x,y:s.y,width:s.width,lowerWidth:s.width,upperWidth:s.width,height:s.height};return xs(xs({},o),{},{value:s.value,payload:s.payload,parentViewBox:s.parentViewBox,viewBox:o,fill:s.fill})});return _.createElement(d4,{value:e?i:void 0},n)}function n5e(t){var{shape:e,activeBar:n,baseProps:r,entry:i,index:s,dataKey:o}=t,l=Ht(Ih),c=Ht(a4),u=n&&String(s)===l&&(c==null||o===c),d=u?n:e;return u?_.createElement(ls,{zIndex:vi.activeBar},_.createElement(rN,Zu({},r,{name:String(r.name)},i,{isActive:u,option:d,index:s,dataKey:o}))):_.createElement(rN,Zu({},r,{name:String(r.name)},i,{isActive:u,option:d,index:s,dataKey:o}))}function r5e(t){var{shape:e,baseProps:n,entry:r,index:i,dataKey:s}=t;return _.createElement(rN,Zu({},n,{name:String(n.name)},r,{isActive:!1,option:e,index:i,dataKey:s}))}function i5e(t){var e,{data:n,props:r}=t,i=(e=Ms(r))!==null&&e!==void 0?e:{},{id:s}=i,o=iN(i,qIe),{shape:l,dataKey:c,activeBar:u}=r,{onMouseEnter:d,onClick:h,onMouseLeave:p}=r,m=iN(r,WIe),b=b4(d,c),y=x4(p),x=y4(h,c);return n?_.createElement(_.Fragment,null,n.map((v,S)=>_.createElement(li,Zu({key:"rectangle-".concat(v?.x,"-").concat(v?.y,"-").concat(v?.value,"-").concat(S),className:"recharts-bar-rectangle"},Yy(m,v,S),{onMouseEnter:b(v,S),onMouseLeave:y(v,S),onClick:x(v,S)}),u?_.createElement(n5e,{shape:l,activeBar:u,baseProps:o,entry:v,index:S,dataKey:c}):_.createElement(r5e,{shape:l,baseProps:o,entry:v,index:S,dataKey:c})))):null}function a5e(t){var{props:e,previousRectanglesRef:n}=t,{data:r,layout:i,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,onAnimationEnd:u,onAnimationStart:d}=e,h=n.current,p=Pb(e,"recharts-bar-"),[m,b]=_.useState(!1),y=!m,x=_.useCallback(()=>{typeof u=="function"&&u(),b(!1)},[u]),v=_.useCallback(()=>{typeof d=="function"&&d(),b(!0)},[d]);return _.createElement(t5e,{showLabels:y,rects:r},_.createElement(Cb,{animationId:p,begin:o,duration:l,isActive:s,easing:c,onAnimationEnd:x,onAnimationStart:v,key:p},S=>{var N=S===1?r:r?.map((T,M)=>{var A=h&&h[M];if(A)return xs(xs({},T),{},{x:pr(A.x,T.x,S),y:pr(A.y,T.y,S),width:pr(A.width,T.width,S),height:pr(A.height,T.height,S)});if(i==="horizontal"){var k=pr(0,T.height,S),R=pr(T.stackedBarStart,T.y,S);return xs(xs({},T),{},{y:R,height:k})}var C=pr(0,T.width,S),P=pr(T.stackedBarStart,T.x,S);return xs(xs({},T),{},{width:C,x:P})});return S>0&&(n.current=N??null),N==null?null:_.createElement(li,null,_.createElement(i5e,{props:e,data:N}))}),_.createElement(NM,{label:e.label}),e.children)}function s5e(t){var e=_.useRef(null);return _.createElement(a5e,{previousRectanglesRef:e,props:t})}var qJ=0,o5e=(t,e)=>{var n=Array.isArray(t.value)?t.value[1]:t.value;return{x:t.x,y:t.y,value:n,errorVal:vr(t,e)}};class l5e extends _.PureComponent{render(){var{hide:e,data:n,dataKey:r,className:i,xAxisId:s,yAxisId:o,needClip:l,background:c,id:u}=this.props;if(e||n==null)return null;var d=nr("recharts-bar",i),h=u;return _.createElement(li,{className:d,id:u},l&&_.createElement("defs",null,_.createElement(_4,{clipPathId:h,xAxisId:s,yAxisId:o})),_.createElement(li,{className:"recharts-bar-rectangles",clipPath:l?"url(#clipPath-".concat(h,")"):void 0},_.createElement(e5e,{data:n,dataKey:r,background:c,allOtherBarProps:this.props}),_.createElement(s5e,this.props)))}}var c5e={activeBar:!1,animationBegin:0,animationDuration:400,animationEasing:"ease",background:!1,hide:!1,isAnimationActive:"auto",label:!1,legendType:"rect",minPointSize:qJ,xAxisId:0,yAxisId:0,zIndex:vi.bar};function u5e(t){var{xAxisId:e,yAxisId:n,hide:r,legendType:i,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:u,isAnimationActive:d}=t,{needClip:h}=PM(e,n),p=Lm(),m=aa(),b=m4(t.children,yv),y=Ht(S=>I5e(S,e,n,m,t.id,b));if(p!=="vertical"&&p!=="horizontal")return null;var x,v=y?.[0];return v==null||v.height==null||v.width==null?x=0:x=p==="vertical"?v.height/2:v.width/2,_.createElement(GJ,{xAxisId:e,yAxisId:n,data:y,dataPointFormatter:o5e,errorBarOffset:x},_.createElement(l5e,Zu({},t,{layout:p,needClip:h,data:y,xAxisId:e,yAxisId:n,hide:r,legendType:i,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:u,isAnimationActive:d})))}function d5e(t){var{layout:e,barSettings:{dataKey:n,minPointSize:r},pos:i,bandSize:s,xAxis:o,yAxis:l,xAxisTicks:c,yAxisTicks:u,stackedData:d,displayedData:h,offset:p,cells:m,parentViewBox:b,dataStartIndex:y}=t,x=e==="horizontal"?l:o,v=d?x.scale.domain():null,S=RTe({numericAxis:x}),N=x.scale(S);return h.map((T,M)=>{var A,k,R,C,P,U;d?A=ATe(d[M+y],v):(A=vr(T,n),Array.isArray(A)||(A=[S,A]));var F=pIe(r,qJ)(A[1],M);if(e==="horizontal"){var H,[D,$]=[l.scale(A[0]),l.scale(A[1])];k=M$({axis:o,ticks:c,bandSize:s,offset:i.offset,entry:T,index:M}),R=(H=$??D)!==null&&H!==void 0?H:void 0,C=i.size;var G=D-$;if(P=Ys(G)?0:G,U={x:k,y:p.top,width:C,height:p.height},Math.abs(F)>0&&Math.abs(P)0&&Math.abs(C)_.createElement(_.Fragment,null,_.createElement(v4,{legendPayload:ZIe(e)}),_.createElement(JIe,{dataKey:e.dataKey,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType}),_.createElement(w4,{type:"bar",id:r,data:void 0,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,stackId:UY(e.stackId),hide:e.hide,barSize:e.barSize,minPointSize:e.minPointSize,maxBarSize:e.maxBarSize,isPanorama:n}),_.createElement(ls,{zIndex:e.zIndex},_.createElement(u5e,Zu({},e,{id:r})))))}var WJ=_.memo(h5e,vv);WJ.displayName="Bar";function uq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function n1(t){for(var e=1;ee,b5e=(t,e,n)=>n,x5e=(t,e,n,r)=>r,y5e=(t,e,n,r,i)=>i,wv=st([dv,y5e],(t,e)=>t.filter(n=>n.type==="bar").find(n=>n.id===e)),v5e=st([wv],t=>t?.maxBarSize),w5e=(t,e,n,r,i,s)=>s,dq=(t,e,n)=>{var r=n??t;if(!Yr(r))return as(r,e,0)},_5e=st([Kn,dv,g5e,b5e,x5e],(t,e,n,r,i)=>e.filter(s=>t==="horizontal"?s.xAxisId===n:s.yAxisId===r).filter(s=>s.isPanorama===i).filter(s=>s.hide===!1).filter(s=>s.type==="bar")),S5e=(t,e,n,r)=>{var i=Kn(t);return i==="horizontal"?Sy(t,"yAxis",n,r):Sy(t,"xAxis",e,r)},N5e=(t,e,n)=>{var r=Kn(t);return r==="horizontal"?aG(t,"xAxis",e):aG(t,"yAxis",n)},k5e=(t,e,n)=>{var r={},i=t.filter(pM),s=t.filter(u=>u.stackId==null),o=i.reduce((u,d)=>(u[d.stackId]||(u[d.stackId]=[]),u[d.stackId].push(d),u),r),l=Object.entries(o).map(u=>{var[d,h]=u,p=h.map(b=>b.dataKey),m=dq(e,n,h[0].barSize);return{stackId:d,dataKeys:p,barSize:m}}),c=s.map(u=>{var d=[u.dataKey].filter(p=>p!=null),h=dq(e,n,u.barSize);return{stackId:void 0,dataKeys:d,barSize:h}});return[...l,...c]},M5e=st([_5e,Q3e,N5e],k5e),E5e=(t,e,n,r,i)=>{var s,o,l=wv(t,e,n,r,i);if(l!=null){var c=Kn(t),u=uZ(t),{maxBarSize:d}=l,h=Yr(d)?u:d,p,m;return c==="horizontal"?(p=_c(t,"xAxis",e,r),m=wc(t,"xAxis",e,r)):(p=_c(t,"yAxis",n,r),m=wc(t,"yAxis",n,r)),(s=(o=Oh(p,m,!0))!==null&&o!==void 0?o:h)!==null&&s!==void 0?s:0}},KJ=(t,e,n,r)=>{var i=Kn(t),s,o;return i==="horizontal"?(s=_c(t,"xAxis",e,r),o=wc(t,"xAxis",e,r)):(s=_c(t,"yAxis",n,r),o=wc(t,"yAxis",n,r)),Oh(s,o)};function T5e(t,e,n,r,i){var s=r.length;if(!(s<1)){var o=as(t,n,0,!0),l,c=[];if(wr(r[0].barSize)){var u=!1,d=n/s,h=r.reduce((v,S)=>v+(S.barSize||0),0);h+=(s-1)*o,h>=n&&(h-=(s-1)*o,o=0),h>=n&&d>0&&(u=!0,d*=.9,h=s*d);var p=(n-h)/2>>0,m={offset:p-o,size:0};l=r.reduce((v,S)=>{var N,T={stackId:S.stackId,dataKeys:S.dataKeys,position:{offset:m.offset+m.size+o,size:u?d:(N=S.barSize)!==null&&N!==void 0?N:0}},M=[...v,T];return m=M[M.length-1].position,M},c)}else{var b=as(e,n,0,!0);n-2*b-(s-1)*o<=0&&(o=0);var y=(n-2*b-(s-1)*o)/s;y>1&&(y>>=0);var x=wr(i)?Math.min(y,i):y;l=r.reduce((v,S,N)=>[...v,{stackId:S.stackId,dataKeys:S.dataKeys,position:{offset:b+(y+o)*N+(y-x)/2,size:x}}],c)}return l}}var A5e=(t,e,n,r,i,s,o)=>{var l=Yr(o)?e:o,c=T5e(n,r,i!==s?i:s,t,l);return i!==s&&c!=null&&(c=c.map(u=>n1(n1({},u),{},{position:n1(n1({},u.position),{},{offset:u.position.offset-i/2})}))),c},C5e=st([M5e,uZ,Y3e,dZ,E5e,KJ,v5e],A5e),P5e=(t,e,n,r)=>_c(t,"xAxis",e,r),j5e=(t,e,n,r)=>_c(t,"yAxis",n,r),D5e=(t,e,n,r)=>wc(t,"xAxis",e,r),R5e=(t,e,n,r)=>wc(t,"yAxis",n,r),O5e=st([C5e,wv],(t,e)=>{if(!(t==null||e==null)){var n=t.find(r=>r.stackId===e.stackId&&e.dataKey!=null&&r.dataKeys.includes(e.dataKey));if(n!=null)return n.position}}),L5e=(t,e)=>{var n=mM(e);if(!(!t||n==null||e==null)){var{stackId:r}=e;if(r!=null){var i=t[r];if(i){var{stackedData:s}=i;if(s)return s.find(o=>o.key===n)}}}},F5e=st([S5e,wv],L5e),I5e=st([ia,KO,P5e,j5e,D5e,R5e,O5e,Kn,ov,KJ,F5e,wv,w5e],(t,e,n,r,i,s,o,l,c,u,d,h,p)=>{var{chartData:m,dataStartIndex:b,dataEndIndex:y}=c;if(!(h==null||o==null||e==null||l!=="horizontal"&&l!=="vertical"||n==null||r==null||i==null||s==null||u==null)){var{data:x}=h,v;if(x!=null&&x.length>0?v=x:v=m?.slice(b,y+1),v!=null)return d5e({layout:l,barSettings:h,pos:o,parentViewBox:e,bandSize:u,xAxis:n,yAxis:r,xAxisTicks:i,yAxisTicks:s,stackedData:d,displayedData:v,offset:t,cells:p,dataStartIndex:b})}}),XJ=t=>{var{chartData:e}=t,n=zr(),r=aa();return _.useEffect(()=>r?()=>{}:(n(xG(e)),()=>{n(xG(void 0))}),[e,n,r]),null},hq={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},YJ=Qs({name:"brush",initialState:hq,reducers:{setBrushSettings(t,e){return e.payload==null?hq:e.payload}}}),{setBrushSettings:kQe}=YJ.actions,z5e=YJ.reducer;function fq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function r1(t){for(var e=1;e{var{x:n,y:r}=t,{x:i,y:s}=e;return{x:Math.min(n,i),y:Math.min(r,s),width:Math.abs(i-n),height:Math.abs(s-r)}},$5e=t=>{var{x1:e,y1:n,x2:r,y2:i}=t;return H5e({x:e,y:n},{x:r,y:i})};class jM{static create(e){return new jM(e)}constructor(e){this.scale=e}get domain(){return this.scale.domain}get range(){return this.scale.range}get rangeMin(){return this.range()[0]}get rangeMax(){return this.range()[1]}get bandwidth(){return this.scale.bandwidth}apply(e){var{bandAware:n,position:r}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(e!==void 0){if(r)switch(r){case"start":return this.scale(e);case"middle":{var i=this.bandwidth?this.bandwidth()/2:0;return this.scale(e)+i}case"end":{var s=this.bandwidth?this.bandwidth():0;return this.scale(e)+s}default:return this.scale(e)}if(n){var o=this.bandwidth?this.bandwidth()/2:0;return this.scale(e)+o}return this.scale(e)}}isInRange(e){var n=this.range(),r=n[0],i=n[n.length-1];return r<=i?e>=r&&e<=i:e>=i&&e<=r}}QJ(jM,"EPS",1e-4);var V5e=t=>{var e=Object.keys(t).reduce((n,r)=>r1(r1({},n),{},{[r]:jM.create(t[r])}),{});return r1(r1({},e),{},{apply(n){var{bandAware:r,position:i}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Object.fromEntries(Object.entries(n).map(s=>{var[o,l]=s;return[o,e[o].apply(l,{bandAware:r,position:i})]}))},isInRange(n){return Object.keys(n).every(r=>e[r].isInRange(n[r]))}})};function G5e(t){return(t%180+180)%180}var q5e=function(e){var{width:n,height:r}=e,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,s=G5e(i),o=s*Math.PI/180,l=Math.atan(r/n),c=o>l&&o{t.dots.push(e.payload)},removeDot:(t,e)=>{var n=Il(t).dots.findIndex(r=>r===e.payload);n!==-1&&t.dots.splice(n,1)},addArea:(t,e)=>{t.areas.push(e.payload)},removeArea:(t,e)=>{var n=Il(t).areas.findIndex(r=>r===e.payload);n!==-1&&t.areas.splice(n,1)},addLine:(t,e)=>{t.lines.push(e.payload)},removeLine:(t,e)=>{var n=Il(t).lines.findIndex(r=>r===e.payload);n!==-1&&t.lines.splice(n,1)}}}),{addDot:MQe,removeDot:EQe,addArea:TQe,removeArea:AQe,addLine:K5e,removeLine:X5e}=ZJ.actions,Y5e=ZJ.reducer,JJ=_.createContext(void 0),Q5e=t=>{var{children:e}=t,[n]=_.useState("".concat(uy("recharts"),"-clip")),r=CM();if(r==null)return null;var{x:i,y:s,width:o,height:l}=r;return _.createElement(JJ.Provider,{value:n},_.createElement("defs",null,_.createElement("clipPath",{id:n},_.createElement("rect",{x:i,y:s,height:l,width:o}))),e)},Z5e=()=>_.useContext(JJ);function mq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function pq(t){for(var e=1;e{var n;if(_.isValidElement(t))n=_.cloneElement(t,e);else if(typeof t=="function")n=t(e);else{if(!wr(e.x1)||!wr(e.y1)||!wr(e.x2)||!wr(e.y2))return null;n=_.createElement("line",aN({},e,{className:"recharts-reference-line-line"}))}return n},rze=(t,e,n,r,i,s)=>{var{x:o,width:l}=s,c=i.y.apply(t,{position:n});if(Ys(c)||e==="discard"&&!i.y.isInRange(c))return null;var u=[{x:o+l,y:c},{x:o,y:c}];return r==="left"?u.reverse():u},ize=(t,e,n,r,i,s)=>{var{y:o,height:l}=s,c=i.x.apply(t,{position:n});if(Ys(c)||e==="discard"&&!i.x.isInRange(c))return null;var u=[{x:c,y:o+l},{x:c,y:o}];return r==="top"?u.reverse():u},aze=(t,e,n,r)=>{var i=t.map(s=>r.apply(s,{position:n}));return e==="discard"&&i.some(s=>!r.isInRange(s))?null:i},sze=(t,e,n,r,i,s)=>{var{x:o,y:l,segment:c,ifOverflow:u}=s,d=fl(o),h=fl(l);return h?rze(l,u,n,i,t,e):d?ize(o,u,n,r,t,e):c!=null&&c.length===2?aze(c,u,n,t):null};function oze(t){var e=zr();return _.useEffect(()=>(e(K5e(t)),()=>{e(X5e(t))})),null}function lze(t){var{xAxisId:e,yAxisId:n,shape:r,className:i,ifOverflow:s}=t,o=aa(),l=Z5e(),c=Ht(A=>Ac(A,e)),u=Ht(A=>Cc(A,n)),d=Ht(A=>Fh(A,"xAxis",e,o)),h=Ht(A=>Fh(A,"yAxis",n,o)),p=tv();if(!l||!p||c==null||u==null||d==null||h==null)return null;var m=V5e({x:d,y:h}),b=sze(m,p,t.position,c.orientation,u.orientation,t);if(!b)return null;var[{x:y,y:x},{x:v,y:S}]=b,N=s==="hidden"?"url(#".concat(l,")"):void 0,T=pq(pq({clipPath:N},Ga(t)),{},{x1:y,y1:x,x2:v,y2:S}),M=$5e({x1:y,y1:x,x2:v,y2:S});return _.createElement(ls,{zIndex:t.zIndex},_.createElement(li,{className:nr("recharts-reference-line",i)},nze(r,T),_.createElement(TJ,aN({},M,{lowerWidth:M.width,upperWidth:M.width}),_.createElement(CJ,{label:t.label}),t.children)))}var cze={ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle",zIndex:vi.line};function m0(t){var e=ci(t,cze);return _.createElement(_.Fragment,null,_.createElement(oze,{yAxisId:e.yAxisId,xAxisId:e.xAxisId,ifOverflow:e.ifOverflow,x:e.x,y:e.y,segment:e.segment}),_.createElement(lze,e))}m0.displayName="ReferenceLine";function eee(t,e){if(e<1)return[];if(e===1)return t;for(var n=[],r=0;rt*i)return!1;var s=n();return t*(e-t*s/2-r)>=0&&t*(e+t*s/2-i)<=0}function hze(t,e){return eee(t,e+1)}function fze(t,e,n,r,i){for(var s=(r||[]).slice(),{start:o,end:l}=e,c=0,u=1,d=o,h=function(){var b=r?.[c];if(b===void 0)return{v:eee(r,u)};var y=c,x,v=()=>(x===void 0&&(x=n(b,y)),x),S=b.coordinate,N=c===0||sN(t,S,v,d,l);N||(c=0,d=o,u+=1),N&&(d=S+t*(v()/2+i),c+=u)},p;u<=s.length;)if(p=h(),p)return p.v;return[]}function gq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Za(t){for(var e=1;e(b===void 0&&(b=n(m,p)),b);if(p===o-1){var x=t*(m.coordinate+t*y()/2-c);s[p]=m=Za(Za({},m),{},{tickCoord:x>0?m.coordinate-x*t:m.coordinate})}else s[p]=m=Za(Za({},m),{},{tickCoord:m.coordinate});if(m.tickCoord!=null){var v=sN(t,m.tickCoord,y,l,c);v&&(c=m.tickCoord-t*(y()/2+i),s[p]=Za(Za({},m),{},{isShow:!0}))}},d=o-1;d>=0;d--)u(d);return s}function xze(t,e,n,r,i,s){var o=(r||[]).slice(),l=o.length,{start:c,end:u}=e;if(s){var d=r[l-1],h=n(d,l-1),p=t*(d.coordinate+t*h/2-u);if(o[l-1]=d=Za(Za({},d),{},{tickCoord:p>0?d.coordinate-p*t:d.coordinate}),d.tickCoord!=null){var m=sN(t,d.tickCoord,()=>h,c,u);m&&(u=d.tickCoord-t*(h/2+i),o[l-1]=Za(Za({},d),{},{isShow:!0}))}}for(var b=s?l-1:l,y=function(S){var N=o[S],T,M=()=>(T===void 0&&(T=n(N,S)),T);if(S===0){var A=t*(N.coordinate-t*M()/2-c);o[S]=N=Za(Za({},N),{},{tickCoord:A<0?N.coordinate-A*t:N.coordinate})}else o[S]=N=Za(Za({},N),{},{tickCoord:N.coordinate});if(N.tickCoord!=null){var k=sN(t,N.tickCoord,M,c,u);k&&(c=N.tickCoord+t*(M()/2+i),o[S]=Za(Za({},N),{},{isShow:!0}))}},x=0;x{var M=typeof u=="function"?u(N.value,T):N.value;return b==="width"?uze(A0(M,{fontSize:e,letterSpacing:n}),y,h):A0(M,{fontSize:e,letterSpacing:n})[b]},v=i.length>=2?wa(i[1].coordinate-i[0].coordinate):1,S=dze(s,v,b);return c==="equidistantPreserveStart"?fze(v,S,x,i,o):(c==="preserveStart"||c==="preserveStartEnd"?m=xze(v,S,x,i,o,c==="preserveStartEnd"):m=bze(v,S,x,i,o),m.filter(N=>N.isShow))}var yze=t=>{var{ticks:e,label:n,labelGapWithTick:r=5,tickSize:i=0,tickMargin:s=0}=t,o=0;if(e){Array.from(e).forEach(d=>{if(d){var h=d.getBoundingClientRect();h.width>o&&(o=h.width)}});var l=n?n.getBoundingClientRect().width:0,c=i+s,u=o+c+l+(n?r:0);return Math.round(u)}return 0},vze=["axisLine","width","height","className","hide","ticks","axisType"];function wze(t,e){if(t==null)return{};var n,r,i=_ze(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var{ticks:n=[],tick:r,tickLine:i,stroke:s,tickFormatter:o,unit:l,padding:c,tickTextProps:u,orientation:d,mirror:h,x:p,y:m,width:b,height:y,tickSize:x,tickMargin:v,fontSize:S,letterSpacing:N,getTicksConfig:T,events:M,axisType:A}=t,k=S4(Fi(Fi({},T),{},{ticks:n}),S,N),R=Tze(d,h),C=Aze(d,h),P=Ms(T),U=vm(r),F={};typeof i=="object"&&(F=i);var H=Fi(Fi({},P),{},{fill:"none"},F),D=k.map(I=>Fi({entry:I},Eze(I,p,m,b,y,d,x,h,v))),$=D.map(I=>{var{entry:K,line:Q}=I;return _.createElement(li,{className:"recharts-cartesian-axis-tick",key:"tick-".concat(K.value,"-").concat(K.coordinate,"-").concat(K.tickCoord)},i&&_.createElement("line",km({},H,Q,{className:nr("recharts-cartesian-axis-tick-line",wm(i,"className"))})))}),G=D.map((I,K)=>{var{entry:Q,tick:oe}=I,B=Fi(Fi(Fi(Fi({textAnchor:R,verticalAnchor:C},P),{},{stroke:"none",fill:s},U),oe),{},{index:K,payload:Q,visibleTicksCount:k.length,tickFormatter:o,padding:c},u);return _.createElement(li,km({className:"recharts-cartesian-axis-tick-label",key:"tick-label-".concat(Q.value,"-").concat(Q.coordinate,"-").concat(Q.tickCoord)},Yy(M,Q,K)),r&&_.createElement(Cze,{option:r,tickProps:B,value:"".concat(typeof o=="function"?o(Q.value,K):Q.value).concat(l||"")}))});return _.createElement("g",{className:"recharts-cartesian-axis-ticks recharts-".concat(A,"-ticks")},G.length>0&&_.createElement(ls,{zIndex:vi.label},_.createElement("g",{className:"recharts-cartesian-axis-tick-labels recharts-".concat(A,"-tick-labels"),ref:e},G)),$.length>0&&_.createElement("g",{className:"recharts-cartesian-axis-tick-lines recharts-".concat(A,"-tick-lines")},$))}),jze=_.forwardRef((t,e)=>{var{axisLine:n,width:r,height:i,className:s,hide:o,ticks:l,axisType:c}=t,u=wze(t,vze),[d,h]=_.useState(""),[p,m]=_.useState(""),b=_.useRef(null);_.useImperativeHandle(e,()=>({getCalculatedWidth:()=>{var x;return yze({ticks:b.current,label:(x=t.labelRef)===null||x===void 0?void 0:x.current,labelGapWithTick:5,tickSize:t.tickSize,tickMargin:t.tickMargin})}}));var y=_.useCallback(x=>{if(x){var v=x.getElementsByClassName("recharts-cartesian-axis-tick-value");b.current=v;var S=v[0];if(S){var N=window.getComputedStyle(S),T=N.fontSize,M=N.letterSpacing;(T!==d||M!==p)&&(h(T),m(M))}}},[d,p]);return o||r!=null&&r<=0||i!=null&&i<=0?null:_.createElement(ls,{zIndex:t.zIndex},_.createElement(li,{className:nr("recharts-cartesian-axis",s)},_.createElement(Mze,{x:t.x,y:t.y,width:r,height:i,orientation:t.orientation,mirror:t.mirror,axisLine:n,otherSvgProps:Ms(t)}),_.createElement(Pze,{ref:y,axisType:c,events:u,fontSize:d,getTicksConfig:t,height:t.height,letterSpacing:p,mirror:t.mirror,orientation:t.orientation,padding:t.padding,stroke:t.stroke,tick:t.tick,tickFormatter:t.tickFormatter,tickLine:t.tickLine,tickMargin:t.tickMargin,tickSize:t.tickSize,tickTextProps:t.tickTextProps,ticks:l,unit:t.unit,width:t.width,x:t.x,y:t.y}),_.createElement(TJ,{x:t.x,y:t.y,width:t.width,height:t.height,lowerWidth:t.width,upperWidth:t.width},_.createElement(CJ,{label:t.label,labelRef:t.labelRef}),t.children)))}),N4=_.forwardRef((t,e)=>{var n=ci(t,Ru);return _.createElement(jze,km({},n,{ref:e}))});N4.displayName="CartesianAxis";var Dze=["x1","y1","x2","y2","key"],Rze=["offset"],Oze=["xAxisId","yAxisId"],Lze=["xAxisId","yAxisId"];function xq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function ts(t){for(var e=1;e{var{fill:e}=t;if(!e||e==="none")return null;var{fillOpacity:n,x:r,y:i,width:s,height:o,ry:l}=t;return _.createElement("rect",{x:r,y:i,ry:l,width:s,height:o,stroke:"none",fill:e,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function tee(t){var{option:e,lineItemProps:n}=t,r;if(_.isValidElement(e))r=_.cloneElement(e,n);else if(typeof e=="function")r=e(n);else{var i,{x1:s,y1:o,x2:l,y2:c,key:u}=n,d=oN(n,Dze),h=(i=Ms(d))!==null&&i!==void 0?i:{},{offset:p}=h,m=oN(h,Rze);r=_.createElement("line",$f({},m,{x1:s,y1:o,x2:l,y2:c,fill:"none",key:u}))}return r}function Hze(t){var{x:e,width:n,horizontal:r=!0,horizontalPoints:i}=t;if(!r||!i||!i.length)return null;var{xAxisId:s,yAxisId:o}=t,l=oN(t,Oze),c=i.map((u,d)=>{var h=ts(ts({},l),{},{x1:e,y1:u,x2:e+n,y2:u,key:"line-".concat(d),index:d});return _.createElement(tee,{key:"line-".concat(d),option:r,lineItemProps:h})});return _.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function $ze(t){var{y:e,height:n,vertical:r=!0,verticalPoints:i}=t;if(!r||!i||!i.length)return null;var{xAxisId:s,yAxisId:o}=t,l=oN(t,Lze),c=i.map((u,d)=>{var h=ts(ts({},l),{},{x1:u,y1:e,x2:u,y2:e+n,key:"line-".concat(d),index:d});return _.createElement(tee,{option:r,lineItemProps:h,key:"line-".concat(d)})});return _.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function Vze(t){var{horizontalFill:e,fillOpacity:n,x:r,y:i,width:s,height:o,horizontalPoints:l,horizontal:c=!0}=t;if(!c||!e||!e.length||l==null)return null;var u=l.map(h=>Math.round(h+i-i)).sort((h,p)=>h-p);i!==u[0]&&u.unshift(0);var d=u.map((h,p)=>{var m=!u[p+1],b=m?i+o-h:u[p+1]-h;if(b<=0)return null;var y=p%e.length;return _.createElement("rect",{key:"react-".concat(p),y:h,x:r,height:b,width:s,stroke:"none",fill:e[y],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return _.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},d)}function Gze(t){var{vertical:e=!0,verticalFill:n,fillOpacity:r,x:i,y:s,width:o,height:l,verticalPoints:c}=t;if(!e||!n||!n.length)return null;var u=c.map(h=>Math.round(h+i-i)).sort((h,p)=>h-p);i!==u[0]&&u.unshift(0);var d=u.map((h,p)=>{var m=!u[p+1],b=m?i+o-h:u[p+1]-h;if(b<=0)return null;var y=p%n.length;return _.createElement("rect",{key:"react-".concat(p),x:h,y:s,width:b,height:l,stroke:"none",fill:n[y],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return _.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},d)}var qze=(t,e)=>{var{xAxis:n,width:r,height:i,offset:s}=t;return IY(S4(ts(ts(ts({},Ru),n),{},{ticks:zY(n),viewBox:{x:0,y:0,width:r,height:i}})),s.left,s.left+s.width,e)},Wze=(t,e)=>{var{yAxis:n,width:r,height:i,offset:s}=t;return IY(S4(ts(ts(ts({},Ru),n),{},{ticks:zY(n),viewBox:{x:0,y:0,width:r,height:i}})),s.top,s.top+s.height,e)},Kze={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:vi.grid};function lN(t){var e=YO(),n=QO(),r=KY(),i=ts(ts({},ci(t,Kze)),{},{x:Vt(t.x)?t.x:r.left,y:Vt(t.y)?t.y:r.top,width:Vt(t.width)?t.width:r.width,height:Vt(t.height)?t.height:r.height}),{xAxisId:s,yAxisId:o,x:l,y:c,width:u,height:d,syncWithTicks:h,horizontalValues:p,verticalValues:m}=i,b=aa(),y=Ht(C=>sG(C,"xAxis",s,b)),x=Ht(C=>sG(C,"yAxis",o,b));if(!yc(u)||!yc(d)||!Vt(l)||!Vt(c))return null;var v=i.verticalCoordinatesGenerator||qze,S=i.horizontalCoordinatesGenerator||Wze,{horizontalPoints:N,verticalPoints:T}=i;if((!N||!N.length)&&typeof S=="function"){var M=p&&p.length,A=S({yAxis:x?ts(ts({},x),{},{ticks:M?p:x.ticks}):void 0,width:e??u,height:n??d,offset:r},M?!0:h);PS(Array.isArray(A),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(typeof A,"]")),Array.isArray(A)&&(N=A)}if((!T||!T.length)&&typeof v=="function"){var k=m&&m.length,R=v({xAxis:y?ts(ts({},y),{},{ticks:k?m:y.ticks}):void 0,width:e??u,height:n??d,offset:r},k?!0:h);PS(Array.isArray(R),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(typeof R,"]")),Array.isArray(R)&&(T=R)}return _.createElement(ls,{zIndex:i.zIndex},_.createElement("g",{className:"recharts-cartesian-grid"},_.createElement(Bze,{fill:i.fill,fillOpacity:i.fillOpacity,x:i.x,y:i.y,width:i.width,height:i.height,ry:i.ry}),_.createElement(Vze,$f({},i,{horizontalPoints:N})),_.createElement(Gze,$f({},i,{verticalPoints:T})),_.createElement(Hze,$f({},i,{offset:r,horizontalPoints:N,xAxis:y,yAxis:x})),_.createElement($ze,$f({},i,{offset:r,verticalPoints:T,xAxis:y,yAxis:x}))))}lN.displayName="CartesianGrid";var nee=(t,e,n,r)=>_c(t,"xAxis",e,r),ree=(t,e,n,r)=>wc(t,"xAxis",e,r),iee=(t,e,n,r)=>_c(t,"yAxis",n,r),aee=(t,e,n,r)=>wc(t,"yAxis",n,r),Xze=st([Kn,nee,iee,ree,aee],(t,e,n,r,i)=>Tc(t,"xAxis")?Oh(e,r,!1):Oh(n,i,!1)),Yze=(t,e,n,r,i)=>i;function Qze(t){return t.type==="line"}var Zze=st([dv,Yze],(t,e)=>t.filter(Qze).find(n=>n.id===e)),Jze=st([Kn,nee,iee,ree,aee,Zze,Xze,ov],(t,e,n,r,i,s,o,l)=>{var{chartData:c,dataStartIndex:u,dataEndIndex:d}=l;if(!(s==null||e==null||n==null||r==null||i==null||r.length===0||i.length===0||o==null||t!=="horizontal"&&t!=="vertical")){var{dataKey:h,data:p}=s,m;if(p!=null&&p.length>0?m=p:m=c?.slice(u,d+1),m!=null)return yUe({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataKey:h,bandSize:o,displayedData:m})}});function see(t){var e=vm(t),n=3,r=2;if(e!=null){var{r:i,strokeWidth:s}=e,o=Number(i),l=Number(s);return(Number.isNaN(o)||o<0)&&(o=n),(Number.isNaN(l)||l<0)&&(l=r),{r:o,strokeWidth:l}}return{r:n,strokeWidth:r}}var eUe=["id"],tUe=["type","layout","connectNulls","needClip","shape"],nUe=["activeDot","animateNewValues","animationBegin","animationDuration","animationEasing","connectNulls","dot","hide","isAnimationActive","label","legendType","xAxisId","yAxisId","id"];function ky(){return ky=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{dataKey:e,name:n,stroke:r,legendType:i,hide:s}=t;return[{inactive:s,dataKey:e,type:i,color:r,value:Hh(n,e),payload:t}]},lUe=_.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:i,fill:s,name:o,hide:l,unit:c,tooltipType:u}=t,d={dataDefinedOnItem:n,positions:void 0,settings:{stroke:r,strokeWidth:i,fill:s,dataKey:e,nameKey:void 0,name:Hh(o,e),hide:l,type:u,color:r,unit:c}};return _.createElement(EM,{tooltipEntrySettings:d})}),oee=(t,e)=>"".concat(e,"px ").concat(t-e,"px");function cUe(t,e){for(var n=t.length%2!==0?[...t,0]:t,r=[],i=0;i{var r=n.reduce((h,p)=>h+p);if(!r)return oee(e,t);for(var i=Math.floor(t/r),s=t%r,o=e-t,l=[],c=0,u=0;cs){l=[...n.slice(0,c),s-u];break}var d=l.length%2===0?[0,o]:[o];return[...cUe(n,i),...l,...d].map(h=>"".concat(h,"px")).join(", ")};function dUe(t){var{clipPathId:e,points:n,props:r}=t,{dot:i,dataKey:s,needClip:o}=r,{id:l}=r,c=k4(r,eUe),u=Ms(c);return _.createElement(HJ,{points:n,dot:i,className:"recharts-line-dots",dotClassName:"recharts-line-dot",dataKey:s,baseProps:u,needClip:o,clipPathId:e})}function hUe(t){var{showLabels:e,children:n,points:r}=t,i=_.useMemo(()=>r?.map(s=>{var o,l,c={x:(o=s.x)!==null&&o!==void 0?o:0,y:(l=s.y)!==null&&l!==void 0?l:0,width:0,lowerWidth:0,upperWidth:0,height:0};return rc(rc({},c),{},{value:s.value,payload:s.payload,viewBox:c,parentViewBox:void 0,fill:void 0})}),[r]);return _.createElement(d4,{value:e?i:void 0},n)}function vq(t){var{clipPathId:e,pathRef:n,points:r,strokeDasharray:i,props:s}=t,{type:o,layout:l,connectNulls:c,needClip:u,shape:d}=s,h=k4(s,tUe),p=rc(rc({},Ga(h)),{},{fill:"none",className:"recharts-line-curve",clipPath:u?"url(#clipPath-".concat(e,")"):void 0,points:r,type:o,layout:l,connectNulls:c,strokeDasharray:i??s.strokeDasharray});return _.createElement(_.Fragment,null,r?.length>1&&_.createElement(g4,ky({shapeType:"curve",option:d},p,{pathRef:n})),_.createElement(dUe,{points:r,clipPathId:e,props:s}))}function fUe(t){try{return t&&t.getTotalLength&&t.getTotalLength()||0}catch{return 0}}function mUe(t){var{clipPathId:e,props:n,pathRef:r,previousPointsRef:i,longestAnimatedLengthRef:s}=t,{points:o,strokeDasharray:l,isAnimationActive:c,animationBegin:u,animationDuration:d,animationEasing:h,animateNewValues:p,width:m,height:b,onAnimationEnd:y,onAnimationStart:x}=n,v=i.current,S=Pb(o,"recharts-line-"),N=_.useRef(S),[T,M]=_.useState(!1),A=!T,k=_.useCallback(()=>{typeof y=="function"&&y(),M(!1)},[y]),R=_.useCallback(()=>{typeof x=="function"&&x(),M(!0)},[x]),C=fUe(r.current),P=_.useRef(0);N.current!==S&&(P.current=s.current,N.current=S);var U=P.current;return _.createElement(hUe,{points:o,showLabels:A},n.children,_.createElement(Cb,{animationId:S,begin:u,duration:d,isActive:c,easing:h,onAnimationEnd:k,onAnimationStart:R,key:S},F=>{var H=pr(U,C+U,F),D=Math.min(H,C),$;if(c)if(l){var G="".concat(l).split(/[,\s]+/gim).map(Q=>parseFloat(Q));$=uUe(D,C,G)}else $=oee(C,D);else $=l==null?void 0:String(l);if(F>0&&C>0&&(i.current=o,s.current=Math.max(s.current,D)),v){var I=v.length/o.length,K=F===1?o:o.map((Q,oe)=>{var B=Math.floor(oe*I);if(v[B]){var W=v[B];return rc(rc({},Q),{},{x:pr(W.x,Q.x,F),y:pr(W.y,Q.y,F)})}return p?rc(rc({},Q),{},{x:pr(m*2,Q.x,F),y:pr(b/2,Q.y,F)}):rc(rc({},Q),{},{x:Q.x,y:Q.y})});return i.current=K,_.createElement(vq,{props:n,points:K,clipPathId:e,pathRef:r,strokeDasharray:$})}return _.createElement(vq,{props:n,points:o,clipPathId:e,pathRef:r,strokeDasharray:$})}),_.createElement(NM,{label:n.label}))}function pUe(t){var{clipPathId:e,props:n}=t,r=_.useRef(null),i=_.useRef(0),s=_.useRef(null);return _.createElement(mUe,{props:n,clipPathId:e,previousPointsRef:r,longestAnimatedLengthRef:i,pathRef:s})}var gUe=(t,e)=>{var n,r;return{x:(n=t.x)!==null&&n!==void 0?n:void 0,y:(r=t.y)!==null&&r!==void 0?r:void 0,value:t.value,errorVal:vr(t.payload,e)}};class bUe extends _.Component{render(){var{hide:e,dot:n,points:r,className:i,xAxisId:s,yAxisId:o,top:l,left:c,width:u,height:d,id:h,needClip:p,zIndex:m}=this.props;if(e)return null;var b=nr("recharts-line",i),y=h,{r:x,strokeWidth:v}=see(n),S=p4(n),N=x*2+v,T=p?"url(#clipPath-".concat(S?"":"dots-").concat(y,")"):void 0;return _.createElement(ls,{zIndex:m},_.createElement(li,{className:b},p&&_.createElement("defs",null,_.createElement(_4,{clipPathId:y,xAxisId:s,yAxisId:o}),!S&&_.createElement("clipPath",{id:"clipPath-dots-".concat(y)},_.createElement("rect",{x:c-N/2,y:l-N/2,width:u+N,height:d+N}))),_.createElement(GJ,{xAxisId:s,yAxisId:o,data:r,dataPointFormatter:gUe,errorBarOffset:0},_.createElement(pUe,{props:this.props,clipPathId:y}))),_.createElement(jD,{activeDot:this.props.activeDot,points:r,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:T}))}}var lee={activeDot:!0,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",connectNulls:!1,dot:!0,fill:"#fff",hide:!1,isAnimationActive:"auto",label:!1,legendType:"line",stroke:"#3182bd",strokeWidth:1,xAxisId:0,yAxisId:0,zIndex:vi.line,type:"linear"};function xUe(t){var e=ci(t,lee),{activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,hide:u,isAnimationActive:d,label:h,legendType:p,xAxisId:m,yAxisId:b,id:y}=e,x=k4(e,nUe),{needClip:v}=PM(m,b),S=CM(),N=Lm(),T=aa(),M=Ht(P=>Jze(P,m,b,T,y));if(N!=="horizontal"&&N!=="vertical"||M==null||S==null)return null;var{height:A,width:k,x:R,y:C}=S;return _.createElement(bUe,ky({},x,{id:y,connectNulls:l,dot:c,activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:s,animationEasing:o,isAnimationActive:d,hide:u,label:h,legendType:p,xAxisId:m,yAxisId:b,points:M,layout:N,height:A,width:k,left:R,top:C,needClip:v}))}function yUe(t){var{layout:e,xAxis:n,yAxis:r,xAxisTicks:i,yAxisTicks:s,dataKey:o,bandSize:l,displayedData:c}=t;return c.map((u,d)=>{var h=vr(u,o);if(e==="horizontal"){var p=CS({axis:n,ticks:i,bandSize:l,entry:u,index:d}),m=Yr(h)?null:r.scale(h);return{x:p,y:m,value:h,payload:u}}var b=Yr(h)?null:n.scale(h),y=CS({axis:r,ticks:s,bandSize:l,entry:u,index:d});return b==null||y==null?null:{x:b,y,value:h,payload:u}}).filter(Boolean)}function vUe(t){var e=ci(t,lee),n=aa();return _.createElement(TM,{id:e.id,type:"line"},r=>_.createElement(_.Fragment,null,_.createElement(v4,{legendPayload:oUe(e)}),_.createElement(lUe,{dataKey:e.dataKey,data:e.data,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType}),_.createElement(w4,{type:"line",id:r,data:e.data,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,hide:e.hide,isPanorama:n}),_.createElement(xUe,ky({},e,{id:r}))))}var cee=_.memo(vUe,vv);cee.displayName="Line";var uee=(t,e,n,r)=>_c(t,"xAxis",e,r),dee=(t,e,n,r)=>wc(t,"xAxis",e,r),hee=(t,e,n,r)=>_c(t,"yAxis",n,r),fee=(t,e,n,r)=>wc(t,"yAxis",n,r),wUe=st([Kn,uee,hee,dee,fee],(t,e,n,r,i)=>Tc(t,"xAxis")?Oh(e,r,!1):Oh(n,i,!1)),_Ue=(t,e,n,r,i)=>i,mee=st([dv,_Ue],(t,e)=>t.filter(n=>n.type==="area").find(n=>n.id===e)),SUe=(t,e,n,r,i)=>{var s,o=mee(t,e,n,r,i);if(o!=null){var l=Kn(t),c=Tc(l,"xAxis"),u;if(c?u=Sy(t,"yAxis",n,r):u=Sy(t,"xAxis",e,r),u!=null){var{stackId:d}=o,h=mM(o);if(!(d==null||h==null)){var p=(s=u[d])===null||s===void 0?void 0:s.stackedData;return p?.find(m=>m.key===h)}}}},NUe=st([Kn,uee,hee,dee,fee,SUe,ov,wUe,mee,Z3e],(t,e,n,r,i,s,o,l,c,u)=>{var{chartData:d,dataStartIndex:h,dataEndIndex:p}=o;if(!(c==null||t!=="horizontal"&&t!=="vertical"||e==null||n==null||r==null||i==null||r.length===0||i.length===0||l==null)){var{data:m}=c,b;if(m&&m.length>0?b=m:b=d?.slice(h,p+1),b!=null)return $Ue({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataStartIndex:h,areaSettings:c,stackedData:s,displayedData:b,chartBaseValue:u,bandSize:l})}}),kUe=["id"],MUe=["activeDot","animationBegin","animationDuration","animationEasing","connectNulls","dot","fill","fillOpacity","hide","isAnimationActive","legendType","stroke","xAxisId","yAxisId"];function nm(){return nm=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{dataKey:e,name:n,stroke:r,fill:i,legendType:s,hide:o}=t;return[{inactive:o,dataKey:e,type:s,color:cN(r,i),value:Hh(n,e),payload:t}]},jUe=_.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:i,fill:s,name:o,hide:l,unit:c,tooltipType:u}=t,d={dataDefinedOnItem:n,positions:void 0,settings:{stroke:r,strokeWidth:i,fill:s,dataKey:e,nameKey:void 0,name:Hh(o,e),hide:l,type:u,color:cN(r,s),unit:c}};return _.createElement(EM,{tooltipEntrySettings:d})});function DUe(t){var{clipPathId:e,points:n,props:r}=t,{needClip:i,dot:s,dataKey:o}=r,l=Ms(r);return _.createElement(HJ,{points:n,dot:s,className:"recharts-area-dots",dotClassName:"recharts-area-dot",dataKey:o,baseProps:l,needClip:i,clipPathId:e})}function RUe(t){var{showLabels:e,children:n,points:r}=t,i=r.map(s=>{var o,l,c={x:(o=s.x)!==null&&o!==void 0?o:0,y:(l=s.y)!==null&&l!==void 0?l:0,width:0,lowerWidth:0,upperWidth:0,height:0};return Sg(Sg({},c),{},{value:s.value,payload:s.payload,parentViewBox:void 0,viewBox:c,fill:void 0})});return _.createElement(d4,{value:e?i:void 0},n)}function _q(t){var{points:e,baseLine:n,needClip:r,clipPathId:i,props:s}=t,{layout:o,type:l,stroke:c,connectNulls:u,isRange:d}=s,{id:h}=s,p=pee(s,kUe),m=Ms(p),b=Ga(p);return _.createElement(_.Fragment,null,e?.length>1&&_.createElement(li,{clipPath:r?"url(#clipPath-".concat(i,")"):void 0},_.createElement(Lg,nm({},b,{id:h,points:e,connectNulls:u,type:l,baseLine:n,layout:o,stroke:"none",className:"recharts-area-area"})),c!=="none"&&_.createElement(Lg,nm({},m,{className:"recharts-area-curve",layout:o,type:l,connectNulls:u,fill:"none",points:e})),c!=="none"&&d&&_.createElement(Lg,nm({},m,{className:"recharts-area-curve",layout:o,type:l,connectNulls:u,fill:"none",points:n}))),_.createElement(DUe,{points:e,props:p,clipPathId:i}))}function OUe(t){var{alpha:e,baseLine:n,points:r,strokeWidth:i}=t,s=r[0].y,o=r[r.length-1].y;if(!wr(s)||!wr(o))return null;var l=e*Math.abs(s-o),c=Math.max(...r.map(u=>u.x||0));return Vt(n)?c=Math.max(n,c):n&&Array.isArray(n)&&n.length&&(c=Math.max(...n.map(u=>u.x||0),c)),Vt(c)?_.createElement("rect",{x:0,y:su.y||0));return Vt(n)?c=Math.max(n,c):n&&Array.isArray(n)&&n.length&&(c=Math.max(...n.map(u=>u.y||0),c)),Vt(c)?_.createElement("rect",{x:s({points:o,baseLine:l}),[o,l]),y=Pb(b,"recharts-area-"),x=gAe(),[v,S]=_.useState(!1),N=!v,T=_.useCallback(()=>{typeof m=="function"&&m(),S(!1)},[m]),M=_.useCallback(()=>{typeof p=="function"&&p(),S(!0)},[p]);if(x==null)return null;var A=i.current,k=s.current;return _.createElement(RUe,{showLabels:N,points:o},r.children,_.createElement(Cb,{animationId:y,begin:u,duration:d,isActive:c,easing:h,onAnimationEnd:T,onAnimationStart:M,key:y},R=>{if(A){var C=A.length/o.length,P=R===1?o:o.map((F,H)=>{var D=Math.floor(H*C);if(A[D]){var $=A[D];return Sg(Sg({},F),{},{x:pr($.x,F.x,R),y:pr($.y,F.y,R)})}return F}),U;return Vt(l)?U=pr(k,l,R):Yr(l)||Ys(l)?U=pr(k,0,R):U=l.map((F,H)=>{var D=Math.floor(H*C);if(Array.isArray(k)&&k[D]){var $=k[D];return Sg(Sg({},F),{},{x:pr($.x,F.x,R),y:pr($.y,F.y,R)})}return F}),R>0&&(i.current=P,s.current=U),_.createElement(_q,{points:P,baseLine:U,needClip:e,clipPathId:n,props:r})}return R>0&&(i.current=o,s.current=l),_.createElement(li,null,c&&_.createElement("defs",null,_.createElement("clipPath",{id:"animationClipPath-".concat(n)},_.createElement(FUe,{alpha:R,points:o,baseLine:l,layout:x,strokeWidth:r.strokeWidth}))),_.createElement(li,{clipPath:"url(#animationClipPath-".concat(n,")")},_.createElement(_q,{points:o,baseLine:l,needClip:e,clipPathId:n,props:r})))}),_.createElement(NM,{label:r.label}))}function zUe(t){var{needClip:e,clipPathId:n,props:r}=t,i=_.useRef(null),s=_.useRef();return _.createElement(IUe,{needClip:e,clipPathId:n,props:r,previousPointsRef:i,previousBaselineRef:s})}class UUe extends _.PureComponent{render(){var{hide:e,dot:n,points:r,className:i,top:s,left:o,needClip:l,xAxisId:c,yAxisId:u,width:d,height:h,id:p,baseLine:m,zIndex:b}=this.props;if(e)return null;var y=nr("recharts-area",i),x=p,{r:v,strokeWidth:S}=see(n),N=p4(n),T=v*2+S,M=l?"url(#clipPath-".concat(N?"":"dots-").concat(x,")"):void 0;return _.createElement(ls,{zIndex:b},_.createElement(li,{className:y},l&&_.createElement("defs",null,_.createElement(_4,{clipPathId:x,xAxisId:c,yAxisId:u}),!N&&_.createElement("clipPath",{id:"clipPath-dots-".concat(x)},_.createElement("rect",{x:o-T/2,y:s-T/2,width:d+T,height:h+T}))),_.createElement(zUe,{needClip:l,clipPathId:x,props:this.props})),_.createElement(jD,{points:r,mainColor:cN(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:M}),this.props.isRange&&Array.isArray(m)&&_.createElement(jD,{points:m,mainColor:cN(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:M}))}}var gee={activeDot:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",connectNulls:!1,dot:!1,fill:"#3182bd",fillOpacity:.6,hide:!1,isAnimationActive:"auto",legendType:"line",stroke:"#3182bd",strokeWidth:1,type:"linear",label:!1,xAxisId:0,yAxisId:0,zIndex:vi.area};function BUe(t){var e,n=ci(t,gee),{activeDot:r,animationBegin:i,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,fill:u,fillOpacity:d,hide:h,isAnimationActive:p,legendType:m,stroke:b,xAxisId:y,yAxisId:x}=n,v=pee(n,MUe),S=Lm(),N=dJ(),{needClip:T}=PM(y,x),M=aa(),{points:A,isRange:k,baseLine:R}=(e=Ht(D=>NUe(D,y,x,M,t.id)))!==null&&e!==void 0?e:{},C=CM();if(S!=="horizontal"&&S!=="vertical"||C==null||N!=="AreaChart"&&N!=="ComposedChart")return null;var{height:P,width:U,x:F,y:H}=C;return!A||!A.length?null:_.createElement(UUe,nm({},v,{activeDot:r,animationBegin:i,animationDuration:s,animationEasing:o,baseLine:R,connectNulls:l,dot:c,fill:u,fillOpacity:d,height:P,hide:h,layout:S,isAnimationActive:p==="auto"?!Ab.isSsr:p,isRange:k,legendType:m,needClip:T,points:A,stroke:b,width:U,left:F,top:H,xAxisId:y,yAxisId:x}))}var HUe=(t,e,n,r,i)=>{var s=n??e;if(Vt(s))return s;var o=t==="horizontal"?i:r,l=o.scale.domain();if(o.type==="number"){var c=Math.max(l[0],l[1]),u=Math.min(l[0],l[1]);return s==="dataMin"?u:s==="dataMax"||c<0?c:Math.max(Math.min(l[0],l[1]),0)}return s==="dataMin"?l[0]:s==="dataMax"?l[1]:l[0]};function $Ue(t){var{areaSettings:{connectNulls:e,baseValue:n,dataKey:r},stackedData:i,layout:s,chartBaseValue:o,xAxis:l,yAxis:c,displayedData:u,dataStartIndex:d,xAxisTicks:h,yAxisTicks:p,bandSize:m}=t,b=i&&i.length,y=HUe(s,o,n,l,c),x=s==="horizontal",v=!1,S=u.map((T,M)=>{var A;b?A=i[d+M]:(A=vr(T,r),Array.isArray(A)?v=!0:A=[y,A]);var k=A[1]==null||b&&!e&&vr(T,r)==null;return x?{x:CS({axis:l,ticks:h,bandSize:m,entry:T,index:M}),y:k?null:c.scale(A[1]),value:A,payload:T}:{x:k?null:l.scale(A[1]),y:CS({axis:c,ticks:p,bandSize:m,entry:T,index:M}),value:A,payload:T}}),N;return b||v?N=S.map(T=>{var M=Array.isArray(T.value)?T.value[0]:null;return x?{x:T.x,y:M!=null&&T.y!=null?c.scale(M):null,payload:T.payload}:{x:M!=null?l.scale(M):null,y:T.y,payload:T.payload}}):N=x?c.scale(y):l.scale(y),{points:S,baseLine:N,isRange:v}}function VUe(t){var e=ci(t,gee),n=aa();return _.createElement(TM,{id:e.id,type:"area"},r=>_.createElement(_.Fragment,null,_.createElement(v4,{legendPayload:PUe(e)}),_.createElement(jUe,{dataKey:e.dataKey,data:e.data,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType}),_.createElement(w4,{type:"area",id:r,data:e.data,dataKey:e.dataKey,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,stackId:UY(e.stackId),hide:e.hide,barSize:void 0,baseValue:e.baseValue,isPanorama:n,connectNulls:e.connectNulls}),_.createElement(BUe,nm({},e,{id:r}))))}var bee=_.memo(VUe,vv);bee.displayName="Area";var GUe=["domain","range"],qUe=["domain","range"];function Sq(t,e){if(t==null)return{};var n,r,i=WUe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{n.current===null?e(GFe(t)):n.current!==t&&e(qFe({prev:n.current,next:t})),n.current=t},[t,e]),_.useLayoutEffect(()=>()=>{n.current&&(e(WFe(n.current)),n.current=null)},[e]),null}var ZUe=t=>{var{xAxisId:e,className:n}=t,r=Ht(KO),i=aa(),s="xAxis",o=Ht(x=>Fh(x,s,e,i)),l=Ht(x=>$Z(x,s,e,i)),c=Ht(x=>zZ(x,e)),u=Ht(x=>XDe(x,e)),d=Ht(x=>vZ(x,e));if(c==null||u==null||d==null)return null;var{dangerouslySetInnerHTML:h,ticks:p}=t,m=kq(t,KUe),{id:b}=d,y=kq(d,XUe);return _.createElement(N4,RD({},m,y,{scale:o,x:u.x,y:u.y,width:c.width,height:c.height,className:nr("recharts-".concat(s," ").concat(s),n),viewBox:r,ticks:l,axisType:s}))},JUe={allowDataOverflow:ga.allowDataOverflow,allowDecimals:ga.allowDecimals,allowDuplicatedCategory:ga.allowDuplicatedCategory,angle:ga.angle,axisLine:Ru.axisLine,height:ga.height,hide:!1,includeHidden:ga.includeHidden,interval:ga.interval,minTickGap:ga.minTickGap,mirror:ga.mirror,orientation:ga.orientation,padding:ga.padding,reversed:ga.reversed,scale:ga.scale,tick:ga.tick,tickCount:ga.tickCount,tickLine:Ru.tickLine,tickSize:Ru.tickSize,type:ga.type,xAxisId:0},eBe=t=>{var e=ci(t,JUe);return _.createElement(_.Fragment,null,_.createElement(QUe,{allowDataOverflow:e.allowDataOverflow,allowDecimals:e.allowDecimals,allowDuplicatedCategory:e.allowDuplicatedCategory,angle:e.angle,dataKey:e.dataKey,domain:e.domain,height:e.height,hide:e.hide,id:e.xAxisId,includeHidden:e.includeHidden,interval:e.interval,minTickGap:e.minTickGap,mirror:e.mirror,name:e.name,orientation:e.orientation,padding:e.padding,reversed:e.reversed,scale:e.scale,tick:e.tick,tickCount:e.tickCount,tickFormatter:e.tickFormatter,ticks:e.ticks,type:e.type,unit:e.unit}),_.createElement(ZUe,e))},uN=_.memo(eBe,xee);uN.displayName="XAxis";var tBe=["dangerouslySetInnerHTML","ticks"],nBe=["id"];function OD(){return OD=Object.assign?Object.assign.bind():function(t){for(var e=1;e{n.current===null?e(KFe(t)):n.current!==t&&e(XFe({prev:n.current,next:t})),n.current=t},[t,e]),_.useLayoutEffect(()=>()=>{n.current&&(e(YFe(n.current)),n.current=null)},[e]),null}var aBe=t=>{var{yAxisId:e,className:n,width:r,label:i}=t,s=_.useRef(null),o=_.useRef(null),l=Ht(KO),c=aa(),u=zr(),d="yAxis",h=Ht(M=>Fh(M,d,e,c)),p=Ht(M=>UZ(M,e)),m=Ht(M=>QDe(M,e)),b=Ht(M=>$Z(M,d,e,c)),y=Ht(M=>wZ(M,e));if(_.useLayoutEffect(()=>{if(!(r!=="auto"||!p||u4(i)||_.isValidElement(i)||y==null)){var M=s.current;if(M){var A=M.getCalculatedWidth();Math.round(p.width)!==Math.round(A)&&u(QFe({id:e,width:A}))}}},[b,p,u,i,e,r,y]),p==null||m==null||y==null)return null;var{dangerouslySetInnerHTML:x,ticks:v}=t,S=Mq(t,tBe),{id:N}=y,T=Mq(y,nBe);return _.createElement(N4,OD({},S,T,{ref:s,labelRef:o,scale:h,x:m.x,y:m.y,tickTextProps:r==="auto"?{width:void 0}:{width:r},width:p.width,height:p.height,className:nr("recharts-".concat(d," ").concat(d),n),viewBox:l,ticks:b,axisType:d}))},sBe={allowDataOverflow:ba.allowDataOverflow,allowDecimals:ba.allowDecimals,allowDuplicatedCategory:ba.allowDuplicatedCategory,angle:ba.angle,axisLine:Ru.axisLine,hide:!1,includeHidden:ba.includeHidden,interval:ba.interval,minTickGap:ba.minTickGap,mirror:ba.mirror,orientation:ba.orientation,padding:ba.padding,reversed:ba.reversed,scale:ba.scale,tick:ba.tick,tickCount:ba.tickCount,tickLine:Ru.tickLine,tickSize:Ru.tickSize,type:ba.type,width:ba.width,yAxisId:0},oBe=t=>{var e=ci(t,sBe);return _.createElement(_.Fragment,null,_.createElement(iBe,{interval:e.interval,id:e.yAxisId,scale:e.scale,type:e.type,domain:e.domain,allowDataOverflow:e.allowDataOverflow,dataKey:e.dataKey,allowDuplicatedCategory:e.allowDuplicatedCategory,allowDecimals:e.allowDecimals,tickCount:e.tickCount,padding:e.padding,includeHidden:e.includeHidden,reversed:e.reversed,ticks:e.ticks,width:e.width,orientation:e.orientation,mirror:e.mirror,hide:e.hide,unit:e.unit,name:e.name,angle:e.angle,minTickGap:e.minTickGap,tick:e.tick,tickFormatter:e.tickFormatter}),_.createElement(aBe,e))},dN=_.memo(oBe,xee);dN.displayName="YAxis";var lBe=(t,e)=>e,M4=st([lBe,Kn,xZ,oa,aJ,rd,hOe,ia],yOe),E4=t=>{var e=t.currentTarget.getBoundingClientRect(),n=e.width/t.currentTarget.offsetWidth,r=e.height/t.currentTarget.offsetHeight;return{chartX:Math.round((t.clientX-e.left)/n),chartY:Math.round((t.clientY-e.top)/r)}},yee=ml("mouseClick"),vee=Jy();vee.startListening({actionCreator:yee,effect:(t,e)=>{var n=t.payload,r=M4(e.getState(),E4(n));r?.activeIndex!=null&&e.dispatch(dRe({activeIndex:r.activeIndex,activeDataKey:void 0,activeCoordinate:r.activeCoordinate}))}});var LD=ml("mouseMove"),wee=Jy(),i1=null;wee.startListening({actionCreator:LD,effect:(t,e)=>{var n=t.payload;i1!==null&&cancelAnimationFrame(i1);var r=E4(n);i1=requestAnimationFrame(()=>{var i=e.getState(),s=JL(i,i.tooltip.settings.shared);if(s==="axis"){var o=M4(i,r);o?.activeIndex!=null?e.dispatch(QZ({activeIndex:o.activeIndex,activeDataKey:void 0,activeCoordinate:o.activeCoordinate})):e.dispatch(YZ())}i1=null})}});var Eq={accessibilityLayer:!0,barCategoryGap:"10%",barGap:4,barSize:void 0,className:void 0,maxBarSize:void 0,stackOffset:"none",syncId:void 0,syncMethod:"index",baseValue:void 0,reverseStackOrder:!1},_ee=Qs({name:"rootProps",initialState:Eq,reducers:{updateOptions:(t,e)=>{var n;t.accessibilityLayer=e.payload.accessibilityLayer,t.barCategoryGap=e.payload.barCategoryGap,t.barGap=(n=e.payload.barGap)!==null&&n!==void 0?n:Eq.barGap,t.barSize=e.payload.barSize,t.maxBarSize=e.payload.maxBarSize,t.stackOffset=e.payload.stackOffset,t.syncId=e.payload.syncId,t.syncMethod=e.payload.syncMethod,t.className=e.payload.className,t.baseValue=e.payload.baseValue,t.reverseStackOrder=e.payload.reverseStackOrder}}}),cBe=_ee.reducer,{updateOptions:uBe}=_ee.actions,See=Qs({name:"polarOptions",initialState:null,reducers:{updatePolarOptions:(t,e)=>e.payload}}),{updatePolarOptions:dBe}=See.actions,hBe=See.reducer,Nee=ml("keyDown"),kee=ml("focus"),T4=Jy();T4.startListening({actionCreator:Nee,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:i}=n.tooltip,s=t.payload;if(!(s!=="ArrowRight"&&s!=="ArrowLeft"&&s!=="Enter")){var o=e4(i,zb(n),fv(n),bv(n)),l=o==null?-1:Number(o);if(!(!Number.isFinite(l)||l<0)){var c=rd(n);if(s==="Enter"){var u=ZS(n,"axis","hover",String(i.index));e.dispatch(MD({active:!i.active,activeIndex:i.index,activeDataKey:i.dataKey,activeCoordinate:u}));return}var d=tRe(n),h=d==="left-to-right"?1:-1,p=s==="ArrowRight"?1:-1,m=l+p*h;if(!(c==null||m>=c.length||m<0)){var b=ZS(n,"axis","hover",String(m));e.dispatch(MD({active:!0,activeIndex:m.toString(),activeDataKey:void 0,activeCoordinate:b}))}}}}}});T4.startListening({actionCreator:kee,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:i}=n.tooltip;if(!i.active&&i.index==null){var s="0",o=ZS(n,"axis","hover",String(s));e.dispatch(MD({activeDataKey:void 0,active:!0,activeIndex:s,activeCoordinate:o}))}}}});var qo=ml("externalEvent"),Mee=Jy(),hP=new Map;Mee.startListening({actionCreator:qo,effect:(t,e)=>{var{handler:n,reactEvent:r}=t.payload;if(n!=null){r.persist();var i=r.type,s=hP.get(i);s!==void 0&&cancelAnimationFrame(s);var o=requestAnimationFrame(()=>{try{var l=e.getState(),c={activeCoordinate:QRe(l),activeDataKey:a4(l),activeIndex:Ih(l),activeLabel:lJ(l),activeTooltipIndex:Ih(l),isTooltipActive:ZRe(l)};n(c,r)}finally{hP.delete(i)}});hP.set(i,o)}}});var fBe=st([Ib],t=>t.tooltipItemPayloads),mBe=st([fBe,pv,(t,e,n)=>e,(t,e,n)=>n],(t,e,n,r)=>{var i=t.find(l=>l.settings.dataKey===r);if(i!=null){var{positions:s}=i;if(s!=null){var o=e(s,n);return o}}}),Eee=ml("touchMove"),Tee=Jy();Tee.startListening({actionCreator:Eee,effect:(t,e)=>{var n=t.payload;if(!(n.touches==null||n.touches.length===0)){var r=e.getState(),i=JL(r,r.tooltip.settings.shared);if(i==="axis"){var s=M4(r,E4({clientX:n.touches[0].clientX,clientY:n.touches[0].clientY,currentTarget:n.currentTarget}));s?.activeIndex!=null&&e.dispatch(QZ({activeIndex:s.activeIndex,activeDataKey:void 0,activeCoordinate:s.activeCoordinate}))}else if(i==="item"){var o,l=n.touches[0];if(document.elementFromPoint==null)return;var c=document.elementFromPoint(l.clientX,l.clientY);if(!c||!c.getAttribute)return;var u=c.getAttribute(HY),d=(o=c.getAttribute($Y))!==null&&o!==void 0?o:void 0,h=mBe(e.getState(),u,d);e.dispatch(XZ({activeDataKey:d,activeIndex:u,activeCoordinate:h}))}}}});var pBe=cY({brush:z5e,cartesianAxis:ZFe,chartData:YOe,errorBars:bIe,graphicalItems:aFe,layout:STe,legend:PAe,options:GOe,polarAxis:v4e,polarOptions:hBe,referenceElements:Y5e,rootProps:cBe,tooltip:hRe,zIndex:DOe}),gBe=function(e){return KEe({reducer:pBe,preloadedState:e,middleware:n=>{var r;return n({serializableCheck:!1,immutableCheck:!["commonjs","es6","production"].includes((r="es6")!==null&&r!==void 0?r:"")}).concat([vee.middleware,wee.middleware,T4.middleware,Mee.middleware,Tee.middleware])},enhancers:n=>{var r=n;return typeof n=="function"&&(r=n()),r.concat(NY({type:"raf"}))},devTools:Ab.devToolsEnabled})};function Aee(t){var{preloadedState:e,children:n,reduxStoreName:r}=t,i=aa(),s=_.useRef(null);if(i)return n;s.current==null&&(s.current=gBe(e));var o=zO;return _.createElement(BIe,{context:o,store:s.current},n)}function bBe(t){var{layout:e,margin:n}=t,r=zr(),i=aa();return _.useEffect(()=>{i||(r(vTe(e)),r(yTe(n)))},[r,i,e,n]),null}var Cee=_.memo(bBe,vv);function Pee(t){var e=zr();return _.useEffect(()=>{e(uBe(t))},[e,t]),null}function Tq(t){var{zIndex:e,isPanorama:n}=t,r=n?"recharts-zindex-panorama-":"recharts-zindex-",i=zJ("".concat(r).concat(e)),s=zr();return _.useLayoutEffect(()=>(s(POe({zIndex:e,elementId:i,isPanorama:n})),()=>{s(jOe({zIndex:e,isPanorama:n}))}),[s,e,i,n]),_.createElement("g",{tabIndex:-1,id:i})}function Aq(t){var{children:e,isPanorama:n}=t,r=Ht(wOe);if(!r||r.length===0)return e;var i=r.filter(o=>o<0),s=r.filter(o=>o>0);return _.createElement(_.Fragment,null,i.map(o=>_.createElement(Tq,{key:o,zIndex:o,isPanorama:n})),e,s.map(o=>_.createElement(Tq,{key:o,zIndex:o,isPanorama:n})))}var xBe=["children"];function yBe(t,e){if(t==null)return{};var n,r,i=vBe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var n=YO(),r=QO(),i=aQ();if(!yc(n)||!yc(r))return null;var{children:s,otherAttributes:o,title:l,desc:c}=t,u,d;return o!=null&&(typeof o.tabIndex=="number"?u=o.tabIndex:u=i?0:void 0,typeof o.role=="string"?d=o.role:d=i?"application":void 0),_.createElement(AO,hN({},o,{title:l,desc:c,role:d,tabIndex:u,width:n,height:r,style:wBe,ref:e}),s)}),SBe=t=>{var{children:e}=t,n=Ht(tM);if(!n)return null;var{width:r,height:i,y:s,x:o}=n;return _.createElement(AO,{width:r,height:i,x:o,y:s},e)},Cq=_.forwardRef((t,e)=>{var{children:n}=t,r=yBe(t,xBe),i=aa();return i?_.createElement(SBe,null,_.createElement(Aq,{isPanorama:!0},n)):_.createElement(_Be,hN({ref:e},r),_.createElement(Aq,{isPanorama:!1},n))});function NBe(){var t=zr(),[e,n]=_.useState(null),r=Ht(UTe);return _.useEffect(()=>{if(e!=null){var i=e.getBoundingClientRect(),s=i.width/e.offsetWidth;wr(s)&&s!==r&&t(_Te(s))}},[e,t,r]),n}function Pq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function kBe(t){for(var e=1;e(aLe(),null);function fN(t){if(typeof t=="number")return t;if(typeof t=="string"){var e=parseFloat(t);if(!Number.isNaN(e))return e}return 0}var CBe=_.forwardRef((t,e)=>{var n,r,i=_.useRef(null),[s,o]=_.useState({containerWidth:fN((n=t.style)===null||n===void 0?void 0:n.width),containerHeight:fN((r=t.style)===null||r===void 0?void 0:r.height)}),l=_.useCallback((u,d)=>{o(h=>{var p=Math.round(u),m=Math.round(d);return h.containerWidth===p&&h.containerHeight===m?h:{containerWidth:p,containerHeight:m}})},[]),c=_.useCallback(u=>{if(typeof e=="function"&&e(u),u!=null&&typeof ResizeObserver<"u"){var{width:d,height:h}=u.getBoundingClientRect();l(d,h);var p=b=>{var{width:y,height:x}=b[0].contentRect;l(y,x)},m=new ResizeObserver(p);m.observe(u),i.current=m}},[e,l]);return _.useEffect(()=>()=>{var u=i.current;u?.disconnect()},[l]),_.createElement(_.Fragment,null,_.createElement(nM,{width:s.containerWidth,height:s.containerHeight}),_.createElement("div",Mm({ref:c},t)))}),PBe=_.forwardRef((t,e)=>{var{width:n,height:r}=t,[i,s]=_.useState({containerWidth:fN(n),containerHeight:fN(r)}),o=_.useCallback((c,u)=>{s(d=>{var h=Math.round(c),p=Math.round(u);return d.containerWidth===h&&d.containerHeight===p?d:{containerWidth:h,containerHeight:p}})},[]),l=_.useCallback(c=>{if(typeof e=="function"&&e(c),c!=null){var{width:u,height:d}=c.getBoundingClientRect();o(u,d)}},[e,o]);return _.createElement(_.Fragment,null,_.createElement(nM,{width:i.containerWidth,height:i.containerHeight}),_.createElement("div",Mm({ref:l},t)))}),jBe=_.forwardRef((t,e)=>{var{width:n,height:r}=t;return _.createElement(_.Fragment,null,_.createElement(nM,{width:n,height:r}),_.createElement("div",Mm({ref:e},t)))}),DBe=_.forwardRef((t,e)=>{var{width:n,height:r}=t;return qu(n)||qu(r)?_.createElement(PBe,Mm({},t,{ref:e})):_.createElement(jBe,Mm({},t,{ref:e}))});function RBe(t){return t===!0?CBe:DBe}var OBe=_.forwardRef((t,e)=>{var{children:n,className:r,height:i,onClick:s,onContextMenu:o,onDoubleClick:l,onMouseDown:c,onMouseEnter:u,onMouseLeave:d,onMouseMove:h,onMouseUp:p,onTouchEnd:m,onTouchMove:b,onTouchStart:y,style:x,width:v,responsive:S,dispatchTouchEvents:N=!0}=t,T=_.useRef(null),M=zr(),[A,k]=_.useState(null),[R,C]=_.useState(null),P=NBe(),U=XO(),F=U?.width>0?U.width:v,H=U?.height>0?U.height:i,D=_.useCallback(se=>{P(se),typeof e=="function"&&e(se),k(se),C(se),se!=null&&(T.current=se)},[P,e,k,C]),$=_.useCallback(se=>{M(yee(se)),M(qo({handler:s,reactEvent:se}))},[M,s]),G=_.useCallback(se=>{M(LD(se)),M(qo({handler:u,reactEvent:se}))},[M,u]),I=_.useCallback(se=>{M(YZ()),M(qo({handler:d,reactEvent:se}))},[M,d]),K=_.useCallback(se=>{M(LD(se)),M(qo({handler:h,reactEvent:se}))},[M,h]),Q=_.useCallback(()=>{M(kee())},[M]),oe=_.useCallback(se=>{M(Nee(se.key))},[M]),B=_.useCallback(se=>{M(qo({handler:o,reactEvent:se}))},[M,o]),W=_.useCallback(se=>{M(qo({handler:l,reactEvent:se}))},[M,l]),J=_.useCallback(se=>{M(qo({handler:c,reactEvent:se}))},[M,c]),ne=_.useCallback(se=>{M(qo({handler:p,reactEvent:se}))},[M,p]),me=_.useCallback(se=>{M(qo({handler:y,reactEvent:se}))},[M,y]),fe=_.useCallback(se=>{N&&M(Eee(se)),M(qo({handler:b,reactEvent:se}))},[M,N,b]),de=_.useCallback(se=>{M(qo({handler:m,reactEvent:se}))},[M,m]),Re=RBe(S);return _.createElement(gJ.Provider,{value:A},_.createElement(NX.Provider,{value:R},_.createElement(Re,{width:F??x?.width,height:H??x?.height,className:nr("recharts-wrapper",r),style:kBe({position:"relative",cursor:"default",width:F,height:H},x),onClick:$,onContextMenu:B,onDoubleClick:W,onFocus:Q,onKeyDown:oe,onMouseDown:J,onMouseEnter:G,onMouseLeave:I,onMouseMove:K,onMouseUp:ne,onTouchEnd:de,onTouchMove:fe,onTouchStart:me,ref:D},_.createElement(ABe,null),n)))}),LBe=["width","height","responsive","children","className","style","compact","title","desc"];function FBe(t,e){if(t==null)return{};var n,r,i=IBe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var{width:n,height:r,responsive:i,children:s,className:o,style:l,compact:c,title:u,desc:d}=t,h=FBe(t,LBe),p=Ms(h);return c?_.createElement(_.Fragment,null,_.createElement(nM,{width:n,height:r}),_.createElement(Cq,{otherAttributes:p,title:u,desc:d},s)):_.createElement(OBe,{className:o,style:l,width:n,height:r,responsive:i??!1,onClick:t.onClick,onMouseLeave:t.onMouseLeave,onMouseEnter:t.onMouseEnter,onMouseMove:t.onMouseMove,onMouseDown:t.onMouseDown,onMouseUp:t.onMouseUp,onContextMenu:t.onContextMenu,onDoubleClick:t.onDoubleClick,onTouchStart:t.onTouchStart,onTouchMove:t.onTouchMove,onTouchEnd:t.onTouchEnd},_.createElement(Cq,{otherAttributes:p,title:u,desc:d,ref:e},_.createElement(Q5e,null,s)))});function FD(){return FD=Object.assign?Object.assign.bind():function(t){for(var e=1;e_.createElement(A4,{chartName:"LineChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:BBe,tooltipPayloadSearcher:_M,categoricalChartProps:t,ref:e})),$Be=["axis","item"],VBe=_.forwardRef((t,e)=>_.createElement(A4,{chartName:"BarChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:$Be,tooltipPayloadSearcher:_M,categoricalChartProps:t,ref:e}));function GBe(t){var e=zr();return _.useEffect(()=>{e(dBe(t))},[e,t]),null}var qBe=["layout"];function ID(){return ID=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var n=ci(t,t8e);return _.createElement(YBe,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:e8e,tooltipPayloadSearcher:_M,categoricalChartProps:n,ref:e})}),r8e=["axis"],i8e=_.forwardRef((t,e)=>_.createElement(A4,{chartName:"AreaChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:r8e,tooltipPayloadSearcher:_M,categoricalChartProps:t,ref:e}));const Rq=[{value:"6h",label:"6h",hours:6},{value:"24h",label:"24h",hours:24},{value:"48h",label:"48h",hours:48},{value:"7d",label:"7d",hours:168}];function a8e({isOpen:t,onClose:e,printerId:n,printerName:r,amsId:i,amsLabel:s,initialMode:o="humidity",thresholds:l}){const{t:c}=Yt(),{mode:u}=Dm(),[d,h]=_.useState("24h"),[p,m]=_.useState(o),b=u==="dark",{data:y}=it({queryKey:["settings"],queryFn:ae.getSettings}),x=y?.time_format||"system";_.useEffect(()=>{if(!t)return;const ne=me=>{me.key==="Escape"&&e()};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[t,e]);const v=Rq.find(ne=>ne.value===d)?.hours||24,{data:S,isLoading:N,error:T}=it({queryKey:["ams-history",n,i,v],queryFn:()=>ae.getAMSHistory(n,i,v),enabled:t,refetchInterval:6e4});if(!t)return null;const M=S?.data.map(ne=>{const me=zi(ne.recorded_at)||new Date,fe={hour:"2-digit",minute:"2-digit",...v>24?{day:"numeric",month:"short"}:{}};return{time:me.getTime(),humidity:ne.humidity,temperature:ne.temperature,timeLabel:me.toLocaleTimeString([],S0(fe,x))}})||[],A=l?.humidityGood||40,k=l?.humidityFair||60,R=l?.tempGood||30,C=l?.tempFair||35,P=M[M.length-1],U=P?.humidity,F=P?.temperature,H=ne=>{const me=ne.filter(Fe=>Fe!=null);if(me.length<4)return"stable";const fe=me.slice(0,Math.floor(me.length/4)),de=me.slice(-Math.floor(me.length/4)),Re=fe.reduce((Fe,ce)=>Fe+ce,0)/fe.length,ke=de.reduce((Fe,ce)=>Fe+ce,0)/de.length-Re;return Math.abs(ke)<2?"stable":ke>0?"up":"down"},D=H(M.map(ne=>ne.humidity)),$=H(M.map(ne=>ne.temperature)),G=({trend:ne})=>ne==="up"?a.jsx(Pj,{className:"w-4 h-4 text-red-400"}):ne==="down"?a.jsx(GW,{className:"w-4 h-4 text-green-400"}):a.jsx(Aj,{className:"w-4 h-4 text-gray-400 dark:text-bambu-gray"}),I=ne=>ne==null?"#9ca3af":ne<=A?"#22a352":ne<=k?"#d4a017":"#c62828",K=ne=>ne==null?"#9ca3af":ne<=R?"#22a352":ne<=C?"#d4a017":"#c62828",Q=b?"#2d2d2d":"#ffffff",oe=b?"#1d1d1d":"#f3f4f6",B=b?"#3d3d3d":"#e5e7eb",W=b?"#ffffff":"#111827",J=b?"#9ca3af":"#4b5563";return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:a.jsxs("div",{className:"rounded-xl w-full max-w-4xl max-h-[90vh] overflow-hidden shadow-xl",style:{backgroundColor:Q},onClick:ne=>ne.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",style:{borderColor:B},children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold",style:{color:W},children:[s," ",c("common.history","History")]}),a.jsx("p",{className:"text-sm",style:{color:J},children:r})]}),a.jsx("button",{onClick:e,className:"p-2 rounded-lg transition-colors",style:{color:J},children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 space-y-6 overflow-y-auto max-h-[calc(90vh-80px)]",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex gap-1 rounded-lg p-1",style:{backgroundColor:oe},children:[a.jsxs("button",{onClick:()=>m("humidity"),className:`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${p==="humidity"?"bg-blue-600 text-white":""}`,style:p!=="humidity"?{color:J}:void 0,children:[a.jsx(HR,{className:"w-4 h-4"}),c("common.humidity","Humidity")]}),a.jsxs("button",{onClick:()=>m("temperature"),className:`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${p==="temperature"?"bg-orange-600 text-white":""}`,style:p!=="temperature"?{color:J}:void 0,children:[a.jsx(Ek,{className:"w-4 h-4"}),c("common.temperature","Temperature")]})]}),a.jsx("div",{className:"flex gap-1 rounded-lg p-1",style:{backgroundColor:oe},children:Rq.map(ne=>a.jsx("button",{onClick:()=>h(ne.value),className:`px-3 py-1 text-sm rounded-md transition-colors ${d===ne.value?"bg-bambu-green text-white":""}`,style:d!==ne.value?{color:J}:void 0,children:ne.label},ne.value))})]}),a.jsx("div",{className:"grid grid-cols-4 gap-4",children:p==="humidity"?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.current","Current")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-2xl font-bold",style:{color:I(U)},children:U!=null?`${U}%`:"—"}),a.jsx(G,{trend:D})]})]}),a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.average","Average")}),a.jsx("p",{className:"text-2xl font-bold",style:{color:W},children:S?.avg_humidity!=null?`${S.avg_humidity}%`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.min","Min")}),a.jsx("p",{className:"text-2xl font-bold text-green-500",children:S?.min_humidity!=null?`${S.min_humidity}%`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.max","Max")}),a.jsx("p",{className:"text-2xl font-bold text-red-500",children:S?.max_humidity!=null?`${S.max_humidity}%`:"—"})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.current","Current")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-2xl font-bold",style:{color:K(F)},children:F!=null?`${F}°C`:"—"}),a.jsx(G,{trend:$})]})]}),a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.average","Average")}),a.jsx("p",{className:"text-2xl font-bold",style:{color:W},children:S?.avg_temperature!=null?`${S.avg_temperature}°C`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.min","Min")}),a.jsx("p",{className:"text-2xl font-bold text-blue-500",children:S?.min_temperature!=null?`${S.min_temperature}°C`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.max","Max")}),a.jsx("p",{className:"text-2xl font-bold text-red-500",children:S?.max_temperature!=null?`${S.max_temperature}°C`:"—"})]})]})}),a.jsx("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:N?a.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:J},children:c("common.loading","Loading...")}):T?a.jsx("div",{className:"h-[300px] flex items-center justify-center text-red-500",children:c("common.error","Error loading data")}):M.length===0?a.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:J},children:c("common.noData","No data available for this time range")}):a.jsx(F1,{width:"100%",height:300,children:a.jsxs(HBe,{data:M,children:[a.jsx(lN,{strokeDasharray:"3 3",stroke:b?"#3d3d3d":"#e5e7eb"}),a.jsx(uN,{dataKey:"time",type:"number",domain:["dataMin","dataMax"],tickFormatter:ne=>{const me=new Date(ne);return v>24?me.toLocaleDateString([],{day:"numeric",month:"short"}):me.toLocaleTimeString([],S0({hour:"2-digit",minute:"2-digit"},x))},stroke:b?"#9ca3af":"#6b7280",tick:{fontSize:12}}),a.jsx(dN,{stroke:b?"#9ca3af":"#6b7280",tick:{fontSize:12},domain:p==="humidity"?[0,100]:["auto","auto"],tickFormatter:ne=>p==="humidity"?`${ne}%`:`${ne}°C`}),a.jsx(z1,{contentStyle:{backgroundColor:b?"#2d2d2d":"#ffffff",border:`1px solid ${b?"#3d3d3d":"#e5e7eb"}`,borderRadius:"8px",color:b?"#fff":"#000"},labelFormatter:ne=>new Date(ne).toLocaleString(void 0,S0({year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},x)),formatter:ne=>[p==="humidity"?`${ne??0}%`:`${ne??0}°C`,p==="humidity"?"Humidity":"Temperature"]}),a.jsx(eL,{}),p==="humidity"?a.jsxs(a.Fragment,{children:[a.jsx(m0,{y:A,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),a.jsx(m0,{y:k,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}):a.jsxs(a.Fragment,{children:[a.jsx(m0,{y:R,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),a.jsx(m0,{y:C,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}),a.jsx(cee,{type:"monotone",dataKey:p,name:p==="humidity"?"Humidity":"Temperature",stroke:p==="humidity"?"#3b82f6":"#f97316",strokeWidth:2,dot:!1,activeDot:{r:4}})]})})}),a.jsx("div",{className:"text-xs text-center",style:{color:J},children:c("amsHistory.recordingInfo","Data is recorded every 5 minutes while the printer is connected")})]})]})})}function fP({data:t,children:e,disabled:n,className:r="",spoolman:i,configureSlot:s}){const{t:o}=Yt(),[l,c]=_.useState(!1),[u,d]=_.useState("top"),[h,p]=_.useState(!1),m=_.useRef(null),b=_.useRef(null),y=_.useRef(null),x=()=>{const k=t.trayUuid;k&&(navigator.clipboard&&window.isSecureContext?navigator.clipboard.writeText(k).then(()=>{p(!0),setTimeout(()=>p(!1),2e3)}).catch(()=>{v(k)}):v(k))},v=k=>{const R=document.createElement("textarea");R.value=k,R.style.position="fixed",R.style.opacity="0",document.body.appendChild(R),R.select();try{document.execCommand("copy"),p(!0),setTimeout(()=>p(!1),2e3)}catch{console.error("Failed to copy to clipboard")}document.body.removeChild(R)};_.useEffect(()=>{if(l&&m.current&&b.current){const k=m.current.getBoundingClientRect(),R=b.current.offsetHeight,P=k.top-56,U=window.innerHeight-k.bottom;PP?d("bottom"):d("top")}},[l]);const S=()=>{n||(y.current&&clearTimeout(y.current),y.current=setTimeout(()=>c(!0),80))},N=()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>c(!1),100)};_.useEffect(()=>()=>{y.current&&clearTimeout(y.current)},[]);const T=k=>k<=15?"#ef4444":k<=30?"#f97316":k<=50?"#eab308":"#22c55e",M=k=>{if(!k)return!1;const R=k.replace("#",""),C=parseInt(R.slice(0,2),16),P=parseInt(R.slice(2,4),16),U=parseInt(R.slice(4,6),16);return(.299*C+.587*P+.114*U)/255>.6},A=t.colorHex?`#${t.colorHex.replace("#","")}`:null;return a.jsxs("div",{ref:m,className:`relative ${r}`,onMouseEnter:S,onMouseLeave:N,children:[e,l&&a.jsxs("div",{ref:b,className:` + `).concat(T.x,",").concat(T.y),A=Yr(t.id)?uy("recharts-radial-line-"):t.id;return _.createElement("text",yu({},r,{dominantBaseline:"central",className:nr("recharts-radial-bar-label",o)}),_.createElement("defs",null,_.createElement("path",{id:A,d:M})),_.createElement("textPath",{xlinkHref:"#".concat(A)},n))},YLe=(t,e,n)=>{var{cx:r,cy:i,innerRadius:s,outerRadius:o,startAngle:l,endAngle:c}=t,u=(l+c)/2;if(n==="outside"){var{x:d,y:h}=Bi(r,i,o+e,u);return{x:d,y:h,textAnchor:d>=r?"start":"end",verticalAnchor:"middle"}}if(n==="center")return{x:r,y:i,textAnchor:"middle",verticalAnchor:"middle"};if(n==="centerTop")return{x:r,y:i,textAnchor:"middle",verticalAnchor:"start"};if(n==="centerBottom")return{x:r,y:i,textAnchor:"middle",verticalAnchor:"end"};var p=(s+o)/2,{x:m,y:b}=Bi(r,i,p,u);return{x:m,y:b,textAnchor:"middle",verticalAnchor:"middle"}},CD=t=>"cx"in t&&Vt(t.cx),QLe=(t,e)=>{var{parentViewBox:n,offset:r,position:i}=t,s;n!=null&&!CD(n)&&(s=n);var{x:o,y:l,upperWidth:c,lowerWidth:u,height:d}=e,h=o,p=o+(c-u)/2,m=(h+p)/2,b=(c+u)/2,y=h+c/2,x=d>=0?1:-1,v=x*r,S=x>0?"end":"start",N=x>0?"start":"end",T=c>=0?1:-1,M=T*r,A=T>0?"end":"start",k=T>0?"start":"end";if(i==="top"){var R={x:h+c/2,y:l-v,textAnchor:"middle",verticalAnchor:S};return Mi(Mi({},R),s?{height:Math.max(l-s.y,0),width:c}:{})}if(i==="bottom"){var C={x:p+u/2,y:l+d+v,textAnchor:"middle",verticalAnchor:N};return Mi(Mi({},C),s?{height:Math.max(s.y+s.height-(l+d),0),width:u}:{})}if(i==="left"){var P={x:m-M,y:l+d/2,textAnchor:A,verticalAnchor:"middle"};return Mi(Mi({},P),s?{width:Math.max(P.x-s.x,0),height:d}:{})}if(i==="right"){var U={x:m+b+M,y:l+d/2,textAnchor:k,verticalAnchor:"middle"};return Mi(Mi({},U),s?{width:Math.max(s.x+s.width-U.x,0),height:d}:{})}var F=s?{width:b,height:d}:{};return i==="insideLeft"?Mi({x:m+M,y:l+d/2,textAnchor:k,verticalAnchor:"middle"},F):i==="insideRight"?Mi({x:m+b-M,y:l+d/2,textAnchor:A,verticalAnchor:"middle"},F):i==="insideTop"?Mi({x:h+c/2,y:l+v,textAnchor:"middle",verticalAnchor:N},F):i==="insideBottom"?Mi({x:p+u/2,y:l+d-v,textAnchor:"middle",verticalAnchor:S},F):i==="insideTopLeft"?Mi({x:h+M,y:l+v,textAnchor:k,verticalAnchor:N},F):i==="insideTopRight"?Mi({x:h+c-M,y:l+v,textAnchor:A,verticalAnchor:N},F):i==="insideBottomLeft"?Mi({x:p+M,y:l+d-v,textAnchor:k,verticalAnchor:S},F):i==="insideBottomRight"?Mi({x:p+u-M,y:l+d-v,textAnchor:A,verticalAnchor:S},F):i&&typeof i=="object"&&(Vt(i.x)||qu(i.x))&&(Vt(i.y)||qu(i.y))?Mi({x:o+as(i.x,b),y:l+as(i.y,d),textAnchor:"end",verticalAnchor:"end"},F):Mi({x:y,y:l+d/2,textAnchor:"middle",verticalAnchor:"middle"},F)},ZLe={angle:0,offset:5,zIndex:vi.label,position:"middle",textBreakAll:!1};function Zd(t){var e=ci(t,ZLe),{viewBox:n,position:r,value:i,children:s,content:o,className:l="",textBreakAll:c,labelRef:u}=e,d=qLe(),h=AJ(),p=r==="center"?h:d??h,m,b,y;if(n==null?m=p:CD(n)?m=n:m=WY(n),!m||Yr(i)&&Yr(s)&&!_.isValidElement(o)&&typeof o!="function")return null;var x=Mi(Mi({},e),{},{viewBox:m});if(_.isValidElement(o)){var{labelRef:v}=x,S=ULe(x,zLe);return _.cloneElement(o,S)}if(typeof o=="function"){if(b=_.createElement(o,x),_.isValidElement(b))return b}else b=WLe(e);var N=Ga(e);if(CD(m)){if(r==="insideStart"||r==="insideEnd"||r==="end")return XLe(e,r,b,N,m);y=YLe(m,e.offset,e.position)}else y=QLe(e,m);return _.createElement(ls,{zIndex:e.zIndex},_.createElement(SM,yu({ref:u,className:nr("recharts-label",l)},N,y,{textAnchor:RLe(N.textAnchor)?N.textAnchor:y.textAnchor,breakAll:c}),b))}Zd.displayName="Label";var JLe=(t,e,n)=>{if(!t)return null;var r={viewBox:e,labelRef:n};return t===!0?_.createElement(Zd,yu({key:"label-implicit"},r)):fl(t)?_.createElement(Zd,yu({key:"label-implicit",value:t},r)):_.isValidElement(t)?t.type===Zd?_.cloneElement(t,Mi({key:"label-implicit"},r)):_.createElement(Zd,yu({key:"label-implicit",content:t},r)):u4(t)?_.createElement(Zd,yu({key:"label-implicit",content:t},r)):t&&typeof t=="object"?_.createElement(Zd,yu({},t,{key:"label-implicit"},r)):null};function CJ(t){var{label:e,labelRef:n}=t,r=AJ();return JLe(e,r,n)||null}var JC={},eP={},RG;function e4e(){return RG||(RG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n[n.length-1]}t.last=e})(eP)),eP}var tP={},OG;function t4e(){return OG||(OG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Array.isArray(n)?n:Array.from(n)}t.toArray=e})(tP)),tP}var LG;function n4e(){return LG||(LG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=e4e(),n=t4e(),r=IO();function i(s){if(r.isArrayLike(s))return e.last(n.toArray(s))}t.last=i})(JC)),JC}var nP,FG;function r4e(){return FG||(FG=1,nP=n4e().last),nP}var i4e=r4e();const a4e=gl(i4e);var s4e=["valueAccessor"],o4e=["dataKey","clockWise","id","textBreakAll","zIndex"];function JS(){return JS=Object.assign?Object.assign.bind():function(t){for(var e=1;eArray.isArray(t.value)?a4e(t.value):t.value,PJ=_.createContext(void 0),d4=PJ.Provider,jJ=_.createContext(void 0),u4e=jJ.Provider;function d4e(){return _.useContext(PJ)}function h4e(){return _.useContext(jJ)}function U1(t){var{valueAccessor:e=c4e}=t,n=IG(t,s4e),{dataKey:r,clockWise:i,id:s,textBreakAll:o,zIndex:l}=n,c=IG(n,o4e),u=d4e(),d=h4e(),h=u||d;return!h||!h.length?null:_.createElement(ls,{zIndex:l??vi.label},_.createElement(li,{className:"recharts-label-list"},h.map((p,m)=>{var b,y=Yr(r)?e(p,m):vr(p&&p.payload,r),x=Yr(s)?{}:{id:"".concat(s,"-").concat(m)};return _.createElement(Zd,JS({key:"label-".concat(m)},Ga(p),c,x,{fill:(b=n.fill)!==null&&b!==void 0?b:p.fill,parentViewBox:p.parentViewBox,value:y,textBreakAll:o,viewBox:p.viewBox,index:m,zIndex:0}))})))}U1.displayName="LabelList";function NM(t){var{label:e}=t;return e?e===!0?_.createElement(U1,{key:"labelList-implicit"}):_.isValidElement(e)||u4(e)?_.createElement(U1,{key:"labelList-implicit",content:e}):typeof e=="object"?_.createElement(U1,JS({key:"labelList-implicit"},e,{type:String(e.type)})):null:null}function PD(){return PD=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{cx:e,cy:n,r,className:i}=t,s=nr("recharts-dot",i);return Vt(e)&&Vt(n)&&Vt(r)?_.createElement("circle",PD({},Ms(t),FO(t),{className:s,cx:e,cy:n,r})):null},RJ=t=>t.graphicalItems.polarItems,f4e=st([ii,cv],RL),kM=st([RJ,ui,f4e],OL),m4e=st([kM],LL),MM=st([m4e,NL],FL),p4e=st([MM,ui,kM],zL);st([MM,ui,kM],(t,e,n)=>n.length>0?t.flatMap(r=>n.flatMap(i=>{var s,o=vr(r,(s=e.dataKey)!==null&&s!==void 0?s:i.dataKey);return{value:o,errorDomain:[]}})).filter(Boolean):e?.dataKey!=null?t.map(r=>({value:vr(r,e.dataKey),errorDomain:[]})):t.map(r=>({value:r,errorDomain:[]})));var zG=()=>{},g4e=st([MM,ui,kM,yM,ii],$L),b4e=st([ui,BL,HL,zG,g4e,zG,Kn,ii],VL),OJ=st([ui,Kn,MM,p4e,lv,ii,b4e],GL),x4e=st([OJ,ui,Fb],KL);st([ui,OJ,x4e,ii],YL);var y4e={radiusAxis:{},angleAxis:{}},LJ=Qs({name:"polarAxis",initialState:y4e,reducers:{addRadiusAxis(t,e){t.radiusAxis[e.payload.id]=e.payload},removeRadiusAxis(t,e){delete t.radiusAxis[e.payload.id]},addAngleAxis(t,e){t.angleAxis[e.payload.id]=e.payload},removeAngleAxis(t,e){delete t.angleAxis[e.payload.id]}}}),{addRadiusAxis:gQe,removeRadiusAxis:bQe,addAngleAxis:xQe,removeAngleAxis:yQe}=LJ.actions,v4e=LJ.reducer;function UG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function BG(t){for(var e=1;ee,h4=st([RJ,N4e],(t,e)=>t.filter(n=>n.type==="pie").find(n=>n.id===e)),k4e=[],f4=(t,e,n)=>n?.length===0?k4e:n,FJ=st([NL,h4,f4],(t,e,n)=>{var{chartData:r}=t;if(e!=null){var i;if(e?.data!=null&&e.data.length>0?i=e.data:i=r,(!i||!i.length)&&n!=null&&(i=n.map(s=>BG(BG({},e.presentationProps),s.props))),i!=null)return i}}),M4e=st([FJ,h4,f4],(t,e,n)=>{if(!(t==null||e==null))return t.map((r,i)=>{var s,o=vr(r,e.nameKey,e.name),l;return n!=null&&(s=n[i])!==null&&s!==void 0&&(s=s.props)!==null&&s!==void 0&&s.fill?l=n[i].props.fill:typeof r=="object"&&r!=null&&"fill"in r?l=r.fill:l=e.fill,{value:Hh(o,e.dataKey),color:l,payload:r,type:e.legendType}})}),E4e=st([FJ,h4,f4,ia],(t,e,n,r)=>{if(!(e==null||t==null))return TFe({offset:r,pieSettings:e,displayedData:t,cells:n})}),rP={exports:{}},Mr={};var HG;function T4e(){if(HG)return Mr;HG=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.suspense_list"),d=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),p=Symbol.for("react.view_transition"),m=Symbol.for("react.client.reference");function b(y){if(typeof y=="object"&&y!==null){var x=y.$$typeof;switch(x){case t:switch(y=y.type,y){case n:case i:case r:case c:case u:case p:return y;default:switch(y=y&&y.$$typeof,y){case o:case l:case h:case d:return y;case s:return y;default:return x}}case e:return x}}}return Mr.ContextConsumer=s,Mr.ContextProvider=o,Mr.Element=t,Mr.ForwardRef=l,Mr.Fragment=n,Mr.Lazy=h,Mr.Memo=d,Mr.Portal=e,Mr.Profiler=i,Mr.StrictMode=r,Mr.Suspense=c,Mr.SuspenseList=u,Mr.isContextConsumer=function(y){return b(y)===s},Mr.isContextProvider=function(y){return b(y)===o},Mr.isElement=function(y){return typeof y=="object"&&y!==null&&y.$$typeof===t},Mr.isForwardRef=function(y){return b(y)===l},Mr.isFragment=function(y){return b(y)===n},Mr.isLazy=function(y){return b(y)===h},Mr.isMemo=function(y){return b(y)===d},Mr.isPortal=function(y){return b(y)===e},Mr.isProfiler=function(y){return b(y)===i},Mr.isStrictMode=function(y){return b(y)===r},Mr.isSuspense=function(y){return b(y)===c},Mr.isSuspenseList=function(y){return b(y)===u},Mr.isValidElementType=function(y){return typeof y=="string"||typeof y=="function"||y===n||y===i||y===r||y===c||y===u||typeof y=="object"&&y!==null&&(y.$$typeof===h||y.$$typeof===d||y.$$typeof===o||y.$$typeof===s||y.$$typeof===l||y.$$typeof===m||y.getModuleId!==void 0)},Mr.typeOf=b,Mr}var $G;function A4e(){return $G||($G=1,rP.exports=T4e()),rP.exports}var C4e=A4e(),VG=t=>typeof t=="string"?t:t?t.displayName||t.name||"Component":"",GG=null,iP=null,IJ=t=>{if(t===GG&&Array.isArray(iP))return iP;var e=[];return _.Children.forEach(t,n=>{Yr(n)||(C4e.isFragment(n)?e=e.concat(IJ(n.props.children)):e.push(n))}),iP=e,GG=t,e};function m4(t,e){var n=[],r=[];return Array.isArray(e)?r=e.map(i=>VG(i)):r=[VG(e)],IJ(t).forEach(i=>{var s=wm(i,"type.displayName")||wm(i,"type.name");s&&r.indexOf(s)!==-1&&n.push(i)}),n}var p4=t=>t&&typeof t=="object"&&"clipDot"in t?!!t.clipDot:!0,aP={},qG;function P4e(){return qG||(qG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){if(typeof n!="object"||n==null)return!1;if(Object.getPrototypeOf(n)===null)return!0;if(Object.prototype.toString.call(n)!=="[object Object]"){const i=n[Symbol.toStringTag];return i==null||!Object.getOwnPropertyDescriptor(n,Symbol.toStringTag)?.writable?!1:n.toString()===`[object ${i}]`}let r=n;for(;Object.getPrototypeOf(r)!==null;)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(n)===r}t.isPlainObject=e})(aP)),aP}var sP,WG;function j4e(){return WG||(WG=1,sP=P4e().isPlainObject),sP}var D4e=j4e();const R4e=gl(D4e);function KG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function XG(t){for(var e=1;e{var s=n-r,o;return o="M ".concat(t,",").concat(e),o+="L ".concat(t+n,",").concat(e),o+="L ".concat(t+n-s/2,",").concat(e+i),o+="L ".concat(t+n-s/2-r,",").concat(e+i),o+="L ".concat(t,",").concat(e," Z"),o},I4e={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},z4e=t=>{var e=ci(t,I4e),{x:n,y:r,upperWidth:i,lowerWidth:s,height:o,className:l}=e,{animationEasing:c,animationDuration:u,animationBegin:d,isUpdateAnimationActive:h}=e,p=_.useRef(null),[m,b]=_.useState(-1),y=_.useRef(i),x=_.useRef(s),v=_.useRef(o),S=_.useRef(n),N=_.useRef(r),T=Pb(t,"trapezoid-");if(_.useEffect(()=>{if(p.current&&p.current.getTotalLength)try{var D=p.current.getTotalLength();D&&b(D)}catch{}},[]),n!==+n||r!==+r||i!==+i||s!==+s||o!==+o||i===0&&s===0||o===0)return null;var M=nr("recharts-trapezoid",l);if(!h)return _.createElement("g",null,_.createElement("path",eN({},Ga(e),{className:M,d:YG(n,r,i,s,o)})));var A=y.current,k=x.current,R=v.current,C=S.current,P=N.current,U="0px ".concat(m===-1?1:m,"px"),F="".concat(m,"px 0px"),H=sQ(["strokeDasharray"],u,c);return _.createElement(Cb,{animationId:T,key:T,canBegin:m>0,duration:u,easing:c,isActive:h,begin:d},D=>{var $=pr(A,i,D),G=pr(k,s,D),I=pr(R,o,D),K=pr(C,n,D),Q=pr(P,r,D);p.current&&(y.current=$,x.current=G,v.current=I,S.current=K,N.current=Q);var oe=D>0?{transition:H,strokeDasharray:F}:{strokeDasharray:U};return _.createElement("path",eN({},Ga(e),{className:M,d:YG(K,Q,$,G,I),ref:p,style:XG(XG({},oe),e.style)}))})},U4e=["option","shapeType","propTransformer","activeClassName"];function B4e(t,e){if(t==null)return{};var n,r,i=H4e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var r=zr();return(i,s)=>o=>{t?.(i,s,o),r(XZ({activeIndex:String(s),activeDataKey:e,activeCoordinate:i.tooltipPosition,activeGraphicalItemId:n}))}},x4=t=>{var e=zr();return(n,r)=>i=>{t?.(n,r,i),e(cRe())}},y4=(t,e,n)=>{var r=zr();return(i,s)=>o=>{t?.(i,s,o),r(uRe({activeIndex:String(s),activeDataKey:e,activeCoordinate:i.tooltipPosition,activeGraphicalItemId:n}))}};function EM(t){var{tooltipEntrySettings:e}=t,n=zr(),r=aa(),i=_.useRef(null);return _.useLayoutEffect(()=>{r||(i.current===null?n(aRe(e)):i.current!==e&&n(sRe({prev:i.current,next:e})),i.current=e)},[e,n,r]),_.useLayoutEffect(()=>()=>{i.current&&(n(oRe(i.current)),i.current=null)},[n]),null}function v4(t){var{legendPayload:e}=t,n=zr(),r=aa(),i=_.useRef(null);return _.useLayoutEffect(()=>{r||(i.current===null?n(nQ(e)):i.current!==e&&n(rQ({prev:i.current,next:e})),i.current=e)},[n,r,e]),_.useLayoutEffect(()=>()=>{i.current&&(n(iQ(i.current)),i.current=null)},[n]),null}function X4e(t){var{legendPayload:e}=t,n=zr(),r=Ht(Kn),i=_.useRef(null);return _.useLayoutEffect(()=>{r!=="centric"&&r!=="radial"||(i.current===null?n(nQ(e)):i.current!==e&&n(rQ({prev:i.current,next:e})),i.current=e)},[n,r,e]),_.useLayoutEffect(()=>()=>{i.current&&(n(iQ(i.current)),i.current=null)},[n]),null}var oP,Y4e=()=>{var[t]=_.useState(()=>uy("uid-"));return t},Q4e=(oP=tse.useId)!==null&&oP!==void 0?oP:Y4e;function zJ(t,e){var n=Q4e();return e||(t?"".concat(t,"-").concat(n):n)}var Z4e=_.createContext(void 0),TM=t=>{var{id:e,type:n,children:r}=t,i=zJ("recharts-".concat(n),e);return _.createElement(Z4e.Provider,{value:i},r(i))},J4e={cartesianItems:[],polarItems:[]},UJ=Qs({name:"graphicalItems",initialState:J4e,reducers:{addCartesianGraphicalItem:{reducer(t,e){t.cartesianItems.push(e.payload)},prepare:Jr()},replaceCartesianGraphicalItem:{reducer(t,e){var{prev:n,next:r}=e.payload,i=Il(t).cartesianItems.indexOf(n);i>-1&&(t.cartesianItems[i]=r)},prepare:Jr()},removeCartesianGraphicalItem:{reducer(t,e){var n=Il(t).cartesianItems.indexOf(e.payload);n>-1&&t.cartesianItems.splice(n,1)},prepare:Jr()},addPolarGraphicalItem:{reducer(t,e){t.polarItems.push(e.payload)},prepare:Jr()},removePolarGraphicalItem:{reducer(t,e){var n=Il(t).polarItems.indexOf(e.payload);n>-1&&t.polarItems.splice(n,1)},prepare:Jr()}}}),{addCartesianGraphicalItem:eFe,replaceCartesianGraphicalItem:tFe,removeCartesianGraphicalItem:nFe,addPolarGraphicalItem:rFe,removePolarGraphicalItem:iFe}=UJ.actions,aFe=UJ.reducer,sFe=t=>{var e=zr(),n=_.useRef(null);return _.useLayoutEffect(()=>{n.current===null?e(eFe(t)):n.current!==t&&e(tFe({prev:n.current,next:t})),n.current=t},[e,t]),_.useLayoutEffect(()=>()=>{n.current&&(e(nFe(n.current)),n.current=null)},[e]),null},w4=_.memo(sFe);function oFe(t){var e=zr();return _.useLayoutEffect(()=>(e(rFe(t)),()=>{e(iFe(t))}),[e,t]),null}var lFe=["key"],cFe=["onMouseEnter","onClick","onMouseLeave"],uFe=["id"],dFe=["id"];function JG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function gi(t){for(var e=1;em4(t.children,yv),[t.children]),n=Ht(r=>M4e(r,t.id,e));return n==null?null:_.createElement(X4e,{legendPayload:n})}var bFe=_.memo(t=>{var{dataKey:e,nameKey:n,sectors:r,stroke:i,strokeWidth:s,fill:o,name:l,hide:c,tooltipType:u}=t,d={dataDefinedOnItem:r.map(h=>h.tooltipPayload),positions:r.map(h=>h.tooltipPosition),settings:{stroke:i,strokeWidth:s,fill:o,dataKey:e,nameKey:n,name:Hh(l,e),hide:c,type:u,color:o,unit:""}};return _.createElement(EM,{tooltipEntrySettings:d})}),xFe=(t,e)=>t>e?"start":tas(typeof e=="function"?e(t):e,n,n*.8),vFe=(t,e,n)=>{var{top:r,left:i,width:s,height:o}=e,l=dQ(s,o),c=i+as(t.cx,s,s/2),u=r+as(t.cy,o,o/2),d=as(t.innerRadius,l,0),h=yFe(n,t.outerRadius,l),p=t.maxRadius||Math.sqrt(s*s+o*o)/2;return{cx:c,cy:u,innerRadius:d,outerRadius:h,maxRadius:p}},wFe=(t,e)=>{var n=wa(e-t),r=Math.min(Math.abs(e-t),360);return n*r};function _Fe(t){return t&&typeof t=="object"&&"className"in t&&typeof t.className=="string"?t.className:""}var SFe=(t,e)=>{if(_.isValidElement(t))return _.cloneElement(t,e);if(typeof t=="function")return t(e);var n=nr("recharts-pie-label-line",typeof t!="boolean"?t.className:""),{key:r}=e,i=AM(e,lFe);return _.createElement(Lg,zh({},i,{type:"linear",className:n}))},NFe=(t,e,n)=>{if(_.isValidElement(t))return _.cloneElement(t,e);var r=n;if(typeof t=="function"&&(r=t(e),_.isValidElement(r)))return r;var i=nr("recharts-pie-label-text",_Fe(t));return _.createElement(SM,zh({},e,{alignmentBaseline:"middle",className:i}),r)};function kFe(t){var{sectors:e,props:n,showLabels:r}=t,{label:i,labelLine:s,dataKey:o}=n;if(!r||!i||!e)return null;var l=Ms(n),c=vm(i),u=vm(s),d=typeof i=="object"&&"offsetRadius"in i&&typeof i.offsetRadius=="number"&&i.offsetRadius||20,h=e.map((p,m)=>{var b=(p.startAngle+p.endAngle)/2,y=Bi(p.cx,p.cy,p.outerRadius+d,b),x=gi(gi(gi(gi({},l),p),{},{stroke:"none"},c),{},{index:m,textAnchor:xFe(y.x,p.cx)},y),v=gi(gi(gi(gi({},l),p),{},{fill:"none",stroke:p.fill},u),{},{index:m,points:[Bi(p.cx,p.cy,p.outerRadius,b),y],key:"line"});return _.createElement(ls,{zIndex:vi.label,key:"label-".concat(p.startAngle,"-").concat(p.endAngle,"-").concat(p.midAngle,"-").concat(m)},_.createElement(li,null,s&&SFe(s,v),NFe(i,x,vr(p,o))))});return _.createElement(li,{className:"recharts-pie-labels"},h)}function MFe(t){var{sectors:e,props:n,showLabels:r}=t,{label:i}=n;return typeof i=="object"&&i!=null&&"position"in i?_.createElement(NM,{label:i}):_.createElement(kFe,{sectors:e,props:n,showLabels:r})}function EFe(t){var{sectors:e,activeShape:n,inactiveShape:r,allOtherPieProps:i,shape:s,id:o}=t,l=Ht(Ih),c=Ht(a4),u=Ht(XRe),{onMouseEnter:d,onClick:h,onMouseLeave:p}=i,m=AM(i,cFe),b=b4(d,i.dataKey,o),y=x4(p),x=y4(h,i.dataKey,o);return e==null||e.length===0?null:_.createElement(_.Fragment,null,e.map((v,S)=>{if(v?.startAngle===0&&v?.endAngle===0&&e.length!==1)return null;var N=u==null||u===o,T=String(S)===l&&(c==null||i.dataKey===c)&&N,M=l?r:null,A=n&&T?n:M,k=gi(gi({},v),{},{stroke:v.stroke,tabIndex:-1,[HY]:S,[$Y]:i.dataKey});return _.createElement(li,zh({key:"sector-".concat(v?.startAngle,"-").concat(v?.endAngle,"-").concat(v.midAngle,"-").concat(S),tabIndex:-1,className:"recharts-pie-sector"},Yy(m,v,S),{onMouseEnter:b(v,S),onMouseLeave:y(v,S),onClick:x(v,S)}),_.createElement(g4,zh({option:s??A,index:S,shapeType:"sector",isActive:T},k)))}))}function TFe(t){var e,{pieSettings:n,displayedData:r,cells:i,offset:s}=t,{cornerRadius:o,startAngle:l,endAngle:c,dataKey:u,nameKey:d,tooltipType:h}=n,p=Math.abs(n.minAngle),m=wFe(l,c),b=Math.abs(m),y=r.length<=1?0:(e=n.paddingAngle)!==null&&e!==void 0?e:0,x=r.filter(A=>vr(A,u,0)!==0).length,v=(b>=360?x:x-1)*y,S=b-x*p-v,N=r.reduce((A,k)=>{var R=vr(k,u,0);return A+(Vt(R)?R:0)},0),T;if(N>0){var M;T=r.map((A,k)=>{var R=vr(A,u,0),C=vr(A,d,k),P=vFe(n,s,A),U=(Vt(R)?R:0)/N,F,H=gi(gi({},A),i&&i[k]&&i[k].props);k?F=M.endAngle+wa(m)*y*(R!==0?1:0):F=l;var D=F+wa(m)*((R!==0?p:0)+U*S),$=(F+D)/2,G=(P.innerRadius+P.outerRadius)/2,I=[{name:C,value:R,payload:H,dataKey:u,type:h}],K=Bi(P.cx,P.cy,G,$);return M=gi(gi(gi(gi({},n.presentationProps),{},{percent:U,cornerRadius:typeof o=="string"?parseFloat(o):o,name:C,tooltipPayload:I,midAngle:$,middleRadius:G,tooltipPosition:K},H),P),{},{value:R,dataKey:u,startAngle:F,endAngle:D,payload:H,paddingAngle:wa(m)*y}),M})}return T}function AFe(t){var{showLabels:e,sectors:n,children:r}=t,i=_.useMemo(()=>!e||!n?[]:n.map(s=>({value:s.value,payload:s.payload,clockWise:!1,parentViewBox:void 0,viewBox:{cx:s.cx,cy:s.cy,innerRadius:s.innerRadius,outerRadius:s.outerRadius,startAngle:s.startAngle,endAngle:s.endAngle,clockWise:!1},fill:s.fill})),[n,e]);return _.createElement(u4e,{value:e?i:void 0},r)}function CFe(t){var{props:e,previousSectorsRef:n,id:r}=t,{sectors:i,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,activeShape:u,inactiveShape:d,onAnimationStart:h,onAnimationEnd:p}=e,m=Pb(e,"recharts-pie-"),b=n.current,[y,x]=_.useState(!1),v=_.useCallback(()=>{typeof p=="function"&&p(),x(!1)},[p]),S=_.useCallback(()=>{typeof h=="function"&&h(),x(!0)},[h]);return _.createElement(AFe,{showLabels:!y,sectors:i},_.createElement(Cb,{animationId:m,begin:o,duration:l,isActive:s,easing:c,onAnimationStart:S,onAnimationEnd:v,key:m},N=>{var T=[],M=i&&i[0],A=M?.startAngle;return i?.forEach((k,R)=>{var C=b&&b[R],P=R>0?wm(k,"paddingAngle",0):0;if(C){var U=pr(C.endAngle-C.startAngle,k.endAngle-k.startAngle,N),F=gi(gi({},k),{},{startAngle:A+P,endAngle:A+U+P});T.push(F),A=F.endAngle}else{var{endAngle:H,startAngle:D}=k,$=pr(0,H-D,N),G=gi(gi({},k),{},{startAngle:A+P,endAngle:A+$+P});T.push(G),A=G.endAngle}}),n.current=T,_.createElement(li,null,_.createElement(EFe,{sectors:T,activeShape:u,inactiveShape:d,allOtherPieProps:e,shape:e.shape,id:r}))}),_.createElement(MFe,{showLabels:!y,sectors:i,props:e}),e.children)}var PFe={animationBegin:400,animationDuration:1500,animationEasing:"ease",cx:"50%",cy:"50%",dataKey:"value",endAngle:360,fill:"#808080",hide:!1,innerRadius:0,isAnimationActive:"auto",label:!1,labelLine:!0,legendType:"rect",minAngle:0,nameKey:"name",outerRadius:"80%",paddingAngle:0,rootTabIndex:0,startAngle:0,stroke:"#fff",zIndex:vi.area};function jFe(t){var{id:e}=t,n=AM(t,uFe),{hide:r,className:i,rootTabIndex:s}=t,o=_.useMemo(()=>m4(t.children,yv),[t.children]),l=Ht(d=>E4e(d,e,o)),c=_.useRef(null),u=nr("recharts-pie",i);return r||l==null?(c.current=null,_.createElement(li,{tabIndex:s,className:u})):_.createElement(ls,{zIndex:t.zIndex},_.createElement(bFe,{dataKey:t.dataKey,nameKey:t.nameKey,sectors:l,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,tooltipType:t.tooltipType}),_.createElement(li,{tabIndex:s,className:u},_.createElement(CFe,{props:gi(gi({},n),{},{sectors:l}),previousSectorsRef:c,id:e})))}function BJ(t){var e=ci(t,PFe),{id:n}=e,r=AM(e,dFe),i=Ms(r);return _.createElement(TM,{id:n,type:"pie"},s=>_.createElement(_.Fragment,null,_.createElement(oFe,{type:"pie",id:s,data:r.data,dataKey:r.dataKey,hide:r.hide,angleAxisId:0,radiusAxisId:0,name:r.name,nameKey:r.nameKey,tooltipType:r.tooltipType,legendType:r.legendType,fill:r.fill,cx:r.cx,cy:r.cy,startAngle:r.startAngle,endAngle:r.endAngle,paddingAngle:r.paddingAngle,minAngle:r.minAngle,innerRadius:r.innerRadius,outerRadius:r.outerRadius,cornerRadius:r.cornerRadius,presentationProps:i,maxRadius:e.maxRadius}),_.createElement(gFe,zh({},r,{id:s})),_.createElement(jFe,zh({},r,{id:s}))))}BJ.displayName="Pie";var DFe=["points"];function eq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function lP(t){for(var e=1;e{var x,v,S=lP(lP(lP({r:3},o),h),{},{index:y,cx:(x=b.x)!==null&&x!==void 0?x:void 0,cy:(v=b.y)!==null&&v!==void 0?v:void 0,dataKey:s,value:b.value,payload:b.payload,points:e});return _.createElement(zFe,{key:"dot-".concat(y),option:n,dotProps:S,className:i})}),m={};return l&&c!=null&&(m.clipPath="url(#clipPath-".concat(d?"":"dots-").concat(c,")")),_.createElement(ls,{zIndex:u},_.createElement(li,nN({className:r},m),p))}function tq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function nq(t){for(var e=1;e({top:t.top,bottom:t.bottom,left:t.left,right:t.right})),eIe=st([JFe,ed,td],(t,e,n)=>{if(!(!t||e==null||n==null))return{x:t.left,y:t.top,width:Math.max(0,e-t.left-t.right),height:Math.max(0,n-t.top-t.bottom)}}),CM=()=>Ht(eIe),tIe=()=>Ht(eOe);function rq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function cP(t){for(var e=1;e{var{point:e,childIndex:n,mainColor:r,activeDot:i,dataKey:s,clipPath:o}=t;if(i===!1||e.x==null||e.y==null)return null;var l={index:n,dataKey:s,cx:e.x,cy:e.y,r:4,fill:r??"none",strokeWidth:2,stroke:"#fff",payload:e.payload,value:e.value},c=cP(cP(cP({},l),vm(i)),FO(i)),u;return _.isValidElement(i)?u=_.cloneElement(i,c):typeof i=="function"?u=i(c):u=_.createElement(DJ,c),_.createElement(li,{className:"recharts-active-dot",clipPath:o},u)};function jD(t){var{points:e,mainColor:n,activeDot:r,itemDataKey:i,clipPath:s,zIndex:o=vi.activeDot}=t,l=Ht(Ih),c=tIe();if(e==null||c==null)return null;var u=e.find(d=>c.includes(d.payload));return Yr(u)?null:_.createElement(ls,{zIndex:o},_.createElement(aIe,{point:u,childIndex:Number(l),mainColor:n,dataKey:i,activeDot:r,clipPath:s}))}var sIe="Invariant failed";function oIe(t,e){throw new Error(sIe)}var lIe=["x","y"];function DD(){return DD=Object.assign?Object.assign.bind():function(t){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:0;return(r,i)=>{if(Vt(e))return e;var s=Vt(r)||Yr(r);return s?e(r,i):(s||oIe(),n)}},gIe={},VJ=Qs({name:"errorBars",initialState:gIe,reducers:{addErrorBar:(t,e)=>{var{itemId:n,errorBar:r}=e.payload;t[n]||(t[n]=[]),t[n].push(r)},replaceErrorBar:(t,e)=>{var{itemId:n,prev:r,next:i}=e.payload;t[n]&&(t[n]=t[n].map(s=>s.dataKey===r.dataKey&&s.direction===r.direction?i:s))},removeErrorBar:(t,e)=>{var{itemId:n,errorBar:r}=e.payload;t[n]&&(t[n]=t[n].filter(i=>i.dataKey!==r.dataKey||i.direction!==r.direction))}}}),{addErrorBar:SQe,replaceErrorBar:NQe,removeErrorBar:kQe}=VJ.actions,bIe=VJ.reducer,xIe=["children"];function yIe(t,e){if(t==null)return{};var n,r,i=vIe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r({x:0,y:0,value:0}),errorBarOffset:0},_Ie=_.createContext(wIe);function GJ(t){var{children:e}=t,n=yIe(t,xIe);return _.createElement(_Ie.Provider,{value:n},e)}function PM(t,e){var n,r,i=Ht(u=>Ac(u,t)),s=Ht(u=>Cc(u,e)),o=(n=i?.allowDataOverflow)!==null&&n!==void 0?n:ga.allowDataOverflow,l=(r=s?.allowDataOverflow)!==null&&r!==void 0?r:ba.allowDataOverflow,c=o||l;return{needClip:c,needClipX:o,needClipY:l}}function _4(t){var{xAxisId:e,yAxisId:n,clipPathId:r}=t,i=CM(),{needClipX:s,needClipY:o,needClip:l}=PM(e,n);if(!l||!i)return null;var{x:c,y:u,width:d,height:h}=i;return _.createElement("clipPath",{id:"clipPath-".concat(r)},_.createElement("rect",{x:s?c:c-d/2,y:o?u:u-h/2,width:s?d:d*2,height:o?h:h*2}))}function SIe(t,e){return t&&typeof t=="object"&&"zIndex"in t&&typeof t.zIndex=="number"&&wr(t.zIndex)?t.zIndex:e}var uP={exports:{}},dP={};var aq;function NIe(){if(aq)return dP;aq=1;var t=yb();function e(c,u){return c===u&&(c!==0||1/c===1/u)||c!==c&&u!==u}var n=typeof Object.is=="function"?Object.is:e,r=t.useSyncExternalStore,i=t.useRef,s=t.useEffect,o=t.useMemo,l=t.useDebugValue;return dP.useSyncExternalStoreWithSelector=function(c,u,d,h,p){var m=i(null);if(m.current===null){var b={hasValue:!1,value:null};m.current=b}else b=m.current;m=o(function(){function x(M){if(!v){if(v=!0,S=M,M=h(M),p!==void 0&&b.hasValue){var A=b.value;if(p(A,M))return N=A}return N=M}if(A=N,n(S,M))return A;var k=h(M);return p!==void 0&&p(A,k)?(S=M,A):(S=M,N=k)}var v=!1,S,N,T=d===void 0?null:d;return[function(){return x(u())},T===null?void 0:function(){return x(T())}]},[u,d,h,p]);var y=r(c,m[0],m[1]);return s(function(){b.hasValue=!0,b.value=y},[y]),l(y),y},dP}var sq;function kIe(){return sq||(sq=1,uP.exports=NIe()),uP.exports}kIe();function MIe(t){t()}function EIe(){let t=null,e=null;return{clear(){t=null,e=null},notify(){MIe(()=>{let n=t;for(;n;)n.callback(),n=n.next})},get(){const n=[];let r=t;for(;r;)n.push(r),r=r.next;return n},subscribe(n){let r=!0;const i=e={callback:n,next:null,prev:e};return i.prev?i.prev.next=i:t=i,function(){!r||t===null||(r=!1,i.next?i.next.prev=i.prev:e=i.prev,i.prev?i.prev.next=i.next:t=i.next)}}}}var oq={notify(){},get:()=>[]};function TIe(t,e){let n,r=oq,i=0,s=!1;function o(y){d();const x=r.subscribe(y);let v=!1;return()=>{v||(v=!0,x(),h())}}function l(){r.notify()}function c(){b.onStateChange&&b.onStateChange()}function u(){return s}function d(){i++,n||(n=t.subscribe(c),r=EIe())}function h(){i--,n&&i===0&&(n(),n=void 0,r.clear(),r=oq)}function p(){s||(s=!0,d())}function m(){s&&(s=!1,h())}const b={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:u,trySubscribe:p,tryUnsubscribe:m,getListeners:()=>r};return b}var AIe=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",CIe=AIe(),PIe=()=>typeof navigator<"u"&&navigator.product==="ReactNative",jIe=PIe(),DIe=()=>CIe||jIe?_.useLayoutEffect:_.useEffect,RIe=DIe();function lq(t,e){return t===e?t!==0||e!==0||1/t===1/e:t!==t&&e!==e}function OIe(t,e){if(lq(t,e))return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(let i=0;i{const c=TIe(i);return{store:i,subscription:c,getServerState:r?()=>r:void 0}},[i,r]),o=_.useMemo(()=>i.getState(),[i]);RIe(()=>{const{subscription:c}=s;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),o!==i.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[s,o]);const l=n||zIe;return _.createElement(l.Provider,{value:s},e)}var BIe=UIe,HIe=new Set(["axisLine","tickLine","activeBar","activeDot","activeLabel","activeShape","allowEscapeViewBox","background","cursor","dot","label","line","margin","padding","position","shape","style","tick","wrapperStyle"]);function $Ie(t,e){return t==null&&e==null?!0:typeof t=="number"&&typeof e=="number"?t===e||t!==t&&e!==e:t===e}function vv(t,e){var n=new Set([...Object.keys(t),...Object.keys(e)]);for(var r of n)if(HIe.has(r)){if(t[r]==null&&e[r]==null)continue;if(!OIe(t[r],e[r]))return!1}else if(!$Ie(t[r],e[r]))return!1;return!0}var VIe=["onMouseEnter","onMouseLeave","onClick"],GIe=["value","background","tooltipPosition"],qIe=["id"],WIe=["onMouseEnter","onClick","onMouseLeave"];function Zu(){return Zu=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{dataKey:e,name:n,fill:r,legendType:i,hide:s}=t;return[{inactive:s,dataKey:e,type:i,color:r,value:Hh(n,e),payload:t}]},JIe=_.memo(t=>{var{dataKey:e,stroke:n,strokeWidth:r,fill:i,name:s,hide:o,unit:l,tooltipType:c}=t,u={dataDefinedOnItem:void 0,positions:void 0,settings:{stroke:n,strokeWidth:r,fill:i,dataKey:e,nameKey:void 0,name:Hh(s,e),hide:o,type:c,color:i,unit:l}};return _.createElement(EM,{tooltipEntrySettings:u})});function e5e(t){var e=Ht(Ih),{data:n,dataKey:r,background:i,allOtherBarProps:s}=t,{onMouseEnter:o,onMouseLeave:l,onClick:c}=s,u=iN(s,VIe),d=b4(o,r),h=x4(l),p=y4(c,r);if(!i||n==null)return null;var m=vm(i);return _.createElement(ls,{zIndex:SIe(i,vi.barBackground)},n.map((b,y)=>{var{value:x,background:v,tooltipPosition:S}=b,N=iN(b,GIe);if(!v)return null;var T=d(b,y),M=h(b,y),A=p(b,y),k=xs(xs(xs(xs(xs({option:i,isActive:String(y)===e},N),{},{fill:"#eee"},v),m),Yy(u,b,y)),{},{onMouseEnter:T,onMouseLeave:M,onClick:A,dataKey:r,index:y,className:"recharts-bar-background-rectangle"});return _.createElement(rN,Zu({key:"background-bar-".concat(y)},k))}))}function t5e(t){var{showLabels:e,children:n,rects:r}=t,i=r?.map(s=>{var o={x:s.x,y:s.y,width:s.width,lowerWidth:s.width,upperWidth:s.width,height:s.height};return xs(xs({},o),{},{value:s.value,payload:s.payload,parentViewBox:s.parentViewBox,viewBox:o,fill:s.fill})});return _.createElement(d4,{value:e?i:void 0},n)}function n5e(t){var{shape:e,activeBar:n,baseProps:r,entry:i,index:s,dataKey:o}=t,l=Ht(Ih),c=Ht(a4),u=n&&String(s)===l&&(c==null||o===c),d=u?n:e;return u?_.createElement(ls,{zIndex:vi.activeBar},_.createElement(rN,Zu({},r,{name:String(r.name)},i,{isActive:u,option:d,index:s,dataKey:o}))):_.createElement(rN,Zu({},r,{name:String(r.name)},i,{isActive:u,option:d,index:s,dataKey:o}))}function r5e(t){var{shape:e,baseProps:n,entry:r,index:i,dataKey:s}=t;return _.createElement(rN,Zu({},n,{name:String(n.name)},r,{isActive:!1,option:e,index:i,dataKey:s}))}function i5e(t){var e,{data:n,props:r}=t,i=(e=Ms(r))!==null&&e!==void 0?e:{},{id:s}=i,o=iN(i,qIe),{shape:l,dataKey:c,activeBar:u}=r,{onMouseEnter:d,onClick:h,onMouseLeave:p}=r,m=iN(r,WIe),b=b4(d,c),y=x4(p),x=y4(h,c);return n?_.createElement(_.Fragment,null,n.map((v,S)=>_.createElement(li,Zu({key:"rectangle-".concat(v?.x,"-").concat(v?.y,"-").concat(v?.value,"-").concat(S),className:"recharts-bar-rectangle"},Yy(m,v,S),{onMouseEnter:b(v,S),onMouseLeave:y(v,S),onClick:x(v,S)}),u?_.createElement(n5e,{shape:l,activeBar:u,baseProps:o,entry:v,index:S,dataKey:c}):_.createElement(r5e,{shape:l,baseProps:o,entry:v,index:S,dataKey:c})))):null}function a5e(t){var{props:e,previousRectanglesRef:n}=t,{data:r,layout:i,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,onAnimationEnd:u,onAnimationStart:d}=e,h=n.current,p=Pb(e,"recharts-bar-"),[m,b]=_.useState(!1),y=!m,x=_.useCallback(()=>{typeof u=="function"&&u(),b(!1)},[u]),v=_.useCallback(()=>{typeof d=="function"&&d(),b(!0)},[d]);return _.createElement(t5e,{showLabels:y,rects:r},_.createElement(Cb,{animationId:p,begin:o,duration:l,isActive:s,easing:c,onAnimationEnd:x,onAnimationStart:v,key:p},S=>{var N=S===1?r:r?.map((T,M)=>{var A=h&&h[M];if(A)return xs(xs({},T),{},{x:pr(A.x,T.x,S),y:pr(A.y,T.y,S),width:pr(A.width,T.width,S),height:pr(A.height,T.height,S)});if(i==="horizontal"){var k=pr(0,T.height,S),R=pr(T.stackedBarStart,T.y,S);return xs(xs({},T),{},{y:R,height:k})}var C=pr(0,T.width,S),P=pr(T.stackedBarStart,T.x,S);return xs(xs({},T),{},{width:C,x:P})});return S>0&&(n.current=N??null),N==null?null:_.createElement(li,null,_.createElement(i5e,{props:e,data:N}))}),_.createElement(NM,{label:e.label}),e.children)}function s5e(t){var e=_.useRef(null);return _.createElement(a5e,{previousRectanglesRef:e,props:t})}var qJ=0,o5e=(t,e)=>{var n=Array.isArray(t.value)?t.value[1]:t.value;return{x:t.x,y:t.y,value:n,errorVal:vr(t,e)}};class l5e extends _.PureComponent{render(){var{hide:e,data:n,dataKey:r,className:i,xAxisId:s,yAxisId:o,needClip:l,background:c,id:u}=this.props;if(e||n==null)return null;var d=nr("recharts-bar",i),h=u;return _.createElement(li,{className:d,id:u},l&&_.createElement("defs",null,_.createElement(_4,{clipPathId:h,xAxisId:s,yAxisId:o})),_.createElement(li,{className:"recharts-bar-rectangles",clipPath:l?"url(#clipPath-".concat(h,")"):void 0},_.createElement(e5e,{data:n,dataKey:r,background:c,allOtherBarProps:this.props}),_.createElement(s5e,this.props)))}}var c5e={activeBar:!1,animationBegin:0,animationDuration:400,animationEasing:"ease",background:!1,hide:!1,isAnimationActive:"auto",label:!1,legendType:"rect",minPointSize:qJ,xAxisId:0,yAxisId:0,zIndex:vi.bar};function u5e(t){var{xAxisId:e,yAxisId:n,hide:r,legendType:i,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:u,isAnimationActive:d}=t,{needClip:h}=PM(e,n),p=Lm(),m=aa(),b=m4(t.children,yv),y=Ht(S=>I5e(S,e,n,m,t.id,b));if(p!=="vertical"&&p!=="horizontal")return null;var x,v=y?.[0];return v==null||v.height==null||v.width==null?x=0:x=p==="vertical"?v.height/2:v.width/2,_.createElement(GJ,{xAxisId:e,yAxisId:n,data:y,dataPointFormatter:o5e,errorBarOffset:x},_.createElement(l5e,Zu({},t,{layout:p,needClip:h,data:y,xAxisId:e,yAxisId:n,hide:r,legendType:i,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:u,isAnimationActive:d})))}function d5e(t){var{layout:e,barSettings:{dataKey:n,minPointSize:r},pos:i,bandSize:s,xAxis:o,yAxis:l,xAxisTicks:c,yAxisTicks:u,stackedData:d,displayedData:h,offset:p,cells:m,parentViewBox:b,dataStartIndex:y}=t,x=e==="horizontal"?l:o,v=d?x.scale.domain():null,S=RTe({numericAxis:x}),N=x.scale(S);return h.map((T,M)=>{var A,k,R,C,P,U;d?A=ATe(d[M+y],v):(A=vr(T,n),Array.isArray(A)||(A=[S,A]));var F=pIe(r,qJ)(A[1],M);if(e==="horizontal"){var H,[D,$]=[l.scale(A[0]),l.scale(A[1])];k=M$({axis:o,ticks:c,bandSize:s,offset:i.offset,entry:T,index:M}),R=(H=$??D)!==null&&H!==void 0?H:void 0,C=i.size;var G=D-$;if(P=Ys(G)?0:G,U={x:k,y:p.top,width:C,height:p.height},Math.abs(F)>0&&Math.abs(P)0&&Math.abs(C)_.createElement(_.Fragment,null,_.createElement(v4,{legendPayload:ZIe(e)}),_.createElement(JIe,{dataKey:e.dataKey,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType}),_.createElement(w4,{type:"bar",id:r,data:void 0,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,stackId:UY(e.stackId),hide:e.hide,barSize:e.barSize,minPointSize:e.minPointSize,maxBarSize:e.maxBarSize,isPanorama:n}),_.createElement(ls,{zIndex:e.zIndex},_.createElement(u5e,Zu({},e,{id:r})))))}var WJ=_.memo(h5e,vv);WJ.displayName="Bar";function uq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function n1(t){for(var e=1;ee,b5e=(t,e,n)=>n,x5e=(t,e,n,r)=>r,y5e=(t,e,n,r,i)=>i,wv=st([dv,y5e],(t,e)=>t.filter(n=>n.type==="bar").find(n=>n.id===e)),v5e=st([wv],t=>t?.maxBarSize),w5e=(t,e,n,r,i,s)=>s,dq=(t,e,n)=>{var r=n??t;if(!Yr(r))return as(r,e,0)},_5e=st([Kn,dv,g5e,b5e,x5e],(t,e,n,r,i)=>e.filter(s=>t==="horizontal"?s.xAxisId===n:s.yAxisId===r).filter(s=>s.isPanorama===i).filter(s=>s.hide===!1).filter(s=>s.type==="bar")),S5e=(t,e,n,r)=>{var i=Kn(t);return i==="horizontal"?Sy(t,"yAxis",n,r):Sy(t,"xAxis",e,r)},N5e=(t,e,n)=>{var r=Kn(t);return r==="horizontal"?aG(t,"xAxis",e):aG(t,"yAxis",n)},k5e=(t,e,n)=>{var r={},i=t.filter(pM),s=t.filter(u=>u.stackId==null),o=i.reduce((u,d)=>(u[d.stackId]||(u[d.stackId]=[]),u[d.stackId].push(d),u),r),l=Object.entries(o).map(u=>{var[d,h]=u,p=h.map(b=>b.dataKey),m=dq(e,n,h[0].barSize);return{stackId:d,dataKeys:p,barSize:m}}),c=s.map(u=>{var d=[u.dataKey].filter(p=>p!=null),h=dq(e,n,u.barSize);return{stackId:void 0,dataKeys:d,barSize:h}});return[...l,...c]},M5e=st([_5e,Q3e,N5e],k5e),E5e=(t,e,n,r,i)=>{var s,o,l=wv(t,e,n,r,i);if(l!=null){var c=Kn(t),u=uZ(t),{maxBarSize:d}=l,h=Yr(d)?u:d,p,m;return c==="horizontal"?(p=_c(t,"xAxis",e,r),m=wc(t,"xAxis",e,r)):(p=_c(t,"yAxis",n,r),m=wc(t,"yAxis",n,r)),(s=(o=Oh(p,m,!0))!==null&&o!==void 0?o:h)!==null&&s!==void 0?s:0}},KJ=(t,e,n,r)=>{var i=Kn(t),s,o;return i==="horizontal"?(s=_c(t,"xAxis",e,r),o=wc(t,"xAxis",e,r)):(s=_c(t,"yAxis",n,r),o=wc(t,"yAxis",n,r)),Oh(s,o)};function T5e(t,e,n,r,i){var s=r.length;if(!(s<1)){var o=as(t,n,0,!0),l,c=[];if(wr(r[0].barSize)){var u=!1,d=n/s,h=r.reduce((v,S)=>v+(S.barSize||0),0);h+=(s-1)*o,h>=n&&(h-=(s-1)*o,o=0),h>=n&&d>0&&(u=!0,d*=.9,h=s*d);var p=(n-h)/2>>0,m={offset:p-o,size:0};l=r.reduce((v,S)=>{var N,T={stackId:S.stackId,dataKeys:S.dataKeys,position:{offset:m.offset+m.size+o,size:u?d:(N=S.barSize)!==null&&N!==void 0?N:0}},M=[...v,T];return m=M[M.length-1].position,M},c)}else{var b=as(e,n,0,!0);n-2*b-(s-1)*o<=0&&(o=0);var y=(n-2*b-(s-1)*o)/s;y>1&&(y>>=0);var x=wr(i)?Math.min(y,i):y;l=r.reduce((v,S,N)=>[...v,{stackId:S.stackId,dataKeys:S.dataKeys,position:{offset:b+(y+o)*N+(y-x)/2,size:x}}],c)}return l}}var A5e=(t,e,n,r,i,s,o)=>{var l=Yr(o)?e:o,c=T5e(n,r,i!==s?i:s,t,l);return i!==s&&c!=null&&(c=c.map(u=>n1(n1({},u),{},{position:n1(n1({},u.position),{},{offset:u.position.offset-i/2})}))),c},C5e=st([M5e,uZ,Y3e,dZ,E5e,KJ,v5e],A5e),P5e=(t,e,n,r)=>_c(t,"xAxis",e,r),j5e=(t,e,n,r)=>_c(t,"yAxis",n,r),D5e=(t,e,n,r)=>wc(t,"xAxis",e,r),R5e=(t,e,n,r)=>wc(t,"yAxis",n,r),O5e=st([C5e,wv],(t,e)=>{if(!(t==null||e==null)){var n=t.find(r=>r.stackId===e.stackId&&e.dataKey!=null&&r.dataKeys.includes(e.dataKey));if(n!=null)return n.position}}),L5e=(t,e)=>{var n=mM(e);if(!(!t||n==null||e==null)){var{stackId:r}=e;if(r!=null){var i=t[r];if(i){var{stackedData:s}=i;if(s)return s.find(o=>o.key===n)}}}},F5e=st([S5e,wv],L5e),I5e=st([ia,KO,P5e,j5e,D5e,R5e,O5e,Kn,ov,KJ,F5e,wv,w5e],(t,e,n,r,i,s,o,l,c,u,d,h,p)=>{var{chartData:m,dataStartIndex:b,dataEndIndex:y}=c;if(!(h==null||o==null||e==null||l!=="horizontal"&&l!=="vertical"||n==null||r==null||i==null||s==null||u==null)){var{data:x}=h,v;if(x!=null&&x.length>0?v=x:v=m?.slice(b,y+1),v!=null)return d5e({layout:l,barSettings:h,pos:o,parentViewBox:e,bandSize:u,xAxis:n,yAxis:r,xAxisTicks:i,yAxisTicks:s,stackedData:d,displayedData:v,offset:t,cells:p,dataStartIndex:b})}}),XJ=t=>{var{chartData:e}=t,n=zr(),r=aa();return _.useEffect(()=>r?()=>{}:(n(xG(e)),()=>{n(xG(void 0))}),[e,n,r]),null},hq={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},YJ=Qs({name:"brush",initialState:hq,reducers:{setBrushSettings(t,e){return e.payload==null?hq:e.payload}}}),{setBrushSettings:MQe}=YJ.actions,z5e=YJ.reducer;function fq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function r1(t){for(var e=1;e{var{x:n,y:r}=t,{x:i,y:s}=e;return{x:Math.min(n,i),y:Math.min(r,s),width:Math.abs(i-n),height:Math.abs(s-r)}},$5e=t=>{var{x1:e,y1:n,x2:r,y2:i}=t;return H5e({x:e,y:n},{x:r,y:i})};class jM{static create(e){return new jM(e)}constructor(e){this.scale=e}get domain(){return this.scale.domain}get range(){return this.scale.range}get rangeMin(){return this.range()[0]}get rangeMax(){return this.range()[1]}get bandwidth(){return this.scale.bandwidth}apply(e){var{bandAware:n,position:r}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(e!==void 0){if(r)switch(r){case"start":return this.scale(e);case"middle":{var i=this.bandwidth?this.bandwidth()/2:0;return this.scale(e)+i}case"end":{var s=this.bandwidth?this.bandwidth():0;return this.scale(e)+s}default:return this.scale(e)}if(n){var o=this.bandwidth?this.bandwidth()/2:0;return this.scale(e)+o}return this.scale(e)}}isInRange(e){var n=this.range(),r=n[0],i=n[n.length-1];return r<=i?e>=r&&e<=i:e>=i&&e<=r}}QJ(jM,"EPS",1e-4);var V5e=t=>{var e=Object.keys(t).reduce((n,r)=>r1(r1({},n),{},{[r]:jM.create(t[r])}),{});return r1(r1({},e),{},{apply(n){var{bandAware:r,position:i}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Object.fromEntries(Object.entries(n).map(s=>{var[o,l]=s;return[o,e[o].apply(l,{bandAware:r,position:i})]}))},isInRange(n){return Object.keys(n).every(r=>e[r].isInRange(n[r]))}})};function G5e(t){return(t%180+180)%180}var q5e=function(e){var{width:n,height:r}=e,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,s=G5e(i),o=s*Math.PI/180,l=Math.atan(r/n),c=o>l&&o{t.dots.push(e.payload)},removeDot:(t,e)=>{var n=Il(t).dots.findIndex(r=>r===e.payload);n!==-1&&t.dots.splice(n,1)},addArea:(t,e)=>{t.areas.push(e.payload)},removeArea:(t,e)=>{var n=Il(t).areas.findIndex(r=>r===e.payload);n!==-1&&t.areas.splice(n,1)},addLine:(t,e)=>{t.lines.push(e.payload)},removeLine:(t,e)=>{var n=Il(t).lines.findIndex(r=>r===e.payload);n!==-1&&t.lines.splice(n,1)}}}),{addDot:EQe,removeDot:TQe,addArea:AQe,removeArea:CQe,addLine:K5e,removeLine:X5e}=ZJ.actions,Y5e=ZJ.reducer,JJ=_.createContext(void 0),Q5e=t=>{var{children:e}=t,[n]=_.useState("".concat(uy("recharts"),"-clip")),r=CM();if(r==null)return null;var{x:i,y:s,width:o,height:l}=r;return _.createElement(JJ.Provider,{value:n},_.createElement("defs",null,_.createElement("clipPath",{id:n},_.createElement("rect",{x:i,y:s,height:l,width:o}))),e)},Z5e=()=>_.useContext(JJ);function mq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function pq(t){for(var e=1;e{var n;if(_.isValidElement(t))n=_.cloneElement(t,e);else if(typeof t=="function")n=t(e);else{if(!wr(e.x1)||!wr(e.y1)||!wr(e.x2)||!wr(e.y2))return null;n=_.createElement("line",aN({},e,{className:"recharts-reference-line-line"}))}return n},rze=(t,e,n,r,i,s)=>{var{x:o,width:l}=s,c=i.y.apply(t,{position:n});if(Ys(c)||e==="discard"&&!i.y.isInRange(c))return null;var u=[{x:o+l,y:c},{x:o,y:c}];return r==="left"?u.reverse():u},ize=(t,e,n,r,i,s)=>{var{y:o,height:l}=s,c=i.x.apply(t,{position:n});if(Ys(c)||e==="discard"&&!i.x.isInRange(c))return null;var u=[{x:c,y:o+l},{x:c,y:o}];return r==="top"?u.reverse():u},aze=(t,e,n,r)=>{var i=t.map(s=>r.apply(s,{position:n}));return e==="discard"&&i.some(s=>!r.isInRange(s))?null:i},sze=(t,e,n,r,i,s)=>{var{x:o,y:l,segment:c,ifOverflow:u}=s,d=fl(o),h=fl(l);return h?rze(l,u,n,i,t,e):d?ize(o,u,n,r,t,e):c!=null&&c.length===2?aze(c,u,n,t):null};function oze(t){var e=zr();return _.useEffect(()=>(e(K5e(t)),()=>{e(X5e(t))})),null}function lze(t){var{xAxisId:e,yAxisId:n,shape:r,className:i,ifOverflow:s}=t,o=aa(),l=Z5e(),c=Ht(A=>Ac(A,e)),u=Ht(A=>Cc(A,n)),d=Ht(A=>Fh(A,"xAxis",e,o)),h=Ht(A=>Fh(A,"yAxis",n,o)),p=tv();if(!l||!p||c==null||u==null||d==null||h==null)return null;var m=V5e({x:d,y:h}),b=sze(m,p,t.position,c.orientation,u.orientation,t);if(!b)return null;var[{x:y,y:x},{x:v,y:S}]=b,N=s==="hidden"?"url(#".concat(l,")"):void 0,T=pq(pq({clipPath:N},Ga(t)),{},{x1:y,y1:x,x2:v,y2:S}),M=$5e({x1:y,y1:x,x2:v,y2:S});return _.createElement(ls,{zIndex:t.zIndex},_.createElement(li,{className:nr("recharts-reference-line",i)},nze(r,T),_.createElement(TJ,aN({},M,{lowerWidth:M.width,upperWidth:M.width}),_.createElement(CJ,{label:t.label}),t.children)))}var cze={ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle",zIndex:vi.line};function m0(t){var e=ci(t,cze);return _.createElement(_.Fragment,null,_.createElement(oze,{yAxisId:e.yAxisId,xAxisId:e.xAxisId,ifOverflow:e.ifOverflow,x:e.x,y:e.y,segment:e.segment}),_.createElement(lze,e))}m0.displayName="ReferenceLine";function eee(t,e){if(e<1)return[];if(e===1)return t;for(var n=[],r=0;rt*i)return!1;var s=n();return t*(e-t*s/2-r)>=0&&t*(e+t*s/2-i)<=0}function hze(t,e){return eee(t,e+1)}function fze(t,e,n,r,i){for(var s=(r||[]).slice(),{start:o,end:l}=e,c=0,u=1,d=o,h=function(){var b=r?.[c];if(b===void 0)return{v:eee(r,u)};var y=c,x,v=()=>(x===void 0&&(x=n(b,y)),x),S=b.coordinate,N=c===0||sN(t,S,v,d,l);N||(c=0,d=o,u+=1),N&&(d=S+t*(v()/2+i),c+=u)},p;u<=s.length;)if(p=h(),p)return p.v;return[]}function gq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Za(t){for(var e=1;e(b===void 0&&(b=n(m,p)),b);if(p===o-1){var x=t*(m.coordinate+t*y()/2-c);s[p]=m=Za(Za({},m),{},{tickCoord:x>0?m.coordinate-x*t:m.coordinate})}else s[p]=m=Za(Za({},m),{},{tickCoord:m.coordinate});if(m.tickCoord!=null){var v=sN(t,m.tickCoord,y,l,c);v&&(c=m.tickCoord-t*(y()/2+i),s[p]=Za(Za({},m),{},{isShow:!0}))}},d=o-1;d>=0;d--)u(d);return s}function xze(t,e,n,r,i,s){var o=(r||[]).slice(),l=o.length,{start:c,end:u}=e;if(s){var d=r[l-1],h=n(d,l-1),p=t*(d.coordinate+t*h/2-u);if(o[l-1]=d=Za(Za({},d),{},{tickCoord:p>0?d.coordinate-p*t:d.coordinate}),d.tickCoord!=null){var m=sN(t,d.tickCoord,()=>h,c,u);m&&(u=d.tickCoord-t*(h/2+i),o[l-1]=Za(Za({},d),{},{isShow:!0}))}}for(var b=s?l-1:l,y=function(S){var N=o[S],T,M=()=>(T===void 0&&(T=n(N,S)),T);if(S===0){var A=t*(N.coordinate-t*M()/2-c);o[S]=N=Za(Za({},N),{},{tickCoord:A<0?N.coordinate-A*t:N.coordinate})}else o[S]=N=Za(Za({},N),{},{tickCoord:N.coordinate});if(N.tickCoord!=null){var k=sN(t,N.tickCoord,M,c,u);k&&(c=N.tickCoord+t*(M()/2+i),o[S]=Za(Za({},N),{},{isShow:!0}))}},x=0;x{var M=typeof u=="function"?u(N.value,T):N.value;return b==="width"?uze(A0(M,{fontSize:e,letterSpacing:n}),y,h):A0(M,{fontSize:e,letterSpacing:n})[b]},v=i.length>=2?wa(i[1].coordinate-i[0].coordinate):1,S=dze(s,v,b);return c==="equidistantPreserveStart"?fze(v,S,x,i,o):(c==="preserveStart"||c==="preserveStartEnd"?m=xze(v,S,x,i,o,c==="preserveStartEnd"):m=bze(v,S,x,i,o),m.filter(N=>N.isShow))}var yze=t=>{var{ticks:e,label:n,labelGapWithTick:r=5,tickSize:i=0,tickMargin:s=0}=t,o=0;if(e){Array.from(e).forEach(d=>{if(d){var h=d.getBoundingClientRect();h.width>o&&(o=h.width)}});var l=n?n.getBoundingClientRect().width:0,c=i+s,u=o+c+l+(n?r:0);return Math.round(u)}return 0},vze=["axisLine","width","height","className","hide","ticks","axisType"];function wze(t,e){if(t==null)return{};var n,r,i=_ze(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var{ticks:n=[],tick:r,tickLine:i,stroke:s,tickFormatter:o,unit:l,padding:c,tickTextProps:u,orientation:d,mirror:h,x:p,y:m,width:b,height:y,tickSize:x,tickMargin:v,fontSize:S,letterSpacing:N,getTicksConfig:T,events:M,axisType:A}=t,k=S4(Fi(Fi({},T),{},{ticks:n}),S,N),R=Tze(d,h),C=Aze(d,h),P=Ms(T),U=vm(r),F={};typeof i=="object"&&(F=i);var H=Fi(Fi({},P),{},{fill:"none"},F),D=k.map(I=>Fi({entry:I},Eze(I,p,m,b,y,d,x,h,v))),$=D.map(I=>{var{entry:K,line:Q}=I;return _.createElement(li,{className:"recharts-cartesian-axis-tick",key:"tick-".concat(K.value,"-").concat(K.coordinate,"-").concat(K.tickCoord)},i&&_.createElement("line",km({},H,Q,{className:nr("recharts-cartesian-axis-tick-line",wm(i,"className"))})))}),G=D.map((I,K)=>{var{entry:Q,tick:oe}=I,B=Fi(Fi(Fi(Fi({textAnchor:R,verticalAnchor:C},P),{},{stroke:"none",fill:s},U),oe),{},{index:K,payload:Q,visibleTicksCount:k.length,tickFormatter:o,padding:c},u);return _.createElement(li,km({className:"recharts-cartesian-axis-tick-label",key:"tick-label-".concat(Q.value,"-").concat(Q.coordinate,"-").concat(Q.tickCoord)},Yy(M,Q,K)),r&&_.createElement(Cze,{option:r,tickProps:B,value:"".concat(typeof o=="function"?o(Q.value,K):Q.value).concat(l||"")}))});return _.createElement("g",{className:"recharts-cartesian-axis-ticks recharts-".concat(A,"-ticks")},G.length>0&&_.createElement(ls,{zIndex:vi.label},_.createElement("g",{className:"recharts-cartesian-axis-tick-labels recharts-".concat(A,"-tick-labels"),ref:e},G)),$.length>0&&_.createElement("g",{className:"recharts-cartesian-axis-tick-lines recharts-".concat(A,"-tick-lines")},$))}),jze=_.forwardRef((t,e)=>{var{axisLine:n,width:r,height:i,className:s,hide:o,ticks:l,axisType:c}=t,u=wze(t,vze),[d,h]=_.useState(""),[p,m]=_.useState(""),b=_.useRef(null);_.useImperativeHandle(e,()=>({getCalculatedWidth:()=>{var x;return yze({ticks:b.current,label:(x=t.labelRef)===null||x===void 0?void 0:x.current,labelGapWithTick:5,tickSize:t.tickSize,tickMargin:t.tickMargin})}}));var y=_.useCallback(x=>{if(x){var v=x.getElementsByClassName("recharts-cartesian-axis-tick-value");b.current=v;var S=v[0];if(S){var N=window.getComputedStyle(S),T=N.fontSize,M=N.letterSpacing;(T!==d||M!==p)&&(h(T),m(M))}}},[d,p]);return o||r!=null&&r<=0||i!=null&&i<=0?null:_.createElement(ls,{zIndex:t.zIndex},_.createElement(li,{className:nr("recharts-cartesian-axis",s)},_.createElement(Mze,{x:t.x,y:t.y,width:r,height:i,orientation:t.orientation,mirror:t.mirror,axisLine:n,otherSvgProps:Ms(t)}),_.createElement(Pze,{ref:y,axisType:c,events:u,fontSize:d,getTicksConfig:t,height:t.height,letterSpacing:p,mirror:t.mirror,orientation:t.orientation,padding:t.padding,stroke:t.stroke,tick:t.tick,tickFormatter:t.tickFormatter,tickLine:t.tickLine,tickMargin:t.tickMargin,tickSize:t.tickSize,tickTextProps:t.tickTextProps,ticks:l,unit:t.unit,width:t.width,x:t.x,y:t.y}),_.createElement(TJ,{x:t.x,y:t.y,width:t.width,height:t.height,lowerWidth:t.width,upperWidth:t.width},_.createElement(CJ,{label:t.label,labelRef:t.labelRef}),t.children)))}),N4=_.forwardRef((t,e)=>{var n=ci(t,Ru);return _.createElement(jze,km({},n,{ref:e}))});N4.displayName="CartesianAxis";var Dze=["x1","y1","x2","y2","key"],Rze=["offset"],Oze=["xAxisId","yAxisId"],Lze=["xAxisId","yAxisId"];function xq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function ts(t){for(var e=1;e{var{fill:e}=t;if(!e||e==="none")return null;var{fillOpacity:n,x:r,y:i,width:s,height:o,ry:l}=t;return _.createElement("rect",{x:r,y:i,ry:l,width:s,height:o,stroke:"none",fill:e,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function tee(t){var{option:e,lineItemProps:n}=t,r;if(_.isValidElement(e))r=_.cloneElement(e,n);else if(typeof e=="function")r=e(n);else{var i,{x1:s,y1:o,x2:l,y2:c,key:u}=n,d=oN(n,Dze),h=(i=Ms(d))!==null&&i!==void 0?i:{},{offset:p}=h,m=oN(h,Rze);r=_.createElement("line",$f({},m,{x1:s,y1:o,x2:l,y2:c,fill:"none",key:u}))}return r}function Hze(t){var{x:e,width:n,horizontal:r=!0,horizontalPoints:i}=t;if(!r||!i||!i.length)return null;var{xAxisId:s,yAxisId:o}=t,l=oN(t,Oze),c=i.map((u,d)=>{var h=ts(ts({},l),{},{x1:e,y1:u,x2:e+n,y2:u,key:"line-".concat(d),index:d});return _.createElement(tee,{key:"line-".concat(d),option:r,lineItemProps:h})});return _.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function $ze(t){var{y:e,height:n,vertical:r=!0,verticalPoints:i}=t;if(!r||!i||!i.length)return null;var{xAxisId:s,yAxisId:o}=t,l=oN(t,Lze),c=i.map((u,d)=>{var h=ts(ts({},l),{},{x1:u,y1:e,x2:u,y2:e+n,key:"line-".concat(d),index:d});return _.createElement(tee,{option:r,lineItemProps:h,key:"line-".concat(d)})});return _.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function Vze(t){var{horizontalFill:e,fillOpacity:n,x:r,y:i,width:s,height:o,horizontalPoints:l,horizontal:c=!0}=t;if(!c||!e||!e.length||l==null)return null;var u=l.map(h=>Math.round(h+i-i)).sort((h,p)=>h-p);i!==u[0]&&u.unshift(0);var d=u.map((h,p)=>{var m=!u[p+1],b=m?i+o-h:u[p+1]-h;if(b<=0)return null;var y=p%e.length;return _.createElement("rect",{key:"react-".concat(p),y:h,x:r,height:b,width:s,stroke:"none",fill:e[y],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return _.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},d)}function Gze(t){var{vertical:e=!0,verticalFill:n,fillOpacity:r,x:i,y:s,width:o,height:l,verticalPoints:c}=t;if(!e||!n||!n.length)return null;var u=c.map(h=>Math.round(h+i-i)).sort((h,p)=>h-p);i!==u[0]&&u.unshift(0);var d=u.map((h,p)=>{var m=!u[p+1],b=m?i+o-h:u[p+1]-h;if(b<=0)return null;var y=p%n.length;return _.createElement("rect",{key:"react-".concat(p),x:h,y:s,width:b,height:l,stroke:"none",fill:n[y],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return _.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},d)}var qze=(t,e)=>{var{xAxis:n,width:r,height:i,offset:s}=t;return IY(S4(ts(ts(ts({},Ru),n),{},{ticks:zY(n),viewBox:{x:0,y:0,width:r,height:i}})),s.left,s.left+s.width,e)},Wze=(t,e)=>{var{yAxis:n,width:r,height:i,offset:s}=t;return IY(S4(ts(ts(ts({},Ru),n),{},{ticks:zY(n),viewBox:{x:0,y:0,width:r,height:i}})),s.top,s.top+s.height,e)},Kze={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:vi.grid};function lN(t){var e=YO(),n=QO(),r=KY(),i=ts(ts({},ci(t,Kze)),{},{x:Vt(t.x)?t.x:r.left,y:Vt(t.y)?t.y:r.top,width:Vt(t.width)?t.width:r.width,height:Vt(t.height)?t.height:r.height}),{xAxisId:s,yAxisId:o,x:l,y:c,width:u,height:d,syncWithTicks:h,horizontalValues:p,verticalValues:m}=i,b=aa(),y=Ht(C=>sG(C,"xAxis",s,b)),x=Ht(C=>sG(C,"yAxis",o,b));if(!yc(u)||!yc(d)||!Vt(l)||!Vt(c))return null;var v=i.verticalCoordinatesGenerator||qze,S=i.horizontalCoordinatesGenerator||Wze,{horizontalPoints:N,verticalPoints:T}=i;if((!N||!N.length)&&typeof S=="function"){var M=p&&p.length,A=S({yAxis:x?ts(ts({},x),{},{ticks:M?p:x.ticks}):void 0,width:e??u,height:n??d,offset:r},M?!0:h);PS(Array.isArray(A),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(typeof A,"]")),Array.isArray(A)&&(N=A)}if((!T||!T.length)&&typeof v=="function"){var k=m&&m.length,R=v({xAxis:y?ts(ts({},y),{},{ticks:k?m:y.ticks}):void 0,width:e??u,height:n??d,offset:r},k?!0:h);PS(Array.isArray(R),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(typeof R,"]")),Array.isArray(R)&&(T=R)}return _.createElement(ls,{zIndex:i.zIndex},_.createElement("g",{className:"recharts-cartesian-grid"},_.createElement(Bze,{fill:i.fill,fillOpacity:i.fillOpacity,x:i.x,y:i.y,width:i.width,height:i.height,ry:i.ry}),_.createElement(Vze,$f({},i,{horizontalPoints:N})),_.createElement(Gze,$f({},i,{verticalPoints:T})),_.createElement(Hze,$f({},i,{offset:r,horizontalPoints:N,xAxis:y,yAxis:x})),_.createElement($ze,$f({},i,{offset:r,verticalPoints:T,xAxis:y,yAxis:x}))))}lN.displayName="CartesianGrid";var nee=(t,e,n,r)=>_c(t,"xAxis",e,r),ree=(t,e,n,r)=>wc(t,"xAxis",e,r),iee=(t,e,n,r)=>_c(t,"yAxis",n,r),aee=(t,e,n,r)=>wc(t,"yAxis",n,r),Xze=st([Kn,nee,iee,ree,aee],(t,e,n,r,i)=>Tc(t,"xAxis")?Oh(e,r,!1):Oh(n,i,!1)),Yze=(t,e,n,r,i)=>i;function Qze(t){return t.type==="line"}var Zze=st([dv,Yze],(t,e)=>t.filter(Qze).find(n=>n.id===e)),Jze=st([Kn,nee,iee,ree,aee,Zze,Xze,ov],(t,e,n,r,i,s,o,l)=>{var{chartData:c,dataStartIndex:u,dataEndIndex:d}=l;if(!(s==null||e==null||n==null||r==null||i==null||r.length===0||i.length===0||o==null||t!=="horizontal"&&t!=="vertical")){var{dataKey:h,data:p}=s,m;if(p!=null&&p.length>0?m=p:m=c?.slice(u,d+1),m!=null)return yUe({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataKey:h,bandSize:o,displayedData:m})}});function see(t){var e=vm(t),n=3,r=2;if(e!=null){var{r:i,strokeWidth:s}=e,o=Number(i),l=Number(s);return(Number.isNaN(o)||o<0)&&(o=n),(Number.isNaN(l)||l<0)&&(l=r),{r:o,strokeWidth:l}}return{r:n,strokeWidth:r}}var eUe=["id"],tUe=["type","layout","connectNulls","needClip","shape"],nUe=["activeDot","animateNewValues","animationBegin","animationDuration","animationEasing","connectNulls","dot","hide","isAnimationActive","label","legendType","xAxisId","yAxisId","id"];function ky(){return ky=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{dataKey:e,name:n,stroke:r,legendType:i,hide:s}=t;return[{inactive:s,dataKey:e,type:i,color:r,value:Hh(n,e),payload:t}]},lUe=_.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:i,fill:s,name:o,hide:l,unit:c,tooltipType:u}=t,d={dataDefinedOnItem:n,positions:void 0,settings:{stroke:r,strokeWidth:i,fill:s,dataKey:e,nameKey:void 0,name:Hh(o,e),hide:l,type:u,color:r,unit:c}};return _.createElement(EM,{tooltipEntrySettings:d})}),oee=(t,e)=>"".concat(e,"px ").concat(t-e,"px");function cUe(t,e){for(var n=t.length%2!==0?[...t,0]:t,r=[],i=0;i{var r=n.reduce((h,p)=>h+p);if(!r)return oee(e,t);for(var i=Math.floor(t/r),s=t%r,o=e-t,l=[],c=0,u=0;cs){l=[...n.slice(0,c),s-u];break}var d=l.length%2===0?[0,o]:[o];return[...cUe(n,i),...l,...d].map(h=>"".concat(h,"px")).join(", ")};function dUe(t){var{clipPathId:e,points:n,props:r}=t,{dot:i,dataKey:s,needClip:o}=r,{id:l}=r,c=k4(r,eUe),u=Ms(c);return _.createElement(HJ,{points:n,dot:i,className:"recharts-line-dots",dotClassName:"recharts-line-dot",dataKey:s,baseProps:u,needClip:o,clipPathId:e})}function hUe(t){var{showLabels:e,children:n,points:r}=t,i=_.useMemo(()=>r?.map(s=>{var o,l,c={x:(o=s.x)!==null&&o!==void 0?o:0,y:(l=s.y)!==null&&l!==void 0?l:0,width:0,lowerWidth:0,upperWidth:0,height:0};return rc(rc({},c),{},{value:s.value,payload:s.payload,viewBox:c,parentViewBox:void 0,fill:void 0})}),[r]);return _.createElement(d4,{value:e?i:void 0},n)}function vq(t){var{clipPathId:e,pathRef:n,points:r,strokeDasharray:i,props:s}=t,{type:o,layout:l,connectNulls:c,needClip:u,shape:d}=s,h=k4(s,tUe),p=rc(rc({},Ga(h)),{},{fill:"none",className:"recharts-line-curve",clipPath:u?"url(#clipPath-".concat(e,")"):void 0,points:r,type:o,layout:l,connectNulls:c,strokeDasharray:i??s.strokeDasharray});return _.createElement(_.Fragment,null,r?.length>1&&_.createElement(g4,ky({shapeType:"curve",option:d},p,{pathRef:n})),_.createElement(dUe,{points:r,clipPathId:e,props:s}))}function fUe(t){try{return t&&t.getTotalLength&&t.getTotalLength()||0}catch{return 0}}function mUe(t){var{clipPathId:e,props:n,pathRef:r,previousPointsRef:i,longestAnimatedLengthRef:s}=t,{points:o,strokeDasharray:l,isAnimationActive:c,animationBegin:u,animationDuration:d,animationEasing:h,animateNewValues:p,width:m,height:b,onAnimationEnd:y,onAnimationStart:x}=n,v=i.current,S=Pb(o,"recharts-line-"),N=_.useRef(S),[T,M]=_.useState(!1),A=!T,k=_.useCallback(()=>{typeof y=="function"&&y(),M(!1)},[y]),R=_.useCallback(()=>{typeof x=="function"&&x(),M(!0)},[x]),C=fUe(r.current),P=_.useRef(0);N.current!==S&&(P.current=s.current,N.current=S);var U=P.current;return _.createElement(hUe,{points:o,showLabels:A},n.children,_.createElement(Cb,{animationId:S,begin:u,duration:d,isActive:c,easing:h,onAnimationEnd:k,onAnimationStart:R,key:S},F=>{var H=pr(U,C+U,F),D=Math.min(H,C),$;if(c)if(l){var G="".concat(l).split(/[,\s]+/gim).map(Q=>parseFloat(Q));$=uUe(D,C,G)}else $=oee(C,D);else $=l==null?void 0:String(l);if(F>0&&C>0&&(i.current=o,s.current=Math.max(s.current,D)),v){var I=v.length/o.length,K=F===1?o:o.map((Q,oe)=>{var B=Math.floor(oe*I);if(v[B]){var W=v[B];return rc(rc({},Q),{},{x:pr(W.x,Q.x,F),y:pr(W.y,Q.y,F)})}return p?rc(rc({},Q),{},{x:pr(m*2,Q.x,F),y:pr(b/2,Q.y,F)}):rc(rc({},Q),{},{x:Q.x,y:Q.y})});return i.current=K,_.createElement(vq,{props:n,points:K,clipPathId:e,pathRef:r,strokeDasharray:$})}return _.createElement(vq,{props:n,points:o,clipPathId:e,pathRef:r,strokeDasharray:$})}),_.createElement(NM,{label:n.label}))}function pUe(t){var{clipPathId:e,props:n}=t,r=_.useRef(null),i=_.useRef(0),s=_.useRef(null);return _.createElement(mUe,{props:n,clipPathId:e,previousPointsRef:r,longestAnimatedLengthRef:i,pathRef:s})}var gUe=(t,e)=>{var n,r;return{x:(n=t.x)!==null&&n!==void 0?n:void 0,y:(r=t.y)!==null&&r!==void 0?r:void 0,value:t.value,errorVal:vr(t.payload,e)}};class bUe extends _.Component{render(){var{hide:e,dot:n,points:r,className:i,xAxisId:s,yAxisId:o,top:l,left:c,width:u,height:d,id:h,needClip:p,zIndex:m}=this.props;if(e)return null;var b=nr("recharts-line",i),y=h,{r:x,strokeWidth:v}=see(n),S=p4(n),N=x*2+v,T=p?"url(#clipPath-".concat(S?"":"dots-").concat(y,")"):void 0;return _.createElement(ls,{zIndex:m},_.createElement(li,{className:b},p&&_.createElement("defs",null,_.createElement(_4,{clipPathId:y,xAxisId:s,yAxisId:o}),!S&&_.createElement("clipPath",{id:"clipPath-dots-".concat(y)},_.createElement("rect",{x:c-N/2,y:l-N/2,width:u+N,height:d+N}))),_.createElement(GJ,{xAxisId:s,yAxisId:o,data:r,dataPointFormatter:gUe,errorBarOffset:0},_.createElement(pUe,{props:this.props,clipPathId:y}))),_.createElement(jD,{activeDot:this.props.activeDot,points:r,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:T}))}}var lee={activeDot:!0,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",connectNulls:!1,dot:!0,fill:"#fff",hide:!1,isAnimationActive:"auto",label:!1,legendType:"line",stroke:"#3182bd",strokeWidth:1,xAxisId:0,yAxisId:0,zIndex:vi.line,type:"linear"};function xUe(t){var e=ci(t,lee),{activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,hide:u,isAnimationActive:d,label:h,legendType:p,xAxisId:m,yAxisId:b,id:y}=e,x=k4(e,nUe),{needClip:v}=PM(m,b),S=CM(),N=Lm(),T=aa(),M=Ht(P=>Jze(P,m,b,T,y));if(N!=="horizontal"&&N!=="vertical"||M==null||S==null)return null;var{height:A,width:k,x:R,y:C}=S;return _.createElement(bUe,ky({},x,{id:y,connectNulls:l,dot:c,activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:s,animationEasing:o,isAnimationActive:d,hide:u,label:h,legendType:p,xAxisId:m,yAxisId:b,points:M,layout:N,height:A,width:k,left:R,top:C,needClip:v}))}function yUe(t){var{layout:e,xAxis:n,yAxis:r,xAxisTicks:i,yAxisTicks:s,dataKey:o,bandSize:l,displayedData:c}=t;return c.map((u,d)=>{var h=vr(u,o);if(e==="horizontal"){var p=CS({axis:n,ticks:i,bandSize:l,entry:u,index:d}),m=Yr(h)?null:r.scale(h);return{x:p,y:m,value:h,payload:u}}var b=Yr(h)?null:n.scale(h),y=CS({axis:r,ticks:s,bandSize:l,entry:u,index:d});return b==null||y==null?null:{x:b,y,value:h,payload:u}}).filter(Boolean)}function vUe(t){var e=ci(t,lee),n=aa();return _.createElement(TM,{id:e.id,type:"line"},r=>_.createElement(_.Fragment,null,_.createElement(v4,{legendPayload:oUe(e)}),_.createElement(lUe,{dataKey:e.dataKey,data:e.data,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType}),_.createElement(w4,{type:"line",id:r,data:e.data,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,hide:e.hide,isPanorama:n}),_.createElement(xUe,ky({},e,{id:r}))))}var cee=_.memo(vUe,vv);cee.displayName="Line";var uee=(t,e,n,r)=>_c(t,"xAxis",e,r),dee=(t,e,n,r)=>wc(t,"xAxis",e,r),hee=(t,e,n,r)=>_c(t,"yAxis",n,r),fee=(t,e,n,r)=>wc(t,"yAxis",n,r),wUe=st([Kn,uee,hee,dee,fee],(t,e,n,r,i)=>Tc(t,"xAxis")?Oh(e,r,!1):Oh(n,i,!1)),_Ue=(t,e,n,r,i)=>i,mee=st([dv,_Ue],(t,e)=>t.filter(n=>n.type==="area").find(n=>n.id===e)),SUe=(t,e,n,r,i)=>{var s,o=mee(t,e,n,r,i);if(o!=null){var l=Kn(t),c=Tc(l,"xAxis"),u;if(c?u=Sy(t,"yAxis",n,r):u=Sy(t,"xAxis",e,r),u!=null){var{stackId:d}=o,h=mM(o);if(!(d==null||h==null)){var p=(s=u[d])===null||s===void 0?void 0:s.stackedData;return p?.find(m=>m.key===h)}}}},NUe=st([Kn,uee,hee,dee,fee,SUe,ov,wUe,mee,Z3e],(t,e,n,r,i,s,o,l,c,u)=>{var{chartData:d,dataStartIndex:h,dataEndIndex:p}=o;if(!(c==null||t!=="horizontal"&&t!=="vertical"||e==null||n==null||r==null||i==null||r.length===0||i.length===0||l==null)){var{data:m}=c,b;if(m&&m.length>0?b=m:b=d?.slice(h,p+1),b!=null)return $Ue({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataStartIndex:h,areaSettings:c,stackedData:s,displayedData:b,chartBaseValue:u,bandSize:l})}}),kUe=["id"],MUe=["activeDot","animationBegin","animationDuration","animationEasing","connectNulls","dot","fill","fillOpacity","hide","isAnimationActive","legendType","stroke","xAxisId","yAxisId"];function nm(){return nm=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{dataKey:e,name:n,stroke:r,fill:i,legendType:s,hide:o}=t;return[{inactive:o,dataKey:e,type:s,color:cN(r,i),value:Hh(n,e),payload:t}]},jUe=_.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:i,fill:s,name:o,hide:l,unit:c,tooltipType:u}=t,d={dataDefinedOnItem:n,positions:void 0,settings:{stroke:r,strokeWidth:i,fill:s,dataKey:e,nameKey:void 0,name:Hh(o,e),hide:l,type:u,color:cN(r,s),unit:c}};return _.createElement(EM,{tooltipEntrySettings:d})});function DUe(t){var{clipPathId:e,points:n,props:r}=t,{needClip:i,dot:s,dataKey:o}=r,l=Ms(r);return _.createElement(HJ,{points:n,dot:s,className:"recharts-area-dots",dotClassName:"recharts-area-dot",dataKey:o,baseProps:l,needClip:i,clipPathId:e})}function RUe(t){var{showLabels:e,children:n,points:r}=t,i=r.map(s=>{var o,l,c={x:(o=s.x)!==null&&o!==void 0?o:0,y:(l=s.y)!==null&&l!==void 0?l:0,width:0,lowerWidth:0,upperWidth:0,height:0};return Sg(Sg({},c),{},{value:s.value,payload:s.payload,parentViewBox:void 0,viewBox:c,fill:void 0})});return _.createElement(d4,{value:e?i:void 0},n)}function _q(t){var{points:e,baseLine:n,needClip:r,clipPathId:i,props:s}=t,{layout:o,type:l,stroke:c,connectNulls:u,isRange:d}=s,{id:h}=s,p=pee(s,kUe),m=Ms(p),b=Ga(p);return _.createElement(_.Fragment,null,e?.length>1&&_.createElement(li,{clipPath:r?"url(#clipPath-".concat(i,")"):void 0},_.createElement(Lg,nm({},b,{id:h,points:e,connectNulls:u,type:l,baseLine:n,layout:o,stroke:"none",className:"recharts-area-area"})),c!=="none"&&_.createElement(Lg,nm({},m,{className:"recharts-area-curve",layout:o,type:l,connectNulls:u,fill:"none",points:e})),c!=="none"&&d&&_.createElement(Lg,nm({},m,{className:"recharts-area-curve",layout:o,type:l,connectNulls:u,fill:"none",points:n}))),_.createElement(DUe,{points:e,props:p,clipPathId:i}))}function OUe(t){var{alpha:e,baseLine:n,points:r,strokeWidth:i}=t,s=r[0].y,o=r[r.length-1].y;if(!wr(s)||!wr(o))return null;var l=e*Math.abs(s-o),c=Math.max(...r.map(u=>u.x||0));return Vt(n)?c=Math.max(n,c):n&&Array.isArray(n)&&n.length&&(c=Math.max(...n.map(u=>u.x||0),c)),Vt(c)?_.createElement("rect",{x:0,y:su.y||0));return Vt(n)?c=Math.max(n,c):n&&Array.isArray(n)&&n.length&&(c=Math.max(...n.map(u=>u.y||0),c)),Vt(c)?_.createElement("rect",{x:s({points:o,baseLine:l}),[o,l]),y=Pb(b,"recharts-area-"),x=gAe(),[v,S]=_.useState(!1),N=!v,T=_.useCallback(()=>{typeof m=="function"&&m(),S(!1)},[m]),M=_.useCallback(()=>{typeof p=="function"&&p(),S(!0)},[p]);if(x==null)return null;var A=i.current,k=s.current;return _.createElement(RUe,{showLabels:N,points:o},r.children,_.createElement(Cb,{animationId:y,begin:u,duration:d,isActive:c,easing:h,onAnimationEnd:T,onAnimationStart:M,key:y},R=>{if(A){var C=A.length/o.length,P=R===1?o:o.map((F,H)=>{var D=Math.floor(H*C);if(A[D]){var $=A[D];return Sg(Sg({},F),{},{x:pr($.x,F.x,R),y:pr($.y,F.y,R)})}return F}),U;return Vt(l)?U=pr(k,l,R):Yr(l)||Ys(l)?U=pr(k,0,R):U=l.map((F,H)=>{var D=Math.floor(H*C);if(Array.isArray(k)&&k[D]){var $=k[D];return Sg(Sg({},F),{},{x:pr($.x,F.x,R),y:pr($.y,F.y,R)})}return F}),R>0&&(i.current=P,s.current=U),_.createElement(_q,{points:P,baseLine:U,needClip:e,clipPathId:n,props:r})}return R>0&&(i.current=o,s.current=l),_.createElement(li,null,c&&_.createElement("defs",null,_.createElement("clipPath",{id:"animationClipPath-".concat(n)},_.createElement(FUe,{alpha:R,points:o,baseLine:l,layout:x,strokeWidth:r.strokeWidth}))),_.createElement(li,{clipPath:"url(#animationClipPath-".concat(n,")")},_.createElement(_q,{points:o,baseLine:l,needClip:e,clipPathId:n,props:r})))}),_.createElement(NM,{label:r.label}))}function zUe(t){var{needClip:e,clipPathId:n,props:r}=t,i=_.useRef(null),s=_.useRef();return _.createElement(IUe,{needClip:e,clipPathId:n,props:r,previousPointsRef:i,previousBaselineRef:s})}class UUe extends _.PureComponent{render(){var{hide:e,dot:n,points:r,className:i,top:s,left:o,needClip:l,xAxisId:c,yAxisId:u,width:d,height:h,id:p,baseLine:m,zIndex:b}=this.props;if(e)return null;var y=nr("recharts-area",i),x=p,{r:v,strokeWidth:S}=see(n),N=p4(n),T=v*2+S,M=l?"url(#clipPath-".concat(N?"":"dots-").concat(x,")"):void 0;return _.createElement(ls,{zIndex:b},_.createElement(li,{className:y},l&&_.createElement("defs",null,_.createElement(_4,{clipPathId:x,xAxisId:c,yAxisId:u}),!N&&_.createElement("clipPath",{id:"clipPath-dots-".concat(x)},_.createElement("rect",{x:o-T/2,y:s-T/2,width:d+T,height:h+T}))),_.createElement(zUe,{needClip:l,clipPathId:x,props:this.props})),_.createElement(jD,{points:r,mainColor:cN(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:M}),this.props.isRange&&Array.isArray(m)&&_.createElement(jD,{points:m,mainColor:cN(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:M}))}}var gee={activeDot:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",connectNulls:!1,dot:!1,fill:"#3182bd",fillOpacity:.6,hide:!1,isAnimationActive:"auto",legendType:"line",stroke:"#3182bd",strokeWidth:1,type:"linear",label:!1,xAxisId:0,yAxisId:0,zIndex:vi.area};function BUe(t){var e,n=ci(t,gee),{activeDot:r,animationBegin:i,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,fill:u,fillOpacity:d,hide:h,isAnimationActive:p,legendType:m,stroke:b,xAxisId:y,yAxisId:x}=n,v=pee(n,MUe),S=Lm(),N=dJ(),{needClip:T}=PM(y,x),M=aa(),{points:A,isRange:k,baseLine:R}=(e=Ht(D=>NUe(D,y,x,M,t.id)))!==null&&e!==void 0?e:{},C=CM();if(S!=="horizontal"&&S!=="vertical"||C==null||N!=="AreaChart"&&N!=="ComposedChart")return null;var{height:P,width:U,x:F,y:H}=C;return!A||!A.length?null:_.createElement(UUe,nm({},v,{activeDot:r,animationBegin:i,animationDuration:s,animationEasing:o,baseLine:R,connectNulls:l,dot:c,fill:u,fillOpacity:d,height:P,hide:h,layout:S,isAnimationActive:p==="auto"?!Ab.isSsr:p,isRange:k,legendType:m,needClip:T,points:A,stroke:b,width:U,left:F,top:H,xAxisId:y,yAxisId:x}))}var HUe=(t,e,n,r,i)=>{var s=n??e;if(Vt(s))return s;var o=t==="horizontal"?i:r,l=o.scale.domain();if(o.type==="number"){var c=Math.max(l[0],l[1]),u=Math.min(l[0],l[1]);return s==="dataMin"?u:s==="dataMax"||c<0?c:Math.max(Math.min(l[0],l[1]),0)}return s==="dataMin"?l[0]:s==="dataMax"?l[1]:l[0]};function $Ue(t){var{areaSettings:{connectNulls:e,baseValue:n,dataKey:r},stackedData:i,layout:s,chartBaseValue:o,xAxis:l,yAxis:c,displayedData:u,dataStartIndex:d,xAxisTicks:h,yAxisTicks:p,bandSize:m}=t,b=i&&i.length,y=HUe(s,o,n,l,c),x=s==="horizontal",v=!1,S=u.map((T,M)=>{var A;b?A=i[d+M]:(A=vr(T,r),Array.isArray(A)?v=!0:A=[y,A]);var k=A[1]==null||b&&!e&&vr(T,r)==null;return x?{x:CS({axis:l,ticks:h,bandSize:m,entry:T,index:M}),y:k?null:c.scale(A[1]),value:A,payload:T}:{x:k?null:l.scale(A[1]),y:CS({axis:c,ticks:p,bandSize:m,entry:T,index:M}),value:A,payload:T}}),N;return b||v?N=S.map(T=>{var M=Array.isArray(T.value)?T.value[0]:null;return x?{x:T.x,y:M!=null&&T.y!=null?c.scale(M):null,payload:T.payload}:{x:M!=null?l.scale(M):null,y:T.y,payload:T.payload}}):N=x?c.scale(y):l.scale(y),{points:S,baseLine:N,isRange:v}}function VUe(t){var e=ci(t,gee),n=aa();return _.createElement(TM,{id:e.id,type:"area"},r=>_.createElement(_.Fragment,null,_.createElement(v4,{legendPayload:PUe(e)}),_.createElement(jUe,{dataKey:e.dataKey,data:e.data,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType}),_.createElement(w4,{type:"area",id:r,data:e.data,dataKey:e.dataKey,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,stackId:UY(e.stackId),hide:e.hide,barSize:void 0,baseValue:e.baseValue,isPanorama:n,connectNulls:e.connectNulls}),_.createElement(BUe,nm({},e,{id:r}))))}var bee=_.memo(VUe,vv);bee.displayName="Area";var GUe=["domain","range"],qUe=["domain","range"];function Sq(t,e){if(t==null)return{};var n,r,i=WUe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{n.current===null?e(GFe(t)):n.current!==t&&e(qFe({prev:n.current,next:t})),n.current=t},[t,e]),_.useLayoutEffect(()=>()=>{n.current&&(e(WFe(n.current)),n.current=null)},[e]),null}var ZUe=t=>{var{xAxisId:e,className:n}=t,r=Ht(KO),i=aa(),s="xAxis",o=Ht(x=>Fh(x,s,e,i)),l=Ht(x=>$Z(x,s,e,i)),c=Ht(x=>zZ(x,e)),u=Ht(x=>XDe(x,e)),d=Ht(x=>vZ(x,e));if(c==null||u==null||d==null)return null;var{dangerouslySetInnerHTML:h,ticks:p}=t,m=kq(t,KUe),{id:b}=d,y=kq(d,XUe);return _.createElement(N4,RD({},m,y,{scale:o,x:u.x,y:u.y,width:c.width,height:c.height,className:nr("recharts-".concat(s," ").concat(s),n),viewBox:r,ticks:l,axisType:s}))},JUe={allowDataOverflow:ga.allowDataOverflow,allowDecimals:ga.allowDecimals,allowDuplicatedCategory:ga.allowDuplicatedCategory,angle:ga.angle,axisLine:Ru.axisLine,height:ga.height,hide:!1,includeHidden:ga.includeHidden,interval:ga.interval,minTickGap:ga.minTickGap,mirror:ga.mirror,orientation:ga.orientation,padding:ga.padding,reversed:ga.reversed,scale:ga.scale,tick:ga.tick,tickCount:ga.tickCount,tickLine:Ru.tickLine,tickSize:Ru.tickSize,type:ga.type,xAxisId:0},eBe=t=>{var e=ci(t,JUe);return _.createElement(_.Fragment,null,_.createElement(QUe,{allowDataOverflow:e.allowDataOverflow,allowDecimals:e.allowDecimals,allowDuplicatedCategory:e.allowDuplicatedCategory,angle:e.angle,dataKey:e.dataKey,domain:e.domain,height:e.height,hide:e.hide,id:e.xAxisId,includeHidden:e.includeHidden,interval:e.interval,minTickGap:e.minTickGap,mirror:e.mirror,name:e.name,orientation:e.orientation,padding:e.padding,reversed:e.reversed,scale:e.scale,tick:e.tick,tickCount:e.tickCount,tickFormatter:e.tickFormatter,ticks:e.ticks,type:e.type,unit:e.unit}),_.createElement(ZUe,e))},uN=_.memo(eBe,xee);uN.displayName="XAxis";var tBe=["dangerouslySetInnerHTML","ticks"],nBe=["id"];function OD(){return OD=Object.assign?Object.assign.bind():function(t){for(var e=1;e{n.current===null?e(KFe(t)):n.current!==t&&e(XFe({prev:n.current,next:t})),n.current=t},[t,e]),_.useLayoutEffect(()=>()=>{n.current&&(e(YFe(n.current)),n.current=null)},[e]),null}var aBe=t=>{var{yAxisId:e,className:n,width:r,label:i}=t,s=_.useRef(null),o=_.useRef(null),l=Ht(KO),c=aa(),u=zr(),d="yAxis",h=Ht(M=>Fh(M,d,e,c)),p=Ht(M=>UZ(M,e)),m=Ht(M=>QDe(M,e)),b=Ht(M=>$Z(M,d,e,c)),y=Ht(M=>wZ(M,e));if(_.useLayoutEffect(()=>{if(!(r!=="auto"||!p||u4(i)||_.isValidElement(i)||y==null)){var M=s.current;if(M){var A=M.getCalculatedWidth();Math.round(p.width)!==Math.round(A)&&u(QFe({id:e,width:A}))}}},[b,p,u,i,e,r,y]),p==null||m==null||y==null)return null;var{dangerouslySetInnerHTML:x,ticks:v}=t,S=Mq(t,tBe),{id:N}=y,T=Mq(y,nBe);return _.createElement(N4,OD({},S,T,{ref:s,labelRef:o,scale:h,x:m.x,y:m.y,tickTextProps:r==="auto"?{width:void 0}:{width:r},width:p.width,height:p.height,className:nr("recharts-".concat(d," ").concat(d),n),viewBox:l,ticks:b,axisType:d}))},sBe={allowDataOverflow:ba.allowDataOverflow,allowDecimals:ba.allowDecimals,allowDuplicatedCategory:ba.allowDuplicatedCategory,angle:ba.angle,axisLine:Ru.axisLine,hide:!1,includeHidden:ba.includeHidden,interval:ba.interval,minTickGap:ba.minTickGap,mirror:ba.mirror,orientation:ba.orientation,padding:ba.padding,reversed:ba.reversed,scale:ba.scale,tick:ba.tick,tickCount:ba.tickCount,tickLine:Ru.tickLine,tickSize:Ru.tickSize,type:ba.type,width:ba.width,yAxisId:0},oBe=t=>{var e=ci(t,sBe);return _.createElement(_.Fragment,null,_.createElement(iBe,{interval:e.interval,id:e.yAxisId,scale:e.scale,type:e.type,domain:e.domain,allowDataOverflow:e.allowDataOverflow,dataKey:e.dataKey,allowDuplicatedCategory:e.allowDuplicatedCategory,allowDecimals:e.allowDecimals,tickCount:e.tickCount,padding:e.padding,includeHidden:e.includeHidden,reversed:e.reversed,ticks:e.ticks,width:e.width,orientation:e.orientation,mirror:e.mirror,hide:e.hide,unit:e.unit,name:e.name,angle:e.angle,minTickGap:e.minTickGap,tick:e.tick,tickFormatter:e.tickFormatter}),_.createElement(aBe,e))},dN=_.memo(oBe,xee);dN.displayName="YAxis";var lBe=(t,e)=>e,M4=st([lBe,Kn,xZ,oa,aJ,rd,hOe,ia],yOe),E4=t=>{var e=t.currentTarget.getBoundingClientRect(),n=e.width/t.currentTarget.offsetWidth,r=e.height/t.currentTarget.offsetHeight;return{chartX:Math.round((t.clientX-e.left)/n),chartY:Math.round((t.clientY-e.top)/r)}},yee=ml("mouseClick"),vee=Jy();vee.startListening({actionCreator:yee,effect:(t,e)=>{var n=t.payload,r=M4(e.getState(),E4(n));r?.activeIndex!=null&&e.dispatch(dRe({activeIndex:r.activeIndex,activeDataKey:void 0,activeCoordinate:r.activeCoordinate}))}});var LD=ml("mouseMove"),wee=Jy(),i1=null;wee.startListening({actionCreator:LD,effect:(t,e)=>{var n=t.payload;i1!==null&&cancelAnimationFrame(i1);var r=E4(n);i1=requestAnimationFrame(()=>{var i=e.getState(),s=JL(i,i.tooltip.settings.shared);if(s==="axis"){var o=M4(i,r);o?.activeIndex!=null?e.dispatch(QZ({activeIndex:o.activeIndex,activeDataKey:void 0,activeCoordinate:o.activeCoordinate})):e.dispatch(YZ())}i1=null})}});var Eq={accessibilityLayer:!0,barCategoryGap:"10%",barGap:4,barSize:void 0,className:void 0,maxBarSize:void 0,stackOffset:"none",syncId:void 0,syncMethod:"index",baseValue:void 0,reverseStackOrder:!1},_ee=Qs({name:"rootProps",initialState:Eq,reducers:{updateOptions:(t,e)=>{var n;t.accessibilityLayer=e.payload.accessibilityLayer,t.barCategoryGap=e.payload.barCategoryGap,t.barGap=(n=e.payload.barGap)!==null&&n!==void 0?n:Eq.barGap,t.barSize=e.payload.barSize,t.maxBarSize=e.payload.maxBarSize,t.stackOffset=e.payload.stackOffset,t.syncId=e.payload.syncId,t.syncMethod=e.payload.syncMethod,t.className=e.payload.className,t.baseValue=e.payload.baseValue,t.reverseStackOrder=e.payload.reverseStackOrder}}}),cBe=_ee.reducer,{updateOptions:uBe}=_ee.actions,See=Qs({name:"polarOptions",initialState:null,reducers:{updatePolarOptions:(t,e)=>e.payload}}),{updatePolarOptions:dBe}=See.actions,hBe=See.reducer,Nee=ml("keyDown"),kee=ml("focus"),T4=Jy();T4.startListening({actionCreator:Nee,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:i}=n.tooltip,s=t.payload;if(!(s!=="ArrowRight"&&s!=="ArrowLeft"&&s!=="Enter")){var o=e4(i,zb(n),fv(n),bv(n)),l=o==null?-1:Number(o);if(!(!Number.isFinite(l)||l<0)){var c=rd(n);if(s==="Enter"){var u=ZS(n,"axis","hover",String(i.index));e.dispatch(MD({active:!i.active,activeIndex:i.index,activeDataKey:i.dataKey,activeCoordinate:u}));return}var d=tRe(n),h=d==="left-to-right"?1:-1,p=s==="ArrowRight"?1:-1,m=l+p*h;if(!(c==null||m>=c.length||m<0)){var b=ZS(n,"axis","hover",String(m));e.dispatch(MD({active:!0,activeIndex:m.toString(),activeDataKey:void 0,activeCoordinate:b}))}}}}}});T4.startListening({actionCreator:kee,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:i}=n.tooltip;if(!i.active&&i.index==null){var s="0",o=ZS(n,"axis","hover",String(s));e.dispatch(MD({activeDataKey:void 0,active:!0,activeIndex:s,activeCoordinate:o}))}}}});var qo=ml("externalEvent"),Mee=Jy(),hP=new Map;Mee.startListening({actionCreator:qo,effect:(t,e)=>{var{handler:n,reactEvent:r}=t.payload;if(n!=null){r.persist();var i=r.type,s=hP.get(i);s!==void 0&&cancelAnimationFrame(s);var o=requestAnimationFrame(()=>{try{var l=e.getState(),c={activeCoordinate:QRe(l),activeDataKey:a4(l),activeIndex:Ih(l),activeLabel:lJ(l),activeTooltipIndex:Ih(l),isTooltipActive:ZRe(l)};n(c,r)}finally{hP.delete(i)}});hP.set(i,o)}}});var fBe=st([Ib],t=>t.tooltipItemPayloads),mBe=st([fBe,pv,(t,e,n)=>e,(t,e,n)=>n],(t,e,n,r)=>{var i=t.find(l=>l.settings.dataKey===r);if(i!=null){var{positions:s}=i;if(s!=null){var o=e(s,n);return o}}}),Eee=ml("touchMove"),Tee=Jy();Tee.startListening({actionCreator:Eee,effect:(t,e)=>{var n=t.payload;if(!(n.touches==null||n.touches.length===0)){var r=e.getState(),i=JL(r,r.tooltip.settings.shared);if(i==="axis"){var s=M4(r,E4({clientX:n.touches[0].clientX,clientY:n.touches[0].clientY,currentTarget:n.currentTarget}));s?.activeIndex!=null&&e.dispatch(QZ({activeIndex:s.activeIndex,activeDataKey:void 0,activeCoordinate:s.activeCoordinate}))}else if(i==="item"){var o,l=n.touches[0];if(document.elementFromPoint==null)return;var c=document.elementFromPoint(l.clientX,l.clientY);if(!c||!c.getAttribute)return;var u=c.getAttribute(HY),d=(o=c.getAttribute($Y))!==null&&o!==void 0?o:void 0,h=mBe(e.getState(),u,d);e.dispatch(XZ({activeDataKey:d,activeIndex:u,activeCoordinate:h}))}}}});var pBe=cY({brush:z5e,cartesianAxis:ZFe,chartData:YOe,errorBars:bIe,graphicalItems:aFe,layout:STe,legend:PAe,options:GOe,polarAxis:v4e,polarOptions:hBe,referenceElements:Y5e,rootProps:cBe,tooltip:hRe,zIndex:DOe}),gBe=function(e){return KEe({reducer:pBe,preloadedState:e,middleware:n=>{var r;return n({serializableCheck:!1,immutableCheck:!["commonjs","es6","production"].includes((r="es6")!==null&&r!==void 0?r:"")}).concat([vee.middleware,wee.middleware,T4.middleware,Mee.middleware,Tee.middleware])},enhancers:n=>{var r=n;return typeof n=="function"&&(r=n()),r.concat(NY({type:"raf"}))},devTools:Ab.devToolsEnabled})};function Aee(t){var{preloadedState:e,children:n,reduxStoreName:r}=t,i=aa(),s=_.useRef(null);if(i)return n;s.current==null&&(s.current=gBe(e));var o=zO;return _.createElement(BIe,{context:o,store:s.current},n)}function bBe(t){var{layout:e,margin:n}=t,r=zr(),i=aa();return _.useEffect(()=>{i||(r(vTe(e)),r(yTe(n)))},[r,i,e,n]),null}var Cee=_.memo(bBe,vv);function Pee(t){var e=zr();return _.useEffect(()=>{e(uBe(t))},[e,t]),null}function Tq(t){var{zIndex:e,isPanorama:n}=t,r=n?"recharts-zindex-panorama-":"recharts-zindex-",i=zJ("".concat(r).concat(e)),s=zr();return _.useLayoutEffect(()=>(s(POe({zIndex:e,elementId:i,isPanorama:n})),()=>{s(jOe({zIndex:e,isPanorama:n}))}),[s,e,i,n]),_.createElement("g",{tabIndex:-1,id:i})}function Aq(t){var{children:e,isPanorama:n}=t,r=Ht(wOe);if(!r||r.length===0)return e;var i=r.filter(o=>o<0),s=r.filter(o=>o>0);return _.createElement(_.Fragment,null,i.map(o=>_.createElement(Tq,{key:o,zIndex:o,isPanorama:n})),e,s.map(o=>_.createElement(Tq,{key:o,zIndex:o,isPanorama:n})))}var xBe=["children"];function yBe(t,e){if(t==null)return{};var n,r,i=vBe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var n=YO(),r=QO(),i=aQ();if(!yc(n)||!yc(r))return null;var{children:s,otherAttributes:o,title:l,desc:c}=t,u,d;return o!=null&&(typeof o.tabIndex=="number"?u=o.tabIndex:u=i?0:void 0,typeof o.role=="string"?d=o.role:d=i?"application":void 0),_.createElement(AO,hN({},o,{title:l,desc:c,role:d,tabIndex:u,width:n,height:r,style:wBe,ref:e}),s)}),SBe=t=>{var{children:e}=t,n=Ht(tM);if(!n)return null;var{width:r,height:i,y:s,x:o}=n;return _.createElement(AO,{width:r,height:i,x:o,y:s},e)},Cq=_.forwardRef((t,e)=>{var{children:n}=t,r=yBe(t,xBe),i=aa();return i?_.createElement(SBe,null,_.createElement(Aq,{isPanorama:!0},n)):_.createElement(_Be,hN({ref:e},r),_.createElement(Aq,{isPanorama:!1},n))});function NBe(){var t=zr(),[e,n]=_.useState(null),r=Ht(UTe);return _.useEffect(()=>{if(e!=null){var i=e.getBoundingClientRect(),s=i.width/e.offsetWidth;wr(s)&&s!==r&&t(_Te(s))}},[e,t,r]),n}function Pq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function kBe(t){for(var e=1;e(aLe(),null);function fN(t){if(typeof t=="number")return t;if(typeof t=="string"){var e=parseFloat(t);if(!Number.isNaN(e))return e}return 0}var CBe=_.forwardRef((t,e)=>{var n,r,i=_.useRef(null),[s,o]=_.useState({containerWidth:fN((n=t.style)===null||n===void 0?void 0:n.width),containerHeight:fN((r=t.style)===null||r===void 0?void 0:r.height)}),l=_.useCallback((u,d)=>{o(h=>{var p=Math.round(u),m=Math.round(d);return h.containerWidth===p&&h.containerHeight===m?h:{containerWidth:p,containerHeight:m}})},[]),c=_.useCallback(u=>{if(typeof e=="function"&&e(u),u!=null&&typeof ResizeObserver<"u"){var{width:d,height:h}=u.getBoundingClientRect();l(d,h);var p=b=>{var{width:y,height:x}=b[0].contentRect;l(y,x)},m=new ResizeObserver(p);m.observe(u),i.current=m}},[e,l]);return _.useEffect(()=>()=>{var u=i.current;u?.disconnect()},[l]),_.createElement(_.Fragment,null,_.createElement(nM,{width:s.containerWidth,height:s.containerHeight}),_.createElement("div",Mm({ref:c},t)))}),PBe=_.forwardRef((t,e)=>{var{width:n,height:r}=t,[i,s]=_.useState({containerWidth:fN(n),containerHeight:fN(r)}),o=_.useCallback((c,u)=>{s(d=>{var h=Math.round(c),p=Math.round(u);return d.containerWidth===h&&d.containerHeight===p?d:{containerWidth:h,containerHeight:p}})},[]),l=_.useCallback(c=>{if(typeof e=="function"&&e(c),c!=null){var{width:u,height:d}=c.getBoundingClientRect();o(u,d)}},[e,o]);return _.createElement(_.Fragment,null,_.createElement(nM,{width:i.containerWidth,height:i.containerHeight}),_.createElement("div",Mm({ref:l},t)))}),jBe=_.forwardRef((t,e)=>{var{width:n,height:r}=t;return _.createElement(_.Fragment,null,_.createElement(nM,{width:n,height:r}),_.createElement("div",Mm({ref:e},t)))}),DBe=_.forwardRef((t,e)=>{var{width:n,height:r}=t;return qu(n)||qu(r)?_.createElement(PBe,Mm({},t,{ref:e})):_.createElement(jBe,Mm({},t,{ref:e}))});function RBe(t){return t===!0?CBe:DBe}var OBe=_.forwardRef((t,e)=>{var{children:n,className:r,height:i,onClick:s,onContextMenu:o,onDoubleClick:l,onMouseDown:c,onMouseEnter:u,onMouseLeave:d,onMouseMove:h,onMouseUp:p,onTouchEnd:m,onTouchMove:b,onTouchStart:y,style:x,width:v,responsive:S,dispatchTouchEvents:N=!0}=t,T=_.useRef(null),M=zr(),[A,k]=_.useState(null),[R,C]=_.useState(null),P=NBe(),U=XO(),F=U?.width>0?U.width:v,H=U?.height>0?U.height:i,D=_.useCallback(se=>{P(se),typeof e=="function"&&e(se),k(se),C(se),se!=null&&(T.current=se)},[P,e,k,C]),$=_.useCallback(se=>{M(yee(se)),M(qo({handler:s,reactEvent:se}))},[M,s]),G=_.useCallback(se=>{M(LD(se)),M(qo({handler:u,reactEvent:se}))},[M,u]),I=_.useCallback(se=>{M(YZ()),M(qo({handler:d,reactEvent:se}))},[M,d]),K=_.useCallback(se=>{M(LD(se)),M(qo({handler:h,reactEvent:se}))},[M,h]),Q=_.useCallback(()=>{M(kee())},[M]),oe=_.useCallback(se=>{M(Nee(se.key))},[M]),B=_.useCallback(se=>{M(qo({handler:o,reactEvent:se}))},[M,o]),W=_.useCallback(se=>{M(qo({handler:l,reactEvent:se}))},[M,l]),J=_.useCallback(se=>{M(qo({handler:c,reactEvent:se}))},[M,c]),ne=_.useCallback(se=>{M(qo({handler:p,reactEvent:se}))},[M,p]),me=_.useCallback(se=>{M(qo({handler:y,reactEvent:se}))},[M,y]),fe=_.useCallback(se=>{N&&M(Eee(se)),M(qo({handler:b,reactEvent:se}))},[M,N,b]),de=_.useCallback(se=>{M(qo({handler:m,reactEvent:se}))},[M,m]),Re=RBe(S);return _.createElement(gJ.Provider,{value:A},_.createElement(NX.Provider,{value:R},_.createElement(Re,{width:F??x?.width,height:H??x?.height,className:nr("recharts-wrapper",r),style:kBe({position:"relative",cursor:"default",width:F,height:H},x),onClick:$,onContextMenu:B,onDoubleClick:W,onFocus:Q,onKeyDown:oe,onMouseDown:J,onMouseEnter:G,onMouseLeave:I,onMouseMove:K,onMouseUp:ne,onTouchEnd:de,onTouchMove:fe,onTouchStart:me,ref:D},_.createElement(ABe,null),n)))}),LBe=["width","height","responsive","children","className","style","compact","title","desc"];function FBe(t,e){if(t==null)return{};var n,r,i=IBe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var{width:n,height:r,responsive:i,children:s,className:o,style:l,compact:c,title:u,desc:d}=t,h=FBe(t,LBe),p=Ms(h);return c?_.createElement(_.Fragment,null,_.createElement(nM,{width:n,height:r}),_.createElement(Cq,{otherAttributes:p,title:u,desc:d},s)):_.createElement(OBe,{className:o,style:l,width:n,height:r,responsive:i??!1,onClick:t.onClick,onMouseLeave:t.onMouseLeave,onMouseEnter:t.onMouseEnter,onMouseMove:t.onMouseMove,onMouseDown:t.onMouseDown,onMouseUp:t.onMouseUp,onContextMenu:t.onContextMenu,onDoubleClick:t.onDoubleClick,onTouchStart:t.onTouchStart,onTouchMove:t.onTouchMove,onTouchEnd:t.onTouchEnd},_.createElement(Cq,{otherAttributes:p,title:u,desc:d,ref:e},_.createElement(Q5e,null,s)))});function FD(){return FD=Object.assign?Object.assign.bind():function(t){for(var e=1;e_.createElement(A4,{chartName:"LineChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:BBe,tooltipPayloadSearcher:_M,categoricalChartProps:t,ref:e})),$Be=["axis","item"],VBe=_.forwardRef((t,e)=>_.createElement(A4,{chartName:"BarChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:$Be,tooltipPayloadSearcher:_M,categoricalChartProps:t,ref:e}));function GBe(t){var e=zr();return _.useEffect(()=>{e(dBe(t))},[e,t]),null}var qBe=["layout"];function ID(){return ID=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var n=ci(t,t8e);return _.createElement(YBe,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:e8e,tooltipPayloadSearcher:_M,categoricalChartProps:n,ref:e})}),r8e=["axis"],i8e=_.forwardRef((t,e)=>_.createElement(A4,{chartName:"AreaChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:r8e,tooltipPayloadSearcher:_M,categoricalChartProps:t,ref:e}));const Rq=[{value:"6h",label:"6h",hours:6},{value:"24h",label:"24h",hours:24},{value:"48h",label:"48h",hours:48},{value:"7d",label:"7d",hours:168}];function a8e({isOpen:t,onClose:e,printerId:n,printerName:r,amsId:i,amsLabel:s,initialMode:o="humidity",thresholds:l}){const{t:c}=Yt(),{mode:u}=Dm(),[d,h]=_.useState("24h"),[p,m]=_.useState(o),b=u==="dark",{data:y}=it({queryKey:["settings"],queryFn:ae.getSettings}),x=y?.time_format||"system";_.useEffect(()=>{if(!t)return;const ne=me=>{me.key==="Escape"&&e()};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[t,e]);const v=Rq.find(ne=>ne.value===d)?.hours||24,{data:S,isLoading:N,error:T}=it({queryKey:["ams-history",n,i,v],queryFn:()=>ae.getAMSHistory(n,i,v),enabled:t,refetchInterval:6e4});if(!t)return null;const M=S?.data.map(ne=>{const me=zi(ne.recorded_at)||new Date,fe={hour:"2-digit",minute:"2-digit",...v>24?{day:"numeric",month:"short"}:{}};return{time:me.getTime(),humidity:ne.humidity,temperature:ne.temperature,timeLabel:me.toLocaleTimeString([],S0(fe,x))}})||[],A=l?.humidityGood||40,k=l?.humidityFair||60,R=l?.tempGood||30,C=l?.tempFair||35,P=M[M.length-1],U=P?.humidity,F=P?.temperature,H=ne=>{const me=ne.filter(Fe=>Fe!=null);if(me.length<4)return"stable";const fe=me.slice(0,Math.floor(me.length/4)),de=me.slice(-Math.floor(me.length/4)),Re=fe.reduce((Fe,ce)=>Fe+ce,0)/fe.length,ke=de.reduce((Fe,ce)=>Fe+ce,0)/de.length-Re;return Math.abs(ke)<2?"stable":ke>0?"up":"down"},D=H(M.map(ne=>ne.humidity)),$=H(M.map(ne=>ne.temperature)),G=({trend:ne})=>ne==="up"?a.jsx(Pj,{className:"w-4 h-4 text-red-400"}):ne==="down"?a.jsx(GW,{className:"w-4 h-4 text-green-400"}):a.jsx(Aj,{className:"w-4 h-4 text-gray-400 dark:text-bambu-gray"}),I=ne=>ne==null?"#9ca3af":ne<=A?"#22a352":ne<=k?"#d4a017":"#c62828",K=ne=>ne==null?"#9ca3af":ne<=R?"#22a352":ne<=C?"#d4a017":"#c62828",Q=b?"#2d2d2d":"#ffffff",oe=b?"#1d1d1d":"#f3f4f6",B=b?"#3d3d3d":"#e5e7eb",W=b?"#ffffff":"#111827",J=b?"#9ca3af":"#4b5563";return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:a.jsxs("div",{className:"rounded-xl w-full max-w-4xl max-h-[90vh] overflow-hidden shadow-xl",style:{backgroundColor:Q},onClick:ne=>ne.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",style:{borderColor:B},children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold",style:{color:W},children:[s," ",c("common.history","History")]}),a.jsx("p",{className:"text-sm",style:{color:J},children:r})]}),a.jsx("button",{onClick:e,className:"p-2 rounded-lg transition-colors",style:{color:J},children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 space-y-6 overflow-y-auto max-h-[calc(90vh-80px)]",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex gap-1 rounded-lg p-1",style:{backgroundColor:oe},children:[a.jsxs("button",{onClick:()=>m("humidity"),className:`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${p==="humidity"?"bg-blue-600 text-white":""}`,style:p!=="humidity"?{color:J}:void 0,children:[a.jsx(HR,{className:"w-4 h-4"}),c("common.humidity","Humidity")]}),a.jsxs("button",{onClick:()=>m("temperature"),className:`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${p==="temperature"?"bg-orange-600 text-white":""}`,style:p!=="temperature"?{color:J}:void 0,children:[a.jsx(Ek,{className:"w-4 h-4"}),c("common.temperature","Temperature")]})]}),a.jsx("div",{className:"flex gap-1 rounded-lg p-1",style:{backgroundColor:oe},children:Rq.map(ne=>a.jsx("button",{onClick:()=>h(ne.value),className:`px-3 py-1 text-sm rounded-md transition-colors ${d===ne.value?"bg-bambu-green text-white":""}`,style:d!==ne.value?{color:J}:void 0,children:ne.label},ne.value))})]}),a.jsx("div",{className:"grid grid-cols-4 gap-4",children:p==="humidity"?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.current","Current")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-2xl font-bold",style:{color:I(U)},children:U!=null?`${U}%`:"—"}),a.jsx(G,{trend:D})]})]}),a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.average","Average")}),a.jsx("p",{className:"text-2xl font-bold",style:{color:W},children:S?.avg_humidity!=null?`${S.avg_humidity}%`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.min","Min")}),a.jsx("p",{className:"text-2xl font-bold text-green-500",children:S?.min_humidity!=null?`${S.min_humidity}%`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.max","Max")}),a.jsx("p",{className:"text-2xl font-bold text-red-500",children:S?.max_humidity!=null?`${S.max_humidity}%`:"—"})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.current","Current")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-2xl font-bold",style:{color:K(F)},children:F!=null?`${F}°C`:"—"}),a.jsx(G,{trend:$})]})]}),a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.average","Average")}),a.jsx("p",{className:"text-2xl font-bold",style:{color:W},children:S?.avg_temperature!=null?`${S.avg_temperature}°C`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.min","Min")}),a.jsx("p",{className:"text-2xl font-bold text-blue-500",children:S?.min_temperature!=null?`${S.min_temperature}°C`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:[a.jsx("p",{className:"text-xs",style:{color:J},children:c("common.max","Max")}),a.jsx("p",{className:"text-2xl font-bold text-red-500",children:S?.max_temperature!=null?`${S.max_temperature}°C`:"—"})]})]})}),a.jsx("div",{className:"rounded-lg p-4",style:{backgroundColor:oe},children:N?a.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:J},children:c("common.loading","Loading...")}):T?a.jsx("div",{className:"h-[300px] flex items-center justify-center text-red-500",children:c("common.error","Error loading data")}):M.length===0?a.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:J},children:c("common.noData","No data available for this time range")}):a.jsx(F1,{width:"100%",height:300,children:a.jsxs(HBe,{data:M,children:[a.jsx(lN,{strokeDasharray:"3 3",stroke:b?"#3d3d3d":"#e5e7eb"}),a.jsx(uN,{dataKey:"time",type:"number",domain:["dataMin","dataMax"],tickFormatter:ne=>{const me=new Date(ne);return v>24?me.toLocaleDateString([],{day:"numeric",month:"short"}):me.toLocaleTimeString([],S0({hour:"2-digit",minute:"2-digit"},x))},stroke:b?"#9ca3af":"#6b7280",tick:{fontSize:12}}),a.jsx(dN,{stroke:b?"#9ca3af":"#6b7280",tick:{fontSize:12},domain:p==="humidity"?[0,100]:["auto","auto"],tickFormatter:ne=>p==="humidity"?`${ne}%`:`${ne}°C`}),a.jsx(z1,{contentStyle:{backgroundColor:b?"#2d2d2d":"#ffffff",border:`1px solid ${b?"#3d3d3d":"#e5e7eb"}`,borderRadius:"8px",color:b?"#fff":"#000"},labelFormatter:ne=>new Date(ne).toLocaleString(void 0,S0({year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},x)),formatter:ne=>[p==="humidity"?`${ne??0}%`:`${ne??0}°C`,p==="humidity"?"Humidity":"Temperature"]}),a.jsx(eL,{}),p==="humidity"?a.jsxs(a.Fragment,{children:[a.jsx(m0,{y:A,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),a.jsx(m0,{y:k,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}):a.jsxs(a.Fragment,{children:[a.jsx(m0,{y:R,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),a.jsx(m0,{y:C,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}),a.jsx(cee,{type:"monotone",dataKey:p,name:p==="humidity"?"Humidity":"Temperature",stroke:p==="humidity"?"#3b82f6":"#f97316",strokeWidth:2,dot:!1,activeDot:{r:4}})]})})}),a.jsx("div",{className:"text-xs text-center",style:{color:J},children:c("amsHistory.recordingInfo","Data is recorded every 5 minutes while the printer is connected")})]})]})})}function fP({data:t,children:e,disabled:n,className:r="",spoolman:i,configureSlot:s}){const{t:o}=Yt(),[l,c]=_.useState(!1),[u,d]=_.useState("top"),[h,p]=_.useState(!1),m=_.useRef(null),b=_.useRef(null),y=_.useRef(null),x=()=>{const k=t.trayUuid;k&&(navigator.clipboard&&window.isSecureContext?navigator.clipboard.writeText(k).then(()=>{p(!0),setTimeout(()=>p(!1),2e3)}).catch(()=>{v(k)}):v(k))},v=k=>{const R=document.createElement("textarea");R.value=k,R.style.position="fixed",R.style.opacity="0",document.body.appendChild(R),R.select();try{document.execCommand("copy"),p(!0),setTimeout(()=>p(!1),2e3)}catch{console.error("Failed to copy to clipboard")}document.body.removeChild(R)};_.useEffect(()=>{if(l&&m.current&&b.current){const k=m.current.getBoundingClientRect(),R=b.current.offsetHeight,P=k.top-56,U=window.innerHeight-k.bottom;PP?d("bottom"):d("top")}},[l]);const S=()=>{n||(y.current&&clearTimeout(y.current),y.current=setTimeout(()=>c(!0),80))},N=()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>c(!1),100)};_.useEffect(()=>()=>{y.current&&clearTimeout(y.current)},[]);const T=k=>k<=15?"#ef4444":k<=30?"#f97316":k<=50?"#eab308":"#22c55e",M=k=>{if(!k)return!1;const R=k.replace("#",""),C=parseInt(R.slice(0,2),16),P=parseInt(R.slice(2,4),16),U=parseInt(R.slice(4,6),16);return(.299*C+.587*P+.114*U)/255>.6},A=t.colorHex?`#${t.colorHex.replace("#","")}`:null;return a.jsxs("div",{ref:m,className:`relative ${r}`,onMouseEnter:S,onMouseLeave:N,children:[e,l&&a.jsxs("div",{ref:b,className:` absolute left-1/2 -translate-x-1/2 z-50 ${u==="top"?"bottom-full mb-2":"top-full mt-2"} animate-in fade-in-0 zoom-in-95 duration-150 @@ -8482,7 +8482,7 @@ void main() { border-l-[5px] border-l-transparent border-r-[5px] border-r-transparent border-t-[5px] border-t-bambu-dark-tertiary - `})]})]})}function s8e({isOpen:t,onClose:e,trayUuid:n,trayInfo:r}){const{t:i}=Yt(),s=an(),{showToast:o}=Tn(),[l,c]=_.useState(null),{data:u,isLoading:d}=it({queryKey:["unlinked-spools"],queryFn:ae.getUnlinkedSpools,enabled:t}),h=dt({mutationFn:m=>ae.linkSpool(m,n),onSuccess:()=>{s.invalidateQueries({queryKey:["unlinked-spools"]}),s.invalidateQueries({queryKey:["linked-spools"]}),s.invalidateQueries({queryKey:["spoolman-status"]}),o(i("spoolman.linkSuccess"),"success"),e()},onError:m=>{o(`${i("spoolman.linkFailed")}: ${m.message}`,"error")}});if(!t)return null;const p=()=>{l&&h.mutate(l)};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-md mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(dc,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("spoolman.linkToSpoolman")})]}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[r&&a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Linking AMS tray:"}),a.jsxs("div",{className:"flex items-center gap-2",children:[r.color&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20",style:{backgroundColor:`#${r.color}`}}),a.jsx("span",{className:"text-white font-medium",children:r.type}),a.jsxs("span",{className:"text-bambu-gray",children:["(",r.location,")"]})]})]}),a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-1",children:[i("spoolman.spoolId"),":"]}),a.jsx("code",{className:"text-xs text-bambu-green font-mono break-all",children:n})]}),a.jsxs("div",{children:[a.jsxs("p",{className:"text-sm text-bambu-gray mb-2",children:[i("spoolman.selectSpool"),":"]}),d?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u&&u.length>0?a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-2",children:u.map(m=>a.jsx("button",{onClick:()=>c(m.id),className:`w-full p-3 rounded-lg border text-left transition-colors ${l===m.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:a.jsxs("div",{className:"flex items-center gap-2",children:[m.filament_color_hex&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:`#${m.filament_color_hex}`}}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-white font-medium truncate",children:m.filament_name||"Unknown filament"}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[m.filament_material||"Unknown",m.remaining_weight!==null&&` - ${Math.round(m.remaining_weight)}g`,m.location&&` - ${m.location}`]})]}),l===m.id&&a.jsx($i,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]})},m.id))}):a.jsx("div",{className:"text-center py-8 text-bambu-gray",children:a.jsx("p",{children:i("spoolman.noUnlinkedSpools")})})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ne,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ne,{onClick:p,disabled:!l||h.isPending,children:h.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),i("spoolman.syncing")]}):a.jsxs(a.Fragment,{children:[a.jsx(dc,{className:"w-4 h-4"}),i("spoolman.linkToSpoolman")]})})]}),h.isError&&a.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:h.error.message})]})]})}function o8e(t,e){if(t===255)return"External";let n,r=!1;t>=128&&t<=135?(n=t-128,r=!0):t>=0&&t<=3?(n=t,r=e===1):n=0,n=Math.max(0,Math.min(n,7));const i=String.fromCharCode(65+n);return r?`HT-${i}`:`AMS-${i}`}function Lq(t){const e=t.includes("_")?t.split("_")[0]:t;return e.startsWith("GFS")?"GF"+e.slice(3):(e.startsWith("PFUS")||e.startsWith("PFSP"),e)}const l8e=["PLA","PETG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function Fq(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const i of l8e){const s=new RegExp(`\\b${i}\\b`,"i");if(s.test(n)){const o=e.split(s),l=o[0]?.trim()||"",c=o[1]?.trim()||"";return{material:i,brand:l,variant:c}}}const r=e.split(/\s+/);return r.length>=2?{material:r[1],brand:r[0],variant:r.slice(2).join(" ")}:{material:e,brand:"",variant:""}}function c8e(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const u8e={white:"FFFFFF",black:"000000",red:"FF0000",green:"00FF00",blue:"0000FF",yellow:"FFFF00",cyan:"00FFFF",magenta:"FF00FF",orange:"FFA500",purple:"800080",pink:"FFC0CB",brown:"8B4513",gray:"808080",grey:"808080","jade white":"FFFEF2",ivory:"FFFFF0",beige:"F5F5DC",cream:"FFFDD0",silver:"C0C0C0",gold:"FFD700",bronze:"CD7F32",copper:"B87333",navy:"000080",teal:"008080",olive:"808000",maroon:"800000",coral:"FF7F50",salmon:"FA8072",lime:"32CD32",mint:"98FF98","forest green":"228B22","sky blue":"87CEEB","royal blue":"4169E1",turquoise:"40E0D0",lavender:"E6E6FA",violet:"EE82EE",plum:"DDA0DD",tan:"D2B48C",chocolate:"D2691E",charcoal:"36454F",slate:"708090",transparent:"000000",natural:"F5F5DC",wood:"DEB887"},d8e=[{name:"White",hex:"FFFFFF"},{name:"Black",hex:"000000"},{name:"Red",hex:"FF0000"},{name:"Blue",hex:"0000FF"},{name:"Green",hex:"00AA00"},{name:"Yellow",hex:"FFFF00"},{name:"Orange",hex:"FFA500"},{name:"Gray",hex:"808080"}],h8e=[{name:"Cyan",hex:"00FFFF"},{name:"Magenta",hex:"FF00FF"},{name:"Purple",hex:"800080"},{name:"Pink",hex:"FFC0CB"},{name:"Brown",hex:"8B4513"},{name:"Beige",hex:"F5F5DC"},{name:"Navy",hex:"000080"},{name:"Teal",hex:"008080"},{name:"Lime",hex:"32CD32"},{name:"Gold",hex:"FFD700"},{name:"Silver",hex:"C0C0C0"},{name:"Maroon",hex:"800000"},{name:"Olive",hex:"808000"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Indigo",hex:"4B0082"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Slate",hex:"708090"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Cream",hex:"FFFDD0"}];function f8e(t){const e=t.toLowerCase().trim();return u8e[e]||null}function m8e({isOpen:t,onClose:e,printerId:n,slotInfo:r,nozzleDiameter:i="0.4",onSuccess:s}){const{t:o}=Yt(),[l,c]=_.useState(""),[u,d]=_.useState(null),[h,p]=_.useState(""),[m,b]=_.useState(""),[y,x]=_.useState(""),[v,S]=_.useState(!1),[N,T]=_.useState(!1),{data:M,isLoading:A}=it({queryKey:["cloudSettings"],queryFn:()=>ae.getCloudSettings(),enabled:t}),{data:k,isLoading:R}=it({queryKey:["localPresets"],queryFn:()=>ae.getLocalPresets(),enabled:t}),{data:C,isLoading:P}=it({queryKey:["kprofiles",n,i],queryFn:()=>ae.getKProfiles(n,i),enabled:t&&!!n}),U=dt({mutationFn:async()=>{if(!l)throw new Error("No filament preset selected");const B=l.startsWith("local_"),W=B?parseInt(l.replace("local_",""),10):null,J=B?k?.filament.find(X=>X.id===W):null,ne=B?null:M?.filament.find(X=>X.setting_id===l);if(!B&&!ne)throw new Error("Selected preset not found");if(B&&!J)throw new Error("Selected local preset not found");const me=B?J.name:ne.name,fe=Fq(me),de=u?.slot_id??-1,Re=h||r.trayColor?.slice(0,6)||"FFFFFF",se=me.replace(/@.+$/,"").trim();let ke,Fe;if(B)ke="",Fe="";else if(ke=Lq(l),Fe=l,!l.startsWith("GFS"))try{const X=await ae.getCloudSettingDetail(l);X.filament_id?ke=X.filament_id:X.base_id&&(ke=Lq(X.base_id),console.log(`Derived tray_info_idx from base_id: ${X.base_id} -> ${ke}`))}catch(X){console.warn("Failed to fetch preset detail for filament_id:",X)}let ce=B&&J?.nozzle_temp_min?J.nozzle_temp_min:190,Ve=B&&J?.nozzle_temp_max?J.nozzle_temp_max:230;if(!B||!J?.nozzle_temp_min&&!J?.nozzle_temp_max){const X=(B&&J?.filament_type||fe.material).toUpperCase();X.includes("PLA")?(ce=190,Ve=230):X.includes("PETG")?(ce=220,Ve=260):X.includes("ABS")||X.includes("ASA")?(ce=240,Ve=280):X.includes("TPU")?(ce=200,Ve=240):X.includes("PC")?(ce=260,Ve=300):(X.includes("PA")||X.includes("NYLON"))&&(ce=250,Ve=290)}const V=u?.k_value?parseFloat(u.k_value):0,Y=B?J?.filament_type||fe.material||"PLA":fe.material||"PLA",ue=await ae.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:ke,tray_type:Y,tray_sub_brands:se,tray_color:Re+"FF",nozzle_temp_min:ce,nozzle_temp_max:Ve,cali_idx:de,nozzle_diameter:i,setting_id:Fe,kprofile_filament_id:u?.filament_id,kprofile_setting_id:u?.setting_id||void 0,k_value:V}),q=B?`local_${W}`:l,re=B?"local":"cloud";try{await ae.saveSlotPreset(n,r.amsId,r.trayId,q,se,re)}catch(X){console.warn("Failed to save slot preset mapping:",X)}return ue},onSuccess:()=>{S(!0),s?.(),setTimeout(()=>{S(!1),e()},1500)}}),F=dt({mutationFn:async()=>ae.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{S(!0),s?.(),setTimeout(()=>{S(!1),e()},1500)}}),H=_.useMemo(()=>{const B=y.toLowerCase(),W=[];if(k?.filament)for(const J of k.filament)(!B||J.name.toLowerCase().includes(B))&&W.push({id:`local_${J.id}`,name:J.name,source:"local",isUser:!1});if(M?.filament)for(const J of M.filament)(!B||J.name.toLowerCase().includes(B))&&W.push({id:J.setting_id,name:J.name,source:"cloud",isUser:c8e(J.setting_id)});return W.sort((J,ne)=>J.source==="local"&&ne.source!=="local"?-1:J.source!=="local"&&ne.source==="local"?1:J.isUser&&!ne.isUser?-1:!J.isUser&&ne.isUser?1:J.name.localeCompare(ne.name))},[M?.filament,k?.filament,y]),D=_.useMemo(()=>{if(!l)return null;let B=null;if(l.startsWith("local_")){const ne=parseInt(l.replace("local_",""),10);B=k?.filament.find(fe=>fe.id===ne)?.name||null}else M?.filament&&(B=M.filament.find(me=>me.setting_id===l)?.name||null);if(!B)return null;let W=B.replace(/@.+$/,"").trim();W.startsWith("# ")&&(W=W.slice(2).trim());const J=Fq(W);return{fullName:W,material:J.material,brand:J.brand}},[l,M?.filament,k?.filament]),$=D?.fullName||"",G=_.useMemo(()=>{if(!C?.profiles||!D)return[];const{fullName:B,material:W,brand:J}=D,ne=B.toUpperCase(),me=W.toUpperCase(),fe=J.toUpperCase();if(!me||me.length<2)return[];const de=C.profiles.filter(se=>{const ke=se.name.toUpperCase();if(fe)return!(!ke.includes(fe)||!ke.includes(me));if(ke.includes(ne)||ke.includes(me))return!0;const ce={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[me]||[];for(const Ve of ce)if(ke.includes(Ve))return!0;return!1}),Re=new Map;for(const se of de){const ke=`${se.name}|${se.k_value}`,Fe=Re.get(ke);Fe?se.extruder_id===1&&Fe.extruder_id===0&&Re.set(ke,se):Re.set(ke,se)}return Array.from(Re.values())},[C?.profiles,D]);_.useEffect(()=>{if(t&&M?.filament){if(r.trayInfoIdx){const B=M.filament.find(W=>W.setting_id===r.trayInfoIdx);B&&c(B.setting_id)}}else t||(c(""),d(null),p(""),b(""),x(""),S(!1))},[t,M?.filament,r.trayInfoIdx]),_.useEffect(()=>{G.length>0?d(G[0]):d(null)},[l,G]);const I=_.useCallback(B=>{B.key==="Escape"&&e()},[e]);if(_.useEffect(()=>{if(t)return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[t,I]),!t)return null;const K=A||R||P,Q=l&&!U.isPending,oe=h||r.trayColor?.slice(0,6)||"FFFFFF";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",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Hu,{className:"w-5 h-5 text-bambu-blue"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Configure AMS Slot"})]}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4 max-h-[60vh] overflow-y-auto",children:[v&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl",children:a.jsxs("div",{className:"text-center space-y-3",children:[a.jsx(mk,{className:"w-16 h-16 text-bambu-green mx-auto"}),a.jsx("p",{className:"text-lg font-semibold text-white",children:"Slot Configured!"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:o("configureAmsSlot.settingsSentToPrinter")})]})}),a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Configuring slot:"}),a.jsxs("div",{className:"flex items-center gap-2",children:[r.trayColor&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),a.jsxs("span",{className:"text-white font-medium",children:[o8e(r.amsId,r.trayCount)," Slot ",r.trayId+1]}),r.traySubBrands&&a.jsxs("span",{className:"text-bambu-gray",children:["(",r.traySubBrands,")"]})]})]}),K?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:["Filament Profile ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:o("configureAmsSlot.searchPresets"),value:y,onChange:B=>x(B.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2"}),a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:H.length===0?a.jsx("p",{className:"text-center py-4 text-bambu-gray",children:M?.filament?.length===0&&!k?.filament?.length?"No presets available. Login to Bambu Cloud or import local profiles.":"No matching presets found."}):H.map(B=>a.jsx("button",{onClick:()=>c(B.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${l===B.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-white text-sm truncate",children:B.name}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[B.source==="local"&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:o("profiles.localProfiles.badge")}),B.isUser&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:o("configureAmsSlot.custom")})]})]})},B.id))})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:["K Profile (Pressure Advance)",$&&a.jsxs("span",{className:"ml-2 text-xs text-bambu-blue",children:["Filtering for: ",$]})]}),G.length>0?a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:u?.name||"",onChange:B=>{const W=G.find(J=>J.name===B.target.value);d(W||null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10",children:[a.jsx("option",{value:"",children:"No K profile (use default 0.020)"}),G.map(B=>a.jsxs("option",{value:B.name,children:[B.name," (K=",B.k_value,")"]},`${B.name}-${B.extruder_id}`))]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):l?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:"No matching K profiles found. Default K=0.020 will be used."}):a.jsx("span",{className:"inline-block text-xs px-2 py-1 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30",children:"Select a filament profile first"}),u&&a.jsxs("p",{className:"text-xs text-bambu-green mt-1",children:["K=",u.k_value," from printer calibration"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Custom Color (optional)"}),a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[d8e.map(B=>a.jsx("button",{onClick:()=>{p(B.hex),b(B.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${h===B.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${B.hex}`},title:B.name},B.hex)),a.jsx("button",{onClick:()=>T(!N),className:"w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs",title:N?"Show less colors":"Show more colors",children:N?"−":"+"})]}),N&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:h8e.map(B=>a.jsx("button",{onClick:()=>{p(B.hex),b(B.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${h===B.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${B.hex}`},title:B.name},B.hex))}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${oe}`}}),a.jsx("input",{type:"text",placeholder:o("configureAmsSlot.colorPlaceholder"),value:m,onChange:B=>{const W=B.target.value;b(W);const J=f8e(W);if(J)p(J);else{const ne=W.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();ne.length===6?p(ne):ne.length===3&&p(ne.split("").map(me=>me+me).join(""))}},className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"}),h&&a.jsx("button",{onClick:()=>{p(""),b("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:o("configureAmsSlot.clearCustomColor"),children:"Clear"})]}),h&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-1.5",children:["Hex: #",h]})]})]})]}),a.jsxs("div",{className:"flex justify-between p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>F.mutate(),disabled:F.isPending||U.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:F.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Resetting..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Bu,{className:"w-4 h-4"}),"Reset Slot"]})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ne,{variant:"secondary",onClick:e,children:"Cancel"}),a.jsx(Ne,{onClick:()=>U.mutate(),disabled:!Q,children:U.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Configuring..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Hu,{className:"w-4 h-4"}),"Configure Slot"]})})]})]}),(U.isError||F.isError)&&a.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:U.error?.message||F.error?.message})]})]})}const Iq={"A00-W1":"Jade White","A00-P0":"Beige","A00-D2":"Light Gray","A00-Y0":"Yellow","A00-Y2":"Sunflower Yellow","A00-A1":"Pumpkin Orange","A00-A0":"Orange","A00-Y4":"Gold","A00-G3":"Bright Green","A00-G1":"Bambu Green","A00-G2":"Mistletoe Green","A00-R3":"Hot Pink","A00-P6":"Magenta","A00-R0":"Red","A00-R2":"Maroon Red","A00-P5":"Purple","A00-P2":"Indigo Purple","A00-B5":"Turquoise","A00-B8":"Cyan","A00-B3":"Cobalt Blue","A00-N0":"Brown","A00-N1":"Cocoa Brown","A00-Y3":"Bronze","A00-D0":"Gray","A00-D1":"Silver","A00-B1":"Blue Grey","A00-D3":"Dark Gray","A00-K0":"Black","A00-M3":"Pink Citrus","A00-M6":"Dusk Glare","A00-M0":"Arctic Whisper","A00-M1":"Solar Breeze","A00-M5":"Blueberry Bubblegum","A00-M4":"Mint Lime","A00-M2":"Ocean to Meadow","A00-M7":"Cotton Candy Cloud","A18-K0":"Black","A18-D0":"Gray","A18-W0":"White","A18-R0":"Red","A18-Y0":"Yellow","A18-B0":"Cyan","A18-B1":"Blue","A18-P0":"Matte Beige","A01-W2":"Ivory White","A01-W3":"Bone White","A01-Y2":"Lemon Yellow","A01-A2":"Mandarin Orange","A01-P3":"Sakura Pink","A01-P4":"Lilac Purple","A01-R3":"Plum","A01-R1":"Scarlet Red","A01-R4":"Dark Red","A01-G0":"Apple Green","A01-G1":"Grass Green","A01-G7":"Dark Green","A01-B4":"Ice Blue","A01-B0":"Sky Blue","A01-B3":"Marine Blue","A01-B6":"Dark Blue","A01-Y3":"Desert Tan","A01-N1":"Latte Brown","A01-N3":"Caramel","A01-R2":"Terracotta","A01-N2":"Dark Brown","A01-N0":"Dark Chocolate","A01-D3":"Ash Gray","A01-D0":"Nardo Gray","A01-K1":"Charcoal","A12-G0":"Green","A12-R0":"Pink","A12-A0":"Orange","A12-Y0":"Yellow","A12-B0":"Blue","A07-R5":"Red Granite","A07-D4":"White Marble","A11-W0":"White","A11-K0":"Black","A08-G3":"Alpine Green Sparkle","A08-D5":"Slate Gray Sparkle","A08-B7":"Royal Purple Sparkle","A08-R2":"Crimson Red Sparkle","A08-K2":"Onyx Black Sparkle","A08-Y1":"Classic Gold Sparkle","A02-B2":"Cobalt Blue Metallic","A02-G2":"Oxide Green Metallic","A02-Y1":"Iridium Gold Metallic","A02-D2":"Iron Gray Metallic","A17-B1":"Blue","A17-A0":"Orange","A17-P0":"Purple","A06-Y1":"Gold","A06-D0":"Titan Gray","A06-D1":"Silver","A06-W0":"White","A06-R0":"Candy Red","A06-G0":"Candy Green","A06-G1":"Mint","A06-B1":"Blue","A06-B0":"Baby Blue","A06-P0":"Purple","A06-R1":"Rose Gold","A06-R2":"Pink","A06-Y0":"Champagne","A05-M8":"Dawn Radiance","A05-M4":"Aurora Purple","A05-M1":"South Beach","A05-T3":"Neon City","A05-T2":"Midnight Blaze","A05-T1":"Gilded Rose","A05-T4":"Blue Hawaii","A05-T5":"Velvet Eclipse","A15-B0":"Purple","A15-G0":"Green","A15-G1":"Nebulae","A15-R0":"Brown","A16-K0":"Black Walnut","A16-R0":"Rosewood","A16-N0":"Clay Brown","A16-G0":"Classic Birch","A16-W0":"White Oak","A16-Y0":"Ochre Yellow","A50-D6":"Lava Gray","A50-K0":"Black","A50-B6":"Royal Blue","A10-W0":"White","A10-D0":"Gray","A09-B5":"Lavender Blue","A09-B4":"Light Blue","A09-A0":"Orange","A09-D1":"Silver","A09-R3":"Vermilion Red","A09-Y0":"Yellow","G02-K0":"Black","G02-W0":"White","G02-R0":"Red","G02-D0":"Gray","G02-D1":"Dark Gray","G02-Y1":"Cream","G02-Y0":"Yellow","G02-A0":"Orange","G02-N1":"Peanut Brown","G02-G1":"Lime Green","G02-G0":"Green","G02-G2":"Forest Green","G02-B1":"Lake Blue","G02-B0":"Blue","G01-G1":"Translucent Teal","G01-B0":"Translucent Light Blue","G01-C0":"Clear","G01-D0":"Translucent Gray","G01-G0":"Translucent Olive","G01-N0":"Translucent Brown","G01-A0":"Translucent Orange","G01-P1":"Translucent Pink","G01-P0":"Translucent Purple","G50-P7":"Violet Purple","G50-K0":"Black","B00-D1":"Silver","B00-K0":"Black","B00-W0":"White","B00-G6":"Bambu Green","B00-G7":"Olive","B00-Y1":"Tangerine Yellow","B00-A0":"Orange","B00-R0":"Red","B00-B4":"Azure","B00-B0":"Blue","B00-B6":"Navy Blue","B50-A0":"Orange","B50-K0":"Black","B01-W0":"White","B01-K0":"Black","B01-D0":"Gray","B02-W0":"White","C00-C1":"Transparent","C00-C0":"Clear Black","C00-K0":"Black","C00-W0":"White","C01-K0":"Black","U02-B0":"Blue","U02-D0":"Gray","U02-K0":"Black","N04-K0":"Black","N08-K0":"Black","S02-W0":"Nature","S02-W1":"White","S05-C0":"Black","S06-W0":"White","S03-G1":"Green","S04-Y0":"Clear"},p8e={W0:"White",W1:"Jade White",W2:"Ivory White",W3:"Bone White",Y0:"Yellow",Y1:"Gold",Y2:"Sunflower Yellow",Y3:"Bronze",Y4:"Gold",A0:"Orange",A1:"Pumpkin Orange",A2:"Mandarin Orange",R0:"Red",R1:"Scarlet Red",R2:"Maroon Red",R3:"Hot Pink",R4:"Dark Red",R5:"Red Granite",P0:"Beige",P1:"Pink",P2:"Indigo Purple",P3:"Sakura Pink",P4:"Lilac Purple",P5:"Purple",P6:"Magenta",P7:"Violet Purple",B0:"Blue",B1:"Blue Grey",B2:"Cobalt Blue",B3:"Cobalt Blue",B4:"Ice Blue",B5:"Turquoise",B6:"Navy Blue",B7:"Royal Purple",B8:"Cyan",G0:"Green",G1:"Grass Green",G2:"Mistletoe Green",G3:"Bright Green",G6:"Bambu Green",G7:"Dark Green",N0:"Brown",N1:"Peanut Brown",N2:"Dark Brown",N3:"Caramel",D0:"Gray",D1:"Silver",D2:"Light Gray",D3:"Dark Gray",D4:"White Marble",D5:"Slate Gray",D6:"Lava Gray",K0:"Black",K1:"Charcoal",K2:"Onyx Black",C0:"Clear Black",C1:"Transparent",M0:"Arctic Whisper",M1:"Solar Breeze",M2:"Ocean to Meadow",M3:"Pink Citrus",M4:"Aurora Purple",M5:"Blueberry Bubblegum",M6:"Dusk Glare",M7:"Cotton Candy Cloud",M8:"Dawn Radiance",T1:"Gilded Rose",T2:"Midnight Blaze",T3:"Neon City",T4:"Blue Hawaii",T5:"Velvet Eclipse"};function mP(t){if(!t)return null;if(Iq[t])return Iq[t];const e=t.split("-");if(e.length<2)return null;const n=e[1];return p8e[n]||null}function pP(t){if(!t||t.length<6)return"Unknown";const e=parseInt(t.substring(0,2),16),n=parseInt(t.substring(2,4),16),r=parseInt(t.substring(4,6),16),i=Math.max(e,n,r)/255,s=Math.min(e,n,r)/255,o=(i+s)/2;let l=0,c=0;if(i!==s){const u=i-s;c=o>.5?u/(2-i-s):u/(i+s);const d=e/255,h=n/255,p=r/255;i===d?l=((h-p)/u+(h.85?"White":c<.15?o<.4?"Dark Gray":o>.6?"Light Gray":"Gray":l>=15&&l<45&&o<.45||l>=45&&l<70&&o<.4?"Brown":l<15||l>=345?"Red":l<45?"Orange":l<70?"Yellow":l<150?"Green":l<200?"Cyan":l<260?"Blue":l<290?"Purple":"Pink"}function gP(t){return(t??.02).toFixed(3)}function zq({side:t}){const{mode:e}=Dm(),n=e==="dark"?"#1a4d2e":"#e7f5e9";return a.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded",style:{backgroundColor:n,color:"#00ae42"},children:t})}function Ree(t){if(!t||t==="00000000"||t.length<6)return null;const e=t.slice(0,2),n=t.slice(2,4),r=t.slice(4,6),i=t.length>=8?parseInt(t.slice(6,8),16)/255:1;return i===0?null:`rgba(${parseInt(e,16)}, ${parseInt(n,16)}, ${parseInt(r,16)}, ${i})`}function Oee(t,e){if(!t)return"";if(t.includes("hardened"))return e("printers.nozzleHardenedSteel");if(t.includes("stainless"))return e("printers.nozzleStainlessSteel");if(t.includes("tungsten"))return e("printers.nozzleTungstenCarbide");if(t.length>=4){const n=t.slice(2,4);if(n==="00")return e("printers.nozzleStainlessSteel");if(n==="01")return e("printers.nozzleHardenedSteel");if(n==="05")return e("printers.nozzleTungstenCarbide")}return t==="00"?e("printers.nozzleStainlessSteel"):t==="01"?e("printers.nozzleHardenedSteel"):t==="05"?e("printers.nozzleTungstenCarbide"):t.startsWith("H")?e("printers.nozzleHardenedSteel"):t}function Lee(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function Fee({slot:t,index:e,activeStatus:n,filamentName:r,children:i}){const{t:s}=Yt(),[o,l]=_.useState(!1),[c,u]=_.useState("top"),d=_.useRef(null),h=_.useRef(null),p=_.useRef(null),m=!t.nozzle_diameter&&!t.nozzle_type,b=t.stat===1;_.useEffect(()=>{if(o&&d.current&&h.current){const T=d.current.getBoundingClientRect(),M=h.current.offsetHeight,k=T.top-56,R=window.innerHeight-T.bottom;kk?u("bottom"):u("top")}},[o]);const y=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},x=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};_.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const v=Ree(t.filament_color),S=Oee(t.nozzle_type,s),N=Lee(t.nozzle_type,s);return a.jsxs("div",{ref:d,className:"relative",onMouseEnter:y,onMouseLeave:x,children:[i,o&&a.jsxs("div",{ref:h,className:` + `})]})]})}function s8e({isOpen:t,onClose:e,trayUuid:n,trayInfo:r}){const{t:i}=Yt(),s=an(),{showToast:o}=Tn(),[l,c]=_.useState(null),{data:u,isLoading:d}=it({queryKey:["unlinked-spools"],queryFn:ae.getUnlinkedSpools,enabled:t}),h=dt({mutationFn:m=>ae.linkSpool(m,n),onSuccess:()=>{s.invalidateQueries({queryKey:["unlinked-spools"]}),s.invalidateQueries({queryKey:["linked-spools"]}),s.invalidateQueries({queryKey:["spoolman-status"]}),o(i("spoolman.linkSuccess"),"success"),e()},onError:m=>{o(`${i("spoolman.linkFailed")}: ${m.message}`,"error")}});if(!t)return null;const p=()=>{l&&h.mutate(l)};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-md mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(dc,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("spoolman.linkToSpoolman")})]}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[r&&a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Linking AMS tray:"}),a.jsxs("div",{className:"flex items-center gap-2",children:[r.color&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20",style:{backgroundColor:`#${r.color}`}}),a.jsx("span",{className:"text-white font-medium",children:r.type}),a.jsxs("span",{className:"text-bambu-gray",children:["(",r.location,")"]})]})]}),a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-1",children:[i("spoolman.spoolId"),":"]}),a.jsx("code",{className:"text-xs text-bambu-green font-mono break-all",children:n})]}),a.jsxs("div",{children:[a.jsxs("p",{className:"text-sm text-bambu-gray mb-2",children:[i("spoolman.selectSpool"),":"]}),d?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u&&u.length>0?a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-2",children:u.map(m=>a.jsx("button",{onClick:()=>c(m.id),className:`w-full p-3 rounded-lg border text-left transition-colors ${l===m.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:a.jsxs("div",{className:"flex items-center gap-2",children:[m.filament_color_hex&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:`#${m.filament_color_hex}`}}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-white font-medium truncate",children:m.filament_name||"Unknown filament"}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[m.filament_material||"Unknown",m.remaining_weight!==null&&` - ${Math.round(m.remaining_weight)}g`,m.location&&` - ${m.location}`]})]}),l===m.id&&a.jsx($i,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]})},m.id))}):a.jsx("div",{className:"text-center py-8 text-bambu-gray",children:a.jsx("p",{children:i("spoolman.noUnlinkedSpools")})})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ne,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ne,{onClick:p,disabled:!l||h.isPending,children:h.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),i("spoolman.syncing")]}):a.jsxs(a.Fragment,{children:[a.jsx(dc,{className:"w-4 h-4"}),i("spoolman.linkToSpoolman")]})})]}),h.isError&&a.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:h.error.message})]})]})}function o8e(t,e){if(t===255)return"External";let n,r=!1;t>=128&&t<=135?(n=t-128,r=!0):t>=0&&t<=3?(n=t,r=e===1):n=0,n=Math.max(0,Math.min(n,7));const i=String.fromCharCode(65+n);return r?`HT-${i}`:`AMS-${i}`}function Lq(t){const e=t.includes("_")?t.split("_")[0]:t;return e.startsWith("GFS")?"GF"+e.slice(3):(e.startsWith("PFUS")||e.startsWith("PFSP"),e)}const l8e=["PLA","PETG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function Fq(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const i of l8e){const s=new RegExp(`\\b${i}\\b`,"i");if(s.test(n)){const o=e.split(s),l=o[0]?.trim()||"",c=o[1]?.trim()||"";return{material:i,brand:l,variant:c}}}const r=e.split(/\s+/);return r.length>=2?{material:r[1],brand:r[0],variant:r.slice(2).join(" ")}:{material:e,brand:"",variant:""}}function c8e(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const u8e={white:"FFFFFF",black:"000000",red:"FF0000",green:"00FF00",blue:"0000FF",yellow:"FFFF00",cyan:"00FFFF",magenta:"FF00FF",orange:"FFA500",purple:"800080",pink:"FFC0CB",brown:"8B4513",gray:"808080",grey:"808080","jade white":"FFFEF2",ivory:"FFFFF0",beige:"F5F5DC",cream:"FFFDD0",silver:"C0C0C0",gold:"FFD700",bronze:"CD7F32",copper:"B87333",navy:"000080",teal:"008080",olive:"808000",maroon:"800000",coral:"FF7F50",salmon:"FA8072",lime:"32CD32",mint:"98FF98","forest green":"228B22","sky blue":"87CEEB","royal blue":"4169E1",turquoise:"40E0D0",lavender:"E6E6FA",violet:"EE82EE",plum:"DDA0DD",tan:"D2B48C",chocolate:"D2691E",charcoal:"36454F",slate:"708090",transparent:"000000",natural:"F5F5DC",wood:"DEB887"},d8e=[{name:"White",hex:"FFFFFF"},{name:"Black",hex:"000000"},{name:"Red",hex:"FF0000"},{name:"Blue",hex:"0000FF"},{name:"Green",hex:"00AA00"},{name:"Yellow",hex:"FFFF00"},{name:"Orange",hex:"FFA500"},{name:"Gray",hex:"808080"}],h8e=[{name:"Cyan",hex:"00FFFF"},{name:"Magenta",hex:"FF00FF"},{name:"Purple",hex:"800080"},{name:"Pink",hex:"FFC0CB"},{name:"Brown",hex:"8B4513"},{name:"Beige",hex:"F5F5DC"},{name:"Navy",hex:"000080"},{name:"Teal",hex:"008080"},{name:"Lime",hex:"32CD32"},{name:"Gold",hex:"FFD700"},{name:"Silver",hex:"C0C0C0"},{name:"Maroon",hex:"800000"},{name:"Olive",hex:"808000"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Indigo",hex:"4B0082"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Slate",hex:"708090"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Cream",hex:"FFFDD0"}];function f8e(t){const e=t.toLowerCase().trim();return u8e[e]||null}function m8e({isOpen:t,onClose:e,printerId:n,slotInfo:r,nozzleDiameter:i="0.4",onSuccess:s}){const{t:o}=Yt(),[l,c]=_.useState(""),[u,d]=_.useState(null),[h,p]=_.useState(""),[m,b]=_.useState(""),[y,x]=_.useState(""),[v,S]=_.useState(!1),[N,T]=_.useState(!1),{data:M,isLoading:A}=it({queryKey:["cloudSettings"],queryFn:()=>ae.getCloudSettings(),enabled:t}),{data:k,isLoading:R}=it({queryKey:["localPresets"],queryFn:()=>ae.getLocalPresets(),enabled:t}),{data:C,isLoading:P}=it({queryKey:["kprofiles",n,i],queryFn:()=>ae.getKProfiles(n,i),enabled:t&&!!n}),U=dt({mutationFn:async()=>{if(!l)throw new Error("No filament preset selected");const B=l.startsWith("local_"),W=B?parseInt(l.replace("local_",""),10):null,J=B?k?.filament.find(X=>X.id===W):null,ne=B?null:M?.filament.find(X=>X.setting_id===l);if(!B&&!ne)throw new Error("Selected preset not found");if(B&&!J)throw new Error("Selected local preset not found");const me=B?J.name:ne.name,fe=Fq(me),de=u?.slot_id??-1,Re=h||r.trayColor?.slice(0,6)||"FFFFFF",se=me.replace(/@.+$/,"").trim();let ke,Fe;if(B)ke="",Fe="";else if(ke=Lq(l),Fe=l,!l.startsWith("GFS"))try{const X=await ae.getCloudSettingDetail(l);X.filament_id?ke=X.filament_id:X.base_id&&(ke=Lq(X.base_id),console.log(`Derived tray_info_idx from base_id: ${X.base_id} -> ${ke}`))}catch(X){console.warn("Failed to fetch preset detail for filament_id:",X)}let ce=B&&J?.nozzle_temp_min?J.nozzle_temp_min:190,Ve=B&&J?.nozzle_temp_max?J.nozzle_temp_max:230;if(!B||!J?.nozzle_temp_min&&!J?.nozzle_temp_max){const X=(B&&J?.filament_type||fe.material).toUpperCase();X.includes("PLA")?(ce=190,Ve=230):X.includes("PETG")?(ce=220,Ve=260):X.includes("ABS")||X.includes("ASA")?(ce=240,Ve=280):X.includes("TPU")?(ce=200,Ve=240):X.includes("PC")?(ce=260,Ve=300):(X.includes("PA")||X.includes("NYLON"))&&(ce=250,Ve=290)}const V=u?.k_value?parseFloat(u.k_value):0,Y=B?J?.filament_type||fe.material||"PLA":fe.material||"PLA",ue=await ae.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:ke,tray_type:Y,tray_sub_brands:se,tray_color:Re+"FF",nozzle_temp_min:ce,nozzle_temp_max:Ve,cali_idx:de,nozzle_diameter:i,setting_id:Fe,kprofile_filament_id:u?.filament_id,kprofile_setting_id:u?.setting_id||void 0,k_value:V}),q=B?`local_${W}`:l,re=B?"local":"cloud";try{await ae.saveSlotPreset(n,r.amsId,r.trayId,q,se,re)}catch(X){console.warn("Failed to save slot preset mapping:",X)}return ue},onSuccess:()=>{S(!0),s?.(),setTimeout(()=>{S(!1),e()},1500)}}),F=dt({mutationFn:async()=>ae.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{S(!0),s?.(),setTimeout(()=>{S(!1),e()},1500)}}),H=_.useMemo(()=>{const B=y.toLowerCase(),W=[];if(k?.filament)for(const J of k.filament)(!B||J.name.toLowerCase().includes(B))&&W.push({id:`local_${J.id}`,name:J.name,source:"local",isUser:!1});if(M?.filament)for(const J of M.filament)(!B||J.name.toLowerCase().includes(B))&&W.push({id:J.setting_id,name:J.name,source:"cloud",isUser:c8e(J.setting_id)});return W.sort((J,ne)=>J.source==="local"&&ne.source!=="local"?-1:J.source!=="local"&&ne.source==="local"?1:J.isUser&&!ne.isUser?-1:!J.isUser&&ne.isUser?1:J.name.localeCompare(ne.name))},[M?.filament,k?.filament,y]),D=_.useMemo(()=>{if(!l)return null;let B=null;if(l.startsWith("local_")){const ne=parseInt(l.replace("local_",""),10);B=k?.filament.find(fe=>fe.id===ne)?.name||null}else M?.filament&&(B=M.filament.find(me=>me.setting_id===l)?.name||null);if(!B)return null;let W=B.replace(/@.+$/,"").trim();W.startsWith("# ")&&(W=W.slice(2).trim());const J=Fq(W);return{fullName:W,material:J.material,brand:J.brand}},[l,M?.filament,k?.filament]),$=D?.fullName||"",G=_.useMemo(()=>{if(!C?.profiles||!D)return[];const{fullName:B,material:W,brand:J}=D,ne=B.toUpperCase(),me=W.toUpperCase(),fe=J.toUpperCase();if(!me||me.length<2)return[];const de=C.profiles.filter(se=>{const ke=se.name.toUpperCase();if(fe)return!(!ke.includes(fe)||!ke.includes(me));if(ke.includes(ne)||ke.includes(me))return!0;const ce={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[me]||[];for(const Ve of ce)if(ke.includes(Ve))return!0;return!1}),Re=new Map;for(const se of de){const ke=`${se.name}|${se.k_value}`,Fe=Re.get(ke);Fe?se.extruder_id===1&&Fe.extruder_id===0&&Re.set(ke,se):Re.set(ke,se)}return Array.from(Re.values())},[C?.profiles,D]);_.useEffect(()=>{if(t&&M?.filament){if(r.trayInfoIdx){const B=M.filament.find(W=>W.setting_id===r.trayInfoIdx);B&&c(B.setting_id)}}else t||(c(""),d(null),p(""),b(""),x(""),S(!1))},[t,M?.filament,r.trayInfoIdx]),_.useEffect(()=>{G.length>0?d(G[0]):d(null)},[l,G]);const I=_.useCallback(B=>{B.key==="Escape"&&e()},[e]);if(_.useEffect(()=>{if(t)return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[t,I]),!t)return null;const K=A||R||P,Q=l&&!U.isPending,oe=h||r.trayColor?.slice(0,6)||"FFFFFF";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",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Hu,{className:"w-5 h-5 text-bambu-blue"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Configure AMS Slot"})]}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4 max-h-[60vh] overflow-y-auto",children:[v&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl",children:a.jsxs("div",{className:"text-center space-y-3",children:[a.jsx(mk,{className:"w-16 h-16 text-bambu-green mx-auto"}),a.jsx("p",{className:"text-lg font-semibold text-white",children:"Slot Configured!"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:o("configureAmsSlot.settingsSentToPrinter")})]})}),a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Configuring slot:"}),a.jsxs("div",{className:"flex items-center gap-2",children:[r.trayColor&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),a.jsxs("span",{className:"text-white font-medium",children:[o8e(r.amsId,r.trayCount)," Slot ",r.trayId+1]}),r.traySubBrands&&a.jsxs("span",{className:"text-bambu-gray",children:["(",r.traySubBrands,")"]})]})]}),K?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:["Filament Profile ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:o("configureAmsSlot.searchPresets"),value:y,onChange:B=>x(B.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2"}),a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:H.length===0?a.jsx("p",{className:"text-center py-4 text-bambu-gray",children:M?.filament?.length===0&&!k?.filament?.length?"No presets available. Login to Bambu Cloud or import local profiles.":"No matching presets found."}):H.map(B=>a.jsx("button",{onClick:()=>c(B.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${l===B.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-white text-sm truncate",children:B.name}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[B.source==="local"&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:o("profiles.localProfiles.badge")}),B.isUser&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:o("configureAmsSlot.custom")})]})]})},B.id))})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:["K Profile (Pressure Advance)",$&&a.jsxs("span",{className:"ml-2 text-xs text-bambu-blue",children:["Filtering for: ",$]})]}),G.length>0?a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:u?.name||"",onChange:B=>{const W=G.find(J=>J.name===B.target.value);d(W||null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10",children:[a.jsx("option",{value:"",children:"No K profile (use default 0.020)"}),G.map(B=>a.jsxs("option",{value:B.name,children:[B.name," (K=",B.k_value,")"]},`${B.name}-${B.extruder_id}`))]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):l?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:"No matching K profiles found. Default K=0.020 will be used."}):a.jsx("span",{className:"inline-block text-xs px-2 py-1 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30",children:"Select a filament profile first"}),u&&a.jsxs("p",{className:"text-xs text-bambu-green mt-1",children:["K=",u.k_value," from printer calibration"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Custom Color (optional)"}),a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[d8e.map(B=>a.jsx("button",{onClick:()=>{p(B.hex),b(B.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${h===B.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${B.hex}`},title:B.name},B.hex)),a.jsx("button",{onClick:()=>T(!N),className:"w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs",title:N?"Show less colors":"Show more colors",children:N?"−":"+"})]}),N&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:h8e.map(B=>a.jsx("button",{onClick:()=>{p(B.hex),b(B.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${h===B.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${B.hex}`},title:B.name},B.hex))}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${oe}`}}),a.jsx("input",{type:"text",placeholder:o("configureAmsSlot.colorPlaceholder"),value:m,onChange:B=>{const W=B.target.value;b(W);const J=f8e(W);if(J)p(J);else{const ne=W.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();ne.length===6?p(ne):ne.length===3&&p(ne.split("").map(me=>me+me).join(""))}},className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"}),h&&a.jsx("button",{onClick:()=>{p(""),b("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:o("configureAmsSlot.clearCustomColor"),children:"Clear"})]}),h&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-1.5",children:["Hex: #",h]})]})]})]}),a.jsxs("div",{className:"flex justify-between p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>F.mutate(),disabled:F.isPending||U.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:F.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Resetting..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Bu,{className:"w-4 h-4"}),"Reset Slot"]})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ne,{variant:"secondary",onClick:e,children:"Cancel"}),a.jsx(Ne,{onClick:()=>U.mutate(),disabled:!Q,children:U.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Configuring..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Hu,{className:"w-4 h-4"}),"Configure Slot"]})})]})]}),(U.isError||F.isError)&&a.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:U.error?.message||F.error?.message})]})]})}const Iq={"A00-W1":"Jade White","A00-P0":"Beige","A00-D2":"Light Gray","A00-Y0":"Yellow","A00-Y2":"Sunflower Yellow","A00-A1":"Pumpkin Orange","A00-A0":"Orange","A00-Y4":"Gold","A00-G3":"Bright Green","A00-G1":"Bambu Green","A00-G2":"Mistletoe Green","A00-R3":"Hot Pink","A00-P6":"Magenta","A00-R0":"Red","A00-R2":"Maroon Red","A00-P5":"Purple","A00-P2":"Indigo Purple","A00-B5":"Turquoise","A00-B8":"Cyan","A00-B3":"Cobalt Blue","A00-N0":"Brown","A00-N1":"Cocoa Brown","A00-Y3":"Bronze","A00-D0":"Gray","A00-D1":"Silver","A00-B1":"Blue Grey","A00-D3":"Dark Gray","A00-K0":"Black","A00-M3":"Pink Citrus","A00-M6":"Dusk Glare","A00-M0":"Arctic Whisper","A00-M1":"Solar Breeze","A00-M5":"Blueberry Bubblegum","A00-M4":"Mint Lime","A00-M2":"Ocean to Meadow","A00-M7":"Cotton Candy Cloud","A18-K0":"Black","A18-D0":"Gray","A18-W0":"White","A18-R0":"Red","A18-Y0":"Yellow","A18-B0":"Cyan","A18-B1":"Blue","A18-P0":"Matte Beige","A01-W2":"Ivory White","A01-W3":"Bone White","A01-Y2":"Lemon Yellow","A01-A2":"Mandarin Orange","A01-P3":"Sakura Pink","A01-P4":"Lilac Purple","A01-R3":"Plum","A01-R1":"Scarlet Red","A01-R4":"Dark Red","A01-G0":"Apple Green","A01-G1":"Grass Green","A01-G7":"Dark Green","A01-B4":"Ice Blue","A01-B0":"Sky Blue","A01-B3":"Marine Blue","A01-B6":"Dark Blue","A01-Y3":"Desert Tan","A01-N1":"Latte Brown","A01-N3":"Caramel","A01-R2":"Terracotta","A01-N2":"Dark Brown","A01-N0":"Dark Chocolate","A01-D3":"Ash Gray","A01-D0":"Nardo Gray","A01-K1":"Charcoal","A12-G0":"Green","A12-R0":"Pink","A12-A0":"Orange","A12-Y0":"Yellow","A12-B0":"Blue","A07-R5":"Red Granite","A07-D4":"White Marble","A11-W0":"White","A11-K0":"Black","A08-G3":"Alpine Green Sparkle","A08-D5":"Slate Gray Sparkle","A08-B7":"Royal Purple Sparkle","A08-R2":"Crimson Red Sparkle","A08-K2":"Onyx Black Sparkle","A08-Y1":"Classic Gold Sparkle","A02-B2":"Cobalt Blue Metallic","A02-G2":"Oxide Green Metallic","A02-Y1":"Iridium Gold Metallic","A02-D2":"Iron Gray Metallic","A17-B1":"Blue","A17-A0":"Orange","A17-P0":"Purple","A06-Y1":"Gold","A06-D0":"Titan Gray","A06-D1":"Silver","A06-W0":"White","A06-R0":"Candy Red","A06-G0":"Candy Green","A06-G1":"Mint","A06-B1":"Blue","A06-B0":"Baby Blue","A06-P0":"Purple","A06-R1":"Rose Gold","A06-R2":"Pink","A06-Y0":"Champagne","A05-M8":"Dawn Radiance","A05-M4":"Aurora Purple","A05-M1":"South Beach","A05-T3":"Neon City","A05-T2":"Midnight Blaze","A05-T1":"Gilded Rose","A05-T4":"Blue Hawaii","A05-T5":"Velvet Eclipse","A15-B0":"Purple","A15-G0":"Green","A15-G1":"Nebulae","A15-R0":"Brown","A16-K0":"Black Walnut","A16-R0":"Rosewood","A16-N0":"Clay Brown","A16-G0":"Classic Birch","A16-W0":"White Oak","A16-Y0":"Ochre Yellow","A50-D6":"Lava Gray","A50-K0":"Black","A50-B6":"Royal Blue","A10-W0":"White","A10-D0":"Gray","A09-B5":"Lavender Blue","A09-B4":"Light Blue","A09-A0":"Orange","A09-D1":"Silver","A09-R3":"Vermilion Red","A09-Y0":"Yellow","G02-K0":"Black","G02-W0":"White","G02-R0":"Red","G02-D0":"Gray","G02-D1":"Dark Gray","G02-Y1":"Cream","G02-Y0":"Yellow","G02-A0":"Orange","G02-N1":"Peanut Brown","G02-G1":"Lime Green","G02-G0":"Green","G02-G2":"Forest Green","G02-B1":"Lake Blue","G02-B0":"Blue","G01-G1":"Translucent Teal","G01-B0":"Translucent Light Blue","G01-C0":"Clear","G01-D0":"Translucent Gray","G01-G0":"Translucent Olive","G01-N0":"Translucent Brown","G01-A0":"Translucent Orange","G01-P1":"Translucent Pink","G01-P0":"Translucent Purple","G50-P7":"Violet Purple","G50-K0":"Black","B00-D1":"Silver","B00-K0":"Black","B00-W0":"White","B00-G6":"Bambu Green","B00-G7":"Olive","B00-Y1":"Tangerine Yellow","B00-A0":"Orange","B00-R0":"Red","B00-B4":"Azure","B00-B0":"Blue","B00-B6":"Navy Blue","B50-A0":"Orange","B50-K0":"Black","B01-W0":"White","B01-K0":"Black","B01-D0":"Gray","B02-W0":"White","C00-C1":"Transparent","C00-C0":"Clear Black","C00-K0":"Black","C00-W0":"White","C01-K0":"Black","U02-B0":"Blue","U02-D0":"Gray","U02-K0":"Black","N04-K0":"Black","N08-K0":"Black","S02-W0":"Nature","S02-W1":"White","S05-C0":"Black","S06-W0":"White","S03-G1":"Green","S04-Y0":"Clear"},p8e={W0:"White",W1:"Jade White",W2:"Ivory White",W3:"Bone White",Y0:"Yellow",Y1:"Gold",Y2:"Sunflower Yellow",Y3:"Bronze",Y4:"Gold",A0:"Orange",A1:"Pumpkin Orange",A2:"Mandarin Orange",R0:"Red",R1:"Scarlet Red",R2:"Maroon Red",R3:"Hot Pink",R4:"Dark Red",R5:"Red Granite",P0:"Beige",P1:"Pink",P2:"Indigo Purple",P3:"Sakura Pink",P4:"Lilac Purple",P5:"Purple",P6:"Magenta",P7:"Violet Purple",B0:"Blue",B1:"Blue Grey",B2:"Cobalt Blue",B3:"Cobalt Blue",B4:"Ice Blue",B5:"Turquoise",B6:"Navy Blue",B7:"Royal Purple",B8:"Cyan",G0:"Green",G1:"Grass Green",G2:"Mistletoe Green",G3:"Bright Green",G6:"Bambu Green",G7:"Dark Green",N0:"Brown",N1:"Peanut Brown",N2:"Dark Brown",N3:"Caramel",D0:"Gray",D1:"Silver",D2:"Light Gray",D3:"Dark Gray",D4:"White Marble",D5:"Slate Gray",D6:"Lava Gray",K0:"Black",K1:"Charcoal",K2:"Onyx Black",C0:"Clear Black",C1:"Transparent",M0:"Arctic Whisper",M1:"Solar Breeze",M2:"Ocean to Meadow",M3:"Pink Citrus",M4:"Aurora Purple",M5:"Blueberry Bubblegum",M6:"Dusk Glare",M7:"Cotton Candy Cloud",M8:"Dawn Radiance",T1:"Gilded Rose",T2:"Midnight Blaze",T3:"Neon City",T4:"Blue Hawaii",T5:"Velvet Eclipse"};function mP(t){if(!t)return null;if(Iq[t])return Iq[t];const e=t.split("-");if(e.length<2)return null;const n=e[1];return p8e[n]||null}function pP(t){if(!t||t.length<6)return"Unknown";const e=parseInt(t.substring(0,2),16),n=parseInt(t.substring(2,4),16),r=parseInt(t.substring(4,6),16),i=Math.max(e,n,r)/255,s=Math.min(e,n,r)/255,o=(i+s)/2;let l=0,c=0;if(i!==s){const u=i-s;c=o>.5?u/(2-i-s):u/(i+s);const d=e/255,h=n/255,p=r/255;i===d?l=((h-p)/u+(h.85?"White":c<.15?o<.4?"Dark Gray":o>.6?"Light Gray":"Gray":l>=15&&l<45&&o<.45||l>=45&&l<70&&o<.4?"Brown":l<15||l>=345?"Red":l<45?"Orange":l<70?"Yellow":l<150?"Green":l<200?"Cyan":l<260?"Blue":l<290?"Purple":"Pink"}function gP(t){return(t??.02).toFixed(3)}function zq({side:t}){const{mode:e}=Dm(),n=e==="dark"?"#1a4d2e":"#e7f5e9";return a.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded",style:{backgroundColor:n,color:"#00ae42"},children:t})}function Ree(t){if(!t||t==="00000000"||t.length<6)return null;const e=t.slice(0,2),n=t.slice(2,4),r=t.slice(4,6),i=t.length>=8?parseInt(t.slice(6,8),16)/255:1;return i===0?null:`rgba(${parseInt(e,16)}, ${parseInt(n,16)}, ${parseInt(r,16)}, ${i})`}function g8e(t){if(!t||t.length<6)return!1;const e=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16);return(.299*e+.587*n+.114*r)/255>.6}function Oee(t,e){if(!t)return"";if(t.includes("hardened"))return e("printers.nozzleHardenedSteel");if(t.includes("stainless"))return e("printers.nozzleStainlessSteel");if(t.includes("tungsten"))return e("printers.nozzleTungstenCarbide");if(t.length>=4){const n=t.slice(2,4);if(n==="00")return e("printers.nozzleStainlessSteel");if(n==="01")return e("printers.nozzleHardenedSteel");if(n==="05")return e("printers.nozzleTungstenCarbide")}return t==="00"?e("printers.nozzleStainlessSteel"):t==="01"?e("printers.nozzleHardenedSteel"):t==="05"?e("printers.nozzleTungstenCarbide"):t.startsWith("H")?e("printers.nozzleHardenedSteel"):t}function Lee(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function Fee({slot:t,index:e,activeStatus:n,filamentName:r,children:i}){const{t:s}=Yt(),[o,l]=_.useState(!1),[c,u]=_.useState("top"),d=_.useRef(null),h=_.useRef(null),p=_.useRef(null),m=!t.nozzle_diameter&&!t.nozzle_type,b=t.stat===1;_.useEffect(()=>{if(o&&d.current&&h.current){const T=d.current.getBoundingClientRect(),M=h.current.offsetHeight,k=T.top-56,R=window.innerHeight-T.bottom;kk?u("bottom"):u("top")}},[o]);const y=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},x=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};_.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const v=Ree(t.filament_color),S=Oee(t.nozzle_type,s),N=Lee(t.nozzle_type,s);return a.jsxs("div",{ref:d,className:"relative",onMouseEnter:y,onMouseLeave:x,children:[i,o&&a.jsxs("div",{ref:h,className:` absolute left-1/2 -translate-x-1/2 z-50 ${c==="top"?"bottom-full mb-2":"top-full mt-2"} animate-in fade-in-0 zoom-in-95 duration-150 @@ -8491,7 +8491,7 @@ void main() { border-l-[6px] border-l-transparent border-r-[6px] border-r-transparent ${c==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"} - `})]})]})}function g8e({leftSlot:t,rightSlot:e,activeNozzle:n,children:r}){const{t:i}=Yt(),[s,o]=_.useState(!1),[l,c]=_.useState("top"),u=_.useRef(null),d=_.useRef(null),h=_.useRef(null);_.useEffect(()=>{if(s&&u.current&&d.current){const y=u.current.getBoundingClientRect(),x=d.current.offsetHeight,S=y.top-56,N=window.innerHeight-y.bottom;SS?c("bottom"):c("top")}},[s]);const p=()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(()=>o(!0),80)},m=()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(()=>o(!1),100)};if(_.useEffect(()=>()=>{h.current&&clearTimeout(h.current)},[]),!t&&!e)return a.jsx(a.Fragment,{children:r});const b=(y,x)=>{const v=n===x,S=Oee(y.nozzle_type,i),N=Lee(y.nozzle_type,i);return a.jsxs("div",{className:"flex-1 space-y-1.5",children:[a.jsx("div",{className:`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${v?"text-amber-400":"text-bambu-gray"}`,children:i(x==="L"?"common.left":"common.right")}),y.nozzle_diameter&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleDiameter")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[y.nozzle_diameter," mm"]})]}),S&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleType")}),a.jsx("span",{className:"text-[10px] text-white font-semibold",children:S})]}),N&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleFlow")}),a.jsx("span",{className:"text-[10px] text-white font-semibold",children:N})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleStatus")}),a.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded ${v?"bg-green-900/50 text-green-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i(v?"printers.nozzleActive":"printers.nozzleIdle")})]}),y.wear!=null&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleWear")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[y.wear,"%"]})]}),x==="R"&&y.max_temp>0&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleMaxTemp")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[y.max_temp,"°C"]})]}),x==="R"&&y.serial_number&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleSerial")}),a.jsx("span",{className:"text-[10px] text-white font-mono",children:y.serial_number})]})]})};return a.jsxs("div",{ref:u,className:"relative flex-1",onMouseEnter:p,onMouseLeave:m,children:[r,s&&a.jsxs("div",{ref:d,className:` + `})]})]})}function b8e({leftSlot:t,rightSlot:e,activeNozzle:n,children:r}){const{t:i}=Yt(),[s,o]=_.useState(!1),[l,c]=_.useState("top"),u=_.useRef(null),d=_.useRef(null),h=_.useRef(null);_.useEffect(()=>{if(s&&u.current&&d.current){const y=u.current.getBoundingClientRect(),x=d.current.offsetHeight,S=y.top-56,N=window.innerHeight-y.bottom;SS?c("bottom"):c("top")}},[s]);const p=()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(()=>o(!0),80)},m=()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(()=>o(!1),100)};if(_.useEffect(()=>()=>{h.current&&clearTimeout(h.current)},[]),!t&&!e)return a.jsx(a.Fragment,{children:r});const b=(y,x)=>{const v=n===x,S=Oee(y.nozzle_type,i),N=Lee(y.nozzle_type,i);return a.jsxs("div",{className:"flex-1 space-y-1.5",children:[a.jsx("div",{className:`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${v?"text-amber-400":"text-bambu-gray"}`,children:i(x==="L"?"common.left":"common.right")}),y.nozzle_diameter&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleDiameter")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[y.nozzle_diameter," mm"]})]}),S&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleType")}),a.jsx("span",{className:"text-[10px] text-white font-semibold",children:S})]}),N&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleFlow")}),a.jsx("span",{className:"text-[10px] text-white font-semibold",children:N})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleStatus")}),a.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded ${v?"bg-green-900/50 text-green-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i(v?"printers.nozzleActive":"printers.nozzleIdle")})]}),y.wear!=null&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleWear")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[y.wear,"%"]})]}),x==="R"&&y.max_temp>0&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleMaxTemp")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[y.max_temp,"°C"]})]}),x==="R"&&y.serial_number&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:i("printers.nozzleSerial")}),a.jsx("span",{className:"text-[10px] text-white font-mono",children:y.serial_number})]})]})};return a.jsxs("div",{ref:u,className:"relative flex-1",onMouseEnter:p,onMouseLeave:m,children:[r,s&&a.jsxs("div",{ref:d,className:` absolute left-1/2 -translate-x-1/2 z-50 ${l==="top"?"bottom-full mb-2":"top-full mt-2"} animate-in fade-in-0 zoom-in-95 duration-150 @@ -8500,7 +8500,7 @@ void main() { border-l-[6px] border-l-transparent border-r-[6px] border-r-transparent ${l==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"} - `})]})]})}function b8e({slots:t,filamentInfo:e}){const{t:n}=Yt(),r=t.filter(l=>l.id>=2),i=6,s=r.length>0?Math.min(...r.map(l=>l.id)):16,o=Array.from({length:i},(l,c)=>r.find(u=>u.id===s+c)??{id:-(c+1),nozzle_type:"",nozzle_diameter:"",wear:null,stat:null,max_temp:0,serial_number:"",filament_color:"",filament_id:"",filament_type:""});return a.jsxs("div",{className:"text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[2_1_190px] flex flex-col justify-center",children:[a.jsx("p",{className:"text-[9px] text-bambu-gray mb-1",children:n("printers.nozzleRack")}),a.jsx("div",{className:"flex gap-[3px] justify-center",children:o.map((l,c)=>{const u=!l.nozzle_diameter&&!l.nozzle_type,d=u?null:Ree(l.filament_color);return a.jsx(Fee,{slot:l,index:c,filamentName:l.filament_id?e?.[l.filament_id]?.name:void 0,children:a.jsx("div",{className:`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${u?"bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20":"bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40"}`,style:d?{backgroundColor:d}:void 0,children:a.jsx("span",{className:`text-[10px] font-semibold ${u?"text-bambu-gray/30":"text-white"}`,style:d?{textShadow:"0 1px 3px rgba(0,0,0,0.9)"}:void 0,children:u?"—":l.nozzle_diameter||"?"})})},l.id>=0?l.id:`empty-${c}`)})})]})}function Uq({className:t}){return a.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:a.jsx("path",{d:"M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z",fill:"#C3C2C1"})})}function x8e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z",fill:"#C3C2C1"}),a.jsx("path",{d:"M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z",fill:"#1F8FEB"})]})}function y8e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z",fill:"#1F8FEB"}),a.jsx("path",{d:"M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z",fill:"#C3C2C1"})]})}function v8e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"}),a.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function w8e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function _8e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function bP({className:t,color:e,isHeating:n}){const i={"text-orange-400":"#fb923c","text-blue-400":"#60a5fa","text-green-400":"#4ade80"}[e]||"#888",s=n?{filter:`drop-shadow(0 0 4px ${i}) drop-shadow(0 0 8px ${i})`}:{};return n?a.jsxs("svg",{className:t,style:s,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:i,rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:i}),a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:i,strokeWidth:"1",fill:"none"})]}):a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:i,strokeWidth:"1",fill:"none"}),a.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:i,strokeWidth:"1",fill:"none"})]})}function Bq({humidity:t,goodThreshold:e=40,fairThreshold:n=60,onClick:r,compact:i}){const s=typeof t=="string"?parseInt(t,10):t,o=typeof e=="number"?e:40,l=typeof n=="number"?n:60;let c,u;isNaN(s)?(c="#C3C2C1",u="Unknown"):s<=o?(c="#22a352",u="Good"):s<=l?(c="#d4a017",u="Fair"):(c="#c62828",u="Bad");let d;return isNaN(s)||s<=o?d=Uq:s<=l?d=x8e:d=y8e,a.jsxs("button",{type:"button",onClick:r,className:`flex items-center gap-1 ${r?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Humidity: ${s}% - ${u}${r?" (click for history)":""}`,children:[a.jsx(d,{className:i?"w-2.5 h-3":"w-3 h-4"}),a.jsxs("span",{className:`font-medium tabular-nums ${i?"text-[10px]":"text-xs"}`,style:{color:c},children:[s,"%"]})]})}function Hq({temp:t,goodThreshold:e=28,fairThreshold:n=35,onClick:r,compact:i}){const s=typeof e=="number"?e:28,o=typeof n=="number"?n:35;let l,c,u;return t<=s?(l="#22a352",c="Good",u=v8e):t<=o?(l="#d4a017",c="Fair",u=w8e):(l="#c62828",c="Bad",u=_8e),a.jsxs("button",{type:"button",onClick:r,className:`flex items-center gap-1 ${r?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Temperature: ${t}°C - ${c}${r?" (click for history)":""}`,children:[a.jsx(u,{className:i?"w-2.5 h-3":"w-3 h-4"}),a.jsxs("span",{className:`tabular-nums text-right ${i?"text-[10px] w-8":"w-12"}`,style:{color:l},children:[t,"°C"]})]})}function Gd(t,e){const n=typeof t=="string"?parseInt(t,10):t,r=isNaN(n)?0:n,i=e===1,s=r>=128?r-128:r,o=String.fromCharCode(65+s);return i?`HT-${o}`:`AMS-${o}`}function xP(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function yP(t){return!t?.remaining_weight||!t?.filament_weight||t.filament_weight<=0?null:Math.min(100,Math.round(t.remaining_weight/t.filament_weight*100))}function S8e(t){const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function N8e(t,e="system"){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={hour:"2-digit",minute:"2-digit"};e==="12h"?o.hour12=!0:e==="24h"&&(o.hour12=!1);const l=r.toLocaleTimeString([],o),c=Math.floor((s.getTime()-i.getTime())/(1e3*60*60*24));return c===0?l:c===1?`Tomorrow ${l}`:r.toLocaleDateString([],{weekday:"short"})+" "+l}function k8e(t){if(!t)return"/img/printers/default.png";const e=t.toLowerCase().replace(/\s+/g,"");return e.includes("x1e")?"/img/printers/x1e.png":e.includes("x1c")||e.includes("x1carbon")||e.includes("x1")?"/img/printers/x1c.png":e.includes("h2d")?"/img/printers/h2d.png":e.includes("h2c")?"/img/printers/h2c.png":e.includes("h2s")?"/img/printers/h2d.png":e.includes("p2s")||e.includes("p1s")?"/img/printers/p1s.png":e.includes("p1p")?"/img/printers/p1p.png":e.includes("a1mini")?"/img/printers/a1mini.png":e.includes("a1")?"/img/printers/a1.png":"/img/printers/default.png"}function M8e(t){return t>=-50?{labelKey:"printers.wifiSignal.excellent",color:"text-bambu-green",bars:4}:t>=-60?{labelKey:"printers.wifiSignal.good",color:"text-bambu-green",bars:3}:t>=-70?{labelKey:"printers.wifiSignal.fair",color:"text-yellow-400",bars:2}:t>=-80?{labelKey:"printers.wifiSignal.weak",color:"text-orange-400",bars:1}:{labelKey:"printers.wifiSignal.veryWeak",color:"text-red-400",bars:1}}function vP(t){return t?!!(t.tray_info_idx&&t.tray_info_idx.startsWith("GF")||t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function E8e({url:t,printName:e}){const{t:n}=Yt(),[r,i]=_.useState(!1),[s,o]=_.useState(!1),[l,c]=_.useState(!1);return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:`w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${t&&r?"cursor-pointer":""}`,onClick:()=>t&&r&&c(!0),children:t&&!s?a.jsxs(a.Fragment,{children:[a.jsx("img",{src:t,alt:n("printers.printPreview"),className:`w-full h-full object-cover ${r?"block":"hidden"}`,onLoad:()=>i(!0),onError:()=>o(!0)}),!r&&a.jsx(Ii,{className:"w-8 h-8 text-bambu-gray"})]}):a.jsx(Ii,{className:"w-8 h-8 text-bambu-gray"})}),l&&t&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8",onClick:()=>c(!1),children:a.jsxs("div",{className:"relative max-w-2xl max-h-full",children:[a.jsx("img",{src:t,alt:n("printers.printPreview"),className:"max-w-full max-h-[80vh] rounded-lg shadow-2xl"}),e&&a.jsx("p",{className:"text-white text-center mt-4 text-lg",children:e})]})})]})}function T8e({printers:t}){const{t:e}=Yt(),n=an(),r=_.useMemo(()=>{let s=0,o=0,l=0,c=0;return t?.forEach(u=>{const d=n.getQueryData(["printerStatus",u.id]);d===void 0?c++:d.connected?d.state==="RUNNING"?s++:o++:l++}),{printing:s,idle:o,offline:l,loading:c,total:t?.length||0}},[t,n]),[,i]=_.useState(0);return _.useEffect(()=>{let s=!1;const o=n.getQueryCache().subscribe(()=>{s||(s=!0,requestAnimationFrame(()=>{i(l=>l+1),s=!1}))});return()=>o()},[n]),t?.length?a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[r.printing>0&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white font-medium",children:r.printing})," ",e("printers.status.printing").toLowerCase()]})]}),r.idle>0&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white font-medium",children:r.idle})," ",e("printers.status.idle").toLowerCase()]})]}),r.offline>0&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-gray-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white font-medium",children:r.offline})," ",e("printers.status.offline").toLowerCase()]})]})]}):null}function $q(t,e){if(e)return e;switch(t){case"RUNNING":return"Printing";case"PAUSE":return"Paused";case"FINISH":return"Finished";case"FAILED":return"Failed";case"IDLE":return"Idle";default:return t?t.charAt(0)+t.slice(1).toLowerCase():"Idle"}}function Vq({printer:t,hideIfDisconnected:e,maintenanceInfo:n,viewMode:r="expanded",cardSize:i=2,amsThresholds:s,spoolmanEnabled:o=!1,hasUnlinkedSpools:l=!1,linkedSpools:c,spoolmanUrl:u,timeFormat:d="system",cameraViewMode:h="window",onOpenEmbeddedCamera:p,checkPrinterFirmware:m=!0}){const{t:b}=Yt(),y=an(),x=Ec(),{showToast:v}=Tn(),{hasPermission:S}=Ir(),[N,T]=_.useState(!1),[M,A]=_.useState(!1),[k,R]=_.useState(!0),[C,P]=_.useState(!1),[U,F]=_.useState(!1),[H,D]=_.useState(!1),[$,G]=_.useState(!1),[I,K]=_.useState(!1),[Q,oe]=_.useState(!1),[B,W]=_.useState(!1),[J,ne]=_.useState(!1),[me,fe]=_.useState(!1),[de,Re]=_.useState(!1),[se,ke]=_.useState(null),[Fe,ce]=_.useState(null),[Ve,V]=_.useState(null),[Y,ue]=_.useState(!1),[q,re]=_.useState(null),[X,le]=_.useState(!1),[pe,ee]=_.useState(!1),[z,O]=_.useState(null),[Z,ge]=_.useState(!1),[Ce,_e]=_.useState(!1),{data:Te}=it({queryKey:["printerStatus",t.id],queryFn:()=>ae.getPrinterStatus(t.id),refetchInterval:3e4}),{data:we}=it({queryKey:["firmwareUpdate",t.id],queryFn:()=>N1.checkPrinterUpdate(t.id),staleTime:300*1e3,refetchInterval:300*1e3,enabled:m&&S("firmware:read")}),$e=_.useMemo(()=>{const gt=new Set;if(Te?.ams)for(const jt of Te.ams)for(const gn of jt.tray||[])gn.tray_info_idx&>.add(gn.tray_info_idx);if(Te?.vt_tray?.tray_info_idx&>.add(Te.vt_tray.tray_info_idx),Te?.nozzle_rack)for(const jt of Te.nozzle_rack)jt.filament_id&>.add(jt.filament_id);return Array.from(gt)},[Te?.ams,Te?.vt_tray,Te?.nozzle_rack]),{data:Ge}=it({queryKey:["filamentInfo",$e],queryFn:()=>ae.getFilamentInfo($e),enabled:$e.length>0,staleTime:300*1e3}),{data:ze}=it({queryKey:["slotPresets",t.id],queryFn:()=>ae.getSlotPresets(t.id),staleTime:120*1e3}),[be,Me]=_.useState(null);_.useEffect(()=>{Te?.wifi_signal!=null&&Me(Te.wifi_signal)},[Te?.wifi_signal]);const Be=Te?.wifi_signal??be,Ae=_.useRef(void 0);_.useEffect(()=>{Te?.connected!==void 0&&(Ae.current=Te.connected)},[Te?.connected]);const qe=Te?.connected??Ae.current,ve=_.useRef({});_.useEffect(()=>{Te?.ams_extruder_map&&Object.keys(Te.ams_extruder_map).length>0&&(ve.current=Te.ams_extruder_map)},[Te?.ams_extruder_map]);const et=Te?.ams_extruder_map&&Object.keys(Te.ams_extruder_map).length>0?Te.ams_extruder_map:ve.current,Ee=_.useRef([]);_.useEffect(()=>{Te?.ams&&Te.ams.length>0&&(Ee.current=Te.ams)},[Te?.ams]);const Ye=Te?.ams&&Te.ams.length>0?Te.ams:Ee.current,je=_.useRef(255),Pe=Te?.tray_now;Pe!==void 0&&Pe!==255&&(je.current=Pe);const ye=Pe===void 0||Pe===255?je.current:Pe,{data:Qe}=it({queryKey:["smartPlugByPrinter",t.id],queryFn:()=>ae.getSmartPlugByPrinter(t.id)}),{data:yt}=it({queryKey:["scriptPlugsByPrinter",t.id],queryFn:()=>ae.getScriptPlugsByPrinter(t.id)}),{data:at}=it({queryKey:["smartPlugStatus",Qe?.id],queryFn:()=>Qe?ae.getSmartPlugStatus(Qe.id):null,enabled:!!Qe,refetchInterval:1e4}),{data:Ut}=it({queryKey:["queue",t.id,"pending"],queryFn:()=>ae.getQueue(t.id,"pending")}),zt=Ut?.length||0,{data:Ie}=it({queryKey:["queue",t.id,"printing"],queryFn:()=>ae.getQueue(t.id,"printing"),enabled:Te?.state==="RUNNING"}),{data:vt}=it({queryKey:["currentPrintUser",t.id],queryFn:()=>ae.getCurrentPrintUser(t.id),enabled:Te?.state==="RUNNING"}),Gt=Ie?.[0]?.created_by_username||vt?.username,{data:dn}=it({queryKey:["archives",t.id,"last"],queryFn:()=>ae.getArchives(t.id,1,0),enabled:Te?.connected&&Te?.state!=="RUNNING"}),fn=dn?.[0],vn=e&&qe===!1,dr=dt({mutationFn:gt=>ae.deletePrinter(t.id,gt.deleteArchives),onSuccess:()=>{y.invalidateQueries({queryKey:["printers"]}),y.invalidateQueries({queryKey:["archives"]}),y.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:gt=>v(gt.message||b("printers.toast.failedToDelete"),"error")}),ar=dt({mutationFn:()=>ae.connectPrinter(t.id),onSuccess:()=>{y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),kn=dt({mutationFn:gt=>Qe?ae.controlSmartPlug(Qe.id,gt):Promise.reject("No plug"),onSuccess:()=>{y.invalidateQueries({queryKey:["smartPlugStatus",Qe?.id]})}}),Bn=dt({mutationFn:gt=>Qe?ae.updateSmartPlug(Qe.id,{auto_off:gt}):Promise.reject("No plug"),onSuccess:()=>{y.invalidateQueries({queryKey:["smartPlugByPrinter",t.id]}),y.invalidateQueries({queryKey:["smart-plugs"]})}}),Hr=dt({mutationFn:gt=>ae.controlSmartPlug(gt,"on"),onSuccess:()=>{v(b("printers.toast.scriptTriggered"))},onError:gt=>v(gt.message||b("printers.toast.failedToRunScript"),"error")}),Ma=dt({mutationFn:()=>ae.stopPrint(t.id),onSuccess:()=>{v(b("printers.toast.printStopped")),y.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:gt=>v(gt.message||b("printers.toast.failedToStopPrint"),"error")}),De=dt({mutationFn:()=>ae.pausePrint(t.id),onSuccess:()=>{v(b("printers.toast.printPaused")),y.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:gt=>v(gt.message||b("printers.toast.failedToPausePrint"),"error")}),tt=dt({mutationFn:()=>ae.resumePrint(t.id),onSuccess:()=>{v(b("printers.toast.printResumed")),y.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:gt=>v(gt.message||b("printers.toast.failedToResumePrint"),"error")}),ht=dt({mutationFn:gt=>ae.setChamberLight(t.id,gt),onMutate:async gt=>{await y.cancelQueries({queryKey:["printerStatus",t.id]});const jt=y.getQueryData(["printerStatus",t.id]);return y.setQueryData(["printerStatus",t.id],gn=>({...gn,chamber_light:gt})),{previousStatus:jt}},onSuccess:(gt,jt)=>{v(`Chamber light ${jt?"on":"off"}`)},onError:(gt,jt,gn)=>{gn?.previousStatus&&y.setQueryData(["printerStatus",t.id],gn.previousStatus),v(gt.message||b("printers.toast.failedToControlChamberLight"),"error")}}),mt=dt({mutationFn:gt=>ae.updatePrinter(t.id,{plate_detection_enabled:gt}),onSuccess:()=>{y.invalidateQueries({queryKey:["printers"]}),v(mt.variables?b("printers.toast.plateCheckEnabled"):b("printers.toast.plateCheckDisabled"))},onError:gt=>v(gt.message||b("printers.toast.failedToUpdateSetting"),"error")}),ut=(Te?.state==="RUNNING"||Te?.state==="PAUSE"||Te?.state==="PAUSED")&&(Te?.printable_objects_count??0)>=2,{data:Dt}=it({queryKey:["printableObjects",t.id],queryFn:()=>ae.getPrintableObjects(t.id),enabled:de||ut,refetchInterval:de?5e3:ut?3e4:!1}),[he,Le]=_.useState(null),Ke=_.useRef(!1),Ue=_.useRef(null),Se=_.useRef(!1),nt=dt({mutationFn:({amsId:gt,slotId:jt})=>ae.refreshAmsSlot(t.id,gt,jt),onMutate:({amsId:gt,slotId:jt})=>{Ue.current&&clearTimeout(Ue.current),Ke.current=!1,Se.current=!1,Le({amsId:gt,slotId:jt}),setTimeout(()=>{Se.current=!0},2e3),Ue.current=setTimeout(()=>{Le(null)},3e4)},onSuccess:gt=>{v(gt.message||b("printers.toast.rfidRereadInitiated"))},onError:gt=>{v(gt.message||b("printers.toast.failedToRereadRfid"),"error"),Ue.current&&clearTimeout(Ue.current),Le(null)}}),[xt,rt]=_.useState(null),[Ct,It]=_.useState(null),Rt=async()=>{try{const gt=await ae.getPlateReferences(t.id);rt(gt)}catch{}},Tt=()=>{mt.mutate(!t.plate_detection_enabled)},mn=async()=>{le(!0),re(null);const gt=Te?.chamber_light===!1;_e(gt),gt&&(await ae.setChamberLight(t.id,!0),await new Promise(jt=>setTimeout(jt,2500)));try{const jt=await ae.checkPlateEmpty(t.id,{includeDebugImage:!0});re(jt),Rt()}catch(jt){v(jt instanceof Error?jt.message:b("printers.toast.failedToCheckPlate"),"error"),gt&&(await ae.setChamberLight(t.id,!1),_e(!1))}finally{le(!1)}},Bt=_.useCallback(async()=>{re(null),Ce&&(await ae.setChamberLight(t.id,!1),_e(!1))},[Ce,t.id]),pn=async gt=>{ee(!0);try{const jt=await ae.calibratePlateDetection(t.id,{label:gt});if(jt.success){v(jt.message||b("printers.toast.calibrationSaved"),"success"),Rt();const gn=await ae.checkPlateEmpty(t.id,{includeDebugImage:!0});re(gn)}else v(jt.message||b("printers.toast.calibrationFailed"),"error")}catch(jt){v(jt instanceof Error?jt.message:b("printers.toast.calibrationFailed"),"error")}finally{ee(!1)}},Mn=async(gt,jt)=>{try{await ae.updatePlateReferenceLabel(t.id,gt,jt),It(null),Rt()}catch(gn){v(gn instanceof Error?gn.message:b("printers.toast.failedToUpdateLabel"),"error")}},jn=async gt=>{try{await ae.deletePlateReference(t.id,gt),v(b("printers.toast.referenceDeleted"),"success"),Rt();const jt=await ae.checkPlateEmpty(t.id,{includeDebugImage:!0});re(jt)}catch(jt){v(jt instanceof Error?jt.message:b("printers.toast.failedToDeleteReference"),"error")}},Kt=async()=>{if(z){ge(!0);try{await ae.updatePrinter(t.id,{plate_detection_roi:z}),v(b("printers.toast.detectionAreaSaved"),"success"),O(null);const gt=await ae.checkPlateEmpty(t.id,{includeDebugImage:!0});re(gt)}catch(gt){v(gt instanceof Error?gt.message:b("printers.toast.failedToSaveDetectionArea"),"error")}finally{ge(!1)}}};_.useEffect(()=>{const gt=jt=>{jt.key==="Escape"&&q&&Bt()};return window.addEventListener("keydown",gt),()=>window.removeEventListener("keydown",gt)},[q,Bt]);const Qt=_.useRef(null);_.useEffect(()=>{if(!he)return;const gt=Te?.ams_status_main??0;return gt!==0&&(Ke.current=!0,Qt.current&&(clearTimeout(Qt.current),Qt.current=null)),Ke.current&>===0&&(Se.current?(Ue.current&&clearTimeout(Ue.current),Le(null)):Qt.current||(Qt.current=setTimeout(()=>{Ue.current&&clearTimeout(Ue.current),Le(null)},2e3))),()=>{Qt.current&&clearTimeout(Qt.current)}},[Te?.ams_status_main,he]);const[Zt,cn]=_.useState(null);if(vn)return null;const $r=()=>{switch(i){case 1:return"w-10 h-10";case 2:return"w-14 h-14";case 3:return"w-16 h-16";case 4:return"w-20 h-20";default:return"w-14 h-14"}},Qn=()=>{switch(i){case 1:return"text-base truncate";case 2:return"text-lg";case 3:return"text-xl";case 4:return"text-2xl";default:return"text-lg"}},ai=()=>{switch(i){case 1:return"mb-2";case 2:return"mb-4";case 3:return"mb-5";case 4:return"mb-6";default:return"mb-4"}};return a.jsxs(St,{className:"relative",children:[a.jsxs(Et,{className:i>=3?"p-5":"",children:[a.jsxs("div",{className:ai(),children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("img",{src:k8e(t.model),alt:t.model||b("common.printer"),className:`object-contain rounded-lg bg-bambu-dark flex-shrink-0 ${$r()}`}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:`font-semibold text-white ${Qn()}`,children:t.name}),r==="compact"&&a.jsx("div",{className:`w-2 h-2 rounded-full flex-shrink-0 ${Te?.connected?"bg-status-ok":"bg-status-error"}`,title:Te?.connected?b("printers.connection.connected"):b("printers.connection.offline")})]}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[t.model||"Unknown Model",r==="expanded"&&Te?.nozzles&&Te.nozzles[0]?.nozzle_diameter&&a.jsxs("span",{className:"ml-1.5 text-bambu-gray",title:Te.nozzles[0].nozzle_type||"Nozzle",children:["• ",Te.nozzles[0].nozzle_diameter,"mm"]}),r==="expanded"&&n&&n.total_print_hours>0&&a.jsxs("span",{className:"ml-2 text-bambu-gray",children:[a.jsx(tr,{className:"w-3 h-3 inline-block mr-1"}),Math.round(n.total_print_hours),"h"]})]})]})]}),a.jsxs("div",{className:"relative flex-shrink-0",children:[a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>T(!N),children:a.jsx(mh,{className:"w-4 h-4"})}),N&&a.jsxs("div",{className:"absolute right-0 mt-2 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-20",children:[a.jsxs("button",{className:`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${S("printers:update")?"hover:bg-bambu-dark-tertiary":"opacity-50 cursor-not-allowed"}`,onClick:()=>{S("printers:update")&&(P(!0),T(!1))},title:S("printers:update")?void 0:b("printers.permission.noEdit"),children:[a.jsx(Ji,{className:"w-4 h-4"}),b("common.edit")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{ar.mutate(),T(!1)},children:[a.jsx(Or,{className:"w-4 h-4"}),b("printers.reconnect")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{D(!0),T(!1)},children:[a.jsx(VW,{className:"w-4 h-4"}),b("printers.mqttDebug")]}),a.jsxs("button",{className:`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${S("printers:delete")?"text-red-400 hover:bg-bambu-dark-tertiary":"text-red-400/50 cursor-not-allowed"}`,onClick:()=>{S("printers:delete")&&(A(!0),T(!1))},title:S("printers:delete")?void 0:b("printers.permission.noDelete"),children:[a.jsx(ln,{className:"w-4 h-4"}),b("common.delete")]})]})]})]}),r==="expanded"&&a.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[a.jsxs("span",{className:`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${Te?.connected?"bg-status-ok/20 text-status-ok":"bg-status-error/20 text-status-error"}`,children:[Te?.connected?a.jsx($y,{className:"w-3 h-3"}):a.jsx(WR,{className:"w-3 h-3"}),Te?.connected?b("printers.connection.connected"):b("printers.connection.offline")]}),Te?.connected&&Be!=null&&a.jsxs("span",{className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${Be>=-50||Be>=-60?"bg-status-ok/20 text-status-ok":Be>=-70?"bg-status-warning/20 text-status-warning":Be>=-80?"bg-orange-500/20 text-orange-600":"bg-status-error/20 text-status-error"}`,title:`WiFi: ${Be} dBm - ${b(M8e(Be).labelKey)}`,children:[a.jsx(qhe,{className:"w-3 h-3"}),Be,"dBm"]}),Te?.connected&&(()=>{const gt=Te.hms_errors?cMe(Te.hms_errors):[];return a.jsxs("button",{onClick:()=>oe(!0),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${gt.length>0?gt.some(jt=>jt.severity<=2)?"bg-status-error/20 text-status-error":"bg-status-warning/20 text-status-warning":"bg-status-ok/20 text-status-ok"}`,title:b("printers.clickToViewHmsErrors"),children:[a.jsx(En,{className:"w-3 h-3"}),gt.length>0?gt.length:"OK"]})})(),n&&a.jsxs("button",{onClick:()=>x("/maintenance"),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${n.due_count>0?"bg-status-error/20 text-status-error":n.warning_count>0?"bg-status-warning/20 text-status-warning":"bg-status-ok/20 text-status-ok"}`,title:n.due_count>0||n.warning_count>0?`${n.due_count>0?`${n.due_count} maintenance due`:""}${n.due_count>0&&n.warning_count>0?", ":""}${n.warning_count>0?`${n.warning_count} due soon`:""} - Click to view`:b("printers.maintenanceUpToDate"),children:[a.jsx(mm,{className:"w-3 h-3"}),n.due_count>0||n.warning_count>0?n.due_count+n.warning_count:"OK"]}),zt>0&&a.jsxs("button",{onClick:()=>x("/queue"),className:"flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-purple-500/20 text-purple-400 hover:opacity-80 transition-opacity",title:b("printers.queue.inQueue",{count:zt}),children:[a.jsx(is,{className:"w-3 h-3"}),zt]}),we?.current_version&&we?.latest_version&&a.jsxs("button",{onClick:()=>ue(!0),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${we.update_available?"bg-orange-500/20 text-orange-400":"bg-status-ok/20 text-status-ok"}`,title:we.update_available?b("printers.firmwareUpdateAvailable",{current:we.current_version,latest:we.latest_version}):b("printers.firmwareUpToDate",{version:we.current_version}),children:[we.update_available?a.jsx(wi,{className:"w-3 h-3"}):a.jsx(mr,{className:"w-3 h-3"}),we.current_version]})]})]}),M&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(St,{className:"w-full max-w-md mx-4",children:a.jsxs(Et,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:"p-2 rounded-full bg-red-500/20",children:a.jsx(En,{className:"w-5 h-5 text-red-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:b("printers.confirm.deleteTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:b("printers.confirm.deleteMessage",{name:t.name})})]})]}),a.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:a.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k,onChange:gt=>R(gt.target.checked),className:"mt-0.5 w-4 h-4 rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:b("printers.deleteArchives")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:b(k?"printers.confirm.deleteArchivesNote":"printers.confirm.keepArchivesNote")})]})]})}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>{A(!1),R(!0)},children:b("common.cancel")}),a.jsx(Ne,{variant:"danger",onClick:()=>{dr.mutate({deleteArchives:k}),A(!1),R(!0)},children:"Delete"})]})]})})}),Te?.connected&&a.jsxs(a.Fragment,{children:[r==="compact"?a.jsx("div",{className:"mt-2",children:Te.state==="RUNNING"?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5",children:a.jsx("div",{className:"bg-bambu-green h-1.5 rounded-full transition-all",style:{width:`${Te.progress||0}%`}})}),a.jsxs("span",{className:"text-xs text-white",children:[Math.round(Te.progress||0),"%"]})]}):a.jsx("p",{className:"text-xs text-bambu-gray",children:$q(Te.state,Te.stg_cur_name)})}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"mb-4 p-3 bg-bambu-dark rounded-lg relative",children:[a.jsxs("button",{onClick:()=>Re(!0),disabled:!(Te.state==="RUNNING"||Te.state==="PAUSE"||Te.state==="PAUSED")||(Te.printable_objects_count??0)<2||!S("printers:control"),className:`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${(Te.state==="RUNNING"||Te.state==="PAUSE"||Te.state==="PAUSED")&&(Te.printable_objects_count??0)>=2&&S("printers:control")?"text-bambu-gray hover:text-white hover:bg-white/10":"text-bambu-gray/30 cursor-not-allowed"}`,title:S("printers:control")?Te.state==="RUNNING"||Te.state==="PAUSE"||Te.state==="PAUSED"?(Te.printable_objects_count??0)>=2?b("printers.skipObjects.tooltip"):b("printers.skipObjects.requiresMultiple"):b("printers.skipObjects.onlyWhilePrinting"):b("printers.permission.noControl"),children:[a.jsx(zk,{className:"w-4 h-4"}),Dt&&Dt.skipped_count>0&&a.jsx("span",{className:"absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-bold bg-red-500 text-white rounded-full",children:Dt.skipped_count})]}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(E8e,{url:Te.state==="RUNNING"?Te.cover_url:null,printName:Te.state==="RUNNING"&&(Te.subtask_name||Te.current_print)||void 0}),a.jsx("div",{className:"flex-1 min-w-0",children:Te.current_print&&Te.state==="RUNNING"?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-1",children:Te.stg_cur_name||"Printing"}),a.jsx("p",{className:"text-white text-sm mb-2 truncate",children:Te.subtask_name||Te.current_print}),a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all",style:{width:`${Te.progress||0}%`}})}),a.jsxs("span",{className:"text-white",children:[Math.round(Te.progress||0),"%"]})]}),a.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-bambu-gray",children:[Te.remaining_time!=null&&Te.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(tr,{className:"w-3 h-3"}),S8e(Te.remaining_time*60)]}),a.jsxs("span",{className:"text-bambu-green font-medium",title:b("printers.estimatedCompletion"),children:["ETA ",N8e(Te.remaining_time,d)]})]}),Te.layer_num!=null&&Te.total_layers!=null&&Te.total_layers>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(is,{className:"w-3 h-3"}),Te.layer_num,"/",Te.total_layers]}),Gt&&a.jsxs("span",{className:"flex items-center gap-1",title:`Started by ${Gt}`,children:[a.jsx($u,{className:"w-3 h-3"}),Gt]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-1",children:b("printers.sort.status")}),a.jsx("p",{className:"text-white text-sm mb-2",children:$q(Te.state,Te.stg_cur_name)}),a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3",children:a.jsx("div",{className:"bg-bambu-dark-tertiary h-2 rounded-full"})}),a.jsx("span",{className:"text-bambu-gray",children:"—"})]}),fn?a.jsxs("p",{className:"text-xs text-bambu-gray mt-2 truncate",title:fn.print_name||fn.filename,children:["Last: ",fn.print_name||fn.filename,fn.completed_at&&a.jsxs("span",{className:"ml-1 text-bambu-gray/60",children:["• ",Gg(fn.completed_at,{month:"short",day:"numeric"})]})]}):a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:b("printers.readyToPrint")})]})})]})]}),Te.state!=="RUNNING"&&a.jsx(fMe,{printerId:t.id})]}),Te.temperatures&&r==="expanded"&&(()=>{const gt=Te.temperatures.nozzle_heating||Te.temperatures.nozzle_2_heating||!1,jt=Te.temperatures.bed_heating||!1,gn=Te.temperatures.chamber_heating||!1,Nt=t.nozzle_count===2||Te.temperatures.nozzle_2!==void 0,un=Te.active_extruder===1?"L":"R",In=Te.nozzle_rack?.find(Si=>Si.id===1),rr=Te.nozzle_rack?.find(Si=>Si.id===0),ua=rr||In;return a.jsxs("div",{className:"flex items-stretch gap-1.5 flex-wrap",children:[a.jsxs("div",{className:"text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center",children:[a.jsx(bP,{className:"w-3.5 h-3.5 mb-0.5",color:"text-orange-400",isHeating:gt}),Te.temperatures.nozzle_2!==void 0?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-[9px] text-bambu-gray",children:"L / R"}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Te.temperatures.nozzle||0),"° / ",Math.round(Te.temperatures.nozzle_2||0),"°"]})]}):ua?a.jsx(Fee,{slot:ua,index:0,activeStatus:!0,filamentName:ua.filament_id?Ge?.[ua.filament_id]?.name:void 0,children:a.jsxs("div",{className:"cursor-default",children:[a.jsx("p",{className:"text-[9px] text-bambu-gray",children:b("printers.temperatures.nozzle")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Te.temperatures.nozzle||0),"°C"]})]})}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-[9px] text-bambu-gray",children:b("printers.temperatures.nozzle")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Te.temperatures.nozzle||0),"°C"]})]})]}),a.jsxs("div",{className:"text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center",children:[a.jsx(bP,{className:"w-3.5 h-3.5 mb-0.5",color:"text-blue-400",isHeating:jt}),a.jsx("p",{className:"text-[9px] text-bambu-gray",children:b("printers.temperatures.bed")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Te.temperatures.bed||0),"°C"]})]}),Te.temperatures.chamber!==void 0&&a.jsxs("div",{className:"text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center",children:[a.jsx(bP,{className:"w-3.5 h-3.5 mb-0.5",color:"text-green-400",isHeating:gn}),a.jsx("p",{className:"text-[9px] text-bambu-gray",children:b("printers.temperatures.chamber")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Te.temperatures.chamber||0),"°C"]})]}),Nt&&a.jsx(g8e,{leftSlot:In,rightSlot:rr,activeNozzle:un,children:a.jsxs("div",{className:"text-center px-3 py-1.5 bg-bambu-dark rounded-lg h-full flex flex-col justify-center items-center cursor-default",title:b("printers.activeNozzle",{nozzle:b(un==="L"?"common.left":"common.right")}),children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsxs("span",{className:`text-[11px] font-bold ${un==="L"?"text-amber-400":"text-gray-500"}`,children:["L",In?.nozzle_diameter?` ${In.nozzle_diameter}`:""]}),a.jsx("span",{className:"text-[9px] text-bambu-gray/40",children:"·"}),a.jsxs("span",{className:`text-[11px] font-bold ${un==="R"?"text-amber-400":"text-gray-500"}`,children:["R",rr?.nozzle_diameter?` ${rr.nozzle_diameter}`:""]})]}),a.jsx("p",{className:"text-[9px] text-bambu-gray",children:b("printers.temperatures.nozzle")})]})}),Te.nozzle_rack&&Te.nozzle_rack.some(Si=>Si.id>=2)&&a.jsx(b8e,{slots:Te.nozzle_rack,filamentInfo:Ge})]})})(),r==="expanded"&&(()=>{const gt=Te.state==="RUNNING",jt=Te.state==="PAUSED"||Te.state==="PAUSE",gn=gt||jt,Nt=Ma.isPending||De.isPending||tt.isPending,un=Te.cooling_fan_speed,In=Te.big_fan1_speed,rr=Te.big_fan2_speed;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:b("printers.controls")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${un&&un>0?"bg-cyan-500/10":"bg-bambu-dark"}`,title:b("printers.fans.partCooling"),children:[a.jsx(RW,{className:`w-3.5 h-3.5 ${un&&un>0?"text-cyan-400":"text-bambu-gray/50"}`}),a.jsxs("span",{className:`text-[10px] ${un&&un>0?"text-cyan-400":"text-bambu-gray/50"}`,children:[un??0,"%"]})]}),a.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${In&&In>0?"bg-blue-500/10":"bg-bambu-dark"}`,title:b("printers.fans.auxiliary"),children:[a.jsx(qW,{className:`w-3.5 h-3.5 ${In&&In>0?"text-blue-400":"text-bambu-gray/50"}`}),a.jsxs("span",{className:`text-[10px] ${In&&In>0?"text-blue-400":"text-bambu-gray/50"}`,children:[In??0,"%"]})]}),a.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${rr&&rr>0?"bg-green-500/10":"bg-bambu-dark"}`,title:b("printers.fans.chamber"),children:[a.jsx(Mce,{className:`w-3.5 h-3.5 ${rr&&rr>0?"text-green-400":"text-bambu-gray/50"}`}),a.jsxs("span",{className:`text-[10px] ${rr&&rr>0?"text-green-400":"text-bambu-gray/50"}`,children:[rr??0,"%"]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("button",{onClick:()=>W(!0),disabled:!gn||Nt||!S("printers:control"),className:` + `})]})]})}function x8e({slots:t,filamentInfo:e}){const{t:n}=Yt(),r=t.filter(l=>l.id>=2),i=6,s=r.length>0?Math.min(...r.map(l=>l.id)):16,o=Array.from({length:i},(l,c)=>r.find(u=>u.id===s+c)??{id:-(c+1),nozzle_type:"",nozzle_diameter:"",wear:null,stat:null,max_temp:0,serial_number:"",filament_color:"",filament_id:"",filament_type:""});return a.jsxs("div",{className:"text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[2_1_190px] flex flex-col justify-center",children:[a.jsx("p",{className:"text-[9px] text-bambu-gray mb-1",children:n("printers.nozzleRack")}),a.jsx("div",{className:"flex gap-[3px] justify-center",children:o.map((l,c)=>{const u=!l.nozzle_diameter&&!l.nozzle_type,d=u?null:Ree(l.filament_color),h=d?g8e(l.filament_color):!1;return a.jsx(Fee,{slot:l,index:c,filamentName:l.filament_id?e?.[l.filament_id]?.name:void 0,children:a.jsx("div",{className:`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${u?"bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20":"bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40"}`,style:d?{backgroundColor:d}:void 0,children:a.jsx("span",{className:`text-[10px] font-semibold ${u?"text-bambu-gray/30":h?"text-black/80":"text-white"}`,style:d&&!h?{textShadow:"0 1px 3px rgba(0,0,0,0.9)"}:void 0,children:u?"—":l.nozzle_diameter||"?"})})},l.id>=0?l.id:`empty-${c}`)})})]})}function Uq({className:t}){return a.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:a.jsx("path",{d:"M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z",fill:"#C3C2C1"})})}function y8e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z",fill:"#C3C2C1"}),a.jsx("path",{d:"M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z",fill:"#1F8FEB"})]})}function v8e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z",fill:"#1F8FEB"}),a.jsx("path",{d:"M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z",fill:"#C3C2C1"})]})}function w8e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"}),a.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function _8e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function S8e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function bP({className:t,color:e,isHeating:n}){const i={"text-orange-400":"#fb923c","text-blue-400":"#60a5fa","text-green-400":"#4ade80"}[e]||"#888",s=n?{filter:`drop-shadow(0 0 4px ${i}) drop-shadow(0 0 8px ${i})`}:{};return n?a.jsxs("svg",{className:t,style:s,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:i,rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:i}),a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:i,strokeWidth:"1",fill:"none"})]}):a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:i,strokeWidth:"1",fill:"none"}),a.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:i,strokeWidth:"1",fill:"none"})]})}function Bq({humidity:t,goodThreshold:e=40,fairThreshold:n=60,onClick:r,compact:i}){const s=typeof t=="string"?parseInt(t,10):t,o=typeof e=="number"?e:40,l=typeof n=="number"?n:60;let c,u;isNaN(s)?(c="#C3C2C1",u="Unknown"):s<=o?(c="#22a352",u="Good"):s<=l?(c="#d4a017",u="Fair"):(c="#c62828",u="Bad");let d;return isNaN(s)||s<=o?d=Uq:s<=l?d=y8e:d=v8e,a.jsxs("button",{type:"button",onClick:r,className:`flex items-center gap-1 ${r?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Humidity: ${s}% - ${u}${r?" (click for history)":""}`,children:[a.jsx(d,{className:i?"w-2.5 h-3":"w-3 h-4"}),a.jsxs("span",{className:`font-medium tabular-nums ${i?"text-[10px]":"text-xs"}`,style:{color:c},children:[s,"%"]})]})}function Hq({temp:t,goodThreshold:e=28,fairThreshold:n=35,onClick:r,compact:i}){const s=typeof e=="number"?e:28,o=typeof n=="number"?n:35;let l,c,u;return t<=s?(l="#22a352",c="Good",u=w8e):t<=o?(l="#d4a017",c="Fair",u=_8e):(l="#c62828",c="Bad",u=S8e),a.jsxs("button",{type:"button",onClick:r,className:`flex items-center gap-1 ${r?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Temperature: ${t}°C - ${c}${r?" (click for history)":""}`,children:[a.jsx(u,{className:i?"w-2.5 h-3":"w-3 h-4"}),a.jsxs("span",{className:`tabular-nums text-right ${i?"text-[10px] w-8":"w-12"}`,style:{color:l},children:[t,"°C"]})]})}function Gd(t,e){const n=typeof t=="string"?parseInt(t,10):t,r=isNaN(n)?0:n,i=e===1,s=r>=128?r-128:r,o=String.fromCharCode(65+s);return i?`HT-${o}`:`AMS-${o}`}function xP(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function yP(t){return!t?.remaining_weight||!t?.filament_weight||t.filament_weight<=0?null:Math.min(100,Math.round(t.remaining_weight/t.filament_weight*100))}function N8e(t){const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function k8e(t,e="system"){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={hour:"2-digit",minute:"2-digit"};e==="12h"?o.hour12=!0:e==="24h"&&(o.hour12=!1);const l=r.toLocaleTimeString([],o),c=Math.floor((s.getTime()-i.getTime())/(1e3*60*60*24));return c===0?l:c===1?`Tomorrow ${l}`:r.toLocaleDateString([],{weekday:"short"})+" "+l}function M8e(t){if(!t)return"/img/printers/default.png";const e=t.toLowerCase().replace(/\s+/g,"");return e.includes("x1e")?"/img/printers/x1e.png":e.includes("x1c")||e.includes("x1carbon")||e.includes("x1")?"/img/printers/x1c.png":e.includes("h2d")?"/img/printers/h2d.png":e.includes("h2c")?"/img/printers/h2c.png":e.includes("h2s")?"/img/printers/h2d.png":e.includes("p2s")||e.includes("p1s")?"/img/printers/p1s.png":e.includes("p1p")?"/img/printers/p1p.png":e.includes("a1mini")?"/img/printers/a1mini.png":e.includes("a1")?"/img/printers/a1.png":"/img/printers/default.png"}function E8e(t){return t>=-50?{labelKey:"printers.wifiSignal.excellent",color:"text-bambu-green",bars:4}:t>=-60?{labelKey:"printers.wifiSignal.good",color:"text-bambu-green",bars:3}:t>=-70?{labelKey:"printers.wifiSignal.fair",color:"text-yellow-400",bars:2}:t>=-80?{labelKey:"printers.wifiSignal.weak",color:"text-orange-400",bars:1}:{labelKey:"printers.wifiSignal.veryWeak",color:"text-red-400",bars:1}}function vP(t){return t?!!(t.tray_info_idx&&t.tray_info_idx.startsWith("GF")||t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function T8e({url:t,printName:e}){const{t:n}=Yt(),[r,i]=_.useState(!1),[s,o]=_.useState(!1),[l,c]=_.useState(!1);return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:`w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${t&&r?"cursor-pointer":""}`,onClick:()=>t&&r&&c(!0),children:t&&!s?a.jsxs(a.Fragment,{children:[a.jsx("img",{src:t,alt:n("printers.printPreview"),className:`w-full h-full object-cover ${r?"block":"hidden"}`,onLoad:()=>i(!0),onError:()=>o(!0)}),!r&&a.jsx(Ii,{className:"w-8 h-8 text-bambu-gray"})]}):a.jsx(Ii,{className:"w-8 h-8 text-bambu-gray"})}),l&&t&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8",onClick:()=>c(!1),children:a.jsxs("div",{className:"relative max-w-2xl max-h-full",children:[a.jsx("img",{src:t,alt:n("printers.printPreview"),className:"max-w-full max-h-[80vh] rounded-lg shadow-2xl"}),e&&a.jsx("p",{className:"text-white text-center mt-4 text-lg",children:e})]})})]})}function A8e({printers:t}){const{t:e}=Yt(),n=an(),r=_.useMemo(()=>{let s=0,o=0,l=0,c=0;return t?.forEach(u=>{const d=n.getQueryData(["printerStatus",u.id]);d===void 0?c++:d.connected?d.state==="RUNNING"?s++:o++:l++}),{printing:s,idle:o,offline:l,loading:c,total:t?.length||0}},[t,n]),[,i]=_.useState(0);return _.useEffect(()=>{let s=!1;const o=n.getQueryCache().subscribe(()=>{s||(s=!0,requestAnimationFrame(()=>{i(l=>l+1),s=!1}))});return()=>o()},[n]),t?.length?a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[r.printing>0&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white font-medium",children:r.printing})," ",e("printers.status.printing").toLowerCase()]})]}),r.idle>0&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white font-medium",children:r.idle})," ",e("printers.status.idle").toLowerCase()]})]}),r.offline>0&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-gray-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white font-medium",children:r.offline})," ",e("printers.status.offline").toLowerCase()]})]})]}):null}function $q(t,e){if(e)return e;switch(t){case"RUNNING":return"Printing";case"PAUSE":return"Paused";case"FINISH":return"Finished";case"FAILED":return"Failed";case"IDLE":return"Idle";default:return t?t.charAt(0)+t.slice(1).toLowerCase():"Idle"}}function Vq({printer:t,hideIfDisconnected:e,maintenanceInfo:n,viewMode:r="expanded",cardSize:i=2,amsThresholds:s,spoolmanEnabled:o=!1,hasUnlinkedSpools:l=!1,linkedSpools:c,spoolmanUrl:u,timeFormat:d="system",cameraViewMode:h="window",onOpenEmbeddedCamera:p,checkPrinterFirmware:m=!0}){const{t:b}=Yt(),y=an(),x=Ec(),{showToast:v}=Tn(),{hasPermission:S}=Ir(),[N,T]=_.useState(!1),[M,A]=_.useState(!1),[k,R]=_.useState(!0),[C,P]=_.useState(!1),[U,F]=_.useState(!1),[H,D]=_.useState(!1),[$,G]=_.useState(!1),[I,K]=_.useState(!1),[Q,oe]=_.useState(!1),[B,W]=_.useState(!1),[J,ne]=_.useState(!1),[me,fe]=_.useState(!1),[de,Re]=_.useState(!1),[se,ke]=_.useState(null),[Fe,ce]=_.useState(null),[Ve,V]=_.useState(null),[Y,ue]=_.useState(!1),[q,re]=_.useState(null),[X,le]=_.useState(!1),[pe,ee]=_.useState(!1),[z,O]=_.useState(null),[Z,ge]=_.useState(!1),[Ce,_e]=_.useState(!1),{data:Te}=it({queryKey:["printerStatus",t.id],queryFn:()=>ae.getPrinterStatus(t.id),refetchInterval:3e4}),{data:we}=it({queryKey:["firmwareUpdate",t.id],queryFn:()=>N1.checkPrinterUpdate(t.id),staleTime:300*1e3,refetchInterval:300*1e3,enabled:m&&S("firmware:read")}),$e=_.useMemo(()=>{const gt=new Set;if(Te?.ams)for(const jt of Te.ams)for(const gn of jt.tray||[])gn.tray_info_idx&>.add(gn.tray_info_idx);if(Te?.vt_tray?.tray_info_idx&>.add(Te.vt_tray.tray_info_idx),Te?.nozzle_rack)for(const jt of Te.nozzle_rack)jt.filament_id&>.add(jt.filament_id);return Array.from(gt)},[Te?.ams,Te?.vt_tray,Te?.nozzle_rack]),{data:Ge}=it({queryKey:["filamentInfo",$e],queryFn:()=>ae.getFilamentInfo($e),enabled:$e.length>0,staleTime:300*1e3}),{data:ze}=it({queryKey:["slotPresets",t.id],queryFn:()=>ae.getSlotPresets(t.id),staleTime:120*1e3}),[be,Me]=_.useState(null);_.useEffect(()=>{Te?.wifi_signal!=null&&Me(Te.wifi_signal)},[Te?.wifi_signal]);const Be=Te?.wifi_signal??be,Ae=_.useRef(void 0);_.useEffect(()=>{Te?.connected!==void 0&&(Ae.current=Te.connected)},[Te?.connected]);const qe=Te?.connected??Ae.current,ve=_.useRef({});_.useEffect(()=>{Te?.ams_extruder_map&&Object.keys(Te.ams_extruder_map).length>0&&(ve.current=Te.ams_extruder_map)},[Te?.ams_extruder_map]);const et=Te?.ams_extruder_map&&Object.keys(Te.ams_extruder_map).length>0?Te.ams_extruder_map:ve.current,Ee=_.useRef([]);_.useEffect(()=>{Te?.ams&&Te.ams.length>0&&(Ee.current=Te.ams)},[Te?.ams]);const Ye=Te?.ams&&Te.ams.length>0?Te.ams:Ee.current,je=_.useRef(255),Pe=Te?.tray_now;Pe!==void 0&&Pe!==255&&(je.current=Pe);const ye=Pe===void 0||Pe===255?je.current:Pe,{data:Qe}=it({queryKey:["smartPlugByPrinter",t.id],queryFn:()=>ae.getSmartPlugByPrinter(t.id)}),{data:yt}=it({queryKey:["scriptPlugsByPrinter",t.id],queryFn:()=>ae.getScriptPlugsByPrinter(t.id)}),{data:at}=it({queryKey:["smartPlugStatus",Qe?.id],queryFn:()=>Qe?ae.getSmartPlugStatus(Qe.id):null,enabled:!!Qe,refetchInterval:1e4}),{data:Ut}=it({queryKey:["queue",t.id,"pending"],queryFn:()=>ae.getQueue(t.id,"pending")}),zt=Ut?.length||0,{data:Ie}=it({queryKey:["queue",t.id,"printing"],queryFn:()=>ae.getQueue(t.id,"printing"),enabled:Te?.state==="RUNNING"}),{data:vt}=it({queryKey:["currentPrintUser",t.id],queryFn:()=>ae.getCurrentPrintUser(t.id),enabled:Te?.state==="RUNNING"}),Gt=Ie?.[0]?.created_by_username||vt?.username,{data:dn}=it({queryKey:["archives",t.id,"last"],queryFn:()=>ae.getArchives(t.id,1,0),enabled:Te?.connected&&Te?.state!=="RUNNING"}),fn=dn?.[0],vn=e&&qe===!1,dr=dt({mutationFn:gt=>ae.deletePrinter(t.id,gt.deleteArchives),onSuccess:()=>{y.invalidateQueries({queryKey:["printers"]}),y.invalidateQueries({queryKey:["archives"]}),y.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:gt=>v(gt.message||b("printers.toast.failedToDelete"),"error")}),ar=dt({mutationFn:()=>ae.connectPrinter(t.id),onSuccess:()=>{y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),kn=dt({mutationFn:gt=>Qe?ae.controlSmartPlug(Qe.id,gt):Promise.reject("No plug"),onSuccess:()=>{y.invalidateQueries({queryKey:["smartPlugStatus",Qe?.id]})}}),Bn=dt({mutationFn:gt=>Qe?ae.updateSmartPlug(Qe.id,{auto_off:gt}):Promise.reject("No plug"),onSuccess:()=>{y.invalidateQueries({queryKey:["smartPlugByPrinter",t.id]}),y.invalidateQueries({queryKey:["smart-plugs"]})}}),Hr=dt({mutationFn:gt=>ae.controlSmartPlug(gt,"on"),onSuccess:()=>{v(b("printers.toast.scriptTriggered"))},onError:gt=>v(gt.message||b("printers.toast.failedToRunScript"),"error")}),Ma=dt({mutationFn:()=>ae.stopPrint(t.id),onSuccess:()=>{v(b("printers.toast.printStopped")),y.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:gt=>v(gt.message||b("printers.toast.failedToStopPrint"),"error")}),De=dt({mutationFn:()=>ae.pausePrint(t.id),onSuccess:()=>{v(b("printers.toast.printPaused")),y.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:gt=>v(gt.message||b("printers.toast.failedToPausePrint"),"error")}),tt=dt({mutationFn:()=>ae.resumePrint(t.id),onSuccess:()=>{v(b("printers.toast.printResumed")),y.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:gt=>v(gt.message||b("printers.toast.failedToResumePrint"),"error")}),ht=dt({mutationFn:gt=>ae.setChamberLight(t.id,gt),onMutate:async gt=>{await y.cancelQueries({queryKey:["printerStatus",t.id]});const jt=y.getQueryData(["printerStatus",t.id]);return y.setQueryData(["printerStatus",t.id],gn=>({...gn,chamber_light:gt})),{previousStatus:jt}},onSuccess:(gt,jt)=>{v(`Chamber light ${jt?"on":"off"}`)},onError:(gt,jt,gn)=>{gn?.previousStatus&&y.setQueryData(["printerStatus",t.id],gn.previousStatus),v(gt.message||b("printers.toast.failedToControlChamberLight"),"error")}}),mt=dt({mutationFn:gt=>ae.updatePrinter(t.id,{plate_detection_enabled:gt}),onSuccess:()=>{y.invalidateQueries({queryKey:["printers"]}),v(mt.variables?b("printers.toast.plateCheckEnabled"):b("printers.toast.plateCheckDisabled"))},onError:gt=>v(gt.message||b("printers.toast.failedToUpdateSetting"),"error")}),ut=(Te?.state==="RUNNING"||Te?.state==="PAUSE"||Te?.state==="PAUSED")&&(Te?.printable_objects_count??0)>=2,{data:Dt}=it({queryKey:["printableObjects",t.id],queryFn:()=>ae.getPrintableObjects(t.id),enabled:de||ut,refetchInterval:de?5e3:ut?3e4:!1}),[he,Le]=_.useState(null),Ke=_.useRef(!1),Ue=_.useRef(null),Se=_.useRef(!1),nt=dt({mutationFn:({amsId:gt,slotId:jt})=>ae.refreshAmsSlot(t.id,gt,jt),onMutate:({amsId:gt,slotId:jt})=>{Ue.current&&clearTimeout(Ue.current),Ke.current=!1,Se.current=!1,Le({amsId:gt,slotId:jt}),setTimeout(()=>{Se.current=!0},2e3),Ue.current=setTimeout(()=>{Le(null)},3e4)},onSuccess:gt=>{v(gt.message||b("printers.toast.rfidRereadInitiated"))},onError:gt=>{v(gt.message||b("printers.toast.failedToRereadRfid"),"error"),Ue.current&&clearTimeout(Ue.current),Le(null)}}),[xt,rt]=_.useState(null),[Ct,It]=_.useState(null),Rt=async()=>{try{const gt=await ae.getPlateReferences(t.id);rt(gt)}catch{}},Tt=()=>{mt.mutate(!t.plate_detection_enabled)},mn=async()=>{le(!0),re(null);const gt=Te?.chamber_light===!1;_e(gt),gt&&(await ae.setChamberLight(t.id,!0),await new Promise(jt=>setTimeout(jt,2500)));try{const jt=await ae.checkPlateEmpty(t.id,{includeDebugImage:!0});re(jt),Rt()}catch(jt){v(jt instanceof Error?jt.message:b("printers.toast.failedToCheckPlate"),"error"),gt&&(await ae.setChamberLight(t.id,!1),_e(!1))}finally{le(!1)}},Bt=_.useCallback(async()=>{re(null),Ce&&(await ae.setChamberLight(t.id,!1),_e(!1))},[Ce,t.id]),pn=async gt=>{ee(!0);try{const jt=await ae.calibratePlateDetection(t.id,{label:gt});if(jt.success){v(jt.message||b("printers.toast.calibrationSaved"),"success"),Rt();const gn=await ae.checkPlateEmpty(t.id,{includeDebugImage:!0});re(gn)}else v(jt.message||b("printers.toast.calibrationFailed"),"error")}catch(jt){v(jt instanceof Error?jt.message:b("printers.toast.calibrationFailed"),"error")}finally{ee(!1)}},Mn=async(gt,jt)=>{try{await ae.updatePlateReferenceLabel(t.id,gt,jt),It(null),Rt()}catch(gn){v(gn instanceof Error?gn.message:b("printers.toast.failedToUpdateLabel"),"error")}},jn=async gt=>{try{await ae.deletePlateReference(t.id,gt),v(b("printers.toast.referenceDeleted"),"success"),Rt();const jt=await ae.checkPlateEmpty(t.id,{includeDebugImage:!0});re(jt)}catch(jt){v(jt instanceof Error?jt.message:b("printers.toast.failedToDeleteReference"),"error")}},Kt=async()=>{if(z){ge(!0);try{await ae.updatePrinter(t.id,{plate_detection_roi:z}),v(b("printers.toast.detectionAreaSaved"),"success"),O(null);const gt=await ae.checkPlateEmpty(t.id,{includeDebugImage:!0});re(gt)}catch(gt){v(gt instanceof Error?gt.message:b("printers.toast.failedToSaveDetectionArea"),"error")}finally{ge(!1)}}};_.useEffect(()=>{const gt=jt=>{jt.key==="Escape"&&q&&Bt()};return window.addEventListener("keydown",gt),()=>window.removeEventListener("keydown",gt)},[q,Bt]);const Qt=_.useRef(null);_.useEffect(()=>{if(!he)return;const gt=Te?.ams_status_main??0;return gt!==0&&(Ke.current=!0,Qt.current&&(clearTimeout(Qt.current),Qt.current=null)),Ke.current&>===0&&(Se.current?(Ue.current&&clearTimeout(Ue.current),Le(null)):Qt.current||(Qt.current=setTimeout(()=>{Ue.current&&clearTimeout(Ue.current),Le(null)},2e3))),()=>{Qt.current&&clearTimeout(Qt.current)}},[Te?.ams_status_main,he]);const[Zt,cn]=_.useState(null);if(vn)return null;const $r=()=>{switch(i){case 1:return"w-10 h-10";case 2:return"w-14 h-14";case 3:return"w-16 h-16";case 4:return"w-20 h-20";default:return"w-14 h-14"}},Qn=()=>{switch(i){case 1:return"text-base truncate";case 2:return"text-lg";case 3:return"text-xl";case 4:return"text-2xl";default:return"text-lg"}},ai=()=>{switch(i){case 1:return"mb-2";case 2:return"mb-4";case 3:return"mb-5";case 4:return"mb-6";default:return"mb-4"}};return a.jsxs(St,{className:"relative",children:[a.jsxs(Et,{className:i>=3?"p-5":"",children:[a.jsxs("div",{className:ai(),children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("img",{src:M8e(t.model),alt:t.model||b("common.printer"),className:`object-contain rounded-lg bg-bambu-dark flex-shrink-0 ${$r()}`}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:`font-semibold text-white ${Qn()}`,children:t.name}),r==="compact"&&a.jsx("div",{className:`w-2 h-2 rounded-full flex-shrink-0 ${Te?.connected?"bg-status-ok":"bg-status-error"}`,title:Te?.connected?b("printers.connection.connected"):b("printers.connection.offline")})]}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[t.model||"Unknown Model",r==="expanded"&&Te?.nozzles&&Te.nozzles[0]?.nozzle_diameter&&a.jsxs("span",{className:"ml-1.5 text-bambu-gray",title:Te.nozzles[0].nozzle_type||"Nozzle",children:["• ",Te.nozzles[0].nozzle_diameter,"mm"]}),r==="expanded"&&n&&n.total_print_hours>0&&a.jsxs("span",{className:"ml-2 text-bambu-gray",children:[a.jsx(tr,{className:"w-3 h-3 inline-block mr-1"}),Math.round(n.total_print_hours),"h"]})]})]})]}),a.jsxs("div",{className:"relative flex-shrink-0",children:[a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>T(!N),children:a.jsx(mh,{className:"w-4 h-4"})}),N&&a.jsxs("div",{className:"absolute right-0 mt-2 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-20",children:[a.jsxs("button",{className:`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${S("printers:update")?"hover:bg-bambu-dark-tertiary":"opacity-50 cursor-not-allowed"}`,onClick:()=>{S("printers:update")&&(P(!0),T(!1))},title:S("printers:update")?void 0:b("printers.permission.noEdit"),children:[a.jsx(Ji,{className:"w-4 h-4"}),b("common.edit")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{ar.mutate(),T(!1)},children:[a.jsx(Or,{className:"w-4 h-4"}),b("printers.reconnect")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{D(!0),T(!1)},children:[a.jsx(VW,{className:"w-4 h-4"}),b("printers.mqttDebug")]}),a.jsxs("button",{className:`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${S("printers:delete")?"text-red-400 hover:bg-bambu-dark-tertiary":"text-red-400/50 cursor-not-allowed"}`,onClick:()=>{S("printers:delete")&&(A(!0),T(!1))},title:S("printers:delete")?void 0:b("printers.permission.noDelete"),children:[a.jsx(ln,{className:"w-4 h-4"}),b("common.delete")]})]})]})]}),r==="expanded"&&a.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[a.jsxs("span",{className:`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${Te?.connected?"bg-status-ok/20 text-status-ok":"bg-status-error/20 text-status-error"}`,children:[Te?.connected?a.jsx($y,{className:"w-3 h-3"}):a.jsx(WR,{className:"w-3 h-3"}),Te?.connected?b("printers.connection.connected"):b("printers.connection.offline")]}),Te?.connected&&Be!=null&&a.jsxs("span",{className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${Be>=-50||Be>=-60?"bg-status-ok/20 text-status-ok":Be>=-70?"bg-status-warning/20 text-status-warning":Be>=-80?"bg-orange-500/20 text-orange-600":"bg-status-error/20 text-status-error"}`,title:`WiFi: ${Be} dBm - ${b(E8e(Be).labelKey)}`,children:[a.jsx(qhe,{className:"w-3 h-3"}),Be,"dBm"]}),Te?.connected&&(()=>{const gt=Te.hms_errors?cMe(Te.hms_errors):[];return a.jsxs("button",{onClick:()=>oe(!0),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${gt.length>0?gt.some(jt=>jt.severity<=2)?"bg-status-error/20 text-status-error":"bg-status-warning/20 text-status-warning":"bg-status-ok/20 text-status-ok"}`,title:b("printers.clickToViewHmsErrors"),children:[a.jsx(En,{className:"w-3 h-3"}),gt.length>0?gt.length:"OK"]})})(),n&&a.jsxs("button",{onClick:()=>x("/maintenance"),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${n.due_count>0?"bg-status-error/20 text-status-error":n.warning_count>0?"bg-status-warning/20 text-status-warning":"bg-status-ok/20 text-status-ok"}`,title:n.due_count>0||n.warning_count>0?`${n.due_count>0?`${n.due_count} maintenance due`:""}${n.due_count>0&&n.warning_count>0?", ":""}${n.warning_count>0?`${n.warning_count} due soon`:""} - Click to view`:b("printers.maintenanceUpToDate"),children:[a.jsx(mm,{className:"w-3 h-3"}),n.due_count>0||n.warning_count>0?n.due_count+n.warning_count:"OK"]}),zt>0&&a.jsxs("button",{onClick:()=>x("/queue"),className:"flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-purple-500/20 text-purple-400 hover:opacity-80 transition-opacity",title:b("printers.queue.inQueue",{count:zt}),children:[a.jsx(is,{className:"w-3 h-3"}),zt]}),we?.current_version&&we?.latest_version&&a.jsxs("button",{onClick:()=>ue(!0),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${we.update_available?"bg-orange-500/20 text-orange-400":"bg-status-ok/20 text-status-ok"}`,title:we.update_available?b("printers.firmwareUpdateAvailable",{current:we.current_version,latest:we.latest_version}):b("printers.firmwareUpToDate",{version:we.current_version}),children:[we.update_available?a.jsx(wi,{className:"w-3 h-3"}):a.jsx(mr,{className:"w-3 h-3"}),we.current_version]})]})]}),M&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(St,{className:"w-full max-w-md mx-4",children:a.jsxs(Et,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:"p-2 rounded-full bg-red-500/20",children:a.jsx(En,{className:"w-5 h-5 text-red-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:b("printers.confirm.deleteTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:b("printers.confirm.deleteMessage",{name:t.name})})]})]}),a.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:a.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k,onChange:gt=>R(gt.target.checked),className:"mt-0.5 w-4 h-4 rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:b("printers.deleteArchives")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:b(k?"printers.confirm.deleteArchivesNote":"printers.confirm.keepArchivesNote")})]})]})}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>{A(!1),R(!0)},children:b("common.cancel")}),a.jsx(Ne,{variant:"danger",onClick:()=>{dr.mutate({deleteArchives:k}),A(!1),R(!0)},children:"Delete"})]})]})})}),Te?.connected&&a.jsxs(a.Fragment,{children:[r==="compact"?a.jsx("div",{className:"mt-2",children:Te.state==="RUNNING"?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5",children:a.jsx("div",{className:"bg-bambu-green h-1.5 rounded-full transition-all",style:{width:`${Te.progress||0}%`}})}),a.jsxs("span",{className:"text-xs text-white",children:[Math.round(Te.progress||0),"%"]})]}):a.jsx("p",{className:"text-xs text-bambu-gray",children:$q(Te.state,Te.stg_cur_name)})}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"mb-4 p-3 bg-bambu-dark rounded-lg relative",children:[a.jsxs("button",{onClick:()=>Re(!0),disabled:!(Te.state==="RUNNING"||Te.state==="PAUSE"||Te.state==="PAUSED")||(Te.printable_objects_count??0)<2||!S("printers:control"),className:`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${(Te.state==="RUNNING"||Te.state==="PAUSE"||Te.state==="PAUSED")&&(Te.printable_objects_count??0)>=2&&S("printers:control")?"text-bambu-gray hover:text-white hover:bg-white/10":"text-bambu-gray/30 cursor-not-allowed"}`,title:S("printers:control")?Te.state==="RUNNING"||Te.state==="PAUSE"||Te.state==="PAUSED"?(Te.printable_objects_count??0)>=2?b("printers.skipObjects.tooltip"):b("printers.skipObjects.requiresMultiple"):b("printers.skipObjects.onlyWhilePrinting"):b("printers.permission.noControl"),children:[a.jsx(zk,{className:"w-4 h-4"}),Dt&&Dt.skipped_count>0&&a.jsx("span",{className:"absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-bold bg-red-500 text-white rounded-full",children:Dt.skipped_count})]}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(T8e,{url:Te.state==="RUNNING"?Te.cover_url:null,printName:Te.state==="RUNNING"&&(Te.subtask_name||Te.current_print)||void 0}),a.jsx("div",{className:"flex-1 min-w-0",children:Te.current_print&&Te.state==="RUNNING"?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-1",children:Te.stg_cur_name||"Printing"}),a.jsx("p",{className:"text-white text-sm mb-2 truncate",children:Te.subtask_name||Te.current_print}),a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all",style:{width:`${Te.progress||0}%`}})}),a.jsxs("span",{className:"text-white",children:[Math.round(Te.progress||0),"%"]})]}),a.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-bambu-gray",children:[Te.remaining_time!=null&&Te.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(tr,{className:"w-3 h-3"}),N8e(Te.remaining_time*60)]}),a.jsxs("span",{className:"text-bambu-green font-medium",title:b("printers.estimatedCompletion"),children:["ETA ",k8e(Te.remaining_time,d)]})]}),Te.layer_num!=null&&Te.total_layers!=null&&Te.total_layers>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(is,{className:"w-3 h-3"}),Te.layer_num,"/",Te.total_layers]}),Gt&&a.jsxs("span",{className:"flex items-center gap-1",title:`Started by ${Gt}`,children:[a.jsx($u,{className:"w-3 h-3"}),Gt]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-1",children:b("printers.sort.status")}),a.jsx("p",{className:"text-white text-sm mb-2",children:$q(Te.state,Te.stg_cur_name)}),a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3",children:a.jsx("div",{className:"bg-bambu-dark-tertiary h-2 rounded-full"})}),a.jsx("span",{className:"text-bambu-gray",children:"—"})]}),fn?a.jsxs("p",{className:"text-xs text-bambu-gray mt-2 truncate",title:fn.print_name||fn.filename,children:["Last: ",fn.print_name||fn.filename,fn.completed_at&&a.jsxs("span",{className:"ml-1 text-bambu-gray/60",children:["• ",Gg(fn.completed_at,{month:"short",day:"numeric"})]})]}):a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:b("printers.readyToPrint")})]})})]})]}),Te.state!=="RUNNING"&&a.jsx(fMe,{printerId:t.id})]}),Te.temperatures&&r==="expanded"&&(()=>{const gt=Te.temperatures.nozzle_heating||Te.temperatures.nozzle_2_heating||!1,jt=Te.temperatures.bed_heating||!1,gn=Te.temperatures.chamber_heating||!1,Nt=t.nozzle_count===2||Te.temperatures.nozzle_2!==void 0,un=Te.active_extruder===1?"L":"R",In=Te.nozzle_rack?.find(Si=>Si.id===1),rr=Te.nozzle_rack?.find(Si=>Si.id===0),ua=rr||In;return a.jsxs("div",{className:"flex items-stretch gap-1.5 flex-wrap",children:[a.jsxs("div",{className:"text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center",children:[a.jsx(bP,{className:"w-3.5 h-3.5 mb-0.5",color:"text-orange-400",isHeating:gt}),Te.temperatures.nozzle_2!==void 0?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-[9px] text-bambu-gray",children:"L / R"}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Te.temperatures.nozzle||0),"° / ",Math.round(Te.temperatures.nozzle_2||0),"°"]})]}):ua?a.jsx(Fee,{slot:ua,index:0,activeStatus:!0,filamentName:ua.filament_id?Ge?.[ua.filament_id]?.name:void 0,children:a.jsxs("div",{className:"cursor-default",children:[a.jsx("p",{className:"text-[9px] text-bambu-gray",children:b("printers.temperatures.nozzle")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Te.temperatures.nozzle||0),"°C"]})]})}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-[9px] text-bambu-gray",children:b("printers.temperatures.nozzle")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Te.temperatures.nozzle||0),"°C"]})]})]}),a.jsxs("div",{className:"text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center",children:[a.jsx(bP,{className:"w-3.5 h-3.5 mb-0.5",color:"text-blue-400",isHeating:jt}),a.jsx("p",{className:"text-[9px] text-bambu-gray",children:b("printers.temperatures.bed")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Te.temperatures.bed||0),"°C"]})]}),Te.temperatures.chamber!==void 0&&a.jsxs("div",{className:"text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center",children:[a.jsx(bP,{className:"w-3.5 h-3.5 mb-0.5",color:"text-green-400",isHeating:gn}),a.jsx("p",{className:"text-[9px] text-bambu-gray",children:b("printers.temperatures.chamber")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Te.temperatures.chamber||0),"°C"]})]}),Nt&&a.jsx(b8e,{leftSlot:In,rightSlot:rr,activeNozzle:un,children:a.jsxs("div",{className:"text-center px-3 py-1.5 bg-bambu-dark rounded-lg h-full flex flex-col justify-center items-center cursor-default",title:b("printers.activeNozzle",{nozzle:b(un==="L"?"common.left":"common.right")}),children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsxs("span",{className:`text-[11px] font-bold ${un==="L"?"text-amber-400":"text-gray-500"}`,children:["L",In?.nozzle_diameter?` ${In.nozzle_diameter}`:""]}),a.jsx("span",{className:"text-[9px] text-bambu-gray/40",children:"·"}),a.jsxs("span",{className:`text-[11px] font-bold ${un==="R"?"text-amber-400":"text-gray-500"}`,children:["R",rr?.nozzle_diameter?` ${rr.nozzle_diameter}`:""]})]}),a.jsx("p",{className:"text-[9px] text-bambu-gray",children:b("printers.temperatures.nozzle")})]})}),Te.nozzle_rack&&Te.nozzle_rack.some(Si=>Si.id>=2)&&a.jsx(x8e,{slots:Te.nozzle_rack,filamentInfo:Ge})]})})(),r==="expanded"&&(()=>{const gt=Te.state==="RUNNING",jt=Te.state==="PAUSED"||Te.state==="PAUSE",gn=gt||jt,Nt=Ma.isPending||De.isPending||tt.isPending,un=Te.cooling_fan_speed,In=Te.big_fan1_speed,rr=Te.big_fan2_speed;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:b("printers.controls")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${un&&un>0?"bg-cyan-500/10":"bg-bambu-dark"}`,title:b("printers.fans.partCooling"),children:[a.jsx(RW,{className:`w-3.5 h-3.5 ${un&&un>0?"text-cyan-400":"text-bambu-gray/50"}`}),a.jsxs("span",{className:`text-[10px] ${un&&un>0?"text-cyan-400":"text-bambu-gray/50"}`,children:[un??0,"%"]})]}),a.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${In&&In>0?"bg-blue-500/10":"bg-bambu-dark"}`,title:b("printers.fans.auxiliary"),children:[a.jsx(qW,{className:`w-3.5 h-3.5 ${In&&In>0?"text-blue-400":"text-bambu-gray/50"}`}),a.jsxs("span",{className:`text-[10px] ${In&&In>0?"text-blue-400":"text-bambu-gray/50"}`,children:[In??0,"%"]})]}),a.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${rr&&rr>0?"bg-green-500/10":"bg-bambu-dark"}`,title:b("printers.fans.chamber"),children:[a.jsx(Mce,{className:`w-3.5 h-3.5 ${rr&&rr>0?"text-green-400":"text-bambu-gray/50"}`}),a.jsxs("span",{className:`text-[10px] ${rr&&rr>0?"text-green-400":"text-bambu-gray/50"}`,children:[rr??0,"%"]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("button",{onClick:()=>W(!0),disabled:!gn||Nt||!S("printers:control"),className:` flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${gn&&S("printers:control")?"bg-red-500/20 text-red-400 hover:bg-red-500/30":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"} @@ -8508,19 +8508,19 @@ void main() { flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${gn&&S("printers:control")?jt?"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30":"bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"} - `,title:S("printers:control")?b(jt?"printers.resume":"printers.pause"):b("printers.permission.noControl"),children:[jt?a.jsx(Eo,{className:"w-3 h-3"}):a.jsx(Sk,{className:"w-3 h-3"}),b(jt?"printers.resume":"printers.pause")]})]})]})]})})(),Ye&&Ye.length>0&&r==="expanded"&&(()=>{const gt=Ye.filter(Nt=>Nt.tray.length>1),jt=Ye.filter(Nt=>Nt.tray.length===1),gn=t.nozzle_count===2||Te?.temperatures?.nozzle_2!==void 0;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:b("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[gt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:gt.map(Nt=>{const un=et[String(Nt.id)],In=Nt.id>=128?Nt.id-128:Nt.id,rr=un!==void 0?un:In,ua=rr===1,Si=rr===0;return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"text-[10px] text-white font-medium",children:Gd(Nt.id,Nt.tray.length)}),gn&&(ua||Si)&&a.jsx(zq,{side:ua?"L":"R"})]}),(Nt.humidity!=null||Nt.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[Nt.humidity!=null&&a.jsx(Bq,{humidity:Nt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>ke({amsId:Nt.id,amsLabel:Gd(Nt.id,Nt.tray.length),mode:"humidity"}),compact:!0}),Nt.temp!=null&&a.jsx(Hq,{temp:Nt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>ke({amsId:Nt.id,amsLabel:Gd(Nt.id,Nt.tray.length),mode:"temperature"}),compact:!0})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(Jt=>{const wn=Nt.tray[Jt]||Nt.tray.find(Qr=>Qr.id===Jt),Ea=wn?.tray_type&&wn.remain>=0,Ta=!wn?.tray_type,si=Nt.id*4+Jt,yl=ye===si,Pc=wn?.tray_info_idx?Ge?.[wn.tray_info_idx]:null,us=ze?.[si],ds=wn?.tray_uuid?.toUpperCase(),jc=ds?c?.[ds]:void 0,hs=yP(jc),Po=Ea&&wn.remain>0?wn.remain:hs??(Ea?wn.remain:null),Aa=Ea&&wn.remain===0&&hs!==null?"spoolman":"ams",_r=wn?.tray_type?{vendor:vP(wn)?"Bambu Lab":"Generic",profile:Pc?.name||us?.preset_name||wn.tray_sub_brands||wn.tray_type,colorName:mP(wn.tray_id_name)||pP(wn.tray_color),colorHex:wn.tray_color||null,kFactor:gP(wn.k),fillLevel:Po,trayUuid:wn.tray_uuid||null,fillSource:Aa}:null,da=he?.amsId===Nt.id&&he?.slotId===Jt,eo=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ta?"opacity-50":""} ${yl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:wn?.tray_color?`#${wn.tray_color}`:wn?.tray_type?"#333":"transparent",borderColor:Ta?"#666":"rgba(255,255,255,0.1)",borderStyle:Ta?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:wn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Po!==null&&Po>=0&&wn?a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Po}%`,backgroundColor:xP(Po)}}):wn?.tray_type?a.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"}):null})]});return a.jsxs("div",{className:"relative group",children:[da&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Or,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Te?.state!=="RUNNING"&&a.jsx("button",{onClick:Qr=>{Qr.stopPropagation(),cn(Zt?.amsId===Nt.id&&Zt?.slotId===Jt?null:{amsId:Nt.id,slotId:Jt})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:b("printers.slotOptions"),children:a.jsx(mh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Te?.state!=="RUNNING"&&Zt?.amsId===Nt.id&&Zt?.slotId===Jt&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${S("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Qr=>{Qr.stopPropagation(),S("printers:ams_rfid")&&(nt.mutate({amsId:Nt.id,slotId:Jt}),cn(null))},disabled:da||!S("printers:ams_rfid"),title:S("printers:ams_rfid")?void 0:b("printers.permission.noAmsRfid"),children:[a.jsx(Or,{className:`w-3 h-3 ${da?"animate-spin":""}`}),b("printers.rfid.reread")]})}),_r?a.jsx(fP,{data:_r,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:_r.trayUuid?c?.[_r.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&_r.trayUuid?Qr=>{ce({trayUuid:Qr,trayInfo:{type:_r.profile,color:_r.colorHex||"",location:`${Gd(Nt.id,Nt.tray.length)} Slot ${Jt+1}`}})}:void 0},configureSlot:{enabled:S("printers:control"),onConfigure:()=>V({amsId:Nt.id,trayId:Jt,trayCount:Nt.tray.length,trayType:wn?.tray_type||void 0,trayColor:wn?.tray_color||void 0,traySubBrands:wn?.tray_sub_brands||void 0,trayInfoIdx:wn?.tray_info_idx||void 0})},children:eo}):a.jsx(Oq,{configureSlot:{enabled:S("printers:control"),onConfigure:()=>V({amsId:Nt.id,trayId:Jt,trayCount:Nt.tray.length})},children:eo})]},Jt)})})]},Nt.id)})}),(jt.length>0||Te.vt_tray&&Te.vt_tray.tray_type)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[jt.map(Nt=>{const un=et[String(Nt.id)],In=Nt.id>=128?Nt.id-128:Nt.id,rr=un!==void 0?un:In,ua=rr===1,Si=rr===0,Jt=Nt.tray[0],wn=Jt?.tray_type&&Jt.remain>=0,Ea=!Jt?.tray_type,Ta=Nt.id*4+(Jt?.id??0),si=ye===Ta,yl=Jt?.tray_info_idx?Ge?.[Jt.tray_info_idx]:null,Pc=ze?.[Ta],us=Jt?.tray_uuid?.toUpperCase(),ds=us?c?.[us]:void 0,jc=yP(ds),hs=wn&&Jt.remain>0?Jt.remain:jc??(wn?Jt.remain:null),Po=wn&&Jt.remain===0&&jc!==null?"spoolman":"ams",Aa=Jt?.tray_type?{vendor:vP(Jt)?"Bambu Lab":"Generic",profile:yl?.name||Pc?.preset_name||Jt.tray_sub_brands||Jt.tray_type,colorName:mP(Jt.tray_id_name)||pP(Jt.tray_color),colorHex:Jt.tray_color||null,kFactor:gP(Jt.k),fillLevel:hs,trayUuid:Jt.tray_uuid||null,fillSource:Po}:null,_r=Jt?.id??0,da=he?.amsId===Nt.id&&he?.slotId===_r,eo=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ea?"opacity-50":""} ${si?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:Jt?.tray_color?`#${Jt.tray_color}`:Jt?.tray_type?"#333":"transparent",borderColor:Ea?"#666":"rgba(255,255,255,0.1)",borderStyle:Ea?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Jt?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:hs!==null&&hs>=0?a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${hs}%`,backgroundColor:xP(hs)}}):Jt?.tray_type?a.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"}):null})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[a.jsx("span",{className:"text-[10px] text-white font-medium",children:Gd(Nt.id,Nt.tray.length)}),gn&&(ua||Si)&&a.jsx(zq,{side:ua?"L":"R"})]}),a.jsxs("div",{className:"flex gap-1.5",children:[a.jsxs("div",{className:"relative group flex-1",children:[da&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Or,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Te?.state!=="RUNNING"&&a.jsx("button",{onClick:Qr=>{Qr.stopPropagation(),cn(Zt?.amsId===Nt.id&&Zt?.slotId===_r?null:{amsId:Nt.id,slotId:_r})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:b("printers.slotOptions"),children:a.jsx(mh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Te?.state!=="RUNNING"&&Zt?.amsId===Nt.id&&Zt?.slotId===_r&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${S("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Qr=>{Qr.stopPropagation(),S("printers:ams_rfid")&&(nt.mutate({amsId:Nt.id,slotId:_r}),cn(null))},disabled:da||!S("printers:ams_rfid"),title:S("printers:ams_rfid")?void 0:b("printers.permission.noAmsRfid"),children:[a.jsx(Or,{className:`w-3 h-3 ${da?"animate-spin":""}`}),b("printers.rfid.reread")]})}),Aa?a.jsx(fP,{data:Aa,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Aa.trayUuid?c?.[Aa.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&Aa.trayUuid?Qr=>{ce({trayUuid:Qr,trayInfo:{type:Aa.profile,color:Aa.colorHex||"",location:Gd(Nt.id,Nt.tray.length)}})}:void 0},configureSlot:{enabled:S("printers:control"),onConfigure:()=>V({amsId:Nt.id,trayId:_r,trayCount:Nt.tray.length,trayType:Jt?.tray_type||void 0,trayColor:Jt?.tray_color||void 0,traySubBrands:Jt?.tray_sub_brands||void 0,trayInfoIdx:Jt?.tray_info_idx||void 0})},children:eo}):a.jsx(Oq,{configureSlot:{enabled:S("printers:control"),onConfigure:()=>V({amsId:Nt.id,trayId:_r,trayCount:Nt.tray.length})},children:eo})]}),(Nt.humidity!=null||Nt.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0",children:[Nt.temp!=null&&a.jsx(Hq,{temp:Nt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>ke({amsId:Nt.id,amsLabel:Gd(Nt.id,Nt.tray.length),mode:"temperature"}),compact:!0}),Nt.humidity!=null&&a.jsx(Bq,{humidity:Nt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>ke({amsId:Nt.id,amsLabel:Gd(Nt.id,Nt.tray.length),mode:"humidity"}),compact:!0})]})]})]},Nt.id)}),Te.vt_tray&&Te.vt_tray.tray_type&&(()=>{const Nt=Te.vt_tray,un=ye===254,In=Nt.tray_info_idx?Ge?.[Nt.tray_info_idx]:null,rr=ze?.[1020],ua=Nt.tray_uuid?.toUpperCase(),Si=ua?c?.[ua]:void 0,Jt=yP(Si),wn={vendor:vP(Nt)?"Bambu Lab":"Generic",profile:In?.name||rr?.preset_name||Nt.tray_sub_brands||Nt.tray_type||"Unknown",colorName:mP(Nt.tray_id_name)||pP(Nt.tray_color),colorHex:Nt.tray_color||null,kFactor:gP(Nt.k),fillLevel:Jt,trayUuid:Nt.tray_uuid||null,fillSource:Jt!==null?"spoolman":void 0},Ea=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center cursor-default ${un?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:Nt.tray_color?`#${Nt.tray_color}`:"#333",borderColor:un?"var(--accent)":"rgba(255,255,255,0.1)"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Nt.tray_type||"Spool"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Jt!==null?a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Jt}%`,backgroundColor:xP(Jt)}}):a.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"})})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsx("div",{className:"flex items-center gap-1 mb-2",children:a.jsx("span",{className:"text-[10px] text-white font-medium",children:b("printers.external")})}),a.jsx(fP,{data:wn,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:wn.trayUuid?c?.[wn.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&wn.trayUuid?Ta=>{ce({trayUuid:Ta,trayInfo:{type:wn.profile,color:wn.colorHex||"",location:"External Spool"}})}:void 0},configureSlot:{enabled:S("printers:control"),onConfigure:()=>V({amsId:255,trayId:0,trayCount:1,trayType:Nt.tray_type||void 0,trayColor:Nt.tray_color||void 0,traySubBrands:Nt.tray_sub_brands||void 0,trayInfoIdx:Nt.tray_info_idx||void 0})},children:Ea})]})})()]})]})]})})()]}),Qe&&r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(Ah,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:Qe.name}),at&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${at.state==="ON"?"bg-bambu-green/20 text-bambu-green":at.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[at.state||"?",at.state==="ON"&&at.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",at.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>G(!0),disabled:kn.isPending||at?.state==="ON"||!S("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${S("smart_plugs:control")?at?.state==="ON"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:S("smart_plugs:control")?void 0:b("printers.permission.noSmartPlugControl"),children:[a.jsx(Ju,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>K(!0),disabled:kn.isPending||at?.state==="OFF"||!S("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${S("smart_plugs:control")?at?.state==="OFF"?"bg-red-500/30 text-red-400":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:S("smart_plugs:control")?void 0:b("printers.permission.noSmartPlugControl"),children:[a.jsx(Nk,{className:"w-3 h-3"}),"Off"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx("span",{className:`text-xs hidden sm:inline ${Qe.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:Qe.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>Bn.mutate(!Qe.auto_off),disabled:Bn.isPending||Qe.auto_off_executed||!S("smart_plugs:control"),title:S("smart_plugs:control")?Qe.auto_off_executed?b("printers.autoOffExecuted"):b("printers.autoOffAfterPrint"):b("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${S("smart_plugs:control")?Qe.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":Qe.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:a.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${Qe.auto_off||Qe.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),yt&&yt.length>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[a.jsx(Hy,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:yt.map(gt=>a.jsxs("button",{onClick:()=>Hr.mutate(gt.id),disabled:Hr.isPending,title:`Run ${gt.ha_entity_id}`,className:"px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1",children:[a.jsx(Eo,{className:"w-2.5 h-2.5"}),gt.name]},gt.id))})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[a.jsxs("div",{className:"text-xs text-bambu-gray",children:[a.jsx("p",{children:t.ip_address}),a.jsx("p",{className:"truncate",children:t.serial_number})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>ht.mutate(!Te?.chamber_light),disabled:!Te?.connected||ht.isPending||!S("printers:control"),title:S("printers:control")?Te?.chamber_light?b("printers.chamberLightOff"):b("printers.chamberLightOn"):b("printers.permission.noControl"),className:Te?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30 border-yellow-500/30":"",children:a.jsx(MO,{on:Te?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>{if(h==="embedded"&&p)p(t.id,t.name);else{const gt=localStorage.getItem("cameraWindowState"),jt=gt?JSON.parse(gt):{width:640,height:400},gn=[`width=${jt.width}`,`height=${jt.height}`,jt.left!==void 0?`left=${jt.left}`:"",jt.top!==void 0?`top=${jt.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,gn)}},disabled:!Te?.connected,title:b(h==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"),children:a.jsx(KR,{className:"w-4 h-4"})}),a.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[a.jsx(Ne,{variant:"secondary",size:"sm",onClick:Tt,disabled:!Te?.connected||mt.isPending||!S("printers:update"),title:S("printers:update")?t.plate_detection_enabled?b("printers.plateDetection.enabledClick"):b("printers.plateDetection.disabledClick"):b("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:mt.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(nS,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:mn,disabled:!Te?.connected||X||!S("printers:update"),title:S("printers:update")?b("printers.plateDetection.manageCalibration"):b("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:X?a.jsx(ct,{className:"w-3 h-3 animate-spin"}):a.jsx(fr,{className:"w-3 h-3"})})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>F(!0),disabled:!S("printers:files"),title:S("printers:files")?b("printers.browseFiles"):b("printers.permission.noFiles"),children:[a.jsx(Sb,{className:"w-4 h-4"}),"Files"]})]})]})]}),U&&a.jsx(tMe,{printerId:t.id,printerName:t.name,onClose:()=>F(!1)}),H&&a.jsx(oMe,{printerId:t.id,printerName:t.name,onClose:()=>D(!1)}),q&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Bt(),children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:gt=>gt.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[q.needs_calibration?a.jsx(nS,{className:"w-5 h-5 text-blue-500"}):q.is_empty?a.jsx(mr,{className:"w-5 h-5 text-green-500"}):a.jsx(Zi,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),q.reference_count!==void 0&&q.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[q.reference_count,"/",q.max_references," refs"]})]}),a.jsx("button",{onClick:()=>Bt(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[q.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[a.jsx("p",{className:"font-medium text-blue-400",children:b("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:b("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:b("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:b("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${q.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[a.jsx("p",{className:`font-medium ${q.is_empty?"text-green-400":"text-yellow-400"}`,children:q.is_empty?b("printers.plateDetection.plateEmpty"):b("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[b("printers.plateDetection.confidence"),": ",Math.round(q.confidence*100),"% | ",b("printers.plateDetection.difference"),": ",q.difference_percent.toFixed(1),"%"]})]}),q.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:b("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:q.debug_image_url,alt:b("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:b("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:q.message})]}),xt&&xt.references.length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:b("printers.plateDetection.savedReferences",{count:xt.references.length,max:xt.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:xt.references.map(gt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:ae.getPlateReferenceThumbnailUrl(t.id,gt.index),alt:gt.label||`Reference ${gt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),a.jsx("button",{onClick:()=>jn(gt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:b("printers.plateDetection.deleteReference"),children:a.jsx(Lt,{className:"w-3 h-3 text-white"})}),Ct?.index===gt.index?a.jsx("input",{type:"text",value:Ct.label,onChange:jt=>It({...Ct,label:jt.target.value}),onBlur:()=>Mn(gt.index,Ct.label),onKeyDown:jt=>{jt.key==="Enter"&&Mn(gt.index,Ct.label),jt.key==="Escape"&&It(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:b("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>It({index:gt.index,label:gt.label}),title:gt.label?b("printers.plateDetection.clickToEdit",{label:gt.label}):b("printers.plateDetection.clickToAddLabel"),children:gt.label||a.jsx("span",{className:"italic opacity-50",children:b("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:gt.timestamp?new Date(gt.timestamp).toLocaleDateString():""})]},gt.index))})]}),!q.needs_calibration&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:b("printers.roi.title")}),z?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>O(null),disabled:Z,children:b("common.cancel")}),a.jsx(Ne,{size:"sm",onClick:Kt,disabled:Z,children:Z?a.jsx(ct,{className:"w-3 h-3 animate-spin"}):b("common.save")})]}):a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:()=>O(q.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(Ji,{className:"w-3 h-3 mr-1"}),b("common.edit")]})]}),z?a.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:z.x,onChange:gt=>O({...z,x:parseFloat(gt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(z.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:z.y,onChange:gt=>O({...z,y:parseFloat(gt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(z.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:z.w,onChange:gt=>O({...z,w:parseFloat(gt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(z.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:z.h,onChange:gt=>O({...z,h:parseFloat(gt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(z.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:b("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((q.roi?.x||.15)*100),"%, Y=",Math.round((q.roi?.y||.35)*100),"%, W=",Math.round((q.roi?.w||.7)*100),"%, H=",Math.round((q.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:q.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(Ne,{variant:"ghost",onClick:()=>Bt(),children:b("common.cancel")}),a.jsx(Ne,{onClick:()=>pn(),disabled:pe,children:pe?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(Ne,{variant:"ghost",onClick:()=>pn(),disabled:pe,children:pe?"Adding...":`Add Reference (${xt?.references.length||0}/${xt?.max_references||5})`}),a.jsx(Ne,{onClick:()=>Bt(),children:"Close"})]})})]})}),$&&Qe&&a.jsx(er,{title:b("printers.confirm.powerOnTitle"),message:b("printers.confirm.powerOnMessage",{name:t.name}),confirmText:b("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{kn.mutate("on"),G(!1)},onCancel:()=>G(!1)}),I&&Qe&&a.jsx(er,{title:b("printers.confirm.powerOffTitle"),message:Te?.state==="RUNNING"?b("printers.confirm.powerOffWarning",{name:t.name}):b("printers.confirm.powerOffMessage",{name:t.name}),confirmText:b("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{kn.mutate("off"),K(!1)},onCancel:()=>K(!1)}),B&&a.jsx(er,{title:b("printers.confirm.stopTitle"),message:b("printers.confirm.stopMessage",{name:t.name}),confirmText:b("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{Ma.mutate(),W(!1)},onCancel:()=>W(!1)}),J&&a.jsx(er,{title:b("printers.confirm.pauseTitle"),message:b("printers.confirm.pauseMessage",{name:t.name}),confirmText:b("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{De.mutate(),ne(!1)},onCancel:()=>ne(!1)}),me&&a.jsx(er,{title:b("printers.confirm.resumeTitle"),message:b("printers.confirm.resumeMessage",{name:t.name}),confirmText:b("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{tt.mutate(),fe(!1)},onCancel:()=>fe(!1)}),a.jsx(EO,{printerId:t.id,isOpen:de,onClose:()=>Re(!1)}),Q&&a.jsx(dMe,{printerName:t.name,errors:Te?.hms_errors||[],onClose:()=>oe(!1)}),se&&a.jsx(a8e,{isOpen:!!se,onClose:()=>ke(null),printerId:t.id,printerName:t.name,amsId:se.amsId,amsLabel:se.amsLabel,initialMode:se.mode,thresholds:s}),Fe&&a.jsx(s8e,{isOpen:!!Fe,onClose:()=>ce(null),trayUuid:Fe.trayUuid,trayInfo:Fe.trayInfo}),Ve&&a.jsx(m8e,{isOpen:!!Ve,onClose:()=>V(null),printerId:t.id,slotInfo:Ve,onSuccess:()=>{y.invalidateQueries({queryKey:["slotPresets",t.id]}),y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),C&&a.jsx(P8e,{printer:t,onClose:()=>P(!1)}),Y&&we&&a.jsx(C8e,{printer:t,firmwareInfo:we,onClose:()=>ue(!1)}),Zt&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>cn(null)})]})}function A8e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Yt(),[i,s]=_.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=_.useState(!1),[c,u]=_.useState([]),[d,h]=_.useState(""),[p,m]=_.useState(!1),[b,y]=_.useState(!1),[x,v]=_.useState([]),[S,N]=_.useState(""),[T,M]=_.useState({scanned:0,total:0});_.useEffect(()=>{Xl.getInfo().then(P=>{y(P.is_docker),P.subnets.length>0&&(v(P.subnets),N(P.subnets[0]))}).catch(()=>{})},[]);const A=c.filter(P=>!n.includes(P.serial)),k=async()=>{h(""),u([]),l(!0),m(!1),M({scanned:0,total:0});try{if(b){await Xl.startSubnetScan(S);const P=setInterval(async()=>{try{const U=await Xl.getScanStatus();M({scanned:U.scanned,total:U.total});const F=await Xl.getDiscoveredPrinters();u(F),U.running||(clearInterval(P),l(!1),m(!0))}catch(U){console.error("Failed to get scan status:",U)}},500)}else{await Xl.startDiscovery(10);const P=setInterval(async()=>{try{const U=await Xl.getDiscoveredPrinters();u(U)}catch(U){console.error("Failed to get discovered printers:",U)}},1e3);setTimeout(async()=>{clearInterval(P);try{await Xl.stopDiscovery()}catch{}l(!1),m(!0);try{const U=await Xl.getDiscoveredPrinters();u(U)}catch(U){console.error("Failed to get final discovered printers:",U)}},1e4)}}catch(P){console.error("Failed to start discovery:",P),h(P instanceof Error?P.message:r("printers.discovery.failedToStart")),l(!1),m(!0)}},R=P=>P?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",P1S:"P1S",P1P:"P1P",P2S:"P2S",A1:"A1","A1 Mini":"A1 Mini",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[P]||P:"",C=P=>{const U=P.serial.startsWith("unknown-")?"":P.serial;s({...i,name:P.name||"",serial_number:U,ip_address:P.ip_address,model:R(P.model)}),u([])};return _.useEffect(()=>()=>{Xl.stopDiscovery().catch(()=>{}),Xl.stopSubnetScan().catch(()=>{})},[]),_.useEffect(()=>{const P=U=>{U.key==="Escape"&&t()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:a.jsx(St,{className:"w-full max-w-md",onClick:P=>P.stopPropagation(),children:a.jsxs(Et,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[b&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),x.length>0?a.jsx("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:S,onChange:P=>N(P.target.value),disabled:o,children:x.map(P=>a.jsx("option",{value:P,children:P},P))}):a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:S,onChange:P=>N(P.target.value),placeholder:"192.168.1.0/24",disabled:o}),a.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),a.jsx(Ne,{type:"button",variant:"secondary",onClick:k,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),b&&T.total>0?r("printers.discovery.scanProgress",{scanned:T.scanned,total:T.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(Qi,{className:"w-4 h-4"}),r(b?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),d&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:d}),A.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:A.map(P=>a.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>C(P),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:P.name||P.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[R(P.model)||r("printers.discovery.unknown")," • ",P.ip_address,P.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(fr,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},P.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(b?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(b?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&A.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:P=>{P.preventDefault(),e(i)},className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.name,onChange:P=>s({...i,name:P.target.value}),placeholder:r("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.ip_address,onChange:P=>s({...i,ip_address:P.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.serial_number,onChange:P=>s({...i,serial_number:P.target.value}),placeholder:"01P00A000000000"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),a.jsx("input",{type:"password",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.access_code,onChange:P=>s({...i,access_code:P.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.model||"",onChange:P=>s({...i,model:P.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.location||"",onChange:P=>s({...i,location:P.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:P=>s({...i,auto_archive:P.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(Ne,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function C8e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Yt(),i=an(),{showToast:s}=Tn(),{hasPermission:o}=Ir(),l=o("firmware:update"),[c,u]=_.useState(null),[d,h]=_.useState(!1),[p,m]=_.useState(null),{data:b,isLoading:y}=it({queryKey:["firmwarePrepare",t.id],queryFn:()=>N1.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),x=dt({mutationFn:()=>N1.startUpload(t.id),onSuccess:()=>{h(!0);const S=setInterval(async()=>{try{const N=await N1.getUploadStatus(t.id);u(N),(N.status==="complete"||N.status==="error")&&(clearInterval(S),m(null),h(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);m(S)},onError:S=>{s(r("printers.firmwareModal.uploadFailed",{error:S.message}),"error"),h(!1)}});_.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const v=()=>{u(null),x.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(St,{className:"w-full max-w-md mx-4",children:a.jsxs(Et,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(wi,{className:"w-5 h-5 text-orange-400"}):a.jsx(mr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),a.jsx("span",{className:`font-mono ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&a.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),a.jsx("span",{className:"text-orange-400 font-mono",children:e.latest_version})]}),e.release_notes&&a.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),a.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:e.release_notes})]})]}),e.update_available?y?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):b&&!d&&!c?a.jsx("div",{className:"mb-4",children:b.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(Ii,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:b.errors.map((S,N)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Ti,{className:"w-4 h-4 flex-shrink-0"}),S]},N))})}):null:null,(d||c)&&c&&a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),a.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&a.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),a.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),a.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(Ne,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),b?.can_proceed&&!d&&c?.status!=="complete"&&l&&a.jsx(Ne,{onClick:v,disabled:x.isPending,children:x.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(wi,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function P8e({printer:t,onClose:e}){const{t:n}=Yt(),r=an(),{showToast:i}=Tn(),[s,o]=_.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=dt({mutationFn:u=>ae.updatePrinter(t.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:u=>i(u.message||n("printers.toast.failedToUpdate"),"error")});_.useEffect(()=>{const u=d=>{d.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const c=u=>{u.preventDefault();const d={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(d.access_code=s.access_code),l.mutate(d)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:a.jsx(St,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:a.jsxs(Et,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:u=>o({...s,name:u.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:u=>o({...s,ip_address:u.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:u=>o({...s,access_code:u.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:u=>o({...s,model:u.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:u=>o({...s,location:u.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:u=>o({...s,auto_archive:u.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(Ne,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function j8e(t){const{data:e}=it({queryKey:["printerStatus",t],queryFn:()=>ae.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function D8e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=j8e(t.id),{data:s}=it({queryKey:["smartPlugStatus",e.id],queryFn:()=>ae.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),a.jsxs("button",{onClick:()=>n(e.id),disabled:r||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[a.jsx(Ju,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function R8e(){const{t}=Yt(),[e,n]=_.useState(!1),[r,i]=_.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=_.useState(!1),[l,c]=_.useState(null),[u,d]=_.useState(()=>localStorage.getItem("printerSortBy")||"name"),[h,p]=_.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[m,b]=_.useState(()=>{const de=localStorage.getItem("printerCardSize");return de?parseInt(de,10):2}),y=m===1?"compact":"expanded",x=an(),{showToast:v}=Tn(),{hasPermission:S}=Ir(),[N,T]=_.useState(()=>{const de=localStorage.getItem("openEmbeddedCameras");if(de)try{const Re=JSON.parse(de);return new Map(Re.map(se=>[se.id,se]))}catch{return new Map}return new Map});_.useEffect(()=>{const de=Array.from(N.values());de.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(de)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:M,isLoading:A}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:k}=it({queryKey:["settings"],queryFn:ae.getSettings});_.useEffect(()=>{k?.camera_view_mode==="window"&&N.size>0&&T(new Map)},[k?.camera_view_mode,N.size]);const{data:R}=it({queryKey:["smart-plugs"],queryFn:ae.getSmartPlugs}),{data:C}=it({queryKey:["maintenanceOverview"],queryFn:ae.getMaintenanceOverview,staleTime:60*1e3}),{data:P}=it({queryKey:["spoolman-status"],queryFn:ae.getSpoolmanStatus,staleTime:60*1e3}),U=P?.enabled&&P?.connected,{data:F}=it({queryKey:["unlinked-spools"],queryFn:ae.getUnlinkedSpools,enabled:!!U,staleTime:30*1e3}),H=F&&F.length>0,{data:D}=it({queryKey:["linked-spools"],queryFn:ae.getLinkedSpools,enabled:!!U,staleTime:30*1e3}),$=D?.linked,G=C?.reduce((de,Re)=>(de[Re.printer_id]={due_count:Re.due_count,warning_count:Re.warning_count,total_print_hours:Re.total_print_hours},de),{})||{},I=R?.reduce((de,Re)=>(Re.printer_id&&(de[Re.printer_id]=Re),de),{})||{},K=dt({mutationFn:ae.createPrinter,onSuccess:()=>{x.invalidateQueries({queryKey:["printers"]}),x.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:de=>v(de.message||t("printers.toast.failedToAdd"),"error")}),Q=dt({mutationFn:de=>ae.controlSmartPlug(de,"on"),onSuccess:()=>{x.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),oe=()=>{const de=!r;i(de),localStorage.setItem("hideDisconnectedPrinters",String(de))},B=de=>{d(de),localStorage.setItem("printerSortBy",de)},W=()=>{const de=!h;p(de),localStorage.setItem("printerSortAsc",String(de))},J=()=>{switch(m){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},ne=["S","M","L","XL"],me=_.useMemo(()=>{if(!M)return[];const de=[...M];switch(u){case"name":de.sort((Re,se)=>Re.name.localeCompare(se.name));break;case"model":de.sort((Re,se)=>(Re.model||"").localeCompare(se.model||""));break;case"location":de.sort((Re,se)=>{const ke=Re.location||"",Fe=se.location||"";return!ke&&Fe?1:ke&&!Fe?-1:ke.localeCompare(Fe)||Re.name.localeCompare(se.name)});break;case"status":de.sort((Re,se)=>{const ke=x.getQueryData(["printerStatus",Re.id]),Fe=x.getQueryData(["printerStatus",se.id]),ce=Ve=>Ve?.connected?Ve.state==="RUNNING"?0:1:2;return ce(ke)-ce(Fe)});break}return h||de.reverse(),de},[M,u,h,x]),fe=_.useMemo(()=>{if(u!=="location")return null;const de={};return me.forEach(Re=>{const se=Re.location||"Ungrouped";de[se]||(de[se]=[]),de[se].push(Re)}),de},[u,me]);return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),a.jsx(T8e,{printers:M})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("select",{value:u,onChange:de=>B(de.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"name",children:t("printers.sort.name")}),a.jsx("option",{value:"status",children:t("printers.sort.status")}),a.jsx("option",{value:"model",children:t("printers.sort.model")}),a.jsx("option",{value:"location",children:t("printers.sort.location")})]}),a.jsx("button",{onClick:W,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(h?"printers.sort.descending":"printers.sort.ascending"),children:h?a.jsx(Hg,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(X0,{className:"w-4 h-4 text-bambu-gray"})})]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:ne.map((de,Re)=>{const se=Re+1,ke=m===se;return a.jsx("button",{onClick:()=>{b(se),localStorage.setItem("printerCardSize",String(se))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${Re===0?"rounded-l-lg":""} ${Re===ne.length-1?"rounded-r-lg":""} ${ke?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(de==="S"?"printers.cardSize.small":de==="M"?"printers.cardSize.medium":de==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:de},de)})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:oe,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(I).length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>o(!s),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg text-gray-600 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white hover:border-bambu-green transition-colors",children:[a.jsx(Ju,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(fr,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),a.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[a.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),M?.filter(de=>I[de.id]).map(de=>a.jsx(D8e,{printer:de,plug:I[de.id],onPowerOn:Re=>{c(Re),Q.mutate(Re)},isPowering:l===I[de.id]?.id},de.id)),M?.filter(de=>I[de.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(Ne,{onClick:()=>n(!0),disabled:!S("printers:create"),title:S("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(cr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),A?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):M?.length===0?a.jsx(St,{children:a.jsxs(Et,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(Ne,{onClick:()=>n(!0),disabled:!S("printers:create"),title:S("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(cr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):fe?a.jsx("div",{className:"space-y-6",children:Object.entries(fe).map(([de,Re])=>a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),de,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",Re.length,")"]})]}),a.jsx("div",{className:`grid gap-4 ${m>=3?"gap-6":""} ${J()}`,children:Re.map(se=>a.jsx(Vq,{printer:se,hideIfDisconnected:r,maintenanceInfo:G[se.id],viewMode:y,cardSize:m,amsThresholds:k?{humidityGood:Number(k.ams_humidity_good)||40,humidityFair:Number(k.ams_humidity_fair)||60,tempGood:Number(k.ams_temp_good)||28,tempFair:Number(k.ams_temp_fair)||35}:void 0,spoolmanEnabled:U,hasUnlinkedSpools:H,linkedSpools:$,spoolmanUrl:P?.url,timeFormat:k?.time_format||"system",cameraViewMode:k?.camera_view_mode||"window",onOpenEmbeddedCamera:(ke,Fe)=>T(ce=>new Map(ce).set(ke,{id:ke,name:Fe})),checkPrinterFirmware:k?.check_printer_firmware!==!1},se.id))})]},de))}):a.jsx("div",{className:`grid gap-4 ${m>=3?"gap-6":""} ${J()}`,children:me.map(de=>a.jsx(Vq,{printer:de,hideIfDisconnected:r,maintenanceInfo:G[de.id],viewMode:y,cardSize:m,spoolmanEnabled:U,hasUnlinkedSpools:H,linkedSpools:$,spoolmanUrl:P?.url,amsThresholds:k?{humidityGood:Number(k.ams_humidity_good)||40,humidityFair:Number(k.ams_humidity_fair)||60,tempGood:Number(k.ams_temp_good)||28,tempFair:Number(k.ams_temp_fair)||35}:void 0,timeFormat:k?.time_format||"system",cameraViewMode:k?.camera_view_mode||"window",onOpenEmbeddedCamera:(Re,se)=>T(ke=>new Map(ke).set(Re,{id:Re,name:se})),checkPrinterFirmware:k?.check_printer_firmware!==!1},de.id))}),e&&a.jsx(A8e,{onClose:()=>n(!1),onAdd:de=>K.mutate(de),existingSerials:M?.map(de=>de.serial_number)||[]}),Array.from(N.values()).map((de,Re)=>a.jsx(sMe,{printerId:de.id,printerName:de.name,viewerIndex:Re,onClose:()=>T(se=>{const ke=new Map(se);return ke.delete(de.id),ke})},de.id))]})}function O8e(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function sc(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:n=`${O8e()==="windows"?"bambustudio":"bambustudioopen"}://${encodeURIComponent(t)}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}function C4({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Yt(),{data:o}=it({queryKey:["settings"],queryFn:ae.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[u,d]=_.useState(null),[h,p]=_.useState(null),[m,b]=_.useState(!0),[y,x]=_.useState(null),[v,S]=_.useState(!1),[N,T]=_.useState(null),[M,A]=_.useState(0),[k,R]=_.useState(!1),[C,P]=_.useState(null),[U,F]=_.useState(!1),[H,D]=_.useState(!1),$=_.useRef(null),G=_.useRef(null),I=10,K=160,Q=240,oe=.35;_.useEffect(()=>{const pe=ee=>{ee.key==="Escape"&&i()};return window.addEventListener("keydown",pe),()=>window.removeEventListener("keydown",pe)},[i]),_.useEffect(()=>{if(b(!0),c){const pe=(r||"").toLowerCase(),ee=pe==="3mf"||pe==="stl",z=pe==="gcode"||pe==="3mf";p({has_model:ee,has_gcode:z,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d(ee?"3d":z?"gcode":null),b(!1);return}if(!t){p(null),d(null),b(!1);return}ae.getArchiveCapabilities(t).then(pe=>{p(pe),pe.has_model?d("3d"):pe.has_gcode&&d("gcode"),b(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d("3d"),b(!1)})},[t,r,c]),_.useEffect(()=>{if(S(!0),T(null),A(0),c){const pe=(r||"").toLowerCase();if(!e||pe!=="3mf"){x(null),S(!1);return}ae.getLibraryFilePlates(e).then(ee=>x(ee)).catch(()=>x(null)).finally(()=>S(!1));return}if(!t){x(null),S(!1);return}ae.getArchivePlates(t).then(pe=>x(pe)).catch(()=>x(null)).finally(()=>S(!1))},[t,r,c,e]);const B=_.useMemo(()=>y?.plates??[],[y]),W=(y?.is_multi_plate??!1)&&B.length>1,J=k&&W,ne=N==null?null:B.find(pe=>pe.index===N)??null,me=pe=>pe.object_count??pe.objects?.length??0,fe=B.reduce((pe,ee)=>pe+me(ee),0),de=ne?me(ne):fe,Re=ne?s("modelViewer.plateNumber",{number:ne.index}):s("modelViewer.allPlates"),se=B.length>0,ke=_.useRef(null),Fe=_.useRef(null),[ce,Ve]=_.useState(10),[V,Y]=_.useState(3),ue=B.length>ce,q=Math.max(1,Math.ceil(B.length/ce)),re=ue?B.slice(M*ce,(M+1)*ce):B;_.useEffect(()=>{if(!J){Ve(10),Y(3);return}const pe=ke.current,ee=Fe.current;if(!pe||!ee)return;let z=0;const O=()=>{const Ce=ee.clientWidth,Te=Math.floor(Ce/210),we=Math.max(3,Math.min(5,Te||3));Y(ve=>ve===we?ve:we);const $e=window.getComputedStyle(pe),Ge=Number.parseFloat($e.rowGap||"0"),be=pe.querySelector("button")?.getBoundingClientRect().height??44,Me=ee.clientHeight,Ae=Math.max(1,Math.floor((Me+Ge)/(be+Ge)))*we,qe=Math.max(1,Ae-1);Ve(ve=>ve===qe?ve:qe)},Z=()=>{z&&cancelAnimationFrame(z),z=requestAnimationFrame(O)};Z();const ge=new ResizeObserver(Z);return ge.observe(ee),ge.observe(pe),()=>{z&&cancelAnimationFrame(z),ge.disconnect()}},[J,B.length]),_.useEffect(()=>{if(!ue){A(0);return}A(pe=>Math.min(pe,q-1))},[B.length,ue,q]),_.useEffect(()=>{if(!ue||N==null)return;const pe=B.findIndex(z=>z.index===N);if(pe<0)return;const ee=Math.floor(pe/ce);A(z=>z===ee?z:ee)},[B,ce,N,ue]),_.useEffect(()=>{if(!J){P(null),D(!1);return}if(H)return;const pe=$.current,ee=G.current;if(!pe||!ee)return;const z=pe.clientHeight;if(!z)return;const O=Math.max(Q,z*oe),Z=Math.max(K,z-I-O),ge=Math.min(ee.scrollHeight,Z);P(Math.max(K,ge))},[J,H,B.length,M,I,K,Q,oe]),_.useEffect(()=>{if(!U)return;const pe=z=>{const O=$.current;if(!O)return;const Z=O.getBoundingClientRect(),ge=Z.height;if(!ge)return;const Ce=Math.max(Q,ge*oe),_e=Math.max(K,ge-I-Ce),Te=Math.min(_e,Math.max(K,z.clientY-Z.top));P(Te)},ee=()=>{F(!1),D(!0)};return document.addEventListener("mousemove",pe),document.addEventListener("mouseup",ee),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",pe),document.removeEventListener("mouseup",ee),document.body.style.cursor="",document.body.style.userSelect=""}},[U,I,K,Q,oe]);const X=c?(r||"").toLowerCase()==="3mf":!0,le=()=>{if(!X)return;const pe=n||"model";if(c){const z=`${window.location.origin}${ae.getLibraryFileDownloadUrl(e)}`;sc(z,l);return}const ee=`${window.location.origin}${ae.getArchiveForSlicer(t,pe)}`;sc(ee,l)};return a.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${k?"p-0":"p-8"}`,onClick:i,children:a.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${k?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:pe=>pe.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),se&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[Re,": ",s("modelViewer.objectCount",{count:de})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:le,disabled:!X,children:[a.jsx(Xr,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>R(pe=>!pe),title:k?"Exit fullscreen":"Enter fullscreen",children:k?a.jsx(VR,{className:"w-4 h-4"}):a.jsx($R,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Lt,{className:"w-5 h-5"})})]})]}),h&&a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>h.has_model&&d("3d"),disabled:!h.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="3d"?"text-bambu-green border-b-2 border-bambu-green":h.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(Ii,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!h.has_model&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),a.jsxs("button",{onClick:()=>h.has_gcode&&d("gcode"),disabled:!h.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="gcode"?"text-bambu-green border-b-2 border-bambu-green":h.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(Sue,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!h.has_gcode&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:m?a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})}):u==="3d"&&h?a.jsxs("div",{ref:$,className:`w-full h-full flex flex-col ${J?"gap-0 min-h-0":"gap-3"}`,children:[W&&a.jsxs("div",{ref:G,style:J&&C!=null?{height:C}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${J?"flex flex-col shrink-0":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(is,{className:"w-4 h-4"}),s("modelViewer.plates"),v&&a.jsx(ct,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:J?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:Fe,className:J?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:ke,className:J?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:J?{gridTemplateColumns:`repeat(${V}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>T(null),className:`flex items-center rounded-lg border text-left transition-colors ${J?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${J?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(is,{className:`${J?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${J?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${J?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:B.length})})]}),N==null&&a.jsx($i,{className:`${J?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),re.map(pe=>a.jsxs("button",{type:"button",onClick:()=>T(pe.index),className:`flex items-center rounded-lg border text-left transition-colors ${J?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===pe.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[pe.has_thumbnail&&pe.thumbnail_url?a.jsx("img",{src:pe.thumbnail_url,alt:`Plate ${pe.index}`,className:`${J?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${J?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(is,{className:`${J?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${J?"text-xs":"text-sm"} text-white font-medium truncate`,children:pe.name||s("modelViewer.plateNumber",{number:pe.index})}),a.jsx("p",{className:`${J?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:pe.object_count??pe.objects?.length??0})})]}),N===pe.index&&a.jsx($i,{className:`${J?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},pe.index))]})}),(ne||ue)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ne&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:ne.index})}),ne.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ne.print_time_seconds/60)})}),ne.filament_used_grams!=null&&a.jsxs("span",{children:[ne.filament_used_grams.toFixed(1)," g"]}),ne.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:ne.filaments.length})})]}),ue&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ne?"ml-auto":""}`,children:[a.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:M+1,total:q})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button",onClick:()=>A(pe=>Math.max(pe-1,0)),disabled:M===0,className:`px-2 py-1 rounded border text-xs ${M===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let ee=Math.max(0,M-Math.floor(2.5));const z=Math.min(q,ee+5);z-ee<5&&(ee=Math.max(0,z-5));const O=Array.from({length:z-ee},(Z,ge)=>ee+ge);return a.jsxs(a.Fragment,{children:[ee>0&&a.jsx("button",{type:"button",onClick:()=>A(0),className:`px-2 py-1 rounded border text-xs ${M===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),ee>1&&a.jsx("span",{className:"px-1",children:"…"}),O.map(Z=>a.jsx("button",{type:"button",onClick:()=>A(Z),className:`px-2 py-1 rounded border text-xs ${M===Z?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Z+1},Z)),zA(q-1),className:`px-2 py-1 rounded border text-xs ${M===q-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:q})]})})(),a.jsx("button",{type:"button",onClick:()=>A(pe=>Math.min(pe+1,q-1)),disabled:M>=q-1,className:`px-2 py-1 rounded border text-xs ${M>=q-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.next")})]})]})]})]})]}),J&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:pe=>{pe.preventDefault(),F(!0),D(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${U?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),a.jsx("div",{className:`flex-1 ${J?"min-h-0":""}`,children:a.jsx(IK,{url:c?ae.getLibraryFileDownloadUrl(e):h.has_source?ae.getSource3mfDownloadUrl(t):ae.getArchiveDownload(t),fileType:r,buildVolume:h.build_volume,filamentColors:h.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):u==="gcode"&&h?a.jsx(vX,{gcodeUrl:c?ae.getLibraryFileGcodeUrl(e):ae.getArchiveGcode(t),filamentColors:h.filament_colors,className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}const Gq={"000000":"Black","001489":"Blue","002e96":"Blue","0047bb":"Blue","00482b":"Pine Green","004ea8":"Blue","0056b8":"Cobalt Blue","0069b1":"Lake Blue","0072ce":"Blue","0078bf":"Marine Blue","0085ad":"Light Blue","0086d6":"Cyan","008bda":"Blue","009639":"Green","009bd8":"Cyan","009fa1":"Teal","00a6a0":"Green","00ae42":"Bambu Green","00b1b7":"Turquoise","00bb31":"Green","018814":"Candy Green","042f56":"Dark Blue","0a2989":"Blue","0a2ca5":"Blue","0c2340":"Navy Blue","0c3b95":"Blue",101820:"Black","147bd1":"Blue","164b35":"Green","16b08e":"Malachite Green","1d7c6a":"Oxide Green Metallic","1f79e5":"Lake Blue","2140b4":"Blue","25282a":"Black","2842ad":"Royal Blue","2d2b28":"Onyx Black Sparkle",324585:"Indigo Blue",353533:"Gray","39541a":"Forest Green","39699e":"Cobalt Blue Metallic","3b665e":"Green","3f5443":"Alpine Green Sparkle","3f8e43":"Mistletoe Green",424379:"Nebulae","43403d":"Iron Gray Metallic",482960:"Indigo Purple","483d8b":"Royal Purple Sparkle","489fdf":"Azure","4c241c":"Rosewood","4ce4a0":"Green","4d3324":"Dark Chocolate","4d5054":"Lava Gray","4dafda":"Cyan","4f3f24":"Black Walnut",515151:"Dark Gray","515a6c":"Gray",545454:"Dark Gray",565656:"Titan Gray","56b7e6":"Sky Blue",583061:"Violet Purple","5898dd":"Blue",594177:"Purple","5b492f":"Brown","5b6579":"Blue Gray","5c9748":"Matcha Green","5e43b7":"Purple","5e4b3c":"Copper","5f6367":"Titan Gray","61b0ff":"Translucent Light Blue","61bf36":"Green","61c680":"Grass Green","6667ab":"Lavender Blue","684a43":"Brown",686865:"Black","68724d":"Dark Green",688197:"Blue Gray","69398e":"Iris Purple","6e88bc":"Jeans Blue","6ee53c":"Lime Green","6f5034":"Cocoa Brown","7248bd":"Lavender","748c45":"Translucent Olive",757575:"Nardo Gray","75aed8":"Blue","77edd7":"Translucent Teal","789d4a":"Olive","792b36":"Crimson Red Sparkle","7ac0e9":"Glow Blue","7ae1bf":"Mint","7cd82b":"Lime Green","7d6556":"Dark Brown","8344b0":"Purple","847d48":"Bronze","854ce4":"Purple","8671cb":"Purple",875718:"Peanut Brown","87909a":"Silver","898d8d":"Gray","8a949e":"Gray","8e8e8e":"Translucent Gray","8e9089":"Gray","90ff1a":"Neon Green",918669:"Classic Birch",939393:"Gray",950051:"Plum","951e23":"Burgundy Red",959698:"Silver","96d8af":"Light Jade","96dcb9":"Mint","995f11":"Clay Brown","999d9d":"Gray","9b9ea0":"Ash Gray","9d2235":"Maroon Red","9d432c":"Brown","9e007e":"Purple","9ea2a2":"Gray","9f332a":"Brick Red",a1ffac:"Glow Green",a3d8e1:"Ice Blue",a6a9aa:"Silver",a8a8aa:"Gray",a8c6ee:"Baby Blue",aa6443:"Copper Brown Metallic",ad4e38:"Red Granite",adb1b2:"Gray",ae835b:"Caramel",ae96d4:"Lilac Purple",af1685:"Purple",afb1ae:"Gray",b15533:"Terracotta",b28b33:"Gold",b39b84:"Iridium Gold Metallic",b50011:"Red",b8acd6:"Lavender",b8cde9:"Ice Blue",ba9594:"Rose Gold",bb3d43:"Dark Red",bc0900:"Red",becf00:"Bright Green",c0df16:"Green",c12e1f:"Red",c2e189:"Apple Green",c3e2d6:"Light Cyan",c5ed48:"Lime",c6001a:"Red",c6c6c6:"Gray",c8102e:"Red",c8c8c8:"Silver",c98935:"Ochre Yellow",c9a381:"Translucent Brown",cbc6b8:"Bone White",cdceca:"Gray",cea629:"Classic Gold Sparkle",d02727:"Candy Red",d1d3d5:"Light Gray",d32941:"Red",d3b7a7:"Latte Brown",d6001c:"Red",d6abff:"Translucent Purple",d6cca3:"White Oak",dc3a27:"Orange",dd3c22:"Vermilion Red",de4343:"Scarlet Red",dfd1a7:"Beige",e02928:"Red",e4bd68:"Gold",e5b03d:"Gold",e83100:"Red",e8afcf:"Sakura Pink",e8dbb7:"Desert Tan",eaeae4:"White",eaeceb:"Silver",ec008c:"Magenta",ed0000:"Red",eeb1c1:"Pink",efe255:"Yellow",f0f1a8:"Clear",f17b8f:"Glow Pink",f3cfb2:"Champagne",f3e600:"Yellow",f48438:"Orange",f4a925:"Gold",f4d53f:"Yellow",f4ee2a:"Yellow",f5547c:"Hot Pink",f55a74:"Pink",f5b6cd:"Cherry Pink",f5dbab:"Mellow Yellow",f5f1dd:"White",f68b1b:"Neon Orange",f74e02:"Orange",f75403:"Orange",f7ada6:"Pink",f7d959:"Lemon Yellow",f7e6de:"Beige",f7f3f0:"White Marble",f8ff80:"Glow Yellow",f99963:"Mandarin Orange",f9c1bd:"Translucent Pink",f9dfb9:"Cream",f9ef41:"Yellow",f9f7f2:"Nature",f9f7f4:"White",fce300:"Yellow",fce900:"Yellow",fec600:"Sunflower Yellow",fedb00:"Yellow",ff4800:"Orange",ff671f:"Orange",ff6a13:"Orange",ff7f41:"Orange",ff9016:"Pumpkin Orange",ff911a:"Translucent Orange",ff9d5b:"Glow Orange",ffb549:"Sunflower Yellow",ffc72c:"Tangerine Yellow",ffce00:"Yellow",ffd00b:"Yellow",ffe133:"Yellow",fffaf2:"White",ffffff:"White"};function L8e(t){if(!t||t.length<6)return"Unknown";const e=t.replace("#",""),n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16),s=Math.max(n,r,i)/255,o=Math.min(n,r,i)/255,l=(s+o)/2;let c=0,u=0;if(s!==o){const d=s-o;u=l>.5?d/(2-s-o):d/(s+o);const h=n/255,p=r/255,m=i/255;s===h?c=((p-m)/d+(p.85?"White":u<.15?l<.4?"Dark Gray":l>.6?"Light Gray":"Gray":c<15||c>=345?"Red":c<45?"Orange":c<70?"Yellow":c<150?"Green":c<200?"Cyan":c<260?"Blue":c<290?"Purple":"Pink"}function ub(t){const e=t.replace("#","").toLowerCase().substring(0,6);return Gq[e]?Gq[e]:L8e(t)}function mN(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function yi(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}function pc(t,e,n=40){const r=yi(t),i=yi(e);if(!r||!i||r.length<6||i.length<6)return!1;const s=parseInt(r.substring(0,2),16),o=parseInt(r.substring(2,4),16),l=parseInt(r.substring(4,6),16),c=parseInt(i.substring(0,2),16),u=parseInt(i.substring(2,4),16),d=parseInt(i.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-u)<=n&&Math.abs(l-d)<=n}function Iee(t,e,n,r){const i=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${i}`:`AMS-${i} Slot ${e+1}`}function zee(t,e,n){return t>=128?t:t*4+e}function F8e(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 qq(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return new Date(t).getTime()>e}function P4(t){const e=[];if(t?.ams?.forEach(n=>{const r=n.tray.length===1;n.tray.forEach(i=>{if(i.tray_type){const s=mN(i.tray_color);e.push({type:i.tray_type,color:s,colorName:ub(s),amsId:n.id,trayId:i.id,isHt:r,isExternal:!1,label:Iee(n.id,i.id,r),globalTrayId:zee(n.id,i.id),trayInfoIdx:i.tray_info_idx||""})}})}),t?.vt_tray?.tray_type){const n=mN(t.vt_tray.tray_color);e.push({type:t.vt_tray.tray_type,color:n,colorName:ub(n),amsId:-1,trayId:0,isHt:!1,isExternal:!0,label:"External",globalTrayId:254,trayInfoIdx:t.vt_tray.tray_info_idx||""})}return e}function Wq(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=P4(e);if(n.length===0)return;const r=new Set,i=t.filaments.map(l=>{const c=l.tray_info_idx||"",u=n.filter(y=>!r.has(y.globalTrayId));let d,h,p,m;if(c){const y=u.filter(x=>x.trayInfoIdx===c);y.length===1?d=y[0]:y.length>1&&(h=y.find(x=>x.type?.toUpperCase()===l.type?.toUpperCase()&&yi(x.color)===yi(l.color)),h||(p=y.find(x=>x.type?.toUpperCase()===l.type?.toUpperCase()&&pc(x.color,l.color))),!h&&!p&&(m=y.find(x=>x.type?.toUpperCase()===l.type?.toUpperCase())))}!d&&!h&&!p&&!m&&(h=u.find(y=>y.type?.toUpperCase()===l.type?.toUpperCase()&&yi(y.color)===yi(l.color)),h||(p=u.find(y=>y.type?.toUpperCase()===l.type?.toUpperCase()&&pc(y.color,l.color))),!h&&!p&&(m=u.find(y=>y.type?.toUpperCase()===l.type?.toUpperCase())));const b=d||h||p||m||void 0;return b&&r.add(b.globalTrayId),{slot_id:l.slot_id,globalTrayId:b?.globalTrayId??-1}}),s=Math.max(...i.map(l=>l.slot_id||0));if(s<=0)return;const o=new Array(s).fill(-1);return i.forEach(l=>{l.slot_id&&l.slot_id>0&&(o[l.slot_id-1]=l.globalTrayId)}),o}function I8e(t){return _.useMemo(()=>{const e=[];if(t?.ams?.forEach(n=>{const r=n.tray.length===1;n.tray.forEach(i=>{if(i.tray_type){const s=mN(i.tray_color);e.push({type:i.tray_type,color:s,colorName:ub(s),amsId:n.id,trayId:i.id,isHt:r,isExternal:!1,label:Iee(n.id,i.id,r),globalTrayId:zee(n.id,i.id),trayInfoIdx:i.tray_info_idx||""})}})}),t?.vt_tray?.tray_type){const n=mN(t.vt_tray.tray_color);e.push({type:t.vt_tray.tray_type,color:n,colorName:ub(n),amsId:-1,trayId:0,isHt:!1,isExternal:!0,label:"External",globalTrayId:254,trayInfoIdx:t.vt_tray.tray_info_idx||""})}return e},[t])}function Uee(t,e,n){const r=I8e(e),i=_.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const c=new Set(Object.values(n));return t.filaments.map(u=>{const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const A=n[d],k=r.find(R=>R.globalTrayId===A);if(k){const R=k.type?.toUpperCase()===u.type?.toUpperCase(),C=yi(k.color)===yi(u.color)||pc(k.color,u.color);let P;return R&&C?P="match":R?P="type_only":P="mismatch",{...u,loaded:k,hasFilament:!0,typeMatch:R,colorMatch:C,status:P,isManual:!0}}}const h=u.tray_info_idx||"",p=r.filter(A=>!c.has(A.globalTrayId));let m,b,y,x;if(h){const A=p.filter(k=>k.trayInfoIdx===h);A.length===1?m=A[0]:A.length>1&&(b=A.find(k=>k.type?.toUpperCase()===u.type?.toUpperCase()&&yi(k.color)===yi(u.color)),b||(y=A.find(k=>k.type?.toUpperCase()===u.type?.toUpperCase()&&pc(k.color,u.color))),!b&&!y&&(x=A.find(k=>k.type?.toUpperCase()===u.type?.toUpperCase())))}!m&&!b&&!y&&!x&&(b=p.find(A=>A.type?.toUpperCase()===u.type?.toUpperCase()&&yi(A.color)===yi(u.color)),b||(y=p.find(A=>A.type?.toUpperCase()===u.type?.toUpperCase()&&pc(A.color,u.color))),!b&&!y&&(x=p.find(A=>A.type?.toUpperCase()===u.type?.toUpperCase())));const v=m||b||y||x||void 0;v&&c.add(v.globalTrayId);const S=!!v,N=S,T=!!m||!!b||!!y;let M;return m||b||y?M="match":x?M="type_only":M="mismatch",{...u,loaded:v,hasFilament:S,typeMatch:N,colorMatch:T,status:M,isManual:!1}})},[t,r,n]),s=_.useMemo(()=>{if(i.length===0)return;const c=Math.max(...i.map(d=>d.slot_id||0));if(c<=0)return;const u=new Array(c).fill(-1);return i.forEach(d=>{d.slot_id&&d.slot_id>0&&(u[d.slot_id-1]=d.loaded?.globalTrayId??-1)}),u},[i]),o=i.some(c=>c.status==="mismatch"),l=i.some(c=>c.status==="type_only");return{loadedFilaments:r,filamentComparison:i,amsMapping:s,hasTypeMismatch:o,hasColorMismatch:l}}function z8e(t,e,n){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let r=0,i=0,s=0;const o=new Set(Object.values(n));for(const u of t){const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const y=n[d],x=e.find(v=>v.globalTrayId===y);if(x){const v=x.type?.toUpperCase()===u.type?.toUpperCase(),S=yi(x.color)===yi(u.color)||pc(x.color,u.color);v&&S?r++:v?i++:s++;continue}}const h=e.find(y=>!o.has(y.globalTrayId)&&y.type?.toUpperCase()===u.type?.toUpperCase()&&yi(y.color)===yi(u.color)),p=h?void 0:e.find(y=>!o.has(y.globalTrayId)&&y.type?.toUpperCase()===u.type?.toUpperCase()&&pc(y.color,u.color)),m=h||p?void 0:e.find(y=>!o.has(y.globalTrayId)&&y.type?.toUpperCase()===u.type?.toUpperCase()),b=h??p??m;b&&o.add(b.globalTrayId),h||p?r++:m?i++:s++}const l=t.length;let c="full";return s>0?c="missing":i>0&&(c="partial"),{exactMatches:r,typeOnlyMatches:i,missingTypes:s,totalSlots:l,status:c}}function U8e(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=P4(e);if(r.length===0)return;const i=new Set(Object.values(n)),s=[];for(const c of t.filaments){const u=c.slot_id||0;if(u>0&&n[u]!==void 0){s.push({slot_id:u,globalTrayId:n[u]});continue}const d=r.find(b=>!i.has(b.globalTrayId)&&b.type?.toUpperCase()===c.type?.toUpperCase()&&yi(b.color)===yi(c.color)),h=d?void 0:r.find(b=>!i.has(b.globalTrayId)&&b.type?.toUpperCase()===c.type?.toUpperCase()&&pc(b.color,c.color)),p=d||h?void 0:r.find(b=>!i.has(b.globalTrayId)&&b.type?.toUpperCase()===c.type?.toUpperCase()),m=d??h??p;m&&i.add(m.globalTrayId),s.push({slot_id:u,globalTrayId:m?.globalTrayId??-1})}const o=Math.max(...s.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return s.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}const Kq={useDefault:!0,manualMappings:{},autoConfigured:!1};function B8e(t,e,n,r,i,s){const o=BR({queries:t.map(b=>({queryKey:["printer-status",b],queryFn:()=>ae.getPrinterStatus(b),enabled:t.length>0,staleTime:5e3}))}),l=_.useMemo(()=>t.map((b,y)=>{const x=o[y],v=x?.data,N=e?.find(P=>P.id===b)?.name||`Printer ${b}`,T=P4(v),M=i[b]||Kq,A=Wq(n,v),k=M.useDefault?r:M.manualMappings,R=U8e(n,v,k),C=z8e(n?.filaments,T,k);return{printerId:b,printerName:N,status:v,isLoading:x?.isLoading??!1,loadedFilaments:T,autoMapping:A,finalMapping:R,matchStatus:C.status,exactMatches:C.exactMatches,typeOnlyMatches:C.typeOnlyMatches,missingTypes:C.missingTypes,totalSlots:C.totalSlots,config:M}}),[t,o,e,n,i,r]),c=o.some(b=>b.isLoading),u=(b,y)=>{s(x=>({...x,[b]:{...x[b]||Kq,...y}}))},d=b=>{const y=l.find(S=>S.printerId===b);if(!y||!y.status||!n?.filaments)return;const x=Wq(n,y.status);if(!x)return;const v={};x.forEach((S,N)=>{S!==-1&&(v[N+1]=S)}),u(b,{useDefault:!1,manualMappings:v,autoConfigured:!0})},h=()=>{for(const b of t)d(b)},p=b=>l.find(x=>x.printerId===b)?.finalMapping,m=l.every(b=>b.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:h,autoConfigurePrinter:d,getFinalMapping:p,allPrintersReady:m}}function H8e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=an(),[i,s]=_.useState(!1),o=(u,d)=>{if(u<=0)return;const h={...t.config.manualMappings};d===""?delete h[u]:h[u]=parseInt(d,10),n({useDefault:!1,manualMappings:h,autoConfigured:!1})},l=async()=>{s(!0);try{await ae.refreshPrinterStatus(t.printerId),await new Promise(u=>setTimeout(u,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(u=>{const d=u.slot_id||0,h=t.config.manualMappings[d];let p,m=!1;if(h!==void 0)p=t.loadedFilaments.find(y=>y.globalTrayId===h),m=!0;else{const y=new Set(Object.values(t.config.manualMappings)),x=t.loadedFilaments.find(N=>!y.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase()&&yi(N.color)===yi(u.color)),v=x?void 0:t.loadedFilaments.find(N=>!y.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase()&&pc(N.color,u.color)),S=x||v?void 0:t.loadedFilaments.find(N=>!y.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase());p=x??v??S}let b="mismatch";if(p){const y=p.type?.toUpperCase()===u.type?.toUpperCase(),x=yi(p.color)===yi(u.color)||pc(p.color,u.color);y&&x?b="match":y&&(b="type_only")}return{req:u,loaded:p,status:b,isManual:m}});return a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),a.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:i,children:[a.jsx(Or,{className:`w-3 h-3 ${i?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),c.map(({req:u,loaded:d,status:h,isManual:p},m)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${u.type} - ${ub(u.color)}`,children:a.jsx(Sj,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),a.jsxs("span",{className:"text-white truncate",children:[u.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:d?.globalTrayId??"",onChange:b=>o(u.slot_id||0,b.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${h==="match"?"border-bambu-green/50 text-bambu-green":h==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${p?"ring-1 ring-blue-400/50":""}`,title:p?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),t.loadedFilaments.map(b=>a.jsxs("option",{value:b.globalTrayId,className:"bg-bambu-dark text-white",children:[b.label,": ",b.type," (",b.colorName,")"]},b.globalTrayId))]}),h==="match"?a.jsx($i,{className:"w-3 h-3 text-bambu-green"}):h==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(En,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(En,{className:"w-3 h-3 text-orange-400"})})]},m))]})}function $8e({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:s=!1,printerMappingResults:o,filamentReqs:l,onAutoConfigurePrinter:c,onUpdatePrinterConfig:u,assignmentMode:d="printer",onAssignmentModeChange:h,targetModel:p,onTargetModelChange:m,targetLocation:b,onTargetLocationChange:y,slicedForModel:x}){const[v,S]=_.useState(!1),N=s?t:t.filter(I=>I.is_active),T=_.useMemo(()=>{if(d!=="printer"||!x||v)return N;const I=N.filter(K=>K.model===x);return I.length>0?I:N},[N,d,x,v]),M=N.length-T.length,A=_.useMemo(()=>{const I=N.map(K=>K.model).filter(K=>!!K);return[...new Set(I)].sort()},[N]),k=_.useMemo(()=>{if(!p)return[];const I=N.filter(K=>K.model===p&&K.location).map(K=>K.location).filter(K=>!!K);return[...new Set(I)].sort()},[N,p]),R=h&&m&&A.length>0,C=i&&e.length>1&&o&&l?.filaments&&l.filaments.length>0&&c&&u;if(r)return a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(T.length===0)return a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[a.jsx(Ti,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const P=I=>{i?e.includes(I)?n(e.filter(K=>K!==I)):n([...e,I]):n([I])},U=()=>{n(T.map(I=>I.id))},F=()=>{n([])},H=(I,K,Q)=>{Q.stopPropagation(),!(!c||!u)&&(K?c(I):u(I,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},D=I=>e.includes(I),$=e.length,G=I=>o?.find(K=>K.printerId===I);return a.jsxs("div",{className:"space-y-2 mb-6",children:[R&&a.jsxs("div",{className:"flex gap-2 mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>{h("printer"),m(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d==="printer"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(jr,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),a.jsxs("button",{type:"button",onClick:()=>{h("model"),n([]);const I=x&&A.includes(x)?x:A[0];m(I)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d==="model"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(zf,{className:"w-4 h-4"}),a.jsxs("span",{className:"text-sm",children:["Any ",x||"Model"]})]})]}),d==="model"&&R&&a.jsxs("div",{className:"space-y-3 mb-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),a.jsxs("select",{value:p||"",onChange:I=>{m(I.target.value||null),y&&y(null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[a.jsx("option",{value:"",children:"Select a model..."}),A.map(I=>a.jsx("option",{value:I,children:I},I))]})]}),p&&k.length>0&&y&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),a.jsxs("select",{value:b||"",onChange:I=>y(I.target.value||null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[a.jsx("option",{value:"",children:"Any location"}),k.map(I=>a.jsx("option",{value:I,children:I},I))]})]}),p&&a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",p," printer",b?` in ${b}`:""]})]}),d==="printer"&&i&&T.length>1&&a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[a.jsx("span",{children:$===0?"Select printers":`${$} printer${$!==1?"s":""} selected`}),a.jsxs("div",{className:"flex gap-2",children:[$0&&a.jsx("button",{type:"button",onClick:F,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),d==="printer"&&T.map(I=>{const K=D(I.id),Q=G(I.id),oe=Q&&!Q.config.useDefault;return a.jsxs("div",{children:[a.jsxs("button",{type:"button",onClick:()=>P(I.id),className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${K?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${I.is_active?"":"opacity-60"}`,children:[a.jsx("div",{className:`p-2 rounded-lg ${K?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(jr,{className:`w-5 h-5 ${K?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{className:"text-left flex-1",children:[a.jsxs("p",{className:"text-white font-medium",children:[I.name,!I.is_active&&a.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[I.model||"Unknown model"," • ",I.ip_address]})]}),i&&a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${K?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:K&&a.jsx($i,{className:"w-3 h-3 text-white"})})]}),K&&C&&Q&&a.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:B=>B.stopPropagation(),children:[a.jsx("input",{type:"checkbox",checked:oe,onChange:B=>H(I.id,B.target.checked,B),className:"w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),a.jsxs("span",{className:`text-xs ml-2 ${Q.matchStatus==="full"?"text-bambu-green":Q.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",Q.exactMatches,"/",Q.totalSlots," matched)"]}),Q.isLoading&&a.jsx(Or,{className:"w-3 h-3 text-bambu-gray animate-spin"}),oe&&a.jsxs("button",{type:"button",onClick:B=>{B.stopPropagation(),c(I.id)},className:"ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",children:[a.jsx(jfe,{className:"w-3 h-3"}),"Auto"]})]}),oe&&a.jsx(H8e,{printerResult:Q,filamentReqs:l.filaments,onUpdateConfig:B=>u(I.id,B)})]})]},I.id)}),d==="printer"&&M>0&&!v&&a.jsxs("button",{type:"button",onClick:()=>S(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[a.jsx(En,{className:"w-3 h-3 text-yellow-400"}),M," other printer",M>1?"s":""," hidden (different model) —",a.jsx("span",{className:"underline",children:"show all"})]}),d==="printer"&&v&&x&&a.jsx("button",{type:"button",onClick:()=>S(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:a.jsxs("span",{className:"underline",children:["Show only ",x," printers"]})}),d==="printer"&&$===0&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Ti,{className:"w-3 h-3"}),"Select at least one printer"]}),d==="model"&&!p&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Ti,{className:"w-3 h-3"}),"Select a target printer model"]})]})}function V8e({plates:t,isMultiPlate:e,selectedPlate:n,onSelect:r}){return!e||t.length<=1?null:a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(is,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"Select Plate to Print"}),!n&&a.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[a.jsx(En,{className:"w-3 h-3"}),"Selection required"]})]}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(i=>a.jsxs("button",{type:"button",onClick:()=>r(i.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${n===i.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[i.has_thumbnail&&i.thumbnail_url!=null?a.jsx("img",{src:i.thumbnail_url,alt:`Plate ${i.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(is,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name||`Plate ${i.index}`}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[i.objects.length>0?i.objects.slice(0,3).join(", ")+(i.objects.length>3?"...":""):`${i.filaments.length} filament${i.filaments.length!==1?"s":""}`,i.print_time_seconds!=null?` • ${F8e(i.print_time_seconds)}`:""]})]}),n===i.index&&a.jsx($i,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},i.index))})]})}function G8e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,defaultExpanded:i=!1}){const s=an(),[o,l]=_.useState(!1),[c,u]=_.useState(i),{data:d}=it({queryKey:["printer-status",t],queryFn:()=>ae.getPrinterStatus(t),enabled:!!t}),{loadedFilaments:h,filamentComparison:p,hasTypeMismatch:m,hasColorMismatch:b}=Uee(e,d,n);if(!(e?.filaments&&e.filaments.length>0)||!d)return null;const x=m?"#f97316":b?"#facc15":"#00ae42",v=(N,T)=>{if(N>0)if(T===""){const M={...n};delete M[N],r(M)}else r({...n,[N]:parseInt(T,10)})},S=async()=>{l(!0);try{await ae.refreshPrinterStatus(t),await new Promise(N=>setTimeout(N,500)),await s.refetchQueries({queryKey:["printer-status",t]})}finally{l(!1)}};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>u(!c),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(Sj,{className:"w-4 h-4",fill:x,stroke:"none"}),a.jsx("span",{children:"Filament Mapping"}),m?a.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):b?a.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):a.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),c?a.jsx(zu,{className:"w-4 h-4 ml-auto"}):a.jsx(fr,{className:"w-4 h-4 ml-auto"})]}),c&&a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),a.jsxs("button",{type:"button",onClick:S,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:o,children:[a.jsx(Or,{className:`w-3 h-3 ${o?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),p.map((N,T)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${N.type} - ${ub(N.color)}`,children:a.jsx(Sj,{className:"w-3 h-3",fill:N.color,stroke:N.color})}),a.jsxs("span",{className:"text-white truncate",children:[N.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",N.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:N.loaded?.globalTrayId??"",onChange:M=>v(N.slot_id||0,M.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${N.status==="match"?"border-bambu-green/50 text-bambu-green":N.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${N.isManual?"ring-1 ring-blue-400/50":""}`,title:N.isManual?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),h.map(M=>a.jsxs("option",{value:M.globalTrayId,className:"bg-bambu-dark text-white",children:[M.label,": ",M.type," (",M.colorName,")"]},M.globalTrayId))]}),N.status==="match"?a.jsx($i,{className:"w-3 h-3 text-bambu-green"}):N.status==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(En,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(En,{className:"w-3 h-3 text-orange-400"})})]},T)),m&&a.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}const q8e=[{key:"bed_levelling",label:"Bed Levelling",desc:"Auto-level bed before print"},{key:"flow_cali",label:"Flow Calibration",desc:"Calibrate extrusion flow"},{key:"vibration_cali",label:"Vibration Calibration",desc:"Reduce ringing artifacts"},{key:"layer_inspect",label:"First Layer Inspection",desc:"AI inspection of first layer"},{key:"timelapse",label:"Timelapse",desc:"Record timelapse video"}];function W8e({options:t,onChange:e,defaultExpanded:n=!1}){const[r,i]=_.useState(n),s=o=>{e({...t,[o]:!t[o]})};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>i(!r),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(Mk,{className:"w-4 h-4"}),a.jsx("span",{children:"Print Options"}),r?a.jsx(zu,{className:"w-4 h-4 ml-auto"}):a.jsx(fr,{className:"w-4 h-4 ml-auto"})]}),r&&a.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:q8e.map(({key:o,label:l,desc:c})=>a.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:l}),a.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),a.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>s(o),children:a.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[o]?"translate-x-5":"translate-x-0.5"}`})})]},o))})]})}function K8e({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system"}){const[i,s]=_.useState(""),[o,l]=_.useState(""),[c,u]=_.useState(!0),[d,h]=_.useState(!0),p=_.useRef(null),m=_.useRef(!1);_.useEffect(()=>{if(t.scheduleType!=="scheduled"){m.current=!1;return}if(!m.current){m.current=!0;let T;t.scheduledTime?(T=new Date(t.scheduledTime),isNaN(T.getTime())&&(T=new Date,T.setHours(T.getHours()+1,0,0,0))):(T=new Date,T.setHours(T.getHours()+1,0,0,0),e({...t,scheduledTime:jj(T)})),s(rB(T,n)),l(iB(T,r)),u(!0),h(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const b=T=>{e({...t,scheduleType:T})},y=(T,M)=>{const A=nme(T,n),k=rme(M);u(!!A),h(!!k),A&&k&&(A.setHours(k.hours,k.minutes,0,0),A>new Date&&e({...t,scheduledTime:jj(A)}))},x=T=>{s(T),y(T,o)},v=T=>{l(T),y(i,T)},S=T=>{const M=T.target.value;if(M){const A=new Date(M);isNaN(A.getTime())||(s(rB(A,n)),l(iB(A,r)),u(!0),h(!0),e({...t,scheduledTime:M}))}},N=()=>{p.current?.showPicker()};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>b("asap"),children:[a.jsx(tr,{className:"w-4 h-4"}),"ASAP"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>b("scheduled"),children:[a.jsx(ti,{className:"w-4 h-4"}),"Scheduled"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>b("manual"),children:[a.jsx(LW,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"flex-1 relative",children:[a.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${c?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:i,onChange:T=>x(T.target.value),placeholder:eme(n)}),a.jsx("button",{type:"button",onClick:N,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:a.jsx(ti,{className:"w-4 h-4"})})]}),a.jsx("div",{className:"w-32",children:a.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${d?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:o,onChange:T=>v(T.target.value),placeholder:tme(r)})})]}),a.jsx("input",{ref:p,type:"datetime-local",className:"sr-only",value:t.scheduledTime,onChange:S,tabIndex:-1}),(!c||!d)&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:T=>e({...t,requirePreviousSuccess:T.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:T=>e({...t,autoOffAfter:T.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("label",{htmlFor:"autoOffAfter",className:"text-sm text-bambu-gray flex items-center gap-1",children:[a.jsx(Ju,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t.scheduleType==="asap"?"Print will start as soon as the printer is idle.":t.scheduleType==="scheduled"?"Print will start at the scheduled time if the printer is idle. If busy, it will wait until the printer becomes available.":"Print will be staged but won't start automatically. Use the Start button to release it to the queue."})]})}const rg={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},X8e={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function Ou({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:i,onClose:s,onSuccess:o}){const{t:l}=Yt(),c=an(),{showToast:u}=Tn(),d=!!n&&!e,[h,p]=_.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[m,b]=_.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[y,x]=_.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??rg.bed_levelling,flow_cali:i.flow_cali??rg.flow_cali,vibration_cali:i.vibration_cali??rg.vibration_cali,layer_inspect:i.layer_inspect??rg.layer_inspect,timelapse:i.timelapse??rg.timelapse}:rg),[v,S]=_.useState(()=>{if(t==="edit-queue-item"&&i){let ze="asap";i.manual_start?ze="manual":i.scheduled_time&&!qq(i.scheduled_time)&&(ze="scheduled");let be="";if(i.scheduled_time&&!qq(i.scheduled_time)){const Me=new Date(i.scheduled_time);be=jj(Me)}return{scheduleType:ze,scheduledTime:be,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after}}return X8e}),[N,T]=_.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const ze={};return i.ams_mapping.forEach((be,Me)=>{be!==-1&&(ze[Me+1]=be)}),ze}return{}}),[M,A]=_.useState({}),[k,R]=_.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[C,P]=_.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[U,F]=_.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[H]=_.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[D]=_.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[$,G]=_.useState(!1),[I,K]=_.useState({current:0,total:0}),[Q,oe]=_.useState(new Set),B=h.length,W=h.length>0?h[0]:null,{data:J}=it({queryKey:["settings"],queryFn:ae.getSettings}),{data:ne,isLoading:me}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:fe}=it({queryKey:["archive",e],queryFn:()=>ae.getArchive(e),enabled:!!e&&!d}),{data:de}=it({queryKey:["library-file",n],queryFn:()=>ae.getLibraryFile(n),enabled:d&&!!n}),Re=fe?.sliced_for_model||de?.sliced_for_model||null,{data:se,isError:ke}=it({queryKey:["archive-plates",e],queryFn:()=>ae.getArchivePlates(e),enabled:!!e&&!d,retry:!1}),{data:Fe}=it({queryKey:["library-file-plates",n],queryFn:()=>ae.getLibraryFilePlates(n),enabled:d&&!!n}),ce=d?Fe:se,{data:Ve,isError:V}=it({queryKey:["archive-filaments",e,m],queryFn:()=>ae.getArchiveFilamentRequirements(e,m??void 0),enabled:!!e&&!d&&(m!==null||!ce?.is_multi_plate),retry:!1}),{data:Y}=it({queryKey:["library-file-filaments",n,m],queryFn:()=>ae.getLibraryFileFilamentRequirements(n,m??void 0),enabled:d&&!!n&&(m!==null||!ce?.is_multi_plate)}),ue=!d&&(ke||V),q=d?Y:Ve,{data:re}=it({queryKey:["printer-status",W],queryFn:()=>ae.getPrinterStatus(W),enabled:!!W}),{amsMapping:X}=Uee(q,re,N),le=B8e(h,ne,q,N,M,A);_.useEffect(()=>{ce?.plates?.length===1&&!m&&b(ce.plates[0].index)},[ce,m]),_.useEffect(()=>{if(t==="edit-queue-item")return;const ze=ne?.filter(be=>be.is_active)||[];ze.length===1&&h.length===0&&p([ze[0].id])},[t,ne,h.length]),_.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(h.sort())!==JSON.stringify(H.sort())||m!==D)&&(T({}),A({}),oe(new Set)):(T({}),A({}),oe(new Set))},[t,h,m,H,D]),_.useEffect(()=>{if(!J?.per_printer_mapping_expanded||h.length<=1)return;const ze=h.filter(be=>{if(Q.has(be))return!1;const Me=le.printerResults.find(Be=>Be.printerId===be);return Me&&Me.status&&!Me.isLoading});ze.length>0&&(oe(be=>{const Me=new Set(be);return ze.forEach(Be=>Me.add(Be)),Me}),ze.forEach(be=>{le.autoConfigurePrinter(be)}))},[J?.per_printer_mapping_expanded,h,Q,le]),_.useEffect(()=>{const ze=be=>{be.key==="Escape"&&!$&&s()};return window.addEventListener("keydown",ze),()=>window.removeEventListener("keydown",ze)},[s,$]);const pe=ce?.is_multi_plate??!1,ee=ce?.plates??[],z=dt({mutationFn:ze=>ae.addToQueue(ze)}),O=dt({mutationFn:ze=>ae.updateQueueItem(i.id,ze),onSuccess:()=>{c.invalidateQueries({queryKey:["queue"]}),u("Queue item updated"),o?.(),s()},onError:ze=>{u(ze.message||"Failed to update queue item","error")}}),Z=async ze=>{if(ze?.preventDefault(),k==="printer"&&h.length===0){u("Please select at least one printer","error");return}if(k==="model"&&!C){u("Please select a target printer model","error");return}G(!0);const be=k==="model"?1:h.length;K({current:0,total:be});const Me={success:0,failed:0,errors:[]},Be=qe=>{if(h.length>1){const ve=M[qe];if(ve&&!ve.useDefault)return le.getFinalMapping(qe)}return X},Ae=qe=>({printer_id:k==="printer"?qe:null,target_model:k==="model"?C:null,target_location:k==="model"?U:null,archive_id:d?void 0:e,library_file_id:d?n:void 0,require_previous_success:v.requirePreviousSuccess,auto_off_after:v.autoOffAfter,manual_start:v.scheduleType==="manual",ams_mapping:qe?Be(qe):void 0,plate_id:m,scheduled_time:v.scheduleType==="scheduled"&&v.scheduledTime?new Date(v.scheduledTime).toISOString():void 0,...y});if(k==="model"){K({current:1,total:1});try{if(t==="reprint"){u("Model-based assignment only works with queue mode","error"),G(!1);return}else if(t==="edit-queue-item"){const qe={printer_id:null,target_model:C,target_location:U,require_previous_success:v.requirePreviousSuccess,auto_off_after:v.autoOffAfter,manual_start:v.scheduleType==="manual",ams_mapping:void 0,plate_id:m,scheduled_time:v.scheduleType==="scheduled"&&v.scheduledTime?new Date(v.scheduledTime).toISOString():null,...y};await O.mutateAsync(qe)}else await z.mutateAsync(Ae(null));Me.success++}catch(qe){Me.failed++,Me.errors.push(qe.message)}}else for(let qe=0;qeYe.id===ve)?.name||`Printer ${ve}`;Me.errors.push(`${Ee}: ${et.message}`)}}if(G(!1),Me.failed===0){if(k==="model")u(t==="edit-queue-item"?"Queue item updated":`Queued for any ${C}`);else{const qe=t==="reprint"?"sent to":t==="edit-queue-item"?"updated/queued for":"queued for";Me.success===1?u(t==="edit-queue-item"?"Queue item updated":`Print ${qe} printer`):u(`Print ${qe} ${Me.success} printers`)}c.invalidateQueries({queryKey:["queue"]}),o?.(),s()}else Me.success===0?u(`Failed: ${Me.errors[0]}`,"error"):(u(`${Me.success} succeeded, ${Me.failed} failed`,"error"),c.invalidateQueries({queryKey:["queue"]}))},ge=$||O.isPending,Ce=_.useMemo(()=>!(ge||k==="printer"&&h.length===0||k==="model"&&!C||k==="model"&&t==="reprint"||!d&&pe&&!m),[h.length,k,C,t,pe,m,ge,d]),Te=(()=>{const ze=h.length;return t==="reprint"?{title:l(d?"queue.print":"queue.reprint"),icon:jr,submitText:ze>1?l("queue.printToPrinters",{count:ze}):l("queue.print"),submitIcon:jr,loadingText:I.total>1?l("queue.sendingProgress",{current:I.current,total:I.total}):l("queue.sending")}:t==="add-to-queue"?{title:l("queue.schedulePrint"),icon:ti,submitText:ze>1?l("queue.queueToPrinters",{count:ze}):l("queue.addToQueue"),submitIcon:ti,loadingText:I.total>1?l("queue.addingProgress",{current:I.current,total:I.total}):l("queue.adding")}:{title:l("queue.editQueueItem"),icon:Ji,submitText:l("common.save"),submitIcon:Ji,loadingText:I.total>1?l("queue.savingProgress",{current:I.current,total:I.total}):l("common.saving")}})(),we=Te.icon,$e=Te.submitIcon,Ge=W&&(d||(pe?m!==null:!0));return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:$?void 0:s,children:a.jsx(St,{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto",onClick:ze=>ze.stopPropagation(),children:a.jsxs(Et,{className:t==="reprint"?"":"p-0",children:[a.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(we,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:Te.title})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:s,disabled:$,children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Z,className:t==="reprint"?"":"p-4 space-y-4",children:[a.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?a.jsxs(a.Fragment,{children:["Send ",a.jsx("span",{className:"text-white",children:r})," to printer(s)"]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),a.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),a.jsx(V8e,{plates:ee,isMultiPlate:pe,selectedPlate:m,onSelect:b}),a.jsx($8e,{printers:ne||[],selectedPrinterIds:h,onMultiSelect:p,isLoading:me,allowMultiple:!0,showInactive:t==="edit-queue-item",printerMappingResults:le.printerResults,filamentReqs:q,onAutoConfigurePrinter:le.autoConfigurePrinter,onUpdatePrinterConfig:le.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":k,onAssignmentModeChange:t!=="reprint"?R:void 0,targetModel:C,onTargetModelChange:t!=="reprint"?P:void 0,targetLocation:U,onTargetLocationChange:t!=="reprint"?F:void 0,slicedForModel:Re}),Re&&k==="printer"&&h.length===1&&(()=>{const ze=ne?.find(be=>be.id===h[0]);return ze&&ze.model&&Re!==ze.model?a.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[a.jsx(En,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",Re,", but printing on ",ze.model]})]}):null})(),ue&&a.jsxs("div",{className:"flex items-start gap-2 p-3 mb-2 bg-orange-500/10 border border-orange-500/30 rounded-lg text-sm",children:[a.jsx(Ti,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),Ge&&!ue&&h.length===1&&a.jsx(G8e,{printerId:W,filamentReqs:q,manualMappings:N,onManualMappingChange:T,defaultExpanded:J?.per_printer_mapping_expanded??!1}),(t==="reprint"||B>0||k==="model"&&C)&&a.jsx(W8e,{options:y,onChange:x}),t!=="reprint"&&a.jsx(K8e,{options:v,onChange:S,dateFormat:J?.date_format||"system",timeFormat:J?.time_format||"system"}),O.isError&&a.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:O.error?.message||"Failed to complete operation"}),a.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:s,className:"flex-1",disabled:$,children:"Cancel"}),a.jsx(Ne,{type:"submit",disabled:!Ce,className:"flex-1",children:ge?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),Te.loadingText]}):a.jsxs(a.Fragment,{children:[a.jsx($e,{className:"w-4 h-4"}),Te.submitText]})})]})]})]})})})}function Y8e({onClose:t,initialFiles:e}){const{t:n}=Yt(),r=an(),{showToast:i}=Tn(),s=_.useRef(null),[o,l]=_.useState(()=>e?.filter(M=>M.name.endsWith(".3mf")).map(M=>({file:M,status:"pending"}))||[]),[c,u]=_.useState(!1),[d,h]=_.useState(null);_.useEffect(()=>{const M=A=>{A.key==="Escape"&&t()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[t]);const p=dt({mutationFn:M=>ae.uploadArchivesBulk(M),onSuccess:M=>{h(M),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(A=>A.map(k=>{const R=M.results.find(P=>P.filename===k.file.name),C=M.errors.find(P=>P.filename===k.file.name);return R?{...k,status:"success",archiveId:R.id}:C?{...k,status:"error",error:C.error}:k})),M.failed===0?i(`${M.uploaded} file${M.uploaded!==1?"s":""} uploaded`):M.uploaded===0?i(`Failed to upload ${M.failed} file${M.failed!==1?"s":""}`,"error"):i(`${M.uploaded} uploaded, ${M.failed} failed`,"warning")},onError:()=>{l(M=>M.map(A=>({...A,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),m=_.useCallback(M=>{M.preventDefault(),u(!0)},[]),b=_.useCallback(M=>{M.preventDefault(),u(!1)},[]),y=_.useCallback(M=>{M.preventDefault(),u(!1);const A=Array.from(M.dataTransfer.files).filter(k=>k.name.endsWith(".3mf"));A.length>0&&l(k=>[...k,...A.map(R=>({file:R,status:"pending"}))])},[]),x=_.useCallback(M=>{const A=Array.from(M.target.files||[]).filter(k=>k.name.endsWith(".3mf"));A.length>0&&l(k=>[...k,...A.map(R=>({file:R,status:"pending"}))]),s.current&&(s.current.value="")},[]),v=_.useCallback(M=>{l(A=>A.filter((k,R)=>R!==M))},[]),S=()=>{if(o.length===0)return;const M=o.filter(A=>A.status==="pending");M.length!==0&&(l(A=>A.map(k=>k.status==="pending"?{...k,status:"uploading"}:k)),p.mutate(M.map(A=>A.file)))},N=o.filter(M=>M.status==="pending").length,T=p.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4",children:a.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:m,onDragLeave:b,onDrop:y,children:[a.jsx(Na,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(Ne,{variant:"secondary",onClick:()=>s.current?.click(),disabled:T,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:x})]})}),a.jsx("div",{className:"px-4 pb-4",children:a.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&a.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:a.jsx("div",{className:"space-y-2",children:o.map((M,A)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(xk,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:M.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(M.file.size/(1024*1024)).toFixed(1)," MB"]}),M.status==="pending"&&a.jsx("button",{onClick:()=>v(A),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:T,children:a.jsx(Lt,{className:"w-4 h-4"})}),M.status==="uploading"&&a.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"}),M.status==="success"&&a.jsx(mr,{className:"w-4 h-4 text-bambu-green"}),M.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:M.error}),a.jsx(Ti,{className:"w-4 h-4 text-red-400"})]})]},`${M.file.name}-${A}`))})}),d&&a.jsx("div",{className:"px-4 pb-4",children:a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"text-bambu-green",children:d.uploaded})," ",n("uploadModal.uploaded"),d.failed>0&&a.jsxs(a.Fragment,{children:[", ",a.jsx("span",{className:"text-red-400",children:d.failed})," ",n("uploadModal.failed")]})]})})}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ne,{variant:"secondary",onClick:t,className:"flex-1",children:n(d?"common.close":"common.cancel")}),!d&&a.jsx(Ne,{onClick:S,disabled:N===0||T,className:"flex-1",children:T?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Na,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const Q8e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],Z8e=["completed","failed","aborted","printing"];function Bee({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Yt();_.useEffect(()=>{const se=ke=>{ke.key==="Escape"&&e()};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[e]);const i=an(),[s,o]=_.useState(t.print_name||""),[l,c]=_.useState(t.printer_id),[u,d]=_.useState(t.project_id??null),[h,p]=_.useState(t.notes||""),[m,b]=_.useState(t.tags||""),[y,x]=_.useState(t.failure_reason||""),[v,S]=_.useState(t.status),[N,T]=_.useState(t.quantity??1),[M,A]=_.useState(t.photos||[]),[k,R]=_.useState(t.external_url||""),[C,P]=_.useState(!1),[U,F]=_.useState(!1),H=_.useRef(null),D=_.useRef(null),$=_.useRef(null),{data:G}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:I}=it({queryKey:["projects"],queryFn:()=>ae.getProjects()}),{data:K}=it({queryKey:["tags"],queryFn:ae.getTags,enabled:n.length===0}),Q=n.length>0?n:K?.map(se=>se.name)||[],oe=m.split(",").map(se=>se.trim()).filter(Boolean),B=m.includes(",")?m.substring(m.lastIndexOf(",")+1).trim().toLowerCase():m.trim().toLowerCase(),W=Q.filter(se=>!oe.includes(se)&&(B===""||se.toLowerCase().includes(B))),J=se=>{let ke;if(B&&!Q.includes(B)?ke=m.includes(",")?m.substring(0,m.lastIndexOf(",")).split(",").map(Fe=>Fe.trim()).filter(Boolean):[]:ke=oe,!ke.includes(se)){const Fe=[...ke,se].join(", ");b(Fe)}$.current!==null&&clearTimeout($.current),H.current?.focus()},ne=se=>{const ke=oe.filter(Fe=>Fe!==se).join(", ");b(ke)},me=dt({mutationFn:se=>ae.updateArchive(t.id,se),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),fe=async se=>{const ke=se.target.files?.[0];if(ke){P(!0);try{const Fe=await ae.uploadArchivePhoto(t.id,ke);A(Fe.photos),i.invalidateQueries({queryKey:["archives"]})}catch(Fe){console.error("Failed to upload photo:",Fe)}finally{P(!1),D.current&&(D.current.value="")}}},de=async se=>{try{const ke=await ae.deleteArchivePhoto(t.id,se);A(ke.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(ke){console.error("Failed to delete photo:",ke)}},Re=se=>{se.preventDefault();const ke={print_name:s||void 0,printer_id:l,project_id:u,notes:h||void 0,tags:m||void 0,quantity:N,external_url:k||null};v!==t.status&&(ke.status=v),v==="failed"||v==="aborted"?ke.failure_reason=y||void 0:(t.status==="failed"||t.status==="aborted")&&(ke.failure_reason=null),me.mutate(ke)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:se=>se.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Re,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),a.jsx("input",{type:"text",value:s,onChange:se=>o(se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("editArchive.namePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),a.jsxs("select",{value:l??"",onChange:se=>c(se.target.value?Number(se.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noPrinter")}),G?.map(se=>a.jsx("option",{value:se.id,children:se.name},se.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(rs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:u??"",onChange:se=>d(se.target.value?Number(se.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noProject")}),I?.map(se=>a.jsx("option",{value:se.id,children:se.name},se.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(_de,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:N,onChange:se=>T(Math.max(1,parseInt(se.target.value)||1)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),a.jsx("textarea",{value:h,onChange:se=>p(se.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:r("editArchive.notesPlaceholder")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx($y,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:k,onChange:se=>R(se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),oe.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:oe.map(se=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[a.jsx(Th,{className:"w-3 h-3"}),se,a.jsx("button",{type:"button",onClick:()=>ne(se),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Lt,{className:"w-3 h-3"})})]},se))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:H,type:"text",value:m,onChange:se=>b(se.target.value),onFocus:()=>{$.current!==null&&clearTimeout($.current),F(!0)},onBlur:()=>{$.current=window.setTimeout(()=>F(!1),200)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:oe.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),U&&W.length>0&&a.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[a.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[B?r("editArchive.matchingTags",{query:B}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:W.map(se=>a.jsx("button",{type:"button",onClick:()=>J(se),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:se},se))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:v,onChange:se=>{S(se.target.value),se.target.value==="completed"&&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:Z8e.map(se=>a.jsx("option",{value:se,children:r(`editArchive.statuses.${se}`)},se))})]}),(v==="failed"||v==="aborted")&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),a.jsxs("select",{value:y,onChange:se=>x(se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.selectReason")}),Q8e.map(se=>a.jsx("option",{value:r(`editArchive.failureReasons.${se}`),children:r(`editArchive.failureReasons.${se}`)},se))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx($g,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[M.map(se=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:ae.getArchivePhotoUrl(t.id,se),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>de(se),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(ln,{className:"w-3 h-3 text-white"})})]},se)),a.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[a.jsx("input",{ref:D,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:fe,className:"hidden",disabled:C}),C?a.jsx(ct,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(cr,{className:"w-6 h-6 text-bambu-gray"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(Ne,{type:"submit",disabled:me.isPending,className:"flex-1",children:[a.jsx(vs,{className:"w-4 h-4"}),me.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function Hee({x:t,y:e,items:n,onClose:r}){const i=_.useRef(null),[s,o]=_.useState(null),l=_.useRef(null),[c,u]=_.useState({x:t,y:e,visible:!1}),[d,h]=_.useState(!1),[p,m]=_.useState({});_.useEffect(()=>{const x=N=>{i.current&&!i.current.contains(N.target)&&r()},v=N=>{N.key==="Escape"&&r()},S=()=>{r()};return document.addEventListener("mousedown",x),document.addEventListener("keydown",v),document.addEventListener("scroll",S,!0),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",v),document.removeEventListener("scroll",S,!0),l.current&&clearTimeout(l.current)}},[r]),_.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const x=i.current.getBoundingClientRect(),v=window.innerWidth,S=window.innerHeight,N=8;let T=t,M=e;t+x.width>v-N&&(T=Math.max(N,v-x.width-N)),TS-N&&(M=Math.max(N,S-x.height-N)),MA),u({x:T,y:M,visible:!0})}},[t,e]);const b=(x,v)=>{l.current&&(clearTimeout(l.current),l.current=null);const S=v.getBoundingClientRect(),N=window.innerHeight,T=300,k=N-S.top-8T;m(R=>({...R,[x]:k?"bottom":"top"})),o(x)},y=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return a.jsx("div",{ref:i,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:n.map((x,v)=>{if(x.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},v);const S=x.submenu&&x.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:N=>S&&b(v,N.currentTarget),onMouseLeave:()=>S&&y(),children:[a.jsxs("button",{onMouseEnter:N=>S&&b(v,N.currentTarget.parentElement),onClick:()=>{S?o(s===v?null:v):x.disabled||(x.onClick(),r())},disabled:x.disabled,title:x.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${x.disabled?"text-bambu-gray cursor-not-allowed":x.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${S&&s===v?"bg-bambu-dark-tertiary":""}`,children:[x.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:x.icon}),a.jsx("span",{className:"flex-1",children:x.label}),S&&a.jsx(ks,{className:"w-4 h-4 text-bambu-gray"})]}),S&&s===v&&a.jsx("div",{className:`absolute min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${d?"right-full mr-1":"left-full ml-1"} ${p[v]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>y(),children:x.submenu.map((N,T)=>a.jsxs("button",{onClick:()=>{N.disabled||(N.onClick(),r())},disabled:N.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${N.disabled?"text-bambu-gray cursor-not-allowed":N.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[N.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:N.icon}),N.label]},T))})]},v)})})}function J8e({selectedIds:t,existingTags:e,onClose:n}){const r=an(),{showToast:i}=Tn(),[s,o]=_.useState(""),[l,c]=_.useState(new Set),[u,d]=_.useState("add");_.useEffect(()=>{const y=x=>{x.key==="Escape"&&n()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[n]);const h=dt({mutationFn:async()=>{const y=Array.from(l);let x=0;for(const v of t)try{const S=await ae.getArchive(v),N=S.tags?S.tags.split(",").map(M=>M.trim()).filter(Boolean):[];let T;u==="add"?T=[...new Set([...N,...y])]:T=N.filter(M=>!l.has(M)),await ae.updateArchive(v,{tags:T.join(", ")}),x++}catch(S){throw console.error(`Failed to update archive ${v}:`,S),new Error(`Failed on archive ${v}: ${S instanceof Error?S.message:"Unknown error"}`)}return{count:x,mode:u,tags:y}},onSuccess:({count:y,mode:x,tags:v})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${x==="add"?"Added":"Removed"} ${v.length} tag${v.length!==1?"s":""} ${x==="add"?"to":"from"} ${y} archive${y!==1?"s":""}`),n()},onError:y=>{i(y.message||"Failed to update tags","error")}}),p=y=>{c(x=>{const v=new Set(x);return v.has(y)?v.delete(y):v.add(y),v})},m=()=>{s.trim()&&!l.has(s.trim())&&(c(y=>new Set([...y,s.trim()])),o(""))},b=y=>{y.key==="Enter"&&(y.preventDefault(),m())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-md",children:a.jsxs(Et,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Th,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:u==="add"?"Add Tags":"Remove Tags"})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:[u==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ne,{size:"sm",variant:u==="add"?"primary":"secondary",onClick:()=>d("add"),children:"Add Tags"}),a.jsx(Ne,{size:"sm",variant:u==="remove"?"primary":"secondary",onClick:()=>d("remove"),children:"Remove Tags"})]}),u==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:y=>o(y.target.value),onKeyDown:b}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:m,disabled:!s.trim(),children:a.jsx(cr,{className:"w-4 h-4"})})]}),e.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(y=>a.jsx("button",{onClick:()=>p(y),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(y)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:y},y))})]}),l.size>0&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",u==="add"?"add":"remove",":"]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(y=>a.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${u==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[y,a.jsx("button",{onClick:()=>p(y),className:"hover:opacity-70",children:a.jsx(Lt,{className:"w-3 h-3"})})]},y))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ne,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(Ne,{onClick:()=>h.mutate(),disabled:l.size===0||h.isPending,className:"flex-1",children:h.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Th,{className:"w-4 h-4"}),u==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function e6e({selectedIds:t,onClose:e}){const n=an(),{showToast:r}=Tn(),{data:i,isLoading:s}=it({queryKey:["projects"],queryFn:()=>ae.getProjects()});_.useEffect(()=>{const d=h=>{h.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=dt({mutationFn:async d=>(await ae.addArchivesToProject(d,t),d),onSuccess:d=>{const h=i?.find(p=>p.id===d);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${h?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=dt({mutationFn:async()=>{for(const d of t)await ae.updateArchive(d,{project_id:null});return t.length},onSuccess:d=>{o(),r(`Removed ${d} archive${d!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),u=l.isPending||c.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Et,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rs,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:u,children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("button",{onClick:()=>c.mutate(),disabled:u,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:a.jsx(Zi,{className:"w-4 h-4 text-red-400"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&a.jsx(ct,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&a.jsxs("div",{className:"flex items-center gap-2 py-2",children:[a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(d=>a.jsxs("button",{onClick:()=>l.mutate(d.id),disabled:u,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:d.color?`${d.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:a.jsx(rs,{className:"w-4 h-4",style:{color:d.color||"rgb(var(--bambu-green))"}})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:d.name}),a.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[d.archive_count," archive",d.archive_count!==1?"s":"",d.status&&` • ${d.status}`]})]}),l.isPending&&l.variables===d.id&&a.jsx(ct,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},d.id)),(!i||i.length===0)&&a.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:a.jsx(Ne,{variant:"secondary",onClick:e,className:"flex-1",disabled:u,children:"Cancel"})})]})})})}function t6e(t,e){return new Date(t,e+1,0).getDate()}function n6e(t,e){return new Date(t,e,1).getDay()}const r6e=["January","February","March","April","May","June","July","August","September","October","November","December"],i6e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function a6e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,s]=_.useState(r.getMonth()),[o,l]=_.useState(r.getFullYear()),[c,u]=_.useState(null),[d,h]=_.useState(null),p=_.useMemo(()=>{const M=new Map;return t.forEach(A=>{const k=zi(A.completed_at||A.created_at)||new Date,R=`${k.getFullYear()}-${String(k.getMonth()+1).padStart(2,"0")}-${String(k.getDate()).padStart(2,"0")}`,C=M.get(R)||[];C.push(A),M.set(R,C)}),M},[t]),m=t6e(o,i),b=n6e(o,i),y=()=>{i===0?(s(11),l(o-1)):s(i-1)},x=()=>{i===11?(s(0),l(o+1)):s(i+1)},v=()=>{s(r.getMonth()),l(r.getFullYear())},S=[];for(let M=0;M{M!==c&&h(null),u(M)};return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("button",{onClick:y,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Eh,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:[r6e[i]," ",o]}),a.jsx("button",{onClick:v,className:"px-2 py-1 text-xs bg-bambu-dark-tertiary hover:bg-bambu-green/20 text-bambu-gray hover:text-white rounded transition-colors",children:"Today"})]}),a.jsx("button",{onClick:x,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(ks,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:i6e.map(M=>a.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:M},M))}),a.jsx("div",{className:"grid grid-cols-7 gap-1",children:S.map((M,A)=>{if(M===null)return a.jsx("div",{className:"aspect-square"},`empty-${A}`);const k=`${o}-${String(i+1).padStart(2,"0")}-${String(M).padStart(2,"0")}`,R=p.get(k)||[],C=R.length>0,P=M===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),U=k===c,F=R.filter(D=>D.status==="completed").length,H=R.filter(D=>D.status==="failed").length;return a.jsxs("button",{onClick:()=>T(U?null:k),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${U?"bg-bambu-green text-white":P?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":C?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[a.jsx("span",{className:`text-sm font-medium ${P&&!U?"text-bambu-green":""}`,children:M}),C&&a.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${H>0&&F===0?"bg-red-400":H>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:R.length})]})]},M)})}),a.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(M=>{const A=new Date(M.completed_at||M.created_at);return A.getMonth()===i&&A.getFullYear()===o}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(M=>{const A=new Date(M.completed_at||M.created_at);return A.getMonth()===i&&A.getFullYear()===o&&M.status==="completed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(M=>{const A=new Date(M.completed_at||M.created_at);return A.getMonth()===i&&A.getFullYear()===o&&M.status==="failed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),a.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(c+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),N.length>0?a.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:N.map(M=>{const A=M.id===d||M.id===n;return a.jsxs("button",{onClick:()=>{h(M.id),e?.(M)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${A?"":"hover:bg-bambu-dark-tertiary"}`,style:A?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[M.thumbnail_path?a.jsx("img",{src:ae.getArchiveThumbnail(M.id),alt:"",className:"w-12 h-12 rounded object-cover"}):a.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:M.print_name||M.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:M.status==="failed"?"text-red-400":"text-green-400",children:M.status==="failed"?"Failed":"Completed"}),M.filament_color&&a.jsx("div",{className:"flex gap-0.5",children:M.filament_color.split(",").map((k,R)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:k}},R))})]})]})]},M.id)})}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):a.jsx("div",{className:"text-center py-8",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function $ee({archiveId:t,archiveName:e,onClose:n}){const r=ae.getArchiveQRCodeUrl(t,300);_.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const i=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 flex flex-col items-center",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),a.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:a.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),a.jsxs(Ne,{onClick:i,className:"w-full",children:[a.jsx(wi,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function Vee({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[s,o]=_.useState(0),[l,c]=_.useState(!1);if(_.useEffect(()=>{const m=b=>{b.key==="Escape"&&r(),b.key==="ArrowLeft"&&o(y=>Math.max(0,y-1)),b.key==="ArrowRight"&&o(y=>Math.min(n.length-1,y+1))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[r,n.length]),_.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return r(),null;const u=n[s],d=ae.getArchivePhotoUrl(t,u),h=()=>{const m=document.createElement("a");m.href=d,m.download=`${e}_photo_${s+1}.jpg`,m.click()},p=()=>{i&&c(!0)};return a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[a.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:m=>m.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:h,children:[a.jsx(wi,{className:"w-4 h-4"}),"Download"]}),i&&a.jsx(Ne,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:a.jsx(ln,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-6 h-6"})})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&a.jsx("button",{onClick:()=>o(m=>m-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(Eh,{className:"w-8 h-8 text-white"})}),a.jsx("img",{src:d,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),so(m=>m+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(ks,{className:"w-8 h-8 text-white"})})]}),n.length>1&&a.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((m,b)=>a.jsx("button",{onClick:()=>o(b),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${b===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:a.jsx("img",{src:ae.getArchivePhotoUrl(t,m),alt:`Thumbnail ${b+1}`,className:"w-full h-full object-cover"})},m))})]}),l&&a.jsx(er,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(u),c(!1)},onCancel:()=>c(!1)})]})}function za(t){this.content=t}za.prototype={constructor:za,find:function(t){for(var e=0;e>1}};za.from=function(t){if(t instanceof za)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new za(e)};function Gee(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(r),s=e.child(r);if(i==s){n+=i.nodeSize;continue}if(!i.sameMarkup(s))return n;if(i.isText&&i.text!=s.text){for(let o=0;i.text[o]==s.text[o];o++)n++;return n}if(i.content.size||s.content.size){let o=Gee(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function qee(t,e,n,r){for(let i=t.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:n,b:r};let o=t.child(--i),l=e.child(--s),c=o.nodeSize;if(o==l){n-=c,r-=c;continue}if(!o.sameMarkup(l))return{a:n,b:r};if(o.isText&&o.text!=l.text){let u=0,d=Math.min(o.text.length,l.text.length);for(;ue&&r(c,i+l,s||null,o)!==!1&&c.content.size){let d=l+1;c.nodesBetween(Math.max(0,e-d),Math.min(c.content.size,n-d),r,i+d)}l=u}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let s="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let u=l.isText?l.text.slice(Math.max(e,c)-c,n-c):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&u||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=u},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),s=1);se)for(let s=0,o=0;oe&&((on)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,n-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,n-o-1))),r.push(l),i+=l.nodeSize),o=c}return new At(r,i)}cutByIndex(e,n){return e==n?At.empty:e==0&&n==this.content.length?this:new At(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new At(i,s)}addToStart(e){return new At([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new At(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let i=this.child(n),s=r+i.nodeSize;if(s>=e)return s==e?a1(n+1,s):a1(n,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return At.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new At(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return At.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),n.push(this),r=!0),n&&n.push(s)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;nr.type.rank-i.type.rank),n}};Lr.none=[];class gN extends Error{}class $t{constructor(e,n,r){this.content=e,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=Kee(this.content,e+this.openStart,n);return r&&new $t(r,this.openStart,this.openEnd)}removeBetween(e,n){return new $t(Wee(this.content,e+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,n){if(!n)return $t.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new $t(At.fromJSON(e,n.content),r,i)}static maxOpen(e,n=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)i++;return new $t(e,r,i)}}$t.empty=new $t(At.empty,0,0);function Wee(t,e,n){let{index:r,offset:i}=t.findIndex(e),s=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(i==e||s.isText){if(l!=n&&!t.child(o).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=o)throw new RangeError("Removing non-flat range");return t.replaceChild(r,s.copy(Wee(s.content,e-i-1,n-i-1)))}function Kee(t,e,n,r){let{index:i,offset:s}=t.findIndex(e),o=t.maybeChild(i);if(s==e||o.isText)return r&&!r.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=Kee(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function s6e(t,e,n){if(n.openStart>t.depth)throw new gN("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new gN("Inconsistent open depths");return Xee(t,e,n,0)}function Xee(t,e,n,r){let i=t.index(r),s=t.node(r);if(i==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function C0(t,e,n,r){let i=(e||t).node(n),s=0,o=e?e.index(n):i.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(rm(t.nodeAfter,r),s++));for(let l=s;li&&UD(t,e,i+1),o=r.depth>i&&UD(n,r,i+1),l=[];return C0(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(Yee(s,o),rm(im(s,Qee(t,e,n,r,i+1)),l)):(s&&rm(im(s,bN(t,e,i+1)),l),C0(e,n,i,l),o&&rm(im(o,bN(n,r,i+1)),l)),C0(r,null,i,l),new At(l)}function bN(t,e,n){let r=[];if(C0(null,t,n,r),t.depth>n){let i=UD(t,e,n+1);rm(im(i,bN(t,e,n+1)),r)}return C0(e,null,n,r),new At(r)}function o6e(t,e){let n=e.depth-t.openStart,i=e.node(n).copy(t.content);for(let s=n-1;s>=0;s--)i=e.node(s).copy(At.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class My{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(n);return r?e.child(n).cut(r):i}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,n){n=this.resolveDepth(n);let r=this.path[n*3],i=n==0?0:this.path[n*3-1]+1;for(let s=0;s0;n--)if(this.start(n)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!n||n(this.node(r))))return new xN(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],i=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),u=s-c;if(r.push(o,l,i+c),!u||(o=o.child(l),o.isText))break;s=u-1,i+=c+1}return new My(n,r,s)}static resolveCached(e,n){let r=Xq.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Zee(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=At.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=i;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let i=At.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Sh.prototype.text=void 0;class yN extends Sh{constructor(e,n,r,i){if(super(e,n,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Zee(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,n){return this.text.slice(e,n)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new yN(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new yN(this.type,this.attrs,e,this.marks)}cut(e=0,n=this.text.length){return e==0&&n==this.text.length?this:this.withText(this.text.slice(e,n))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Zee(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Em{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new d6e(e,n);if(r.next==null)return Em.empty;let i=Jee(r);r.next&&r.err("Unexpected trailing text");let s=x6e(b6e(i));return y6e(s,r),s}matchType(e){for(let n=0;nu.createAndFill()));for(let u=0;u=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` -`)}}Em.empty=new Em(!0);class d6e{constructor(e,n){this.string=e,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Jee(t){let e=[];do e.push(h6e(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function h6e(t){let e=[];do e.push(f6e(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function f6e(t){let e=g6e(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=m6e(t,e);else break;return e}function Yq(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function m6e(t,e){let n=Yq(t),r=n;return t.eat(",")&&(t.next!="}"?r=Yq(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function p6e(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let s in n){let o=n[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function g6e(t){if(t.eat("(")){let e=Jee(t);return t.eat(")")||t.err("Missing closing paren"),e}else if(/\W/.test(t.next))t.err("Unexpected token '"+t.next+"'");else{let e=p6e(t,t.next).map(n=>(t.inline==null?t.inline=n.isInline:t.inline!=n.isInline&&t.err("Mixing inline and block content"),{type:"name",value:n}));return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function b6e(t){let e=[[]];return i(s(t,0),n()),e;function n(){return e.push([])-1}function r(o,l,c){let u={term:c,to:l};return e[o].push(u),u}function i(o,l){o.forEach(c=>c.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((c,u)=>c.concat(s(u,l)),[]);if(o.type=="seq")for(let c=0;;c++){let u=s(o.exprs[c],l);if(c==o.exprs.length-1)return u;i(u,l=n())}else if(o.type=="star"){let c=n();return r(l,c),i(s(o.expr,c),c),[r(c)]}else if(o.type=="plus"){let c=n();return i(s(o.expr,l),c),i(s(o.expr,c),c),[r(c)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let c=l;for(let u=0;u{t[o].forEach(({term:l,to:c})=>{if(!l)return;let u;for(let d=0;d{u||i.push([l,u=[]]),u.indexOf(d)==-1&&u.push(d)})})});let s=e[r.join(",")]=new Em(r.indexOf(t.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:nte(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Sh(this,this.computeAttrs(e),At.from(n),Lr.setFrom(r))}createChecked(e=null,n,r){return n=At.from(n),this.checkContent(n),new Sh(this,this.computeAttrs(e),n,Lr.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=At.from(n),n.size){let o=this.contentMatch.fillBefore(n);if(!o)return null;n=o.append(n)}let i=this.contentMatch.matchFragment(n),s=i&&i.fillBefore(At.empty,!0);return s?new Sh(this,e,n.append(s),Lr.setFrom(r)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;nr[s]=new ate(s,n,o));let i=n.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function v6e(t,e,n){let r=n.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${s}`)}}class w6e{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?v6e(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class DM{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=ite(e,i.attrs),this.excluded=null;let s=tte(this.attrs);this.instance=s?new Lr(this,s):null}create(e=null){return!e&&this.instance?this.instance:new Lr(this,nte(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new DM(s,i++,n,o)),r}removeFromSet(e){for(var n=0;n-1}}class ste{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let i in e)n[i]=e[i];n.nodes=za.from(e.nodes),n.marks=za.from(e.marks||{}),this.nodes=Zq.compile(this.spec.nodes,this),this.marks=DM.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Em.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Jq(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Jq(this,o.split(" "))}this.nodeFromJSON=i=>Sh.fromJSON(this,i),this.markFromJSON=i=>Lr.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Zq){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(n,r,i)}text(e,n){let r=this.nodes.text;return new yN(r,r.defaultAttrs,e,Lr.setFrom(n))}mark(e,n){return typeof e=="string"&&(e=this.marks[e]),e.create(n)}nodeType(e){let n=this.nodes[e];if(!n)throw new RangeError("Unknown node type: "+e);return n}}function Jq(t,e){let n=[];for(let r=0;r-1)&&n.push(o=c)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function _6e(t){return t.tag!=null}function S6e(t){return t.style!=null}let P0=class HD{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(_6e(i))this.tags.push(i);else if(S6e(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,n={}){let r=new t7(this,n,!1);return r.addAll(e,Lr.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new t7(this,n,!0);return r.addAll(e,Lr.none,n.from,n.to),$t.maxOpen(r.finish())}matchTag(e,n,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=n))){if(o.getAttrs){let c=o.getAttrs(n);if(c===!1)continue;o.attrs=c||void 0}return o}}}static schemaRules(e){let n=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=n7(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=n7(o)),o.node||o.ignore||o.mark||(o.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new HD(e,HD.schemaRules(e)))}};const ote={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},N6e={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},lte={ol:!0,ul:!0},Ey=1,$D=2,j0=4;function e7(t,e,n){return e!=null?(e?Ey:0)|(e==="full"?$D:0):t&&t.whitespace=="pre"?Ey|$D:n&~j0}class s1{constructor(e,n,r,i,s,o){this.type=e,this.attrs=n,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=Lr.none,this.match=s||(o&j0?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(At.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&Ey)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let n=At.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(At.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!ote.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class t7{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=n.topNode,s,o=e7(null,n.preserveWhitespace,0)|(r?j0:0);i?s=new s1(i.type,i.attrs,Lr.none,!0,n.topMatch||i.type.contentMatch,o):r?s=new s1(null,null,Lr.none,!0,null,o):s=new s1(e.schema.topNodeType,null,Lr.none,!0,null,o),this.nodes=[s],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,n){e.nodeType==3?this.addTextNode(e,n):e.nodeType==1&&this.addElement(e,n)}addTextNode(e,n){let r=e.nodeValue,i=this.top,s=i.options&$D?"full":this.localPreserveWS||(i.options&Ey)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` -`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let c=0;c!c.clearMark(u)):n=n.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)l=c;else break}}return n}addElementByRule(e,n,r,i){let s,o;if(n.node)if(o=this.parser.schema.nodes[n.node],o.isLeaf)this.insertNode(o.create(n.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let c=this.enter(o,n.attrs||null,r,n.preserveWhitespace);c&&(s=!0,r=c)}else{let c=this.parser.schema.marks[n.mark];r=r.concat(c.create(n.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(c=>this.insertNode(c,r,!1));else{let c=e;typeof n.contentElement=="string"?c=e.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(e):n.contentElement&&(c=n.contentElement),this.findAround(e,c,!0),this.addAll(c,r),this.findAround(e,c,!1)}s&&this.sync(l)&&this.open--}addAll(e,n,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,n);this.findAtPoint(e,s)}findPlace(e,n,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let c=this.nodes[o],u=c.findWrapping(e);if(u&&(!i||i.length>u.length+l)&&(i=u,s=c,!u.length))break;if(c.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(u.type):r7(u.type,e))?(c=u.addToSet(c),!1):!0),this.nodes.push(new s1(e,n,c,i,null,l)),this.open++,r}closeExtra(e=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let n=this.open;n>=0;n--){if(this.nodes[n]==e)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=Ey)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let n=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,c)=>{for(;l>=0;l--){let u=n[l];if(u==""){if(l==n.length-1||l==0)continue;for(;c>=s;c--)if(o(l-1,c))return!0;return!1}else{let d=c>0||c==0&&i?this.nodes[c].type:r&&c>=s?r.node(c-s).type:null;if(!d||d.name!=u&&!d.isInGroup(u))return!1;c--}}return!0};return o(n.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let n=e.depth;n>=0;n--){let r=e.node(n).contentMatchAt(e.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function k6e(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&<e.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function M6e(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function n7(t){let e={};for(let n in t)e[n]=t[n];return e}function r7(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(t))continue;let s=[],o=l=>{s.push(l);for(let c=0;c{if(s.length||o.marks.length){let l=0,c=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,n);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,n,r={}){let i=this.marks[e.type.name];return i&&B1(_P(r),i(e,n),null,e.attrs)}static renderSpec(e,n,r=null,i){return B1(e,n,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new zm(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=i7(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return i7(e.marks)}}function i7(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function _P(t){return t.document||window.document}const a7=new WeakMap;function E6e(t){let e=a7.get(t);return e===void 0&&a7.set(t,e=T6e(t)),e}function T6e(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(n=i.slice(0,o),i=i.slice(o+1));let l,c=n?t.createElementNS(n,i):t.createElement(i),u=e[1],d=1;if(u&&typeof u=="object"&&u.nodeType==null&&!Array.isArray(u)){d=2;for(let h in u)if(u[h]!=null){let p=h.indexOf(" ");p>0?c.setAttributeNS(h.slice(0,p),h.slice(p+1),u[h]):h=="style"&&c.style?c.style.cssText=u[h]:c.setAttribute(h,u[h])}}for(let h=d;hd)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:m,contentDOM:b}=B1(t,p,n,r);if(c.appendChild(m),b){if(l)throw new RangeError("Multiple content holes");l=b}}}return{dom:c,contentDOM:l}}const cte=65535,ute=Math.pow(2,16);function A6e(t,e){return t+e*ute}function s7(t){return t&cte}function C6e(t){return(t-(t&cte))/ute}const dte=1,hte=2,H1=4,fte=8;class VD{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&fte)>0}get deletedBefore(){return(this.delInfo&(dte|H1))>0}get deletedAfter(){return(this.delInfo&(hte|H1))>0}get deletedAcross(){return(this.delInfo&H1)>0}}class bo{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&bo.empty)return bo.empty}recover(e){let n=0,r=s7(e);if(!this.inverted)for(let i=0;ie)break;let u=this.ranges[l+s],d=this.ranges[l+o],h=c+u;if(e<=h){let p=u?e==c?-1:e==h?1:n:n,m=c+i+(p<0?0:d);if(r)return m;let b=e==(n<0?c:h)?null:A6e(l/3,e-c),y=e==c?hte:e==h?dte:H1;return(n<0?e!=c:e!=h)&&(y|=fte),new VD(m,y,b)}i+=d-u}return r?e+i:new VD(e+i,0,null)}touches(e,n){let r=0,i=s7(n),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let u=this.ranges[l+s],d=c+u;if(e<=d&&l==i*3)return!0;r+=this.ranges[l+o]-u}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;n--){let i=e.getMirror(n);this.appendMap(e._maps[n].invert(),i!=null&&i>n?r-i-1:void 0)}}invert(){let e=new Ty;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let r=this.from;rs&&c!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),n.openStart,n.openEnd);return Hi.fromReplace(e,this.from,this.to,s)}invert(){return new Fl(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new uh(n.pos,r.pos,this.mark)}merge(e){return e instanceof uh&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new uh(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new uh(n.from,n.to,e.markFromJSON(n.mark))}}cs.jsonID("addMark",uh);class Fl extends cs{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=new $t(j4(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return Hi.fromReplace(e,this.from,this.to,r)}invert(){return new uh(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Fl(n.pos,r.pos,this.mark)}merge(e){return e instanceof Fl&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Fl(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new Fl(n.from,n.to,e.markFromJSON(n.mark))}}cs.jsonID("removeMark",Fl);class dh extends cs{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return Hi.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Hi.fromReplace(e,this.pos,this.pos+1,new $t(At.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let i=0;ir.pos?null:new _a(n.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new _a(n.from,n.to,n.gapFrom,n.gapTo,$t.fromJSON(e,n.slice),n.insert,!!n.structure)}}cs.jsonID("replaceAround",_a);function GD(t,e,n){let r=t.resolve(e),i=n-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function P6e(t,e,n,r){let i=[],s=[],o,l;t.doc.nodesBetween(e,n,(c,u,d)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&d.type.allowsMarkType(r.type)){let p=Math.max(u,e),m=Math.min(u+c.nodeSize,n),b=r.addToSet(h);for(let y=0;yt.step(c)),s.forEach(c=>t.step(c))}function j6e(t,e,n,r){let i=[],s=0;t.doc.nodesBetween(e,n,(o,l)=>{if(!o.isInline)return;s++;let c=null;if(r instanceof DM){let u=o.marks,d;for(;d=r.isInSet(u);)(c||(c=[])).push(d),u=d.removeFromSet(u)}else r?r.isInSet(o.marks)&&(c=[r]):c=o.marks;if(c&&c.length){let u=Math.min(l+o.nodeSize,n);for(let d=0;dt.step(new Fl(o.from,o.to,o.style)))}function D4(t,e,n,r=n.contentMatch,i=!0){let s=t.doc.nodeAt(e),o=[],l=e+1;for(let c=0;c=0;c--)t.step(o[c])}function D6e(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function Ub(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,s=0;;--r){let o=t.$from.node(r),l=t.$from.index(r)+i,c=t.$to.indexAfter(r)-s;if(rn;b--)y||r.index(b)>0?(y=!0,d=At.from(r.node(b).copy(d)),h++):c--;let p=At.empty,m=0;for(let b=s,y=!1;b>n;b--)y||i.after(b+1)=0;o--){if(r.size){let l=n[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=At.from(n[o].type.create(n[o].attrs,r))}let i=e.start,s=e.end;t.step(new _a(i,s,i,s,new $t(r,0,0),n.length,!0))}function I6e(t,e,n,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=t.steps.length;t.doc.nodesBetween(e,n,(o,l)=>{let c=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,c)&&z6e(t.doc,t.mapping.slice(s).map(l),r)){let u=null;if(r.schema.linebreakReplacement){let m=r.whitespace=="pre",b=!!r.contentMatch.matchType(r.schema.linebreakReplacement);m&&!b?u=!1:!m&&b&&(u=!0)}u===!1&&pte(t,o,l,s),D4(t,t.mapping.slice(s).map(l,1),r,void 0,u===null);let d=t.mapping.slice(s),h=d.map(l,1),p=d.map(l+o.nodeSize,1);return t.step(new _a(h,p,h+1,p-1,new $t(At.from(r.create(c,null,o.marks)),0,0),1,!0)),u===!0&&mte(t,o,l,s),!1}})}function mte(t,e,n,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let c=t.mapping.slice(r).map(n+1+s+o.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function pte(t,e,n,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=t.mapping.slice(r).map(n+1+s);t.replaceWith(o,o+1,e.type.schema.text(` -`))}})}function z6e(t,e,n){let r=t.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function U6e(t,e,n,r,i){let s=t.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");n||(n=s.type);let o=n.create(r,null,i||s.marks);if(s.isLeaf)return t.replaceWith(e,e+s.nodeSize,o);if(!n.validContent(s.content))throw new RangeError("Invalid content for node type "+n.name);t.step(new _a(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new $t(At.from(o),0,0),1,!0))}function Lu(t,e,n=1,r){let i=t.resolve(e),s=i.depth-n,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let u=i.depth-1,d=n-2;u>s;u--,d--){let h=i.node(u),p=i.index(u);if(h.type.spec.isolating)return!1;let m=h.content.cutByIndex(p,h.childCount),b=r&&r[d+1];b&&(m=m.replaceChild(0,b.type.create(b.attrs)));let y=r&&r[d]||h;if(!h.canReplace(p+1,h.childCount)||!y.type.validContent(m))return!1}let l=i.indexAfter(s),c=r&&r[0];return i.node(s).canReplaceWith(l,l,c?c.type:i.node(s+1).type)}function B6e(t,e,n=1,r){let i=t.doc.resolve(e),s=At.empty,o=At.empty;for(let l=i.depth,c=i.depth-n,u=n-1;l>c;l--,u--){s=At.from(i.node(l).copy(s));let d=r&&r[u];o=At.from(d?d.type.create(d.attrs,o):i.node(l).copy(o))}t.step(new va(e,e,new $t(s.append(o),n,n),!0))}function qh(t,e){let n=t.resolve(e),r=n.index();return gte(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function H6e(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&>e(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=n<0?r.before(i):r.after(i)}}function $6e(t,e,n){let r=null,{linebreakReplacement:i}=t.doc.type.schema,s=t.doc.resolve(e-n),o=s.node().type;if(i&&o.inlineContent){let d=o.whitespace=="pre",h=!!o.contentMatch.matchType(i);d&&!h?r=!1:!d&&h&&(r=!0)}let l=t.steps.length;if(r===!1){let d=t.doc.resolve(e+n);pte(t,d.node(),d.before(),l)}o.inlineContent&&D4(t,e+n-1,o,s.node().contentMatchAt(s.index()),r==null);let c=t.mapping.slice(l),u=c.map(e-n);if(t.step(new va(u,c.map(e+n,-1),$t.empty,!0)),r===!0){let d=t.doc.resolve(u);mte(t,d.node(),d.before(),t.steps.length)}return t}function V6e(t,e,n){let r=t.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),n))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,n))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,n))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,c=r.index(o)+(l>0?1:0),u=r.node(o),d=!1;if(s==1)d=u.canReplace(c,c,i);else{let h=u.contentMatchAt(c).findWrapping(i.firstChild.type);d=h&&u.canReplaceWith(c,c,h[0])}if(d)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function OM(t,e,n=e,r=$t.empty){if(e==n&&!r.size)return null;let i=t.resolve(e),s=t.resolve(n);return xte(i,s,r)?new va(e,n,r):new G6e(i,s,r).fit()}function xte(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class G6e{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=At.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=At.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let u=this.findFittable();u?this.placeNodes(u):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let c=new $t(s,o,l);return e>-1?new _a(r.pos,e,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new va(r.pos,i.pos,c):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}n=s.content}for(let n=1;n<=2;n++)for(let r=n==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=NP(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:c,match:u}=this.frontier[l],d,h=null;if(n==1&&(o?u.matchType(o.type)||(h=u.fillBefore(At.from(o),!1)):s&&c.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:h};if(n==2&&o&&(d=u.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:d};if(s&&u.matchType(s.type))break}}}openMore(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=NP(e,n);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new $t(e,n+1,Math.max(r,i.size+n>=e.size-r?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=NP(e,n);if(i.childCount<=1&&n>0){let s=e.size-n<=n+i.size;this.unplaced=new $t(p0(e,n-1,1),n-1,s?n-1:r)}else this.unplaced=new $t(p0(e,n,1),n,r)}placeNodes({sliceDepth:e,frontierDepth:n,parent:r,inject:i,wrap:s}){for(;this.depth>n;)this.closeFrontierNode();if(s)for(let y=0;y1||c==0||y.content.size)&&(h=x,d.push(yte(y.mark(p.allowedMarks(y.marks)),u==1?c:0,u==l.childCount?m:-1)))}let b=u==l.childCount;b||(m=-1),this.placed=g0(this.placed,n,At.from(d)),this.frontier[n].match=h,b&&m<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let y=0,x=l;y1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:i}=this.frontier[n],s=n=0;l--){let{match:c,type:u}=this.frontier[l],d=kP(e,l,u,c,!0);if(!d||d.childCount)continue e}return{depth:n,fit:o,move:s?e.doc.resolve(e.after(n+1)):e}}}}close(e){let n=this.findCloseLevel(e);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=g0(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,n=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=g0(this.placed,this.depth,At.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(At.empty,!0);n.childCount&&(this.placed=g0(this.placed,this.frontier.length,n))}}function p0(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(p0(t.firstChild.content,e-1,n)))}function g0(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(g0(t.lastChild.content,e-1,n)))}function NP(t,e){for(let n=0;n1&&(r=r.replaceChild(0,yte(r.firstChild,e-1,r.childCount==1?n-1:0))),e>0&&(r=t.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(At.empty,!0)))),t.copy(r)}function kP(t,e,n,r,i){let s=t.node(e),o=i?t.indexAfter(e):t.index(e);if(o==s.childCount&&!n.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!q6e(n,s.content,o)?l:null}function q6e(t,e,n){for(let r=n;r0;p--,m--){let b=i.node(p).type.spec;if(b.defining||b.definingAsContext||b.isolating)break;o.indexOf(p)>-1?l=p:i.before(p)==m&&o.splice(1,0,-p)}let c=o.indexOf(l),u=[],d=r.openStart;for(let p=r.content,m=0;;m++){let b=p.firstChild;if(u.push(b),m==r.openStart)break;p=b.content}for(let p=d-1;p>=0;p--){let m=u[p],b=W6e(m.type);if(b&&!m.sameMarkup(i.node(Math.abs(l)-1)))d=p;else if(b||!m.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let m=(p+d+1)%(r.openStart+1),b=u[m];if(b)for(let y=0;y=0&&(t.replace(e,n,r),!(t.steps.length>h));p--){let m=o[p];m<0||(e=i.before(m),n=s.after(m))}}function vte(t,e,n,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(t).append(t);t=o.append(s.matchFragment(o).fillBefore(At.empty,!0))}return t}function X6e(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let i=V6e(t.doc,e,r.type);i!=null&&(e=n=i)}t.replaceRange(e,n,new $t(At.from(r),0,0))}function Y6e(t,e,n){let r=t.doc.resolve(e),i=t.doc.resolve(n),s=wte(r,i);for(let o=0;o0&&(c||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return t.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&n>r.end(o)&&i.end(o)-n!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return t.delete(r.before(o),n);t.delete(e,n)}function wte(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let i=r;i>=0;i--){let s=t.start(i);if(se.pos+(e.depth-i)||t.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==t.depth&&i==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&n.push(i)}return n}class Ig extends cs{constructor(e,n,r){super(),this.pos=e,this.attr=n,this.value=r}apply(e){let n=e.nodeAt(this.pos);if(!n)return Hi.fail("No node at attribute step's position");let r=Object.create(null);for(let s in n.attrs)r[s]=n.attrs[s];r[this.attr]=this.value;let i=n.type.create(r,null,n.marks);return Hi.fromReplace(e,this.pos,this.pos+1,new $t(At.from(i),0,n.isLeaf?0:1))}getMap(){return bo.empty}invert(e){return new Ig(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Ig(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Ig(n.pos,n.attr,n.value)}}cs.jsonID("attr",Ig);class Ay extends cs{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let i in e.attrs)n[i]=e.attrs[i];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return Hi.ok(r)}getMap(){return bo.empty}invert(e){return new Ay(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Ay(n.attr,n.value)}}cs.jsonID("docAttr",Ay);let db=class extends Error{};db=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};db.prototype=Object.create(Error.prototype);db.prototype.constructor=db;db.prototype.name="TransformError";class _te{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new Ty}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new db(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,r=$t.empty){let i=OM(this.doc,e,n,r);return i&&this.step(i),this}replaceWith(e,n,r){return this.replace(e,n,new $t(At.from(r),0,0))}delete(e,n){return this.replace(e,n,$t.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return K6e(this,e,n,r),this}replaceRangeWith(e,n,r){return X6e(this,e,n,r),this}deleteRange(e,n){return Y6e(this,e,n),this}lift(e,n){return R6e(this,e,n),this}join(e,n=1){return $6e(this,e,n),this}wrap(e,n){return F6e(this,e,n),this}setBlockType(e,n=e,r,i=null){return I6e(this,e,n,r,i),this}setNodeMarkup(e,n,r=null,i){return U6e(this,e,n,r,i),this}setNodeAttribute(e,n,r){return this.step(new Ig(e,n,r)),this}setDocAttribute(e,n){return this.step(new Ay(e,n)),this}addNodeMark(e,n){return this.step(new dh(e,n)),this}removeNodeMark(e,n){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(n instanceof Lr)n.isInSet(r.marks)&&this.step(new Tm(e,n));else{let i=r.marks,s,o=[];for(;s=n.isInSet(i);)o.push(new Tm(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,n=1,r){return B6e(this,e,n,r),this}addMark(e,n,r){return P6e(this,e,n,r),this}removeMark(e,n,r){return j6e(this,e,n,r),this}clearIncompatible(e,n,r){return D4(this,e,n,r),this}}const MP=Object.create(null);class Fn{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new Q6e(e.min(n),e.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let n=0;n=0;s--){let o=n<0?hg(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):hg(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,n,r);if(o)return o}return null}static near(e,n=1){return this.findFrom(e,n)||this.findFrom(e,-n)||new ko(e.node(0))}static atStart(e){return hg(e,e,0,0,1)||new ko(e)}static atEnd(e){return hg(e,e,e.content.size,e.childCount,-1)||new ko(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=MP[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in MP)throw new RangeError("Duplicate use of selection JSON ID "+e);return MP[e]=n,n.prototype.jsonID=e,n}getBookmark(){return yn.between(this.$anchor,this.$head).getBookmark()}}Fn.prototype.visible=!0;class Q6e{constructor(e,n){this.$from=e,this.$to=n}}let l7=!1;function c7(t){!l7&&!t.parent.inlineContent&&(l7=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class yn extends Fn{constructor(e,n=e){c7(e),c7(n),super(e,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return Fn.near(r);let i=e.resolve(n.map(this.anchor));return new yn(i.parent.inlineContent?i:r,r)}replace(e,n=$t.empty){if(super.replace(e,n),n==$t.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof yn&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new LM(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new yn(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let i=e.resolve(n);return new this(i,r==n?i:e.resolve(r))}static between(e,n,r){let i=e.pos-n.pos;if((!r||i)&&(r=i>=0?1:-1),!n.parent.inlineContent){let s=Fn.findFrom(n,r,!0)||Fn.findFrom(n,-r,!0);if(s)n=s.$head;else return Fn.near(n,r)}return e.parent.inlineContent||(i==0?e=n:(e=(Fn.findFrom(e,-r,!0)||Fn.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&rn.isSelectable(l))return rn.create(t,n-(i<0?l.nodeSize:0))}else{let c=hg(t,l,n+i,i<0?l.childCount:0,i,s);if(c)return c}n+=l.nodeSize*i}return null}function u7(t,e,n){let r=t.steps.length-1;if(r{o==null&&(o=d)}),t.setSelection(Fn.near(t.doc.resolve(o),n))}const d7=1,o1=2,h7=4;class J6e extends _te{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=o1,this}ensureMarks(e){return Lr.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&o1)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~o1,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,n=!0){let r=this.selection;return n&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||Lr.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let i=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=n),!e)return this.deleteRange(n,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(n);s=r==n?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,i.text(e,s)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(Fn.near(this.selection.$to)),this}}setMeta(e,n){return this.meta[typeof e=="string"?e:e.key]=n,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=h7,this}get scrolledIntoView(){return(this.updated&h7)>0}}function f7(t,e){return!e||!t?t:t.bind(e)}class b0{constructor(e,n,r){this.name=e,this.init=f7(n.init,r),this.apply=f7(n.apply,r)}}const eHe=[new b0("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new b0("selection",{init(t,e){return t.selection||Fn.atStart(e.doc)},apply(t){return t.selection}}),new b0("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new b0("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class EP{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=eHe.slice(),n&&n.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new b0(r.key,r.spec.state,r))})}}class Ng{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,n=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(n[r]=s.toJSON.call(i,this[i.key]))}return n}static fromJSON(e,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new EP(e.schema,e.plugins),s=new Ng(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=Sh.fromJSON(e.schema,n.doc);else if(o.name=="selection")s.selection=Fn.fromJSON(s.doc,n.selection);else if(o.name=="storedMarks")n.storedMarks&&(s.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let c=r[l],u=c.spec.state;if(c.key==o.name&&u&&u.fromJSON&&Object.prototype.hasOwnProperty.call(n,l)){s[o.name]=u.fromJSON.call(c,e,n[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ste(t,e,n){for(let r in t){let i=t[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ste(i,e,{})),n[r]=i}return n}class di{constructor(e){this.spec=e,this.props={},e.props&&Ste(e.props,this,this.props),this.key=e.key?e.key.key:Nte("plugin")}getState(e){return e[this.key]}}const TP=Object.create(null);function Nte(t){return t in TP?t+"$"+ ++TP[t]:(TP[t]=0,t+"$")}class ca{constructor(e="key"){this.key=Nte(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const L4=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function kte(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const Mte=(t,e,n)=>{let r=kte(t,n);if(!r)return!1;let i=F4(r);if(!i){let o=r.blockRange(),l=o&&Ub(o);return l==null?!1:(e&&e(t.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Ote(t,i,e,-1))return!0;if(r.parent.content.size==0&&(hb(s,"end")||rn.isSelectable(s)))for(let o=r.depth;;o--){let l=OM(t.doc,r.before(o),r.after(o),$t.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(t.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},tHe=(t,e,n)=>{let r=kte(t,n);if(!r)return!1;let i=F4(r);return i?Ete(t,i,e):!1},nHe=(t,e,n)=>{let r=Ate(t,n);if(!r)return!1;let i=I4(r);return i?Ete(t,i,e):!1};function Ete(t,e,n){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let d=i.lastChild;if(!d)return!1;i=d}let o=e.nodeAfter,l=o,c=e.pos+1;for(;!l.isTextblock;c++){if(l.type.spec.isolating)return!1;let d=l.firstChild;if(!d)return!1;l=d}let u=OM(t.doc,s,c,$t.empty);if(!u||u.from!=s||u instanceof va&&u.slice.size>=c-s)return!1;if(n){let d=t.tr.step(u);d.setSelection(yn.create(d.doc,s)),n(d.scrollIntoView())}return!0}function hb(t,e,n=!1){for(let r=t;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}const Tte=(t,e,n)=>{let{$head:r,empty:i}=t.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;s=F4(r)}let o=s&&s.nodeBefore;return!o||!rn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(rn.create(t.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function F4(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function Ate(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset{let r=Ate(t,n);if(!r)return!1;let i=I4(r);if(!i)return!1;let s=i.nodeAfter;if(Ote(t,i,e,1))return!0;if(r.parent.content.size==0&&(hb(s,"start")||rn.isSelectable(s))){let o=OM(t.doc,r.before(),r.after(),$t.empty);if(o&&o.slice.size{let{$head:r,empty:i}=t.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset=0;e--){let n=t.node(e);if(t.index(e)+1{let n=t.selection,r=n instanceof rn,i;if(r){if(n.node.isTextblock||!qh(t.doc,n.from))return!1;i=n.from}else if(i=RM(t.doc,n.from,-1),i==null)return!1;if(e){let s=t.tr.join(i);r&&s.setSelection(rn.create(s.doc,i-t.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},iHe=(t,e)=>{let n=t.selection,r;if(n instanceof rn){if(n.node.isTextblock||!qh(t.doc,n.to))return!1;r=n.to}else if(r=RM(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},aHe=(t,e)=>{let{$from:n,$to:r}=t.selection,i=n.blockRange(r),s=i&&Ub(i);return s==null?!1:(e&&e(t.tr.lift(i,s).scrollIntoView()),!0)},jte=(t,e)=>{let{$head:n,$anchor:r}=t.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(e&&e(t.tr.insertText(` -`).scrollIntoView()),!0)};function z4(t){for(let e=0;e{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),s=n.indexAfter(-1),o=z4(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=n.after(),c=t.tr.replaceWith(l,l,o.createAndFill());c.setSelection(Fn.near(c.doc.resolve(l),1)),e(c.scrollIntoView())}return!0},Dte=(t,e)=>{let n=t.selection,{$from:r,$to:i}=n;if(n instanceof ko||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=z4(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let s=n.before();if(Lu(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),i=r&&Ub(r);return i==null?!1:(e&&e(t.tr.lift(r,i).scrollIntoView()),!0)};function oHe(t){return(e,n)=>{let{$from:r,$to:i}=e.selection;if(e.selection instanceof rn&&e.selection.node.isBlock)return!r.parentOffset||!Lu(e.doc,r.pos)?!1:(n&&n(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let s=[],o,l,c=!1,u=!1;for(let m=r.depth;;m--)if(r.node(m).isBlock){c=r.end(m)==r.pos+(r.depth-m),u=r.start(m)==r.pos-(r.depth-m),l=z4(r.node(m-1).contentMatchAt(r.indexAfter(m-1))),s.unshift(c&&l?{type:l}:null),o=m;break}else{if(m==1)return!1;s.unshift(null)}let d=e.tr;(e.selection instanceof yn||e.selection instanceof ko)&&d.deleteSelection();let h=d.mapping.map(r.pos),p=Lu(d.doc,h,s.length,s);if(p||(s[0]=l?{type:l}:null,p=Lu(d.doc,h,s.length,s)),!p)return!1;if(d.split(h,s.length,s),!c&&u&&r.node(o).type!=l){let m=d.mapping.map(r.before(o)),b=d.doc.resolve(m);l&&r.node(o-1).canReplaceWith(b.index(),b.index()+1,l)&&d.setNodeMarkup(d.mapping.map(r.before(o)),l)}return n&&n(d.scrollIntoView()),!0}}const lHe=oHe(),cHe=(t,e)=>{let{$from:n,to:r}=t.selection,i,s=n.sharedDepth(r);return s==0?!1:(i=n.before(s),e&&e(t.tr.setSelection(rn.create(t.doc,i))),!0)};function uHe(t,e,n){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(n&&n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||qh(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function Ote(t,e,n,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,c=i.type.spec.isolating||s.type.spec.isolating;if(!c&&uHe(t,e,n))return!0;let u=!c&&e.parent.canReplace(e.index(),e.index()+1);if(u&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(n){let m=e.pos+s.nodeSize,b=At.empty;for(let v=o.length-1;v>=0;v--)b=At.from(o[v].create(null,b));b=At.from(i.copy(b));let y=t.tr.step(new _a(e.pos-1,m,e.pos,m,new $t(b,1,0),o.length,!0)),x=y.doc.resolve(m+2*o.length);x.nodeAfter&&x.nodeAfter.type==i.type&&qh(y.doc,x.pos)&&y.join(x.pos),n(y.scrollIntoView())}return!0}let d=s.type.spec.isolating||r>0&&c?null:Fn.findFrom(e,1),h=d&&d.$from.blockRange(d.$to),p=h&&Ub(h);if(p!=null&&p>=e.depth)return n&&n(t.tr.lift(h,p).scrollIntoView()),!0;if(u&&hb(s,"start",!0)&&hb(i,"end")){let m=i,b=[];for(;b.push(m),!m.isTextblock;)m=m.lastChild;let y=s,x=1;for(;!y.isTextblock;y=y.firstChild)x++;if(m.canReplace(m.childCount,m.childCount,y.content)){if(n){let v=At.empty;for(let N=b.length-1;N>=0;N--)v=At.from(b[N].copy(v));let S=t.tr.step(new _a(e.pos-b.length,e.pos+s.nodeSize,e.pos+x,e.pos+s.nodeSize-x,new $t(v,b.length,0),0,!0));n(S.scrollIntoView())}return!0}}return!1}function Lte(t){return function(e,n){let r=e.selection,i=t<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(n&&n(e.tr.setSelection(yn.create(e.doc,t<0?i.start(s):i.end(s)))),!0):!1}}const dHe=Lte(-1),hHe=Lte(1);function fHe(t,e=null){return function(n,r){let{$from:i,$to:s}=n.selection,o=i.blockRange(s),l=o&&R4(o,t,e);return l?(r&&r(n.tr.wrap(o,l).scrollIntoView()),!0):!1}}function m7(t,e=null){return function(n,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!c.isTextblock||c.hasMarkup(t,e)))if(c.type==t)i=!0;else{let d=n.doc.resolve(u),h=d.index();i=d.parent.canReplaceWith(h,h+1,t)}})}if(!i)return!1;if(r){let s=n.tr;for(let o=0;o=2&&e.$from.node(e.depth-1).type.compatibleContent(n)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let c=o.resolve(e.start-2);s=new xN(c,c,e.depth),e.endIndex=0;d--)s=At.from(n[d].type.create(n[d].attrs,s));t.step(new _a(e.start-(r?2:0),e.end,e.start,e.end,new $t(s,0,0),n.length,!0));let o=0;for(let d=0;do.childCount>0&&o.firstChild.type==t);return s?n?r.node(s.depth-1).type==t?xHe(e,n,t,s):yHe(e,n,s):!0:!1}}function xHe(t,e,n,r){let i=t.tr,s=r.end,o=r.$to.end(r.depth);sy;b--)m-=i.child(b).nodeSize,r.delete(m-1,m+1);let s=r.doc.resolve(n.start),o=s.nodeAfter;if(r.mapping.map(n.end)!=n.start+s.nodeAfter.nodeSize)return!1;let l=n.startIndex==0,c=n.endIndex==i.childCount,u=s.node(-1),d=s.index(-1);if(!u.canReplace(d+(l?0:1),d+1,o.content.append(c?At.empty:At.from(i))))return!1;let h=s.pos,p=h+o.nodeSize;return r.step(new _a(h-(l?1:0),p+(c?1:0),h+1,p-1,new $t((l?At.empty:At.from(i.copy(At.empty))).append(c?At.empty:At.from(i.copy(At.empty))),l?0:1,c?0:1),l?0:1)),e(r.scrollIntoView()),!0}function vHe(t){return function(e,n){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,u=>u.childCount>0&&u.firstChild.type==t);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,c=l.child(o-1);if(c.type!=t)return!1;if(n){let u=c.lastChild&&c.lastChild.type==l.type,d=At.from(u?t.create():null),h=new $t(At.from(t.create(null,At.from(l.type.create(null,d)))),u?3:1,0),p=s.start,m=s.end;n(e.tr.step(new _a(p-(u?3:1),m,p,m,h,1,!0)).scrollIntoView())}return!0}}const $a=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},fb=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let qD=null;const pu=function(t,e,n){let r=qD||(qD=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},wHe=function(){qD=null},Am=function(t,e,n,r){return n&&(p7(t,e,n,r,-1)||p7(t,e,n,r,1))},_He=/^(img|br|input|textarea|hr)$/i;function p7(t,e,n,r,i){for(var s;;){if(t==n&&e==r)return!0;if(e==(i<0?0:rl(t))){let o=t.parentNode;if(!o||o.nodeType!=1||_v(t)||_He.test(t.nodeName)||t.contentEditable=="false")return!1;e=$a(t)+(i<0?0:1),t=o}else if(t.nodeType==1){let o=t.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else t=o,e=i<0?rl(t):0}else return!1}}function rl(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function SHe(t,e){for(;;){if(t.nodeType==3&&e)return t;if(t.nodeType==1&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=rl(t)}else if(t.parentNode&&!_v(t))e=$a(t),t=t.parentNode;else return null}}function NHe(t,e){for(;;){if(t.nodeType==3&&e2),Qo=mb||(Sc?/Mac/.test(Sc.platform):!1),THe=Sc?/Win/.test(Sc.platform):!1,Eu=/Android \d/.test(Wh),Sv=!!g7&&"webkitFontSmoothing"in g7.documentElement.style,AHe=Sv?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function CHe(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function lu(t,e){return typeof t=="number"?t:t[e]}function PHe(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function b7(t,e,n){let r=t.someProp("scrollThreshold")||0,i=t.someProp("scrollMargin")||5,s=t.dom.ownerDocument;for(let o=n||t.dom;o;){if(o.nodeType!=1){o=fb(o);continue}let l=o,c=l==s.body,u=c?CHe(s):PHe(l),d=0,h=0;if(e.topu.bottom-lu(r,"bottom")&&(h=e.bottom-e.top>u.bottom-u.top?e.top+lu(i,"top")-u.top:e.bottom-u.bottom+lu(i,"bottom")),e.leftu.right-lu(r,"right")&&(d=e.right-u.right+lu(i,"right")),d||h)if(c)s.defaultView.scrollBy(d,h);else{let m=l.scrollLeft,b=l.scrollTop;h&&(l.scrollTop+=h),d&&(l.scrollLeft+=d);let y=l.scrollLeft-m,x=l.scrollTop-b;e={left:e.left-y,top:e.top-x,right:e.right-y,bottom:e.bottom-x}}let p=c?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(p))break;o=p=="absolute"?o.offsetParent:fb(o)}}function jHe(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=n+1;o=n-20){r=l,i=c.top;break}}return{refDOM:r,refTop:i,stack:zte(t.dom)}}function zte(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=fb(r));return e}function DHe({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;Ute(n,r==0?0:r-e)}function Ute(t,e){for(let n=0;n=l){o=Math.max(b.bottom,o),l=Math.min(b.top,l);let y=b.left>e.left?b.left-e.left:b.right=(b.left+b.right)/2?1:0));continue}}else b.top>e.top&&!c&&b.left<=e.left&&b.right>=e.left&&(c=d,u={left:Math.max(b.left,Math.min(b.right,e.left)),top:b.top});!n&&(e.left>=b.right&&e.top>=b.top||e.left>=b.left&&e.top>=b.bottom)&&(s=h+1)}}return!n&&c&&(n=c,i=u,r=0),n&&n.nodeType==3?OHe(n,i):!n||r&&n.nodeType==1?{node:t,offset:s}:Bte(n,i)}function OHe(t,e){let n=t.nodeValue.length,r=document.createRange();for(let i=0;i=(s.left+s.right)/2?1:0)}}return{node:t,offset:0}}function B4(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function LHe(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left(o.left+o.right)/2?1:-1}return t.docView.posFromDOM(r,i,s)}function IHe(t,e,n,r){let i=-1;for(let s=e,o=!1;s!=t.dom;){let l=t.docView.nearestDesc(s,!0),c;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((c=l.dom.getBoundingClientRect()).width||c.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&c.left>r.left||c.top>r.top?i=l.posBefore:(!o&&c.right-1?i:t.docView.posFromDOM(e,n,-1)}function Hte(t,e,n){let r=t.childNodes.length;if(r&&n.tope.top&&i++}let u;Sv&&i&&r.nodeType==1&&(u=r.childNodes[i-1]).nodeType==1&&u.contentEditable=="false"&&u.getBoundingClientRect().top>=e.top&&i--,r==t.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=t.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=IHe(t,r,i,e))}l==null&&(l=FHe(t,o,e));let c=t.docView.nearestDesc(o,!0);return{pos:l,inside:c?c.posAtStart-c.border:-1}}function x7(t){return t.top=0&&i==r.nodeValue.length?(c--,d=1):n<0?c--:u++,i0(Kd(pu(r,c,u),d),d<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(n<0||i==rl(r))){let c=r.childNodes[i-1];if(c.nodeType==1)return AP(c.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(n<0||i==rl(r))){let c=r.childNodes[i-1],u=c.nodeType==3?pu(c,rl(c)-(o?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(u)return i0(Kd(u,1),!1)}if(s==null&&i=0)}function i0(t,e){if(t.width==0)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function AP(t,e){if(t.height==0)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function Vte(t,e,n){let r=t.state,i=t.root.activeElement;r!=e&&t.updateState(e),i!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),i!=t.dom&&i&&i.focus()}}function BHe(t,e,n){let r=e.selection,i=n=="up"?r.$from:r.$to;return Vte(t,e,()=>{let{node:s}=t.docView.domFromPos(i.pos,n=="up"?-1:1);for(;;){let l=t.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=$te(t,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let c;if(l.nodeType==1)c=l.getClientRects();else if(l.nodeType==3)c=pu(l,0,l.nodeValue.length).getClientRects();else continue;for(let u=0;ud.top+1&&(n=="up"?o.top-d.top>(d.bottom-o.top)*2:d.bottom-o.bottom>(o.bottom-d.top)*2))return!1}}return!0})}const HHe=/[\u0590-\u08ac]/;function $He(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=t.domSelection();return l?!HHe.test(r.parent.textContent)||!l.modify?n=="left"||n=="backward"?s:o:Vte(t,e,()=>{let{focusNode:c,focusOffset:u,anchorNode:d,anchorOffset:h}=t.domSelectionRange(),p=l.caretBidiLevel;l.modify("move",n,"character");let m=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:b,focusOffset:y}=t.domSelectionRange(),x=b&&!m.contains(b.nodeType==1?b:b.parentNode)||c==b&&u==y;try{l.collapse(d,h),c&&(c!=d||u!=h)&&l.extend&&l.extend(c,u)}catch{}return p!=null&&(l.caretBidiLevel=p),x}):r.pos==r.start()||r.pos==r.end()}let y7=null,v7=null,w7=!1;function VHe(t,e,n){return y7==e&&v7==n?w7:(y7=e,v7=n,w7=n=="up"||n=="down"?BHe(t,e,n):$He(t,e,n))}const cl=0,_7=1,Vf=2,Nc=3;class Nv{constructor(e,n,r,i){this.parent=e,this.children=n,this.dom=r,this.contentDOM=i,this.dirty=cl,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,n,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let n=0;n$a(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&n==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!n||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let n=e.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(e,n,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;ne||o instanceof qte){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,n);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof Gte&&s.side>=0;r--);if(n<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&n&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,n):{node:this.contentDOM,offset:s?$a(s.dom)+1:0}}else{let s,o=!0;for(;s=r=d&&n<=u-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(e,n,d);e=o;for(let h=l;h>0;h--){let p=this.children[h-1];if(p.size&&p.dom.parentNode==this.contentDOM&&!p.emptyChildAt(1)){i=$a(p.dom)+1;break}e-=p.size}i==-1&&(i=0)}if(i>-1&&(u>n||l==this.children.length-1)){n=u;for(let d=l+1;db&&on){let b=l;l=c,c=b}let m=document.createRange();m.setEnd(c.node,c.offset),m.setStart(l.node,l.offset),u.removeAllRanges(),u.addRange(m)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,n){for(let r=0,i=0;i=r:er){let l=r+s.border,c=o-s.border;if(e>=l&&n<=c){this.dirty=e==r||n==o?Vf:_7,e==l&&n==c&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=Nc:s.markDirty(e-l,n-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Vf:Nc}r=o}this.dirty=Vf}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?Vf:_7;n.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!n.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.contentEditable="false",o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=n,this.widget=n,s=this}matchesWidget(e){return this.dirty==cl&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let n=this.widget.spec.stopEvent;return n?n(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class GHe extends Nv{constructor(e,n,r,i){super(e,[],n,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Cm extends Nv{constructor(e,n,r,i,s){super(e,[],r,i),this.mark=n,this.spec=s}static create(e,n,r,i){let s=i.nodeViews[n.type.name],o=s&&s(n,i,r);return(!o||!o.dom)&&(o=zm.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new Cm(e,n,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&Nc||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Nc&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=cl){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=QD(s,0,e,r));for(let l=0;l{if(!c)return o;if(c.parent)return c.parent.posBeforeChild(c)},r,i),d=u&&u.dom,h=u&&u.contentDOM;if(n.isText){if(!d)d=document.createTextNode(n.text);else if(d.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else d||({dom:d,contentDOM:h}=zm.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!h&&!n.isText&&d.nodeName!="BR"&&(d.hasAttribute("contenteditable")||(d.contentEditable="false"),n.type.spec.draggable&&(d.draggable=!0));let p=d;return d=Xte(d,r,n),u?c=new qHe(e,n,r,i,d,h||null,p,u,s,o+1):n.isText?new IM(e,n,r,i,d,p,s):new kh(e,n,r,i,d,h||null,p,s,o+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>At.empty)}return e}matchesNode(e,n,r){return this.dirty==cl&&e.eq(this.node)&&vN(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,n){let r=this.node.inlineContent,i=n,s=e.composing?this.localCompositionInfo(e,n):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,c=new KHe(this,o&&o.node,e);QHe(this.node,this.innerDeco,(u,d,h)=>{u.spec.marks?c.syncToMarks(u.spec.marks,r,e):u.type.side>=0&&!h&&c.syncToMarks(d==this.node.childCount?Lr.none:this.node.child(d).marks,r,e),c.placeWidget(u,e,i)},(u,d,h,p)=>{c.syncToMarks(u.marks,r,e);let m;c.findNodeMatch(u,d,h,p)||l&&e.state.selection.from>i&&e.state.selection.to-1&&c.updateNodeAt(u,d,h,m,e)||c.updateNextNode(u,d,h,e,p,i)||c.addNode(u,d,h,e,i),i+=u.nodeSize}),c.syncToMarks([],r,e),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==Vf)&&(o&&this.protectLocalComposition(e,o),Wte(this.contentDOM,this.children,e),mb&&ZHe(this.dom))}localCompositionInfo(e,n){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof yn)||rn+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=JHe(this.node.content,o,r-n,i-n);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:n,pos:r,text:i}){if(this.getDesc(n))return;let s=n;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new GHe(this,s,n,i);e.input.compositionNodes.push(o),this.children=QD(this.children,r,r+i.length,e,o)}update(e,n,r,i){return this.dirty==Nc||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,i),!0)}updateInner(e,n,r,i){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=cl}updateOuterDeco(e){if(vN(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Kte(this.dom,this.nodeDOM,YD(this.outerDeco,this.node,n),YD(e,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function S7(t,e,n,r,i){Xte(r,e,t);let s=new kh(void 0,t,e,n,r,r,r,i,0);return s.contentDOM&&s.updateChildren(i,0),s}class IM extends kh{constructor(e,n,r,i,s,o,l){super(e,n,r,i,s,null,o,l,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,n,r,i){return this.dirty==Nc||this.dirty!=cl&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=cl||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=cl,!0)}inParent(){let e=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,n,r){return e==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(e,n,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,n,r){let i=this.node.cut(e,n),s=document.createTextNode(i.text);return new IM(this.parent,i,this.outerDeco,this.innerDeco,s,s,r)}markDirty(e,n){super.markDirty(e,n),this.dom!=this.nodeDOM&&(e==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=Nc)}get domAtom(){return!1}isText(e){return this.node.text==e}}class qte extends Nv{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==cl&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class qHe extends kh{constructor(e,n,r,i,s,o,l,c,u,d){super(e,n,r,i,s,o,l,u,d),this.spec=c}update(e,n,r,i){if(this.dirty==Nc)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,n,r);return s&&this.updateInner(e,n,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,i){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function Wte(t,e,n){let r=t.firstChild,i=!1;for(let s=0;s>1,o=Math.min(s,e.length);for(;i-1)l>this.index&&(this.changed=!0,this.destroyBetween(this.index,l)),this.top=this.top.children[this.index];else{let c=Cm.create(this.top,e[s],n,r);this.top.children.splice(this.index,0,c),this.top=c,this.changed=!0}this.index=0,s++}}findNodeMatch(e,n,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,n,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,c=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let u=n.children[r-1];if(u instanceof Cm)n=u,r=u.children.length;else{l=u,r--;break}}else{if(n==e)break e;r=n.parent.children.indexOf(n),n=n.parent}let c=l.node;if(c){if(c!=t.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function YHe(t,e){return t.type.side-e.type.side}function QHe(t,e,n,r){let i=e.locals(t),s=0;if(i.length==0){for(let u=0;us;)l.push(i[o++]);let b=s+p.nodeSize;if(p.isText){let x=b;o!x.inline):l.slice();r(p,y,e.forChild(s,p),m),s=b}}function ZHe(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function JHe(t,e,n,r){for(let i=0,s=0;i=n){if(s>=r&&c.slice(r-e.length-l,r-l)==e)return r-e.length;let u=l=0&&u+e.length+l>=n)return l+u;if(n==r&&c.length>=r+e.length-l&&c.slice(r-l,r-l+e.length)==e)return r}}return-1}function QD(t,e,n,r,i){let s=[];for(let o=0,l=0;o=n||d<=e?s.push(c):(un&&s.push(c.slice(n-u,c.size,r)))}return s}function H4(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let i=t.docView.nearestDesc(n.focusNode),s=i&&i.size==0,o=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(o<0)return null;let l=r.resolve(o),c,u;if(FM(n)){for(c=o;i&&!i.node;)i=i.parent;let h=i.node;if(i&&h.isAtom&&rn.isSelectable(h)&&i.parent&&!(h.isInline&&kHe(n.focusNode,n.focusOffset,i.dom))){let p=i.posBefore;u=new rn(o==p?l:r.resolve(p))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=o,p=o;for(let m=0;m{(n.anchorNode!=r||n.anchorOffset!=i)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Yte(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function t$e(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,$a(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&Ks&&Nh<=11&&(n.disabled=!0,n.disabled=!1)}function Qte(t,e){if(e instanceof rn){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(T7(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else T7(t)}function T7(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function $4(t,e,n,r){return t.someProp("createSelectionBetween",i=>i(t,e,n))||yn.between(e,n,r)}function A7(t){return t.editable&&!t.hasFocus()?!1:Zte(t)}function Zte(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function n$e(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Am(e.node,e.offset,n.anchorNode,n.anchorOffset)}function ZD(t,e){let{$anchor:n,$head:r}=t.selection,i=e>0?n.max(r):n.min(r),s=i.parent.inlineContent?i.depth?t.doc.resolve(e>0?i.after():i.before()):null:i;return s&&Fn.findFrom(s,e)}function Jd(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function C7(t,e,n){let r=t.state.selection;if(r instanceof yn)if(n.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=t.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Jd(t,new yn(r.$anchor,o))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let i=ZD(t.state,e);return i&&i instanceof rn?Jd(t,i):!1}else if(!(Qo&&n.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=t.docView.descAt(l))&&!o.contentDOM?rn.isSelectable(s)?Jd(t,new rn(e<0?t.state.doc.resolve(i.pos-s.nodeSize):i)):Sv?Jd(t,new yn(t.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof rn&&r.node.isInline)return Jd(t,new yn(e>0?r.$to:r.$from));{let i=ZD(t.state,e);return i?Jd(t,i):!1}}}function wN(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function R0(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function ag(t,e){return e<0?r$e(t):i$e(t)}function r$e(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i,s,o=!1;for(ll&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let l=n.childNodes[r-1];if(R0(l,-1))i=n,s=--r;else if(l.nodeType==3)n=l,r=n.nodeValue.length;else break}}else{if(Jte(n))break;{let l=n.previousSibling;for(;l&&R0(l,-1);)i=n.parentNode,s=$a(l),l=l.previousSibling;if(l)n=l,r=wN(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}o?JD(t,n,r):i&&JD(t,i,s)}function i$e(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i=wN(n),s,o;for(;;)if(r{t.state==i&&Fu(t)},50)}function P7(t,e){let n=t.state.doc.resolve(e);if(!(ns||THe)&&n.parent.inlineContent){let i=t.coordsAtPos(e);if(e>n.start()){let s=t.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function j7(t,e,n){let r=t.state.selection;if(r instanceof yn&&!r.empty||n.indexOf("s")>-1||Qo&&n.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let o=ZD(t.state,e);if(o&&o instanceof rn)return Jd(t,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof ko?Fn.near(o,e):Fn.findFrom(o,e);return l?Jd(t,l):!1}return!1}function D7(t,e){if(!(t.state.selection instanceof yn))return!0;let{$head:n,$anchor:r,empty:i}=t.state.selection;if(!n.sameParent(r))return!0;if(!i)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(s&&!s.isText){let o=t.state.tr;return e<0?o.delete(n.pos-s.nodeSize,n.pos):o.delete(n.pos,n.pos+s.nodeSize),t.dispatch(o),!0}return!1}function R7(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function o$e(t){if(!Ts||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&e.nodeType==1&&n==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;R7(t,r,"true"),setTimeout(()=>R7(t,r,"false"),20)}return!1}function l$e(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function c$e(t,e){let n=e.keyCode,r=l$e(e);if(n==8||Qo&&n==72&&r=="c")return D7(t,-1)||ag(t,-1);if(n==46&&!e.shiftKey||Qo&&n==68&&r=="c")return D7(t,1)||ag(t,1);if(n==13||n==27)return!0;if(n==37||Qo&&n==66&&r=="c"){let i=n==37?P7(t,t.state.selection.from)=="ltr"?-1:1:-1;return C7(t,i,r)||ag(t,i)}else if(n==39||Qo&&n==70&&r=="c"){let i=n==39?P7(t,t.state.selection.from)=="ltr"?1:-1:1;return C7(t,i,r)||ag(t,i)}else{if(n==38||Qo&&n==80&&r=="c")return j7(t,-1,r)||ag(t,-1);if(n==40||Qo&&n==78&&r=="c")return o$e(t)||j7(t,1,r)||ag(t,1);if(r==(Qo?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function V4(t,e){t.someProp("transformCopied",m=>{e=m(e,t)});let n=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let m=r.firstChild;n.push(m.type.name,m.attrs!=m.type.defaultAttrs?m.attrs:null),r=m.content}let o=t.someProp("clipboardSerializer")||zm.fromSchema(t.state.schema),l=ane(),c=l.createElement("div");c.appendChild(o.serializeFragment(r,{document:l}));let u=c.firstChild,d,h=0;for(;u&&u.nodeType==1&&(d=ine[u.nodeName.toLowerCase()]);){for(let m=d.length-1;m>=0;m--){let b=l.createElement(d[m]);for(;c.firstChild;)b.appendChild(c.firstChild);c.appendChild(b),h++}u=c.firstChild}u&&u.nodeType==1&&u.setAttribute("data-pm-slice",`${i} ${s}${h?` -${h}`:""} ${JSON.stringify(n)}`);let p=t.someProp("clipboardTextSerializer",m=>m(e,t))||e.content.textBetween(0,e.content.size,` + `,title:S("printers:control")?b(jt?"printers.resume":"printers.pause"):b("printers.permission.noControl"),children:[jt?a.jsx(Eo,{className:"w-3 h-3"}):a.jsx(Sk,{className:"w-3 h-3"}),b(jt?"printers.resume":"printers.pause")]})]})]})]})})(),Ye&&Ye.length>0&&r==="expanded"&&(()=>{const gt=Ye.filter(Nt=>Nt.tray.length>1),jt=Ye.filter(Nt=>Nt.tray.length===1),gn=t.nozzle_count===2||Te?.temperatures?.nozzle_2!==void 0;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:b("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[gt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:gt.map(Nt=>{const un=et[String(Nt.id)],In=Nt.id>=128?Nt.id-128:Nt.id,rr=un!==void 0?un:In,ua=rr===1,Si=rr===0;return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"text-[10px] text-white font-medium",children:Gd(Nt.id,Nt.tray.length)}),gn&&(ua||Si)&&a.jsx(zq,{side:ua?"L":"R"})]}),(Nt.humidity!=null||Nt.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[Nt.humidity!=null&&a.jsx(Bq,{humidity:Nt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>ke({amsId:Nt.id,amsLabel:Gd(Nt.id,Nt.tray.length),mode:"humidity"}),compact:!0}),Nt.temp!=null&&a.jsx(Hq,{temp:Nt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>ke({amsId:Nt.id,amsLabel:Gd(Nt.id,Nt.tray.length),mode:"temperature"}),compact:!0})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(Jt=>{const wn=Nt.tray[Jt]||Nt.tray.find(Qr=>Qr.id===Jt),Ea=wn?.tray_type&&wn.remain>=0,Ta=!wn?.tray_type,si=Nt.id*4+Jt,yl=ye===si,Pc=wn?.tray_info_idx?Ge?.[wn.tray_info_idx]:null,us=ze?.[si],ds=wn?.tray_uuid?.toUpperCase(),jc=ds?c?.[ds]:void 0,hs=yP(jc),Po=Ea&&wn.remain>0?wn.remain:hs??(Ea?wn.remain:null),Aa=Ea&&wn.remain===0&&hs!==null?"spoolman":"ams",_r=wn?.tray_type?{vendor:vP(wn)?"Bambu Lab":"Generic",profile:Pc?.name||us?.preset_name||wn.tray_sub_brands||wn.tray_type,colorName:mP(wn.tray_id_name)||pP(wn.tray_color),colorHex:wn.tray_color||null,kFactor:gP(wn.k),fillLevel:Po,trayUuid:wn.tray_uuid||null,fillSource:Aa}:null,da=he?.amsId===Nt.id&&he?.slotId===Jt,eo=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ta?"opacity-50":""} ${yl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:wn?.tray_color?`#${wn.tray_color}`:wn?.tray_type?"#333":"transparent",borderColor:Ta?"#666":"rgba(255,255,255,0.1)",borderStyle:Ta?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:wn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Po!==null&&Po>=0&&wn?a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Po}%`,backgroundColor:xP(Po)}}):wn?.tray_type?a.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"}):null})]});return a.jsxs("div",{className:"relative group",children:[da&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Or,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Te?.state!=="RUNNING"&&a.jsx("button",{onClick:Qr=>{Qr.stopPropagation(),cn(Zt?.amsId===Nt.id&&Zt?.slotId===Jt?null:{amsId:Nt.id,slotId:Jt})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:b("printers.slotOptions"),children:a.jsx(mh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Te?.state!=="RUNNING"&&Zt?.amsId===Nt.id&&Zt?.slotId===Jt&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${S("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Qr=>{Qr.stopPropagation(),S("printers:ams_rfid")&&(nt.mutate({amsId:Nt.id,slotId:Jt}),cn(null))},disabled:da||!S("printers:ams_rfid"),title:S("printers:ams_rfid")?void 0:b("printers.permission.noAmsRfid"),children:[a.jsx(Or,{className:`w-3 h-3 ${da?"animate-spin":""}`}),b("printers.rfid.reread")]})}),_r?a.jsx(fP,{data:_r,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:_r.trayUuid?c?.[_r.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&_r.trayUuid?Qr=>{ce({trayUuid:Qr,trayInfo:{type:_r.profile,color:_r.colorHex||"",location:`${Gd(Nt.id,Nt.tray.length)} Slot ${Jt+1}`}})}:void 0},configureSlot:{enabled:S("printers:control"),onConfigure:()=>V({amsId:Nt.id,trayId:Jt,trayCount:Nt.tray.length,trayType:wn?.tray_type||void 0,trayColor:wn?.tray_color||void 0,traySubBrands:wn?.tray_sub_brands||void 0,trayInfoIdx:wn?.tray_info_idx||void 0})},children:eo}):a.jsx(Oq,{configureSlot:{enabled:S("printers:control"),onConfigure:()=>V({amsId:Nt.id,trayId:Jt,trayCount:Nt.tray.length})},children:eo})]},Jt)})})]},Nt.id)})}),(jt.length>0||Te.vt_tray&&Te.vt_tray.tray_type)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[jt.map(Nt=>{const un=et[String(Nt.id)],In=Nt.id>=128?Nt.id-128:Nt.id,rr=un!==void 0?un:In,ua=rr===1,Si=rr===0,Jt=Nt.tray[0],wn=Jt?.tray_type&&Jt.remain>=0,Ea=!Jt?.tray_type,Ta=Nt.id*4+(Jt?.id??0),si=ye===Ta,yl=Jt?.tray_info_idx?Ge?.[Jt.tray_info_idx]:null,Pc=ze?.[Ta],us=Jt?.tray_uuid?.toUpperCase(),ds=us?c?.[us]:void 0,jc=yP(ds),hs=wn&&Jt.remain>0?Jt.remain:jc??(wn?Jt.remain:null),Po=wn&&Jt.remain===0&&jc!==null?"spoolman":"ams",Aa=Jt?.tray_type?{vendor:vP(Jt)?"Bambu Lab":"Generic",profile:yl?.name||Pc?.preset_name||Jt.tray_sub_brands||Jt.tray_type,colorName:mP(Jt.tray_id_name)||pP(Jt.tray_color),colorHex:Jt.tray_color||null,kFactor:gP(Jt.k),fillLevel:hs,trayUuid:Jt.tray_uuid||null,fillSource:Po}:null,_r=Jt?.id??0,da=he?.amsId===Nt.id&&he?.slotId===_r,eo=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ea?"opacity-50":""} ${si?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:Jt?.tray_color?`#${Jt.tray_color}`:Jt?.tray_type?"#333":"transparent",borderColor:Ea?"#666":"rgba(255,255,255,0.1)",borderStyle:Ea?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Jt?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:hs!==null&&hs>=0?a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${hs}%`,backgroundColor:xP(hs)}}):Jt?.tray_type?a.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"}):null})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[a.jsx("span",{className:"text-[10px] text-white font-medium",children:Gd(Nt.id,Nt.tray.length)}),gn&&(ua||Si)&&a.jsx(zq,{side:ua?"L":"R"})]}),a.jsxs("div",{className:"flex gap-1.5",children:[a.jsxs("div",{className:"relative group flex-1",children:[da&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Or,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Te?.state!=="RUNNING"&&a.jsx("button",{onClick:Qr=>{Qr.stopPropagation(),cn(Zt?.amsId===Nt.id&&Zt?.slotId===_r?null:{amsId:Nt.id,slotId:_r})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:b("printers.slotOptions"),children:a.jsx(mh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Te?.state!=="RUNNING"&&Zt?.amsId===Nt.id&&Zt?.slotId===_r&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${S("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Qr=>{Qr.stopPropagation(),S("printers:ams_rfid")&&(nt.mutate({amsId:Nt.id,slotId:_r}),cn(null))},disabled:da||!S("printers:ams_rfid"),title:S("printers:ams_rfid")?void 0:b("printers.permission.noAmsRfid"),children:[a.jsx(Or,{className:`w-3 h-3 ${da?"animate-spin":""}`}),b("printers.rfid.reread")]})}),Aa?a.jsx(fP,{data:Aa,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Aa.trayUuid?c?.[Aa.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&Aa.trayUuid?Qr=>{ce({trayUuid:Qr,trayInfo:{type:Aa.profile,color:Aa.colorHex||"",location:Gd(Nt.id,Nt.tray.length)}})}:void 0},configureSlot:{enabled:S("printers:control"),onConfigure:()=>V({amsId:Nt.id,trayId:_r,trayCount:Nt.tray.length,trayType:Jt?.tray_type||void 0,trayColor:Jt?.tray_color||void 0,traySubBrands:Jt?.tray_sub_brands||void 0,trayInfoIdx:Jt?.tray_info_idx||void 0})},children:eo}):a.jsx(Oq,{configureSlot:{enabled:S("printers:control"),onConfigure:()=>V({amsId:Nt.id,trayId:_r,trayCount:Nt.tray.length})},children:eo})]}),(Nt.humidity!=null||Nt.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0",children:[Nt.temp!=null&&a.jsx(Hq,{temp:Nt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>ke({amsId:Nt.id,amsLabel:Gd(Nt.id,Nt.tray.length),mode:"temperature"}),compact:!0}),Nt.humidity!=null&&a.jsx(Bq,{humidity:Nt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>ke({amsId:Nt.id,amsLabel:Gd(Nt.id,Nt.tray.length),mode:"humidity"}),compact:!0})]})]})]},Nt.id)}),Te.vt_tray&&Te.vt_tray.tray_type&&(()=>{const Nt=Te.vt_tray,un=ye===254,In=Nt.tray_info_idx?Ge?.[Nt.tray_info_idx]:null,rr=ze?.[1020],ua=Nt.tray_uuid?.toUpperCase(),Si=ua?c?.[ua]:void 0,Jt=yP(Si),wn={vendor:vP(Nt)?"Bambu Lab":"Generic",profile:In?.name||rr?.preset_name||Nt.tray_sub_brands||Nt.tray_type||"Unknown",colorName:mP(Nt.tray_id_name)||pP(Nt.tray_color),colorHex:Nt.tray_color||null,kFactor:gP(Nt.k),fillLevel:Jt,trayUuid:Nt.tray_uuid||null,fillSource:Jt!==null?"spoolman":void 0},Ea=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center cursor-default ${un?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:Nt.tray_color?`#${Nt.tray_color}`:"#333",borderColor:un?"var(--accent)":"rgba(255,255,255,0.1)"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Nt.tray_type||"Spool"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Jt!==null?a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Jt}%`,backgroundColor:xP(Jt)}}):a.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"})})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsx("div",{className:"flex items-center gap-1 mb-2",children:a.jsx("span",{className:"text-[10px] text-white font-medium",children:b("printers.external")})}),a.jsx(fP,{data:wn,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:wn.trayUuid?c?.[wn.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&wn.trayUuid?Ta=>{ce({trayUuid:Ta,trayInfo:{type:wn.profile,color:wn.colorHex||"",location:"External Spool"}})}:void 0},configureSlot:{enabled:S("printers:control"),onConfigure:()=>V({amsId:255,trayId:0,trayCount:1,trayType:Nt.tray_type||void 0,trayColor:Nt.tray_color||void 0,traySubBrands:Nt.tray_sub_brands||void 0,trayInfoIdx:Nt.tray_info_idx||void 0})},children:Ea})]})})()]})]})]})})()]}),Qe&&r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(Ah,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:Qe.name}),at&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${at.state==="ON"?"bg-bambu-green/20 text-bambu-green":at.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[at.state||"?",at.state==="ON"&&at.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",at.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>G(!0),disabled:kn.isPending||at?.state==="ON"||!S("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${S("smart_plugs:control")?at?.state==="ON"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:S("smart_plugs:control")?void 0:b("printers.permission.noSmartPlugControl"),children:[a.jsx(Ju,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>K(!0),disabled:kn.isPending||at?.state==="OFF"||!S("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${S("smart_plugs:control")?at?.state==="OFF"?"bg-red-500/30 text-red-400":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:S("smart_plugs:control")?void 0:b("printers.permission.noSmartPlugControl"),children:[a.jsx(Nk,{className:"w-3 h-3"}),"Off"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx("span",{className:`text-xs hidden sm:inline ${Qe.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:Qe.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>Bn.mutate(!Qe.auto_off),disabled:Bn.isPending||Qe.auto_off_executed||!S("smart_plugs:control"),title:S("smart_plugs:control")?Qe.auto_off_executed?b("printers.autoOffExecuted"):b("printers.autoOffAfterPrint"):b("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${S("smart_plugs:control")?Qe.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":Qe.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:a.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${Qe.auto_off||Qe.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),yt&&yt.length>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[a.jsx(Hy,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:yt.map(gt=>a.jsxs("button",{onClick:()=>Hr.mutate(gt.id),disabled:Hr.isPending,title:`Run ${gt.ha_entity_id}`,className:"px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1",children:[a.jsx(Eo,{className:"w-2.5 h-2.5"}),gt.name]},gt.id))})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[a.jsxs("div",{className:"text-xs text-bambu-gray",children:[a.jsx("p",{children:t.ip_address}),a.jsx("p",{className:"truncate",children:t.serial_number})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>ht.mutate(!Te?.chamber_light),disabled:!Te?.connected||ht.isPending||!S("printers:control"),title:S("printers:control")?Te?.chamber_light?b("printers.chamberLightOff"):b("printers.chamberLightOn"):b("printers.permission.noControl"),className:Te?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30 border-yellow-500/30":"",children:a.jsx(MO,{on:Te?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>{if(h==="embedded"&&p)p(t.id,t.name);else{const gt=localStorage.getItem("cameraWindowState"),jt=gt?JSON.parse(gt):{width:640,height:400},gn=[`width=${jt.width}`,`height=${jt.height}`,jt.left!==void 0?`left=${jt.left}`:"",jt.top!==void 0?`top=${jt.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,gn)}},disabled:!Te?.connected,title:b(h==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"),children:a.jsx(KR,{className:"w-4 h-4"})}),a.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[a.jsx(Ne,{variant:"secondary",size:"sm",onClick:Tt,disabled:!Te?.connected||mt.isPending||!S("printers:update"),title:S("printers:update")?t.plate_detection_enabled?b("printers.plateDetection.enabledClick"):b("printers.plateDetection.disabledClick"):b("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:mt.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(nS,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:mn,disabled:!Te?.connected||X||!S("printers:update"),title:S("printers:update")?b("printers.plateDetection.manageCalibration"):b("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:X?a.jsx(ct,{className:"w-3 h-3 animate-spin"}):a.jsx(fr,{className:"w-3 h-3"})})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>F(!0),disabled:!S("printers:files"),title:S("printers:files")?b("printers.browseFiles"):b("printers.permission.noFiles"),children:[a.jsx(Sb,{className:"w-4 h-4"}),"Files"]})]})]})]}),U&&a.jsx(tMe,{printerId:t.id,printerName:t.name,onClose:()=>F(!1)}),H&&a.jsx(oMe,{printerId:t.id,printerName:t.name,onClose:()=>D(!1)}),q&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Bt(),children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:gt=>gt.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[q.needs_calibration?a.jsx(nS,{className:"w-5 h-5 text-blue-500"}):q.is_empty?a.jsx(mr,{className:"w-5 h-5 text-green-500"}):a.jsx(Zi,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),q.reference_count!==void 0&&q.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[q.reference_count,"/",q.max_references," refs"]})]}),a.jsx("button",{onClick:()=>Bt(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[q.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[a.jsx("p",{className:"font-medium text-blue-400",children:b("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:b("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:b("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:b("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${q.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[a.jsx("p",{className:`font-medium ${q.is_empty?"text-green-400":"text-yellow-400"}`,children:q.is_empty?b("printers.plateDetection.plateEmpty"):b("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[b("printers.plateDetection.confidence"),": ",Math.round(q.confidence*100),"% | ",b("printers.plateDetection.difference"),": ",q.difference_percent.toFixed(1),"%"]})]}),q.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:b("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:q.debug_image_url,alt:b("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:b("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:q.message})]}),xt&&xt.references.length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:b("printers.plateDetection.savedReferences",{count:xt.references.length,max:xt.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:xt.references.map(gt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:ae.getPlateReferenceThumbnailUrl(t.id,gt.index),alt:gt.label||`Reference ${gt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),a.jsx("button",{onClick:()=>jn(gt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:b("printers.plateDetection.deleteReference"),children:a.jsx(Lt,{className:"w-3 h-3 text-white"})}),Ct?.index===gt.index?a.jsx("input",{type:"text",value:Ct.label,onChange:jt=>It({...Ct,label:jt.target.value}),onBlur:()=>Mn(gt.index,Ct.label),onKeyDown:jt=>{jt.key==="Enter"&&Mn(gt.index,Ct.label),jt.key==="Escape"&&It(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:b("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>It({index:gt.index,label:gt.label}),title:gt.label?b("printers.plateDetection.clickToEdit",{label:gt.label}):b("printers.plateDetection.clickToAddLabel"),children:gt.label||a.jsx("span",{className:"italic opacity-50",children:b("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:gt.timestamp?new Date(gt.timestamp).toLocaleDateString():""})]},gt.index))})]}),!q.needs_calibration&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:b("printers.roi.title")}),z?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>O(null),disabled:Z,children:b("common.cancel")}),a.jsx(Ne,{size:"sm",onClick:Kt,disabled:Z,children:Z?a.jsx(ct,{className:"w-3 h-3 animate-spin"}):b("common.save")})]}):a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:()=>O(q.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(Ji,{className:"w-3 h-3 mr-1"}),b("common.edit")]})]}),z?a.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:z.x,onChange:gt=>O({...z,x:parseFloat(gt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(z.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:z.y,onChange:gt=>O({...z,y:parseFloat(gt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(z.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:z.w,onChange:gt=>O({...z,w:parseFloat(gt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(z.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:z.h,onChange:gt=>O({...z,h:parseFloat(gt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(z.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:b("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((q.roi?.x||.15)*100),"%, Y=",Math.round((q.roi?.y||.35)*100),"%, W=",Math.round((q.roi?.w||.7)*100),"%, H=",Math.round((q.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:q.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(Ne,{variant:"ghost",onClick:()=>Bt(),children:b("common.cancel")}),a.jsx(Ne,{onClick:()=>pn(),disabled:pe,children:pe?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(Ne,{variant:"ghost",onClick:()=>pn(),disabled:pe,children:pe?"Adding...":`Add Reference (${xt?.references.length||0}/${xt?.max_references||5})`}),a.jsx(Ne,{onClick:()=>Bt(),children:"Close"})]})})]})}),$&&Qe&&a.jsx(er,{title:b("printers.confirm.powerOnTitle"),message:b("printers.confirm.powerOnMessage",{name:t.name}),confirmText:b("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{kn.mutate("on"),G(!1)},onCancel:()=>G(!1)}),I&&Qe&&a.jsx(er,{title:b("printers.confirm.powerOffTitle"),message:Te?.state==="RUNNING"?b("printers.confirm.powerOffWarning",{name:t.name}):b("printers.confirm.powerOffMessage",{name:t.name}),confirmText:b("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{kn.mutate("off"),K(!1)},onCancel:()=>K(!1)}),B&&a.jsx(er,{title:b("printers.confirm.stopTitle"),message:b("printers.confirm.stopMessage",{name:t.name}),confirmText:b("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{Ma.mutate(),W(!1)},onCancel:()=>W(!1)}),J&&a.jsx(er,{title:b("printers.confirm.pauseTitle"),message:b("printers.confirm.pauseMessage",{name:t.name}),confirmText:b("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{De.mutate(),ne(!1)},onCancel:()=>ne(!1)}),me&&a.jsx(er,{title:b("printers.confirm.resumeTitle"),message:b("printers.confirm.resumeMessage",{name:t.name}),confirmText:b("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{tt.mutate(),fe(!1)},onCancel:()=>fe(!1)}),a.jsx(EO,{printerId:t.id,isOpen:de,onClose:()=>Re(!1)}),Q&&a.jsx(dMe,{printerName:t.name,errors:Te?.hms_errors||[],onClose:()=>oe(!1)}),se&&a.jsx(a8e,{isOpen:!!se,onClose:()=>ke(null),printerId:t.id,printerName:t.name,amsId:se.amsId,amsLabel:se.amsLabel,initialMode:se.mode,thresholds:s}),Fe&&a.jsx(s8e,{isOpen:!!Fe,onClose:()=>ce(null),trayUuid:Fe.trayUuid,trayInfo:Fe.trayInfo}),Ve&&a.jsx(m8e,{isOpen:!!Ve,onClose:()=>V(null),printerId:t.id,slotInfo:Ve,onSuccess:()=>{y.invalidateQueries({queryKey:["slotPresets",t.id]}),y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),C&&a.jsx(j8e,{printer:t,onClose:()=>P(!1)}),Y&&we&&a.jsx(P8e,{printer:t,firmwareInfo:we,onClose:()=>ue(!1)}),Zt&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>cn(null)})]})}function C8e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Yt(),[i,s]=_.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=_.useState(!1),[c,u]=_.useState([]),[d,h]=_.useState(""),[p,m]=_.useState(!1),[b,y]=_.useState(!1),[x,v]=_.useState([]),[S,N]=_.useState(""),[T,M]=_.useState({scanned:0,total:0});_.useEffect(()=>{Xl.getInfo().then(P=>{y(P.is_docker),P.subnets.length>0&&(v(P.subnets),N(P.subnets[0]))}).catch(()=>{})},[]);const A=c.filter(P=>!n.includes(P.serial)),k=async()=>{h(""),u([]),l(!0),m(!1),M({scanned:0,total:0});try{if(b){await Xl.startSubnetScan(S);const P=setInterval(async()=>{try{const U=await Xl.getScanStatus();M({scanned:U.scanned,total:U.total});const F=await Xl.getDiscoveredPrinters();u(F),U.running||(clearInterval(P),l(!1),m(!0))}catch(U){console.error("Failed to get scan status:",U)}},500)}else{await Xl.startDiscovery(10);const P=setInterval(async()=>{try{const U=await Xl.getDiscoveredPrinters();u(U)}catch(U){console.error("Failed to get discovered printers:",U)}},1e3);setTimeout(async()=>{clearInterval(P);try{await Xl.stopDiscovery()}catch{}l(!1),m(!0);try{const U=await Xl.getDiscoveredPrinters();u(U)}catch(U){console.error("Failed to get final discovered printers:",U)}},1e4)}}catch(P){console.error("Failed to start discovery:",P),h(P instanceof Error?P.message:r("printers.discovery.failedToStart")),l(!1),m(!0)}},R=P=>P?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",P1S:"P1S",P1P:"P1P",P2S:"P2S",A1:"A1","A1 Mini":"A1 Mini",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[P]||P:"",C=P=>{const U=P.serial.startsWith("unknown-")?"":P.serial;s({...i,name:P.name||"",serial_number:U,ip_address:P.ip_address,model:R(P.model)}),u([])};return _.useEffect(()=>()=>{Xl.stopDiscovery().catch(()=>{}),Xl.stopSubnetScan().catch(()=>{})},[]),_.useEffect(()=>{const P=U=>{U.key==="Escape"&&t()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:a.jsx(St,{className:"w-full max-w-md",onClick:P=>P.stopPropagation(),children:a.jsxs(Et,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[b&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),x.length>0?a.jsx("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:S,onChange:P=>N(P.target.value),disabled:o,children:x.map(P=>a.jsx("option",{value:P,children:P},P))}):a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:S,onChange:P=>N(P.target.value),placeholder:"192.168.1.0/24",disabled:o}),a.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),a.jsx(Ne,{type:"button",variant:"secondary",onClick:k,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),b&&T.total>0?r("printers.discovery.scanProgress",{scanned:T.scanned,total:T.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(Qi,{className:"w-4 h-4"}),r(b?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),d&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:d}),A.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:A.map(P=>a.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>C(P),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:P.name||P.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[R(P.model)||r("printers.discovery.unknown")," • ",P.ip_address,P.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(fr,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},P.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(b?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(b?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&A.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:P=>{P.preventDefault(),e(i)},className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.name,onChange:P=>s({...i,name:P.target.value}),placeholder:r("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.ip_address,onChange:P=>s({...i,ip_address:P.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.serial_number,onChange:P=>s({...i,serial_number:P.target.value}),placeholder:"01P00A000000000"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),a.jsx("input",{type:"password",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.access_code,onChange:P=>s({...i,access_code:P.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.model||"",onChange:P=>s({...i,model:P.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.location||"",onChange:P=>s({...i,location:P.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:P=>s({...i,auto_archive:P.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(Ne,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function P8e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Yt(),i=an(),{showToast:s}=Tn(),{hasPermission:o}=Ir(),l=o("firmware:update"),[c,u]=_.useState(null),[d,h]=_.useState(!1),[p,m]=_.useState(null),{data:b,isLoading:y}=it({queryKey:["firmwarePrepare",t.id],queryFn:()=>N1.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),x=dt({mutationFn:()=>N1.startUpload(t.id),onSuccess:()=>{h(!0);const S=setInterval(async()=>{try{const N=await N1.getUploadStatus(t.id);u(N),(N.status==="complete"||N.status==="error")&&(clearInterval(S),m(null),h(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);m(S)},onError:S=>{s(r("printers.firmwareModal.uploadFailed",{error:S.message}),"error"),h(!1)}});_.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const v=()=>{u(null),x.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(St,{className:"w-full max-w-md mx-4",children:a.jsxs(Et,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(wi,{className:"w-5 h-5 text-orange-400"}):a.jsx(mr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),a.jsx("span",{className:`font-mono ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&a.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),a.jsx("span",{className:"text-orange-400 font-mono",children:e.latest_version})]}),e.release_notes&&a.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),a.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:e.release_notes})]})]}),e.update_available?y?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):b&&!d&&!c?a.jsx("div",{className:"mb-4",children:b.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(Ii,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:b.errors.map((S,N)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Ti,{className:"w-4 h-4 flex-shrink-0"}),S]},N))})}):null:null,(d||c)&&c&&a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),a.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&a.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),a.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),a.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(Ne,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),b?.can_proceed&&!d&&c?.status!=="complete"&&l&&a.jsx(Ne,{onClick:v,disabled:x.isPending,children:x.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(wi,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function j8e({printer:t,onClose:e}){const{t:n}=Yt(),r=an(),{showToast:i}=Tn(),[s,o]=_.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=dt({mutationFn:u=>ae.updatePrinter(t.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:u=>i(u.message||n("printers.toast.failedToUpdate"),"error")});_.useEffect(()=>{const u=d=>{d.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const c=u=>{u.preventDefault();const d={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(d.access_code=s.access_code),l.mutate(d)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:a.jsx(St,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:a.jsxs(Et,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:u=>o({...s,name:u.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:u=>o({...s,ip_address:u.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:u=>o({...s,access_code:u.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:u=>o({...s,model:u.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:u=>o({...s,location:u.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:u=>o({...s,auto_archive:u.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(Ne,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function D8e(t){const{data:e}=it({queryKey:["printerStatus",t],queryFn:()=>ae.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function R8e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=D8e(t.id),{data:s}=it({queryKey:["smartPlugStatus",e.id],queryFn:()=>ae.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),a.jsxs("button",{onClick:()=>n(e.id),disabled:r||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[a.jsx(Ju,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function O8e(){const{t}=Yt(),[e,n]=_.useState(!1),[r,i]=_.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=_.useState(!1),[l,c]=_.useState(null),[u,d]=_.useState(()=>localStorage.getItem("printerSortBy")||"name"),[h,p]=_.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[m,b]=_.useState(()=>{const de=localStorage.getItem("printerCardSize");return de?parseInt(de,10):2}),y=m===1?"compact":"expanded",x=an(),{showToast:v}=Tn(),{hasPermission:S}=Ir(),[N,T]=_.useState(()=>{const de=localStorage.getItem("openEmbeddedCameras");if(de)try{const Re=JSON.parse(de);return new Map(Re.map(se=>[se.id,se]))}catch{return new Map}return new Map});_.useEffect(()=>{const de=Array.from(N.values());de.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(de)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:M,isLoading:A}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:k}=it({queryKey:["settings"],queryFn:ae.getSettings});_.useEffect(()=>{k?.camera_view_mode==="window"&&N.size>0&&T(new Map)},[k?.camera_view_mode,N.size]);const{data:R}=it({queryKey:["smart-plugs"],queryFn:ae.getSmartPlugs}),{data:C}=it({queryKey:["maintenanceOverview"],queryFn:ae.getMaintenanceOverview,staleTime:60*1e3}),{data:P}=it({queryKey:["spoolman-status"],queryFn:ae.getSpoolmanStatus,staleTime:60*1e3}),U=P?.enabled&&P?.connected,{data:F}=it({queryKey:["unlinked-spools"],queryFn:ae.getUnlinkedSpools,enabled:!!U,staleTime:30*1e3}),H=F&&F.length>0,{data:D}=it({queryKey:["linked-spools"],queryFn:ae.getLinkedSpools,enabled:!!U,staleTime:30*1e3}),$=D?.linked,G=C?.reduce((de,Re)=>(de[Re.printer_id]={due_count:Re.due_count,warning_count:Re.warning_count,total_print_hours:Re.total_print_hours},de),{})||{},I=R?.reduce((de,Re)=>(Re.printer_id&&(de[Re.printer_id]=Re),de),{})||{},K=dt({mutationFn:ae.createPrinter,onSuccess:()=>{x.invalidateQueries({queryKey:["printers"]}),x.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:de=>v(de.message||t("printers.toast.failedToAdd"),"error")}),Q=dt({mutationFn:de=>ae.controlSmartPlug(de,"on"),onSuccess:()=>{x.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),oe=()=>{const de=!r;i(de),localStorage.setItem("hideDisconnectedPrinters",String(de))},B=de=>{d(de),localStorage.setItem("printerSortBy",de)},W=()=>{const de=!h;p(de),localStorage.setItem("printerSortAsc",String(de))},J=()=>{switch(m){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},ne=["S","M","L","XL"],me=_.useMemo(()=>{if(!M)return[];const de=[...M];switch(u){case"name":de.sort((Re,se)=>Re.name.localeCompare(se.name));break;case"model":de.sort((Re,se)=>(Re.model||"").localeCompare(se.model||""));break;case"location":de.sort((Re,se)=>{const ke=Re.location||"",Fe=se.location||"";return!ke&&Fe?1:ke&&!Fe?-1:ke.localeCompare(Fe)||Re.name.localeCompare(se.name)});break;case"status":de.sort((Re,se)=>{const ke=x.getQueryData(["printerStatus",Re.id]),Fe=x.getQueryData(["printerStatus",se.id]),ce=Ve=>Ve?.connected?Ve.state==="RUNNING"?0:1:2;return ce(ke)-ce(Fe)});break}return h||de.reverse(),de},[M,u,h,x]),fe=_.useMemo(()=>{if(u!=="location")return null;const de={};return me.forEach(Re=>{const se=Re.location||"Ungrouped";de[se]||(de[se]=[]),de[se].push(Re)}),de},[u,me]);return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),a.jsx(A8e,{printers:M})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("select",{value:u,onChange:de=>B(de.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"name",children:t("printers.sort.name")}),a.jsx("option",{value:"status",children:t("printers.sort.status")}),a.jsx("option",{value:"model",children:t("printers.sort.model")}),a.jsx("option",{value:"location",children:t("printers.sort.location")})]}),a.jsx("button",{onClick:W,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(h?"printers.sort.descending":"printers.sort.ascending"),children:h?a.jsx(Hg,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(X0,{className:"w-4 h-4 text-bambu-gray"})})]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:ne.map((de,Re)=>{const se=Re+1,ke=m===se;return a.jsx("button",{onClick:()=>{b(se),localStorage.setItem("printerCardSize",String(se))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${Re===0?"rounded-l-lg":""} ${Re===ne.length-1?"rounded-r-lg":""} ${ke?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(de==="S"?"printers.cardSize.small":de==="M"?"printers.cardSize.medium":de==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:de},de)})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:oe,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(I).length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>o(!s),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg text-gray-600 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white hover:border-bambu-green transition-colors",children:[a.jsx(Ju,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(fr,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),a.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[a.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),M?.filter(de=>I[de.id]).map(de=>a.jsx(R8e,{printer:de,plug:I[de.id],onPowerOn:Re=>{c(Re),Q.mutate(Re)},isPowering:l===I[de.id]?.id},de.id)),M?.filter(de=>I[de.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(Ne,{onClick:()=>n(!0),disabled:!S("printers:create"),title:S("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(cr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),A?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):M?.length===0?a.jsx(St,{children:a.jsxs(Et,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(Ne,{onClick:()=>n(!0),disabled:!S("printers:create"),title:S("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(cr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):fe?a.jsx("div",{className:"space-y-6",children:Object.entries(fe).map(([de,Re])=>a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),de,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",Re.length,")"]})]}),a.jsx("div",{className:`grid gap-4 ${m>=3?"gap-6":""} ${J()}`,children:Re.map(se=>a.jsx(Vq,{printer:se,hideIfDisconnected:r,maintenanceInfo:G[se.id],viewMode:y,cardSize:m,amsThresholds:k?{humidityGood:Number(k.ams_humidity_good)||40,humidityFair:Number(k.ams_humidity_fair)||60,tempGood:Number(k.ams_temp_good)||28,tempFair:Number(k.ams_temp_fair)||35}:void 0,spoolmanEnabled:U,hasUnlinkedSpools:H,linkedSpools:$,spoolmanUrl:P?.url,timeFormat:k?.time_format||"system",cameraViewMode:k?.camera_view_mode||"window",onOpenEmbeddedCamera:(ke,Fe)=>T(ce=>new Map(ce).set(ke,{id:ke,name:Fe})),checkPrinterFirmware:k?.check_printer_firmware!==!1},se.id))})]},de))}):a.jsx("div",{className:`grid gap-4 ${m>=3?"gap-6":""} ${J()}`,children:me.map(de=>a.jsx(Vq,{printer:de,hideIfDisconnected:r,maintenanceInfo:G[de.id],viewMode:y,cardSize:m,spoolmanEnabled:U,hasUnlinkedSpools:H,linkedSpools:$,spoolmanUrl:P?.url,amsThresholds:k?{humidityGood:Number(k.ams_humidity_good)||40,humidityFair:Number(k.ams_humidity_fair)||60,tempGood:Number(k.ams_temp_good)||28,tempFair:Number(k.ams_temp_fair)||35}:void 0,timeFormat:k?.time_format||"system",cameraViewMode:k?.camera_view_mode||"window",onOpenEmbeddedCamera:(Re,se)=>T(ke=>new Map(ke).set(Re,{id:Re,name:se})),checkPrinterFirmware:k?.check_printer_firmware!==!1},de.id))}),e&&a.jsx(C8e,{onClose:()=>n(!1),onAdd:de=>K.mutate(de),existingSerials:M?.map(de=>de.serial_number)||[]}),Array.from(N.values()).map((de,Re)=>a.jsx(sMe,{printerId:de.id,printerName:de.name,viewerIndex:Re,onClose:()=>T(se=>{const ke=new Map(se);return ke.delete(de.id),ke})},de.id))]})}function L8e(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function sc(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:n=`${L8e()==="windows"?"bambustudio":"bambustudioopen"}://${encodeURIComponent(t)}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}function C4({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Yt(),{data:o}=it({queryKey:["settings"],queryFn:ae.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[u,d]=_.useState(null),[h,p]=_.useState(null),[m,b]=_.useState(!0),[y,x]=_.useState(null),[v,S]=_.useState(!1),[N,T]=_.useState(null),[M,A]=_.useState(0),[k,R]=_.useState(!1),[C,P]=_.useState(null),[U,F]=_.useState(!1),[H,D]=_.useState(!1),$=_.useRef(null),G=_.useRef(null),I=10,K=160,Q=240,oe=.35;_.useEffect(()=>{const pe=ee=>{ee.key==="Escape"&&i()};return window.addEventListener("keydown",pe),()=>window.removeEventListener("keydown",pe)},[i]),_.useEffect(()=>{if(b(!0),c){const pe=(r||"").toLowerCase(),ee=pe==="3mf"||pe==="stl",z=pe==="gcode"||pe==="3mf";p({has_model:ee,has_gcode:z,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d(ee?"3d":z?"gcode":null),b(!1);return}if(!t){p(null),d(null),b(!1);return}ae.getArchiveCapabilities(t).then(pe=>{p(pe),pe.has_model?d("3d"):pe.has_gcode&&d("gcode"),b(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d("3d"),b(!1)})},[t,r,c]),_.useEffect(()=>{if(S(!0),T(null),A(0),c){const pe=(r||"").toLowerCase();if(!e||pe!=="3mf"){x(null),S(!1);return}ae.getLibraryFilePlates(e).then(ee=>x(ee)).catch(()=>x(null)).finally(()=>S(!1));return}if(!t){x(null),S(!1);return}ae.getArchivePlates(t).then(pe=>x(pe)).catch(()=>x(null)).finally(()=>S(!1))},[t,r,c,e]);const B=_.useMemo(()=>y?.plates??[],[y]),W=(y?.is_multi_plate??!1)&&B.length>1,J=k&&W,ne=N==null?null:B.find(pe=>pe.index===N)??null,me=pe=>pe.object_count??pe.objects?.length??0,fe=B.reduce((pe,ee)=>pe+me(ee),0),de=ne?me(ne):fe,Re=ne?s("modelViewer.plateNumber",{number:ne.index}):s("modelViewer.allPlates"),se=B.length>0,ke=_.useRef(null),Fe=_.useRef(null),[ce,Ve]=_.useState(10),[V,Y]=_.useState(3),ue=B.length>ce,q=Math.max(1,Math.ceil(B.length/ce)),re=ue?B.slice(M*ce,(M+1)*ce):B;_.useEffect(()=>{if(!J){Ve(10),Y(3);return}const pe=ke.current,ee=Fe.current;if(!pe||!ee)return;let z=0;const O=()=>{const Ce=ee.clientWidth,Te=Math.floor(Ce/210),we=Math.max(3,Math.min(5,Te||3));Y(ve=>ve===we?ve:we);const $e=window.getComputedStyle(pe),Ge=Number.parseFloat($e.rowGap||"0"),be=pe.querySelector("button")?.getBoundingClientRect().height??44,Me=ee.clientHeight,Ae=Math.max(1,Math.floor((Me+Ge)/(be+Ge)))*we,qe=Math.max(1,Ae-1);Ve(ve=>ve===qe?ve:qe)},Z=()=>{z&&cancelAnimationFrame(z),z=requestAnimationFrame(O)};Z();const ge=new ResizeObserver(Z);return ge.observe(ee),ge.observe(pe),()=>{z&&cancelAnimationFrame(z),ge.disconnect()}},[J,B.length]),_.useEffect(()=>{if(!ue){A(0);return}A(pe=>Math.min(pe,q-1))},[B.length,ue,q]),_.useEffect(()=>{if(!ue||N==null)return;const pe=B.findIndex(z=>z.index===N);if(pe<0)return;const ee=Math.floor(pe/ce);A(z=>z===ee?z:ee)},[B,ce,N,ue]),_.useEffect(()=>{if(!J){P(null),D(!1);return}if(H)return;const pe=$.current,ee=G.current;if(!pe||!ee)return;const z=pe.clientHeight;if(!z)return;const O=Math.max(Q,z*oe),Z=Math.max(K,z-I-O),ge=Math.min(ee.scrollHeight,Z);P(Math.max(K,ge))},[J,H,B.length,M,I,K,Q,oe]),_.useEffect(()=>{if(!U)return;const pe=z=>{const O=$.current;if(!O)return;const Z=O.getBoundingClientRect(),ge=Z.height;if(!ge)return;const Ce=Math.max(Q,ge*oe),_e=Math.max(K,ge-I-Ce),Te=Math.min(_e,Math.max(K,z.clientY-Z.top));P(Te)},ee=()=>{F(!1),D(!0)};return document.addEventListener("mousemove",pe),document.addEventListener("mouseup",ee),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",pe),document.removeEventListener("mouseup",ee),document.body.style.cursor="",document.body.style.userSelect=""}},[U,I,K,Q,oe]);const X=c?(r||"").toLowerCase()==="3mf":!0,le=()=>{if(!X)return;const pe=n||"model";if(c){const z=`${window.location.origin}${ae.getLibraryFileDownloadUrl(e)}`;sc(z,l);return}const ee=`${window.location.origin}${ae.getArchiveForSlicer(t,pe)}`;sc(ee,l)};return a.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${k?"p-0":"p-8"}`,onClick:i,children:a.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${k?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:pe=>pe.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),se&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[Re,": ",s("modelViewer.objectCount",{count:de})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:le,disabled:!X,children:[a.jsx(Xr,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>R(pe=>!pe),title:k?"Exit fullscreen":"Enter fullscreen",children:k?a.jsx(VR,{className:"w-4 h-4"}):a.jsx($R,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Lt,{className:"w-5 h-5"})})]})]}),h&&a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>h.has_model&&d("3d"),disabled:!h.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="3d"?"text-bambu-green border-b-2 border-bambu-green":h.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(Ii,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!h.has_model&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),a.jsxs("button",{onClick:()=>h.has_gcode&&d("gcode"),disabled:!h.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="gcode"?"text-bambu-green border-b-2 border-bambu-green":h.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(Sue,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!h.has_gcode&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:m?a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})}):u==="3d"&&h?a.jsxs("div",{ref:$,className:`w-full h-full flex flex-col ${J?"gap-0 min-h-0":"gap-3"}`,children:[W&&a.jsxs("div",{ref:G,style:J&&C!=null?{height:C}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${J?"flex flex-col shrink-0":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(is,{className:"w-4 h-4"}),s("modelViewer.plates"),v&&a.jsx(ct,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:J?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:Fe,className:J?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:ke,className:J?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:J?{gridTemplateColumns:`repeat(${V}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>T(null),className:`flex items-center rounded-lg border text-left transition-colors ${J?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${J?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(is,{className:`${J?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${J?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${J?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:B.length})})]}),N==null&&a.jsx($i,{className:`${J?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),re.map(pe=>a.jsxs("button",{type:"button",onClick:()=>T(pe.index),className:`flex items-center rounded-lg border text-left transition-colors ${J?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===pe.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[pe.has_thumbnail&&pe.thumbnail_url?a.jsx("img",{src:pe.thumbnail_url,alt:`Plate ${pe.index}`,className:`${J?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${J?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(is,{className:`${J?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${J?"text-xs":"text-sm"} text-white font-medium truncate`,children:pe.name||s("modelViewer.plateNumber",{number:pe.index})}),a.jsx("p",{className:`${J?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:pe.object_count??pe.objects?.length??0})})]}),N===pe.index&&a.jsx($i,{className:`${J?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},pe.index))]})}),(ne||ue)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ne&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:ne.index})}),ne.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ne.print_time_seconds/60)})}),ne.filament_used_grams!=null&&a.jsxs("span",{children:[ne.filament_used_grams.toFixed(1)," g"]}),ne.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:ne.filaments.length})})]}),ue&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ne?"ml-auto":""}`,children:[a.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:M+1,total:q})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button",onClick:()=>A(pe=>Math.max(pe-1,0)),disabled:M===0,className:`px-2 py-1 rounded border text-xs ${M===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let ee=Math.max(0,M-Math.floor(2.5));const z=Math.min(q,ee+5);z-ee<5&&(ee=Math.max(0,z-5));const O=Array.from({length:z-ee},(Z,ge)=>ee+ge);return a.jsxs(a.Fragment,{children:[ee>0&&a.jsx("button",{type:"button",onClick:()=>A(0),className:`px-2 py-1 rounded border text-xs ${M===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),ee>1&&a.jsx("span",{className:"px-1",children:"…"}),O.map(Z=>a.jsx("button",{type:"button",onClick:()=>A(Z),className:`px-2 py-1 rounded border text-xs ${M===Z?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Z+1},Z)),zA(q-1),className:`px-2 py-1 rounded border text-xs ${M===q-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:q})]})})(),a.jsx("button",{type:"button",onClick:()=>A(pe=>Math.min(pe+1,q-1)),disabled:M>=q-1,className:`px-2 py-1 rounded border text-xs ${M>=q-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.next")})]})]})]})]})]}),J&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:pe=>{pe.preventDefault(),F(!0),D(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${U?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),a.jsx("div",{className:`flex-1 ${J?"min-h-0":""}`,children:a.jsx(IK,{url:c?ae.getLibraryFileDownloadUrl(e):h.has_source?ae.getSource3mfDownloadUrl(t):ae.getArchiveDownload(t),fileType:r,buildVolume:h.build_volume,filamentColors:h.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):u==="gcode"&&h?a.jsx(vX,{gcodeUrl:c?ae.getLibraryFileGcodeUrl(e):ae.getArchiveGcode(t),filamentColors:h.filament_colors,className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}const Gq={"000000":"Black","001489":"Blue","002e96":"Blue","0047bb":"Blue","00482b":"Pine Green","004ea8":"Blue","0056b8":"Cobalt Blue","0069b1":"Lake Blue","0072ce":"Blue","0078bf":"Marine Blue","0085ad":"Light Blue","0086d6":"Cyan","008bda":"Blue","009639":"Green","009bd8":"Cyan","009fa1":"Teal","00a6a0":"Green","00ae42":"Bambu Green","00b1b7":"Turquoise","00bb31":"Green","018814":"Candy Green","042f56":"Dark Blue","0a2989":"Blue","0a2ca5":"Blue","0c2340":"Navy Blue","0c3b95":"Blue",101820:"Black","147bd1":"Blue","164b35":"Green","16b08e":"Malachite Green","1d7c6a":"Oxide Green Metallic","1f79e5":"Lake Blue","2140b4":"Blue","25282a":"Black","2842ad":"Royal Blue","2d2b28":"Onyx Black Sparkle",324585:"Indigo Blue",353533:"Gray","39541a":"Forest Green","39699e":"Cobalt Blue Metallic","3b665e":"Green","3f5443":"Alpine Green Sparkle","3f8e43":"Mistletoe Green",424379:"Nebulae","43403d":"Iron Gray Metallic",482960:"Indigo Purple","483d8b":"Royal Purple Sparkle","489fdf":"Azure","4c241c":"Rosewood","4ce4a0":"Green","4d3324":"Dark Chocolate","4d5054":"Lava Gray","4dafda":"Cyan","4f3f24":"Black Walnut",515151:"Dark Gray","515a6c":"Gray",545454:"Dark Gray",565656:"Titan Gray","56b7e6":"Sky Blue",583061:"Violet Purple","5898dd":"Blue",594177:"Purple","5b492f":"Brown","5b6579":"Blue Gray","5c9748":"Matcha Green","5e43b7":"Purple","5e4b3c":"Copper","5f6367":"Titan Gray","61b0ff":"Translucent Light Blue","61bf36":"Green","61c680":"Grass Green","6667ab":"Lavender Blue","684a43":"Brown",686865:"Black","68724d":"Dark Green",688197:"Blue Gray","69398e":"Iris Purple","6e88bc":"Jeans Blue","6ee53c":"Lime Green","6f5034":"Cocoa Brown","7248bd":"Lavender","748c45":"Translucent Olive",757575:"Nardo Gray","75aed8":"Blue","77edd7":"Translucent Teal","789d4a":"Olive","792b36":"Crimson Red Sparkle","7ac0e9":"Glow Blue","7ae1bf":"Mint","7cd82b":"Lime Green","7d6556":"Dark Brown","8344b0":"Purple","847d48":"Bronze","854ce4":"Purple","8671cb":"Purple",875718:"Peanut Brown","87909a":"Silver","898d8d":"Gray","8a949e":"Gray","8e8e8e":"Translucent Gray","8e9089":"Gray","90ff1a":"Neon Green",918669:"Classic Birch",939393:"Gray",950051:"Plum","951e23":"Burgundy Red",959698:"Silver","96d8af":"Light Jade","96dcb9":"Mint","995f11":"Clay Brown","999d9d":"Gray","9b9ea0":"Ash Gray","9d2235":"Maroon Red","9d432c":"Brown","9e007e":"Purple","9ea2a2":"Gray","9f332a":"Brick Red",a1ffac:"Glow Green",a3d8e1:"Ice Blue",a6a9aa:"Silver",a8a8aa:"Gray",a8c6ee:"Baby Blue",aa6443:"Copper Brown Metallic",ad4e38:"Red Granite",adb1b2:"Gray",ae835b:"Caramel",ae96d4:"Lilac Purple",af1685:"Purple",afb1ae:"Gray",b15533:"Terracotta",b28b33:"Gold",b39b84:"Iridium Gold Metallic",b50011:"Red",b8acd6:"Lavender",b8cde9:"Ice Blue",ba9594:"Rose Gold",bb3d43:"Dark Red",bc0900:"Red",becf00:"Bright Green",c0df16:"Green",c12e1f:"Red",c2e189:"Apple Green",c3e2d6:"Light Cyan",c5ed48:"Lime",c6001a:"Red",c6c6c6:"Gray",c8102e:"Red",c8c8c8:"Silver",c98935:"Ochre Yellow",c9a381:"Translucent Brown",cbc6b8:"Bone White",cdceca:"Gray",cea629:"Classic Gold Sparkle",d02727:"Candy Red",d1d3d5:"Light Gray",d32941:"Red",d3b7a7:"Latte Brown",d6001c:"Red",d6abff:"Translucent Purple",d6cca3:"White Oak",dc3a27:"Orange",dd3c22:"Vermilion Red",de4343:"Scarlet Red",dfd1a7:"Beige",e02928:"Red",e4bd68:"Gold",e5b03d:"Gold",e83100:"Red",e8afcf:"Sakura Pink",e8dbb7:"Desert Tan",eaeae4:"White",eaeceb:"Silver",ec008c:"Magenta",ed0000:"Red",eeb1c1:"Pink",efe255:"Yellow",f0f1a8:"Clear",f17b8f:"Glow Pink",f3cfb2:"Champagne",f3e600:"Yellow",f48438:"Orange",f4a925:"Gold",f4d53f:"Yellow",f4ee2a:"Yellow",f5547c:"Hot Pink",f55a74:"Pink",f5b6cd:"Cherry Pink",f5dbab:"Mellow Yellow",f5f1dd:"White",f68b1b:"Neon Orange",f74e02:"Orange",f75403:"Orange",f7ada6:"Pink",f7d959:"Lemon Yellow",f7e6de:"Beige",f7f3f0:"White Marble",f8ff80:"Glow Yellow",f99963:"Mandarin Orange",f9c1bd:"Translucent Pink",f9dfb9:"Cream",f9ef41:"Yellow",f9f7f2:"Nature",f9f7f4:"White",fce300:"Yellow",fce900:"Yellow",fec600:"Sunflower Yellow",fedb00:"Yellow",ff4800:"Orange",ff671f:"Orange",ff6a13:"Orange",ff7f41:"Orange",ff9016:"Pumpkin Orange",ff911a:"Translucent Orange",ff9d5b:"Glow Orange",ffb549:"Sunflower Yellow",ffc72c:"Tangerine Yellow",ffce00:"Yellow",ffd00b:"Yellow",ffe133:"Yellow",fffaf2:"White",ffffff:"White"};function F8e(t){if(!t||t.length<6)return"Unknown";const e=t.replace("#",""),n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16),s=Math.max(n,r,i)/255,o=Math.min(n,r,i)/255,l=(s+o)/2;let c=0,u=0;if(s!==o){const d=s-o;u=l>.5?d/(2-s-o):d/(s+o);const h=n/255,p=r/255,m=i/255;s===h?c=((p-m)/d+(p.85?"White":u<.15?l<.4?"Dark Gray":l>.6?"Light Gray":"Gray":c<15||c>=345?"Red":c<45?"Orange":c<70?"Yellow":c<150?"Green":c<200?"Cyan":c<260?"Blue":c<290?"Purple":"Pink"}function ub(t){const e=t.replace("#","").toLowerCase().substring(0,6);return Gq[e]?Gq[e]:F8e(t)}function mN(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function yi(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}function pc(t,e,n=40){const r=yi(t),i=yi(e);if(!r||!i||r.length<6||i.length<6)return!1;const s=parseInt(r.substring(0,2),16),o=parseInt(r.substring(2,4),16),l=parseInt(r.substring(4,6),16),c=parseInt(i.substring(0,2),16),u=parseInt(i.substring(2,4),16),d=parseInt(i.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-u)<=n&&Math.abs(l-d)<=n}function Iee(t,e,n,r){const i=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${i}`:`AMS-${i} Slot ${e+1}`}function zee(t,e,n){return t>=128?t:t*4+e}function I8e(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 qq(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return new Date(t).getTime()>e}function P4(t){const e=[];if(t?.ams?.forEach(n=>{const r=n.tray.length===1;n.tray.forEach(i=>{if(i.tray_type){const s=mN(i.tray_color);e.push({type:i.tray_type,color:s,colorName:ub(s),amsId:n.id,trayId:i.id,isHt:r,isExternal:!1,label:Iee(n.id,i.id,r),globalTrayId:zee(n.id,i.id),trayInfoIdx:i.tray_info_idx||""})}})}),t?.vt_tray?.tray_type){const n=mN(t.vt_tray.tray_color);e.push({type:t.vt_tray.tray_type,color:n,colorName:ub(n),amsId:-1,trayId:0,isHt:!1,isExternal:!0,label:"External",globalTrayId:254,trayInfoIdx:t.vt_tray.tray_info_idx||""})}return e}function Wq(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=P4(e);if(n.length===0)return;const r=new Set,i=t.filaments.map(l=>{const c=l.tray_info_idx||"",u=n.filter(y=>!r.has(y.globalTrayId));let d,h,p,m;if(c){const y=u.filter(x=>x.trayInfoIdx===c);y.length===1?d=y[0]:y.length>1&&(h=y.find(x=>x.type?.toUpperCase()===l.type?.toUpperCase()&&yi(x.color)===yi(l.color)),h||(p=y.find(x=>x.type?.toUpperCase()===l.type?.toUpperCase()&&pc(x.color,l.color))),!h&&!p&&(m=y.find(x=>x.type?.toUpperCase()===l.type?.toUpperCase())))}!d&&!h&&!p&&!m&&(h=u.find(y=>y.type?.toUpperCase()===l.type?.toUpperCase()&&yi(y.color)===yi(l.color)),h||(p=u.find(y=>y.type?.toUpperCase()===l.type?.toUpperCase()&&pc(y.color,l.color))),!h&&!p&&(m=u.find(y=>y.type?.toUpperCase()===l.type?.toUpperCase())));const b=d||h||p||m||void 0;return b&&r.add(b.globalTrayId),{slot_id:l.slot_id,globalTrayId:b?.globalTrayId??-1}}),s=Math.max(...i.map(l=>l.slot_id||0));if(s<=0)return;const o=new Array(s).fill(-1);return i.forEach(l=>{l.slot_id&&l.slot_id>0&&(o[l.slot_id-1]=l.globalTrayId)}),o}function z8e(t){return _.useMemo(()=>{const e=[];if(t?.ams?.forEach(n=>{const r=n.tray.length===1;n.tray.forEach(i=>{if(i.tray_type){const s=mN(i.tray_color);e.push({type:i.tray_type,color:s,colorName:ub(s),amsId:n.id,trayId:i.id,isHt:r,isExternal:!1,label:Iee(n.id,i.id,r),globalTrayId:zee(n.id,i.id),trayInfoIdx:i.tray_info_idx||""})}})}),t?.vt_tray?.tray_type){const n=mN(t.vt_tray.tray_color);e.push({type:t.vt_tray.tray_type,color:n,colorName:ub(n),amsId:-1,trayId:0,isHt:!1,isExternal:!0,label:"External",globalTrayId:254,trayInfoIdx:t.vt_tray.tray_info_idx||""})}return e},[t])}function Uee(t,e,n){const r=z8e(e),i=_.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const c=new Set(Object.values(n));return t.filaments.map(u=>{const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const A=n[d],k=r.find(R=>R.globalTrayId===A);if(k){const R=k.type?.toUpperCase()===u.type?.toUpperCase(),C=yi(k.color)===yi(u.color)||pc(k.color,u.color);let P;return R&&C?P="match":R?P="type_only":P="mismatch",{...u,loaded:k,hasFilament:!0,typeMatch:R,colorMatch:C,status:P,isManual:!0}}}const h=u.tray_info_idx||"",p=r.filter(A=>!c.has(A.globalTrayId));let m,b,y,x;if(h){const A=p.filter(k=>k.trayInfoIdx===h);A.length===1?m=A[0]:A.length>1&&(b=A.find(k=>k.type?.toUpperCase()===u.type?.toUpperCase()&&yi(k.color)===yi(u.color)),b||(y=A.find(k=>k.type?.toUpperCase()===u.type?.toUpperCase()&&pc(k.color,u.color))),!b&&!y&&(x=A.find(k=>k.type?.toUpperCase()===u.type?.toUpperCase())))}!m&&!b&&!y&&!x&&(b=p.find(A=>A.type?.toUpperCase()===u.type?.toUpperCase()&&yi(A.color)===yi(u.color)),b||(y=p.find(A=>A.type?.toUpperCase()===u.type?.toUpperCase()&&pc(A.color,u.color))),!b&&!y&&(x=p.find(A=>A.type?.toUpperCase()===u.type?.toUpperCase())));const v=m||b||y||x||void 0;v&&c.add(v.globalTrayId);const S=!!v,N=S,T=!!m||!!b||!!y;let M;return m||b||y?M="match":x?M="type_only":M="mismatch",{...u,loaded:v,hasFilament:S,typeMatch:N,colorMatch:T,status:M,isManual:!1}})},[t,r,n]),s=_.useMemo(()=>{if(i.length===0)return;const c=Math.max(...i.map(d=>d.slot_id||0));if(c<=0)return;const u=new Array(c).fill(-1);return i.forEach(d=>{d.slot_id&&d.slot_id>0&&(u[d.slot_id-1]=d.loaded?.globalTrayId??-1)}),u},[i]),o=i.some(c=>c.status==="mismatch"),l=i.some(c=>c.status==="type_only");return{loadedFilaments:r,filamentComparison:i,amsMapping:s,hasTypeMismatch:o,hasColorMismatch:l}}function U8e(t,e,n){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let r=0,i=0,s=0;const o=new Set(Object.values(n));for(const u of t){const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const y=n[d],x=e.find(v=>v.globalTrayId===y);if(x){const v=x.type?.toUpperCase()===u.type?.toUpperCase(),S=yi(x.color)===yi(u.color)||pc(x.color,u.color);v&&S?r++:v?i++:s++;continue}}const h=e.find(y=>!o.has(y.globalTrayId)&&y.type?.toUpperCase()===u.type?.toUpperCase()&&yi(y.color)===yi(u.color)),p=h?void 0:e.find(y=>!o.has(y.globalTrayId)&&y.type?.toUpperCase()===u.type?.toUpperCase()&&pc(y.color,u.color)),m=h||p?void 0:e.find(y=>!o.has(y.globalTrayId)&&y.type?.toUpperCase()===u.type?.toUpperCase()),b=h??p??m;b&&o.add(b.globalTrayId),h||p?r++:m?i++:s++}const l=t.length;let c="full";return s>0?c="missing":i>0&&(c="partial"),{exactMatches:r,typeOnlyMatches:i,missingTypes:s,totalSlots:l,status:c}}function B8e(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=P4(e);if(r.length===0)return;const i=new Set(Object.values(n)),s=[];for(const c of t.filaments){const u=c.slot_id||0;if(u>0&&n[u]!==void 0){s.push({slot_id:u,globalTrayId:n[u]});continue}const d=r.find(b=>!i.has(b.globalTrayId)&&b.type?.toUpperCase()===c.type?.toUpperCase()&&yi(b.color)===yi(c.color)),h=d?void 0:r.find(b=>!i.has(b.globalTrayId)&&b.type?.toUpperCase()===c.type?.toUpperCase()&&pc(b.color,c.color)),p=d||h?void 0:r.find(b=>!i.has(b.globalTrayId)&&b.type?.toUpperCase()===c.type?.toUpperCase()),m=d??h??p;m&&i.add(m.globalTrayId),s.push({slot_id:u,globalTrayId:m?.globalTrayId??-1})}const o=Math.max(...s.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return s.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}const Kq={useDefault:!0,manualMappings:{},autoConfigured:!1};function H8e(t,e,n,r,i,s){const o=BR({queries:t.map(b=>({queryKey:["printer-status",b],queryFn:()=>ae.getPrinterStatus(b),enabled:t.length>0,staleTime:5e3}))}),l=_.useMemo(()=>t.map((b,y)=>{const x=o[y],v=x?.data,N=e?.find(P=>P.id===b)?.name||`Printer ${b}`,T=P4(v),M=i[b]||Kq,A=Wq(n,v),k=M.useDefault?r:M.manualMappings,R=B8e(n,v,k),C=U8e(n?.filaments,T,k);return{printerId:b,printerName:N,status:v,isLoading:x?.isLoading??!1,loadedFilaments:T,autoMapping:A,finalMapping:R,matchStatus:C.status,exactMatches:C.exactMatches,typeOnlyMatches:C.typeOnlyMatches,missingTypes:C.missingTypes,totalSlots:C.totalSlots,config:M}}),[t,o,e,n,i,r]),c=o.some(b=>b.isLoading),u=(b,y)=>{s(x=>({...x,[b]:{...x[b]||Kq,...y}}))},d=b=>{const y=l.find(S=>S.printerId===b);if(!y||!y.status||!n?.filaments)return;const x=Wq(n,y.status);if(!x)return;const v={};x.forEach((S,N)=>{S!==-1&&(v[N+1]=S)}),u(b,{useDefault:!1,manualMappings:v,autoConfigured:!0})},h=()=>{for(const b of t)d(b)},p=b=>l.find(x=>x.printerId===b)?.finalMapping,m=l.every(b=>b.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:h,autoConfigurePrinter:d,getFinalMapping:p,allPrintersReady:m}}function $8e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=an(),[i,s]=_.useState(!1),o=(u,d)=>{if(u<=0)return;const h={...t.config.manualMappings};d===""?delete h[u]:h[u]=parseInt(d,10),n({useDefault:!1,manualMappings:h,autoConfigured:!1})},l=async()=>{s(!0);try{await ae.refreshPrinterStatus(t.printerId),await new Promise(u=>setTimeout(u,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(u=>{const d=u.slot_id||0,h=t.config.manualMappings[d];let p,m=!1;if(h!==void 0)p=t.loadedFilaments.find(y=>y.globalTrayId===h),m=!0;else{const y=new Set(Object.values(t.config.manualMappings)),x=t.loadedFilaments.find(N=>!y.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase()&&yi(N.color)===yi(u.color)),v=x?void 0:t.loadedFilaments.find(N=>!y.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase()&&pc(N.color,u.color)),S=x||v?void 0:t.loadedFilaments.find(N=>!y.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase());p=x??v??S}let b="mismatch";if(p){const y=p.type?.toUpperCase()===u.type?.toUpperCase(),x=yi(p.color)===yi(u.color)||pc(p.color,u.color);y&&x?b="match":y&&(b="type_only")}return{req:u,loaded:p,status:b,isManual:m}});return a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),a.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:i,children:[a.jsx(Or,{className:`w-3 h-3 ${i?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),c.map(({req:u,loaded:d,status:h,isManual:p},m)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${u.type} - ${ub(u.color)}`,children:a.jsx(Sj,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),a.jsxs("span",{className:"text-white truncate",children:[u.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:d?.globalTrayId??"",onChange:b=>o(u.slot_id||0,b.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${h==="match"?"border-bambu-green/50 text-bambu-green":h==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${p?"ring-1 ring-blue-400/50":""}`,title:p?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),t.loadedFilaments.map(b=>a.jsxs("option",{value:b.globalTrayId,className:"bg-bambu-dark text-white",children:[b.label,": ",b.type," (",b.colorName,")"]},b.globalTrayId))]}),h==="match"?a.jsx($i,{className:"w-3 h-3 text-bambu-green"}):h==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(En,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(En,{className:"w-3 h-3 text-orange-400"})})]},m))]})}function V8e({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:s=!1,printerMappingResults:o,filamentReqs:l,onAutoConfigurePrinter:c,onUpdatePrinterConfig:u,assignmentMode:d="printer",onAssignmentModeChange:h,targetModel:p,onTargetModelChange:m,targetLocation:b,onTargetLocationChange:y,slicedForModel:x}){const[v,S]=_.useState(!1),N=s?t:t.filter(I=>I.is_active),T=_.useMemo(()=>{if(d!=="printer"||!x||v)return N;const I=N.filter(K=>K.model===x);return I.length>0?I:N},[N,d,x,v]),M=N.length-T.length,A=_.useMemo(()=>{const I=N.map(K=>K.model).filter(K=>!!K);return[...new Set(I)].sort()},[N]),k=_.useMemo(()=>{if(!p)return[];const I=N.filter(K=>K.model===p&&K.location).map(K=>K.location).filter(K=>!!K);return[...new Set(I)].sort()},[N,p]),R=h&&m&&A.length>0,C=i&&e.length>1&&o&&l?.filaments&&l.filaments.length>0&&c&&u;if(r)return a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(T.length===0)return a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[a.jsx(Ti,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const P=I=>{i?e.includes(I)?n(e.filter(K=>K!==I)):n([...e,I]):n([I])},U=()=>{n(T.map(I=>I.id))},F=()=>{n([])},H=(I,K,Q)=>{Q.stopPropagation(),!(!c||!u)&&(K?c(I):u(I,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},D=I=>e.includes(I),$=e.length,G=I=>o?.find(K=>K.printerId===I);return a.jsxs("div",{className:"space-y-2 mb-6",children:[R&&a.jsxs("div",{className:"flex gap-2 mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>{h("printer"),m(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d==="printer"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(jr,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),a.jsxs("button",{type:"button",onClick:()=>{h("model"),n([]);const I=x&&A.includes(x)?x:A[0];m(I)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d==="model"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(zf,{className:"w-4 h-4"}),a.jsxs("span",{className:"text-sm",children:["Any ",x||"Model"]})]})]}),d==="model"&&R&&a.jsxs("div",{className:"space-y-3 mb-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),a.jsxs("select",{value:p||"",onChange:I=>{m(I.target.value||null),y&&y(null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[a.jsx("option",{value:"",children:"Select a model..."}),A.map(I=>a.jsx("option",{value:I,children:I},I))]})]}),p&&k.length>0&&y&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),a.jsxs("select",{value:b||"",onChange:I=>y(I.target.value||null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[a.jsx("option",{value:"",children:"Any location"}),k.map(I=>a.jsx("option",{value:I,children:I},I))]})]}),p&&a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",p," printer",b?` in ${b}`:""]})]}),d==="printer"&&i&&T.length>1&&a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[a.jsx("span",{children:$===0?"Select printers":`${$} printer${$!==1?"s":""} selected`}),a.jsxs("div",{className:"flex gap-2",children:[$0&&a.jsx("button",{type:"button",onClick:F,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),d==="printer"&&T.map(I=>{const K=D(I.id),Q=G(I.id),oe=Q&&!Q.config.useDefault;return a.jsxs("div",{children:[a.jsxs("button",{type:"button",onClick:()=>P(I.id),className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${K?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${I.is_active?"":"opacity-60"}`,children:[a.jsx("div",{className:`p-2 rounded-lg ${K?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(jr,{className:`w-5 h-5 ${K?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{className:"text-left flex-1",children:[a.jsxs("p",{className:"text-white font-medium",children:[I.name,!I.is_active&&a.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[I.model||"Unknown model"," • ",I.ip_address]})]}),i&&a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${K?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:K&&a.jsx($i,{className:"w-3 h-3 text-white"})})]}),K&&C&&Q&&a.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:B=>B.stopPropagation(),children:[a.jsx("input",{type:"checkbox",checked:oe,onChange:B=>H(I.id,B.target.checked,B),className:"w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),a.jsxs("span",{className:`text-xs ml-2 ${Q.matchStatus==="full"?"text-bambu-green":Q.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",Q.exactMatches,"/",Q.totalSlots," matched)"]}),Q.isLoading&&a.jsx(Or,{className:"w-3 h-3 text-bambu-gray animate-spin"}),oe&&a.jsxs("button",{type:"button",onClick:B=>{B.stopPropagation(),c(I.id)},className:"ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",children:[a.jsx(jfe,{className:"w-3 h-3"}),"Auto"]})]}),oe&&a.jsx($8e,{printerResult:Q,filamentReqs:l.filaments,onUpdateConfig:B=>u(I.id,B)})]})]},I.id)}),d==="printer"&&M>0&&!v&&a.jsxs("button",{type:"button",onClick:()=>S(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[a.jsx(En,{className:"w-3 h-3 text-yellow-400"}),M," other printer",M>1?"s":""," hidden (different model) —",a.jsx("span",{className:"underline",children:"show all"})]}),d==="printer"&&v&&x&&a.jsx("button",{type:"button",onClick:()=>S(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:a.jsxs("span",{className:"underline",children:["Show only ",x," printers"]})}),d==="printer"&&$===0&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Ti,{className:"w-3 h-3"}),"Select at least one printer"]}),d==="model"&&!p&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Ti,{className:"w-3 h-3"}),"Select a target printer model"]})]})}function G8e({plates:t,isMultiPlate:e,selectedPlate:n,onSelect:r}){return!e||t.length<=1?null:a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(is,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"Select Plate to Print"}),!n&&a.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[a.jsx(En,{className:"w-3 h-3"}),"Selection required"]})]}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(i=>a.jsxs("button",{type:"button",onClick:()=>r(i.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${n===i.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[i.has_thumbnail&&i.thumbnail_url!=null?a.jsx("img",{src:i.thumbnail_url,alt:`Plate ${i.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(is,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name||`Plate ${i.index}`}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[i.objects.length>0?i.objects.slice(0,3).join(", ")+(i.objects.length>3?"...":""):`${i.filaments.length} filament${i.filaments.length!==1?"s":""}`,i.print_time_seconds!=null?` • ${I8e(i.print_time_seconds)}`:""]})]}),n===i.index&&a.jsx($i,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},i.index))})]})}function q8e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,defaultExpanded:i=!1}){const s=an(),[o,l]=_.useState(!1),[c,u]=_.useState(i),{data:d}=it({queryKey:["printer-status",t],queryFn:()=>ae.getPrinterStatus(t),enabled:!!t}),{loadedFilaments:h,filamentComparison:p,hasTypeMismatch:m,hasColorMismatch:b}=Uee(e,d,n);if(!(e?.filaments&&e.filaments.length>0)||!d)return null;const x=m?"#f97316":b?"#facc15":"#00ae42",v=(N,T)=>{if(N>0)if(T===""){const M={...n};delete M[N],r(M)}else r({...n,[N]:parseInt(T,10)})},S=async()=>{l(!0);try{await ae.refreshPrinterStatus(t),await new Promise(N=>setTimeout(N,500)),await s.refetchQueries({queryKey:["printer-status",t]})}finally{l(!1)}};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>u(!c),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(Sj,{className:"w-4 h-4",fill:x,stroke:"none"}),a.jsx("span",{children:"Filament Mapping"}),m?a.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):b?a.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):a.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),c?a.jsx(zu,{className:"w-4 h-4 ml-auto"}):a.jsx(fr,{className:"w-4 h-4 ml-auto"})]}),c&&a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),a.jsxs("button",{type:"button",onClick:S,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:o,children:[a.jsx(Or,{className:`w-3 h-3 ${o?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),p.map((N,T)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${N.type} - ${ub(N.color)}`,children:a.jsx(Sj,{className:"w-3 h-3",fill:N.color,stroke:N.color})}),a.jsxs("span",{className:"text-white truncate",children:[N.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",N.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:N.loaded?.globalTrayId??"",onChange:M=>v(N.slot_id||0,M.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${N.status==="match"?"border-bambu-green/50 text-bambu-green":N.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${N.isManual?"ring-1 ring-blue-400/50":""}`,title:N.isManual?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),h.map(M=>a.jsxs("option",{value:M.globalTrayId,className:"bg-bambu-dark text-white",children:[M.label,": ",M.type," (",M.colorName,")"]},M.globalTrayId))]}),N.status==="match"?a.jsx($i,{className:"w-3 h-3 text-bambu-green"}):N.status==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(En,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(En,{className:"w-3 h-3 text-orange-400"})})]},T)),m&&a.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}const W8e=[{key:"bed_levelling",label:"Bed Levelling",desc:"Auto-level bed before print"},{key:"flow_cali",label:"Flow Calibration",desc:"Calibrate extrusion flow"},{key:"vibration_cali",label:"Vibration Calibration",desc:"Reduce ringing artifacts"},{key:"layer_inspect",label:"First Layer Inspection",desc:"AI inspection of first layer"},{key:"timelapse",label:"Timelapse",desc:"Record timelapse video"}];function K8e({options:t,onChange:e,defaultExpanded:n=!1}){const[r,i]=_.useState(n),s=o=>{e({...t,[o]:!t[o]})};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>i(!r),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(Mk,{className:"w-4 h-4"}),a.jsx("span",{children:"Print Options"}),r?a.jsx(zu,{className:"w-4 h-4 ml-auto"}):a.jsx(fr,{className:"w-4 h-4 ml-auto"})]}),r&&a.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:W8e.map(({key:o,label:l,desc:c})=>a.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:l}),a.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),a.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>s(o),children:a.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[o]?"translate-x-5":"translate-x-0.5"}`})})]},o))})]})}function X8e({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system"}){const[i,s]=_.useState(""),[o,l]=_.useState(""),[c,u]=_.useState(!0),[d,h]=_.useState(!0),p=_.useRef(null),m=_.useRef(!1);_.useEffect(()=>{if(t.scheduleType!=="scheduled"){m.current=!1;return}if(!m.current){m.current=!0;let T;t.scheduledTime?(T=new Date(t.scheduledTime),isNaN(T.getTime())&&(T=new Date,T.setHours(T.getHours()+1,0,0,0))):(T=new Date,T.setHours(T.getHours()+1,0,0,0),e({...t,scheduledTime:jj(T)})),s(rB(T,n)),l(iB(T,r)),u(!0),h(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const b=T=>{e({...t,scheduleType:T})},y=(T,M)=>{const A=nme(T,n),k=rme(M);u(!!A),h(!!k),A&&k&&(A.setHours(k.hours,k.minutes,0,0),A>new Date&&e({...t,scheduledTime:jj(A)}))},x=T=>{s(T),y(T,o)},v=T=>{l(T),y(i,T)},S=T=>{const M=T.target.value;if(M){const A=new Date(M);isNaN(A.getTime())||(s(rB(A,n)),l(iB(A,r)),u(!0),h(!0),e({...t,scheduledTime:M}))}},N=()=>{p.current?.showPicker()};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>b("asap"),children:[a.jsx(tr,{className:"w-4 h-4"}),"ASAP"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>b("scheduled"),children:[a.jsx(ti,{className:"w-4 h-4"}),"Scheduled"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>b("manual"),children:[a.jsx(LW,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"flex-1 relative",children:[a.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${c?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:i,onChange:T=>x(T.target.value),placeholder:eme(n)}),a.jsx("button",{type:"button",onClick:N,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:a.jsx(ti,{className:"w-4 h-4"})})]}),a.jsx("div",{className:"w-32",children:a.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${d?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:o,onChange:T=>v(T.target.value),placeholder:tme(r)})})]}),a.jsx("input",{ref:p,type:"datetime-local",className:"sr-only",value:t.scheduledTime,onChange:S,tabIndex:-1}),(!c||!d)&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:T=>e({...t,requirePreviousSuccess:T.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:T=>e({...t,autoOffAfter:T.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("label",{htmlFor:"autoOffAfter",className:"text-sm text-bambu-gray flex items-center gap-1",children:[a.jsx(Ju,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t.scheduleType==="asap"?"Print will start as soon as the printer is idle.":t.scheduleType==="scheduled"?"Print will start at the scheduled time if the printer is idle. If busy, it will wait until the printer becomes available.":"Print will be staged but won't start automatically. Use the Start button to release it to the queue."})]})}const rg={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},Y8e={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function Ou({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:i,onClose:s,onSuccess:o}){const{t:l}=Yt(),c=an(),{showToast:u}=Tn(),d=!!n&&!e,[h,p]=_.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[m,b]=_.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[y,x]=_.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??rg.bed_levelling,flow_cali:i.flow_cali??rg.flow_cali,vibration_cali:i.vibration_cali??rg.vibration_cali,layer_inspect:i.layer_inspect??rg.layer_inspect,timelapse:i.timelapse??rg.timelapse}:rg),[v,S]=_.useState(()=>{if(t==="edit-queue-item"&&i){let ze="asap";i.manual_start?ze="manual":i.scheduled_time&&!qq(i.scheduled_time)&&(ze="scheduled");let be="";if(i.scheduled_time&&!qq(i.scheduled_time)){const Me=new Date(i.scheduled_time);be=jj(Me)}return{scheduleType:ze,scheduledTime:be,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after}}return Y8e}),[N,T]=_.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const ze={};return i.ams_mapping.forEach((be,Me)=>{be!==-1&&(ze[Me+1]=be)}),ze}return{}}),[M,A]=_.useState({}),[k,R]=_.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[C,P]=_.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[U,F]=_.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[H]=_.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[D]=_.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[$,G]=_.useState(!1),[I,K]=_.useState({current:0,total:0}),[Q,oe]=_.useState(new Set),B=h.length,W=h.length>0?h[0]:null,{data:J}=it({queryKey:["settings"],queryFn:ae.getSettings}),{data:ne,isLoading:me}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:fe}=it({queryKey:["archive",e],queryFn:()=>ae.getArchive(e),enabled:!!e&&!d}),{data:de}=it({queryKey:["library-file",n],queryFn:()=>ae.getLibraryFile(n),enabled:d&&!!n}),Re=fe?.sliced_for_model||de?.sliced_for_model||null,{data:se,isError:ke}=it({queryKey:["archive-plates",e],queryFn:()=>ae.getArchivePlates(e),enabled:!!e&&!d,retry:!1}),{data:Fe}=it({queryKey:["library-file-plates",n],queryFn:()=>ae.getLibraryFilePlates(n),enabled:d&&!!n}),ce=d?Fe:se,{data:Ve,isError:V}=it({queryKey:["archive-filaments",e,m],queryFn:()=>ae.getArchiveFilamentRequirements(e,m??void 0),enabled:!!e&&!d&&(m!==null||!ce?.is_multi_plate),retry:!1}),{data:Y}=it({queryKey:["library-file-filaments",n,m],queryFn:()=>ae.getLibraryFileFilamentRequirements(n,m??void 0),enabled:d&&!!n&&(m!==null||!ce?.is_multi_plate)}),ue=!d&&(ke||V),q=d?Y:Ve,{data:re}=it({queryKey:["printer-status",W],queryFn:()=>ae.getPrinterStatus(W),enabled:!!W}),{amsMapping:X}=Uee(q,re,N),le=H8e(h,ne,q,N,M,A);_.useEffect(()=>{ce?.plates?.length===1&&!m&&b(ce.plates[0].index)},[ce,m]),_.useEffect(()=>{if(t==="edit-queue-item")return;const ze=ne?.filter(be=>be.is_active)||[];ze.length===1&&h.length===0&&p([ze[0].id])},[t,ne,h.length]),_.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(h.sort())!==JSON.stringify(H.sort())||m!==D)&&(T({}),A({}),oe(new Set)):(T({}),A({}),oe(new Set))},[t,h,m,H,D]),_.useEffect(()=>{if(!J?.per_printer_mapping_expanded||h.length<=1)return;const ze=h.filter(be=>{if(Q.has(be))return!1;const Me=le.printerResults.find(Be=>Be.printerId===be);return Me&&Me.status&&!Me.isLoading});ze.length>0&&(oe(be=>{const Me=new Set(be);return ze.forEach(Be=>Me.add(Be)),Me}),ze.forEach(be=>{le.autoConfigurePrinter(be)}))},[J?.per_printer_mapping_expanded,h,Q,le]),_.useEffect(()=>{const ze=be=>{be.key==="Escape"&&!$&&s()};return window.addEventListener("keydown",ze),()=>window.removeEventListener("keydown",ze)},[s,$]);const pe=ce?.is_multi_plate??!1,ee=ce?.plates??[],z=dt({mutationFn:ze=>ae.addToQueue(ze)}),O=dt({mutationFn:ze=>ae.updateQueueItem(i.id,ze),onSuccess:()=>{c.invalidateQueries({queryKey:["queue"]}),u("Queue item updated"),o?.(),s()},onError:ze=>{u(ze.message||"Failed to update queue item","error")}}),Z=async ze=>{if(ze?.preventDefault(),k==="printer"&&h.length===0){u("Please select at least one printer","error");return}if(k==="model"&&!C){u("Please select a target printer model","error");return}G(!0);const be=k==="model"?1:h.length;K({current:0,total:be});const Me={success:0,failed:0,errors:[]},Be=qe=>{if(h.length>1){const ve=M[qe];if(ve&&!ve.useDefault)return le.getFinalMapping(qe)}return X},Ae=qe=>({printer_id:k==="printer"?qe:null,target_model:k==="model"?C:null,target_location:k==="model"?U:null,archive_id:d?void 0:e,library_file_id:d?n:void 0,require_previous_success:v.requirePreviousSuccess,auto_off_after:v.autoOffAfter,manual_start:v.scheduleType==="manual",ams_mapping:qe?Be(qe):void 0,plate_id:m,scheduled_time:v.scheduleType==="scheduled"&&v.scheduledTime?new Date(v.scheduledTime).toISOString():void 0,...y});if(k==="model"){K({current:1,total:1});try{if(t==="reprint"){u("Model-based assignment only works with queue mode","error"),G(!1);return}else if(t==="edit-queue-item"){const qe={printer_id:null,target_model:C,target_location:U,require_previous_success:v.requirePreviousSuccess,auto_off_after:v.autoOffAfter,manual_start:v.scheduleType==="manual",ams_mapping:void 0,plate_id:m,scheduled_time:v.scheduleType==="scheduled"&&v.scheduledTime?new Date(v.scheduledTime).toISOString():null,...y};await O.mutateAsync(qe)}else await z.mutateAsync(Ae(null));Me.success++}catch(qe){Me.failed++,Me.errors.push(qe.message)}}else for(let qe=0;qeYe.id===ve)?.name||`Printer ${ve}`;Me.errors.push(`${Ee}: ${et.message}`)}}if(G(!1),Me.failed===0){if(k==="model")u(t==="edit-queue-item"?"Queue item updated":`Queued for any ${C}`);else{const qe=t==="reprint"?"sent to":t==="edit-queue-item"?"updated/queued for":"queued for";Me.success===1?u(t==="edit-queue-item"?"Queue item updated":`Print ${qe} printer`):u(`Print ${qe} ${Me.success} printers`)}c.invalidateQueries({queryKey:["queue"]}),o?.(),s()}else Me.success===0?u(`Failed: ${Me.errors[0]}`,"error"):(u(`${Me.success} succeeded, ${Me.failed} failed`,"error"),c.invalidateQueries({queryKey:["queue"]}))},ge=$||O.isPending,Ce=_.useMemo(()=>!(ge||k==="printer"&&h.length===0||k==="model"&&!C||k==="model"&&t==="reprint"||!d&&pe&&!m),[h.length,k,C,t,pe,m,ge,d]),Te=(()=>{const ze=h.length;return t==="reprint"?{title:l(d?"queue.print":"queue.reprint"),icon:jr,submitText:ze>1?l("queue.printToPrinters",{count:ze}):l("queue.print"),submitIcon:jr,loadingText:I.total>1?l("queue.sendingProgress",{current:I.current,total:I.total}):l("queue.sending")}:t==="add-to-queue"?{title:l("queue.schedulePrint"),icon:ti,submitText:ze>1?l("queue.queueToPrinters",{count:ze}):l("queue.addToQueue"),submitIcon:ti,loadingText:I.total>1?l("queue.addingProgress",{current:I.current,total:I.total}):l("queue.adding")}:{title:l("queue.editQueueItem"),icon:Ji,submitText:l("common.save"),submitIcon:Ji,loadingText:I.total>1?l("queue.savingProgress",{current:I.current,total:I.total}):l("common.saving")}})(),we=Te.icon,$e=Te.submitIcon,Ge=W&&(d||(pe?m!==null:!0));return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:$?void 0:s,children:a.jsx(St,{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto",onClick:ze=>ze.stopPropagation(),children:a.jsxs(Et,{className:t==="reprint"?"":"p-0",children:[a.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(we,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:Te.title})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:s,disabled:$,children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Z,className:t==="reprint"?"":"p-4 space-y-4",children:[a.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?a.jsxs(a.Fragment,{children:["Send ",a.jsx("span",{className:"text-white",children:r})," to printer(s)"]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),a.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),a.jsx(G8e,{plates:ee,isMultiPlate:pe,selectedPlate:m,onSelect:b}),a.jsx(V8e,{printers:ne||[],selectedPrinterIds:h,onMultiSelect:p,isLoading:me,allowMultiple:!0,showInactive:t==="edit-queue-item",printerMappingResults:le.printerResults,filamentReqs:q,onAutoConfigurePrinter:le.autoConfigurePrinter,onUpdatePrinterConfig:le.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":k,onAssignmentModeChange:t!=="reprint"?R:void 0,targetModel:C,onTargetModelChange:t!=="reprint"?P:void 0,targetLocation:U,onTargetLocationChange:t!=="reprint"?F:void 0,slicedForModel:Re}),Re&&k==="printer"&&h.length===1&&(()=>{const ze=ne?.find(be=>be.id===h[0]);return ze&&ze.model&&Re!==ze.model?a.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[a.jsx(En,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",Re,", but printing on ",ze.model]})]}):null})(),ue&&a.jsxs("div",{className:"flex items-start gap-2 p-3 mb-2 bg-orange-500/10 border border-orange-500/30 rounded-lg text-sm",children:[a.jsx(Ti,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),Ge&&!ue&&h.length===1&&a.jsx(q8e,{printerId:W,filamentReqs:q,manualMappings:N,onManualMappingChange:T,defaultExpanded:J?.per_printer_mapping_expanded??!1}),(t==="reprint"||B>0||k==="model"&&C)&&a.jsx(K8e,{options:y,onChange:x}),t!=="reprint"&&a.jsx(X8e,{options:v,onChange:S,dateFormat:J?.date_format||"system",timeFormat:J?.time_format||"system"}),O.isError&&a.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:O.error?.message||"Failed to complete operation"}),a.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:s,className:"flex-1",disabled:$,children:"Cancel"}),a.jsx(Ne,{type:"submit",disabled:!Ce,className:"flex-1",children:ge?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),Te.loadingText]}):a.jsxs(a.Fragment,{children:[a.jsx($e,{className:"w-4 h-4"}),Te.submitText]})})]})]})]})})})}function Q8e({onClose:t,initialFiles:e}){const{t:n}=Yt(),r=an(),{showToast:i}=Tn(),s=_.useRef(null),[o,l]=_.useState(()=>e?.filter(M=>M.name.endsWith(".3mf")).map(M=>({file:M,status:"pending"}))||[]),[c,u]=_.useState(!1),[d,h]=_.useState(null);_.useEffect(()=>{const M=A=>{A.key==="Escape"&&t()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[t]);const p=dt({mutationFn:M=>ae.uploadArchivesBulk(M),onSuccess:M=>{h(M),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(A=>A.map(k=>{const R=M.results.find(P=>P.filename===k.file.name),C=M.errors.find(P=>P.filename===k.file.name);return R?{...k,status:"success",archiveId:R.id}:C?{...k,status:"error",error:C.error}:k})),M.failed===0?i(`${M.uploaded} file${M.uploaded!==1?"s":""} uploaded`):M.uploaded===0?i(`Failed to upload ${M.failed} file${M.failed!==1?"s":""}`,"error"):i(`${M.uploaded} uploaded, ${M.failed} failed`,"warning")},onError:()=>{l(M=>M.map(A=>({...A,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),m=_.useCallback(M=>{M.preventDefault(),u(!0)},[]),b=_.useCallback(M=>{M.preventDefault(),u(!1)},[]),y=_.useCallback(M=>{M.preventDefault(),u(!1);const A=Array.from(M.dataTransfer.files).filter(k=>k.name.endsWith(".3mf"));A.length>0&&l(k=>[...k,...A.map(R=>({file:R,status:"pending"}))])},[]),x=_.useCallback(M=>{const A=Array.from(M.target.files||[]).filter(k=>k.name.endsWith(".3mf"));A.length>0&&l(k=>[...k,...A.map(R=>({file:R,status:"pending"}))]),s.current&&(s.current.value="")},[]),v=_.useCallback(M=>{l(A=>A.filter((k,R)=>R!==M))},[]),S=()=>{if(o.length===0)return;const M=o.filter(A=>A.status==="pending");M.length!==0&&(l(A=>A.map(k=>k.status==="pending"?{...k,status:"uploading"}:k)),p.mutate(M.map(A=>A.file)))},N=o.filter(M=>M.status==="pending").length,T=p.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4",children:a.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:m,onDragLeave:b,onDrop:y,children:[a.jsx(Na,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(Ne,{variant:"secondary",onClick:()=>s.current?.click(),disabled:T,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:x})]})}),a.jsx("div",{className:"px-4 pb-4",children:a.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&a.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:a.jsx("div",{className:"space-y-2",children:o.map((M,A)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(xk,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:M.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(M.file.size/(1024*1024)).toFixed(1)," MB"]}),M.status==="pending"&&a.jsx("button",{onClick:()=>v(A),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:T,children:a.jsx(Lt,{className:"w-4 h-4"})}),M.status==="uploading"&&a.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"}),M.status==="success"&&a.jsx(mr,{className:"w-4 h-4 text-bambu-green"}),M.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:M.error}),a.jsx(Ti,{className:"w-4 h-4 text-red-400"})]})]},`${M.file.name}-${A}`))})}),d&&a.jsx("div",{className:"px-4 pb-4",children:a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"text-bambu-green",children:d.uploaded})," ",n("uploadModal.uploaded"),d.failed>0&&a.jsxs(a.Fragment,{children:[", ",a.jsx("span",{className:"text-red-400",children:d.failed})," ",n("uploadModal.failed")]})]})})}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ne,{variant:"secondary",onClick:t,className:"flex-1",children:n(d?"common.close":"common.cancel")}),!d&&a.jsx(Ne,{onClick:S,disabled:N===0||T,className:"flex-1",children:T?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Na,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const Z8e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],J8e=["completed","failed","aborted","printing"];function Bee({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Yt();_.useEffect(()=>{const se=ke=>{ke.key==="Escape"&&e()};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[e]);const i=an(),[s,o]=_.useState(t.print_name||""),[l,c]=_.useState(t.printer_id),[u,d]=_.useState(t.project_id??null),[h,p]=_.useState(t.notes||""),[m,b]=_.useState(t.tags||""),[y,x]=_.useState(t.failure_reason||""),[v,S]=_.useState(t.status),[N,T]=_.useState(t.quantity??1),[M,A]=_.useState(t.photos||[]),[k,R]=_.useState(t.external_url||""),[C,P]=_.useState(!1),[U,F]=_.useState(!1),H=_.useRef(null),D=_.useRef(null),$=_.useRef(null),{data:G}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:I}=it({queryKey:["projects"],queryFn:()=>ae.getProjects()}),{data:K}=it({queryKey:["tags"],queryFn:ae.getTags,enabled:n.length===0}),Q=n.length>0?n:K?.map(se=>se.name)||[],oe=m.split(",").map(se=>se.trim()).filter(Boolean),B=m.includes(",")?m.substring(m.lastIndexOf(",")+1).trim().toLowerCase():m.trim().toLowerCase(),W=Q.filter(se=>!oe.includes(se)&&(B===""||se.toLowerCase().includes(B))),J=se=>{let ke;if(B&&!Q.includes(B)?ke=m.includes(",")?m.substring(0,m.lastIndexOf(",")).split(",").map(Fe=>Fe.trim()).filter(Boolean):[]:ke=oe,!ke.includes(se)){const Fe=[...ke,se].join(", ");b(Fe)}$.current!==null&&clearTimeout($.current),H.current?.focus()},ne=se=>{const ke=oe.filter(Fe=>Fe!==se).join(", ");b(ke)},me=dt({mutationFn:se=>ae.updateArchive(t.id,se),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),fe=async se=>{const ke=se.target.files?.[0];if(ke){P(!0);try{const Fe=await ae.uploadArchivePhoto(t.id,ke);A(Fe.photos),i.invalidateQueries({queryKey:["archives"]})}catch(Fe){console.error("Failed to upload photo:",Fe)}finally{P(!1),D.current&&(D.current.value="")}}},de=async se=>{try{const ke=await ae.deleteArchivePhoto(t.id,se);A(ke.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(ke){console.error("Failed to delete photo:",ke)}},Re=se=>{se.preventDefault();const ke={print_name:s||void 0,printer_id:l,project_id:u,notes:h||void 0,tags:m||void 0,quantity:N,external_url:k||null};v!==t.status&&(ke.status=v),v==="failed"||v==="aborted"?ke.failure_reason=y||void 0:(t.status==="failed"||t.status==="aborted")&&(ke.failure_reason=null),me.mutate(ke)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:se=>se.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Re,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),a.jsx("input",{type:"text",value:s,onChange:se=>o(se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("editArchive.namePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),a.jsxs("select",{value:l??"",onChange:se=>c(se.target.value?Number(se.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noPrinter")}),G?.map(se=>a.jsx("option",{value:se.id,children:se.name},se.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(rs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:u??"",onChange:se=>d(se.target.value?Number(se.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noProject")}),I?.map(se=>a.jsx("option",{value:se.id,children:se.name},se.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(_de,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:N,onChange:se=>T(Math.max(1,parseInt(se.target.value)||1)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),a.jsx("textarea",{value:h,onChange:se=>p(se.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:r("editArchive.notesPlaceholder")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx($y,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:k,onChange:se=>R(se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),oe.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:oe.map(se=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[a.jsx(Th,{className:"w-3 h-3"}),se,a.jsx("button",{type:"button",onClick:()=>ne(se),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Lt,{className:"w-3 h-3"})})]},se))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:H,type:"text",value:m,onChange:se=>b(se.target.value),onFocus:()=>{$.current!==null&&clearTimeout($.current),F(!0)},onBlur:()=>{$.current=window.setTimeout(()=>F(!1),200)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:oe.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),U&&W.length>0&&a.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[a.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[B?r("editArchive.matchingTags",{query:B}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:W.map(se=>a.jsx("button",{type:"button",onClick:()=>J(se),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:se},se))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:v,onChange:se=>{S(se.target.value),se.target.value==="completed"&&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:J8e.map(se=>a.jsx("option",{value:se,children:r(`editArchive.statuses.${se}`)},se))})]}),(v==="failed"||v==="aborted")&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),a.jsxs("select",{value:y,onChange:se=>x(se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.selectReason")}),Z8e.map(se=>a.jsx("option",{value:r(`editArchive.failureReasons.${se}`),children:r(`editArchive.failureReasons.${se}`)},se))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx($g,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[M.map(se=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:ae.getArchivePhotoUrl(t.id,se),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>de(se),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(ln,{className:"w-3 h-3 text-white"})})]},se)),a.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[a.jsx("input",{ref:D,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:fe,className:"hidden",disabled:C}),C?a.jsx(ct,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(cr,{className:"w-6 h-6 text-bambu-gray"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(Ne,{type:"submit",disabled:me.isPending,className:"flex-1",children:[a.jsx(vs,{className:"w-4 h-4"}),me.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function Hee({x:t,y:e,items:n,onClose:r}){const i=_.useRef(null),[s,o]=_.useState(null),l=_.useRef(null),[c,u]=_.useState({x:t,y:e,visible:!1}),[d,h]=_.useState(!1),[p,m]=_.useState({});_.useEffect(()=>{const x=N=>{i.current&&!i.current.contains(N.target)&&r()},v=N=>{N.key==="Escape"&&r()},S=()=>{r()};return document.addEventListener("mousedown",x),document.addEventListener("keydown",v),document.addEventListener("scroll",S,!0),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",v),document.removeEventListener("scroll",S,!0),l.current&&clearTimeout(l.current)}},[r]),_.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const x=i.current.getBoundingClientRect(),v=window.innerWidth,S=window.innerHeight,N=8;let T=t,M=e;t+x.width>v-N&&(T=Math.max(N,v-x.width-N)),TS-N&&(M=Math.max(N,S-x.height-N)),MA),u({x:T,y:M,visible:!0})}},[t,e]);const b=(x,v)=>{l.current&&(clearTimeout(l.current),l.current=null);const S=v.getBoundingClientRect(),N=window.innerHeight,T=300,k=N-S.top-8T;m(R=>({...R,[x]:k?"bottom":"top"})),o(x)},y=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return a.jsx("div",{ref:i,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:n.map((x,v)=>{if(x.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},v);const S=x.submenu&&x.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:N=>S&&b(v,N.currentTarget),onMouseLeave:()=>S&&y(),children:[a.jsxs("button",{onMouseEnter:N=>S&&b(v,N.currentTarget.parentElement),onClick:()=>{S?o(s===v?null:v):x.disabled||(x.onClick(),r())},disabled:x.disabled,title:x.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${x.disabled?"text-bambu-gray cursor-not-allowed":x.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${S&&s===v?"bg-bambu-dark-tertiary":""}`,children:[x.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:x.icon}),a.jsx("span",{className:"flex-1",children:x.label}),S&&a.jsx(ks,{className:"w-4 h-4 text-bambu-gray"})]}),S&&s===v&&a.jsx("div",{className:`absolute min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${d?"right-full mr-1":"left-full ml-1"} ${p[v]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>y(),children:x.submenu.map((N,T)=>a.jsxs("button",{onClick:()=>{N.disabled||(N.onClick(),r())},disabled:N.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${N.disabled?"text-bambu-gray cursor-not-allowed":N.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[N.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:N.icon}),N.label]},T))})]},v)})})}function e6e({selectedIds:t,existingTags:e,onClose:n}){const r=an(),{showToast:i}=Tn(),[s,o]=_.useState(""),[l,c]=_.useState(new Set),[u,d]=_.useState("add");_.useEffect(()=>{const y=x=>{x.key==="Escape"&&n()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[n]);const h=dt({mutationFn:async()=>{const y=Array.from(l);let x=0;for(const v of t)try{const S=await ae.getArchive(v),N=S.tags?S.tags.split(",").map(M=>M.trim()).filter(Boolean):[];let T;u==="add"?T=[...new Set([...N,...y])]:T=N.filter(M=>!l.has(M)),await ae.updateArchive(v,{tags:T.join(", ")}),x++}catch(S){throw console.error(`Failed to update archive ${v}:`,S),new Error(`Failed on archive ${v}: ${S instanceof Error?S.message:"Unknown error"}`)}return{count:x,mode:u,tags:y}},onSuccess:({count:y,mode:x,tags:v})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${x==="add"?"Added":"Removed"} ${v.length} tag${v.length!==1?"s":""} ${x==="add"?"to":"from"} ${y} archive${y!==1?"s":""}`),n()},onError:y=>{i(y.message||"Failed to update tags","error")}}),p=y=>{c(x=>{const v=new Set(x);return v.has(y)?v.delete(y):v.add(y),v})},m=()=>{s.trim()&&!l.has(s.trim())&&(c(y=>new Set([...y,s.trim()])),o(""))},b=y=>{y.key==="Enter"&&(y.preventDefault(),m())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-md",children:a.jsxs(Et,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Th,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:u==="add"?"Add Tags":"Remove Tags"})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:[u==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ne,{size:"sm",variant:u==="add"?"primary":"secondary",onClick:()=>d("add"),children:"Add Tags"}),a.jsx(Ne,{size:"sm",variant:u==="remove"?"primary":"secondary",onClick:()=>d("remove"),children:"Remove Tags"})]}),u==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:y=>o(y.target.value),onKeyDown:b}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:m,disabled:!s.trim(),children:a.jsx(cr,{className:"w-4 h-4"})})]}),e.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(y=>a.jsx("button",{onClick:()=>p(y),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(y)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:y},y))})]}),l.size>0&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",u==="add"?"add":"remove",":"]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(y=>a.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${u==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[y,a.jsx("button",{onClick:()=>p(y),className:"hover:opacity-70",children:a.jsx(Lt,{className:"w-3 h-3"})})]},y))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ne,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(Ne,{onClick:()=>h.mutate(),disabled:l.size===0||h.isPending,className:"flex-1",children:h.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Th,{className:"w-4 h-4"}),u==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function t6e({selectedIds:t,onClose:e}){const n=an(),{showToast:r}=Tn(),{data:i,isLoading:s}=it({queryKey:["projects"],queryFn:()=>ae.getProjects()});_.useEffect(()=>{const d=h=>{h.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=dt({mutationFn:async d=>(await ae.addArchivesToProject(d,t),d),onSuccess:d=>{const h=i?.find(p=>p.id===d);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${h?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=dt({mutationFn:async()=>{for(const d of t)await ae.updateArchive(d,{project_id:null});return t.length},onSuccess:d=>{o(),r(`Removed ${d} archive${d!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),u=l.isPending||c.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Et,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rs,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:u,children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("button",{onClick:()=>c.mutate(),disabled:u,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:a.jsx(Zi,{className:"w-4 h-4 text-red-400"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&a.jsx(ct,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&a.jsxs("div",{className:"flex items-center gap-2 py-2",children:[a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(d=>a.jsxs("button",{onClick:()=>l.mutate(d.id),disabled:u,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:d.color?`${d.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:a.jsx(rs,{className:"w-4 h-4",style:{color:d.color||"rgb(var(--bambu-green))"}})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:d.name}),a.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[d.archive_count," archive",d.archive_count!==1?"s":"",d.status&&` • ${d.status}`]})]}),l.isPending&&l.variables===d.id&&a.jsx(ct,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},d.id)),(!i||i.length===0)&&a.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:a.jsx(Ne,{variant:"secondary",onClick:e,className:"flex-1",disabled:u,children:"Cancel"})})]})})})}function n6e(t,e){return new Date(t,e+1,0).getDate()}function r6e(t,e){return new Date(t,e,1).getDay()}const i6e=["January","February","March","April","May","June","July","August","September","October","November","December"],a6e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function s6e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,s]=_.useState(r.getMonth()),[o,l]=_.useState(r.getFullYear()),[c,u]=_.useState(null),[d,h]=_.useState(null),p=_.useMemo(()=>{const M=new Map;return t.forEach(A=>{const k=zi(A.completed_at||A.created_at)||new Date,R=`${k.getFullYear()}-${String(k.getMonth()+1).padStart(2,"0")}-${String(k.getDate()).padStart(2,"0")}`,C=M.get(R)||[];C.push(A),M.set(R,C)}),M},[t]),m=n6e(o,i),b=r6e(o,i),y=()=>{i===0?(s(11),l(o-1)):s(i-1)},x=()=>{i===11?(s(0),l(o+1)):s(i+1)},v=()=>{s(r.getMonth()),l(r.getFullYear())},S=[];for(let M=0;M{M!==c&&h(null),u(M)};return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("button",{onClick:y,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Eh,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:[i6e[i]," ",o]}),a.jsx("button",{onClick:v,className:"px-2 py-1 text-xs bg-bambu-dark-tertiary hover:bg-bambu-green/20 text-bambu-gray hover:text-white rounded transition-colors",children:"Today"})]}),a.jsx("button",{onClick:x,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(ks,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:a6e.map(M=>a.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:M},M))}),a.jsx("div",{className:"grid grid-cols-7 gap-1",children:S.map((M,A)=>{if(M===null)return a.jsx("div",{className:"aspect-square"},`empty-${A}`);const k=`${o}-${String(i+1).padStart(2,"0")}-${String(M).padStart(2,"0")}`,R=p.get(k)||[],C=R.length>0,P=M===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),U=k===c,F=R.filter(D=>D.status==="completed").length,H=R.filter(D=>D.status==="failed").length;return a.jsxs("button",{onClick:()=>T(U?null:k),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${U?"bg-bambu-green text-white":P?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":C?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[a.jsx("span",{className:`text-sm font-medium ${P&&!U?"text-bambu-green":""}`,children:M}),C&&a.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${H>0&&F===0?"bg-red-400":H>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:R.length})]})]},M)})}),a.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(M=>{const A=new Date(M.completed_at||M.created_at);return A.getMonth()===i&&A.getFullYear()===o}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(M=>{const A=new Date(M.completed_at||M.created_at);return A.getMonth()===i&&A.getFullYear()===o&&M.status==="completed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(M=>{const A=new Date(M.completed_at||M.created_at);return A.getMonth()===i&&A.getFullYear()===o&&M.status==="failed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),a.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(c+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),N.length>0?a.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:N.map(M=>{const A=M.id===d||M.id===n;return a.jsxs("button",{onClick:()=>{h(M.id),e?.(M)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${A?"":"hover:bg-bambu-dark-tertiary"}`,style:A?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[M.thumbnail_path?a.jsx("img",{src:ae.getArchiveThumbnail(M.id),alt:"",className:"w-12 h-12 rounded object-cover"}):a.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:M.print_name||M.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:M.status==="failed"?"text-red-400":"text-green-400",children:M.status==="failed"?"Failed":"Completed"}),M.filament_color&&a.jsx("div",{className:"flex gap-0.5",children:M.filament_color.split(",").map((k,R)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:k}},R))})]})]})]},M.id)})}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):a.jsx("div",{className:"text-center py-8",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function $ee({archiveId:t,archiveName:e,onClose:n}){const r=ae.getArchiveQRCodeUrl(t,300);_.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const i=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 flex flex-col items-center",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),a.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:a.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),a.jsxs(Ne,{onClick:i,className:"w-full",children:[a.jsx(wi,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function Vee({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[s,o]=_.useState(0),[l,c]=_.useState(!1);if(_.useEffect(()=>{const m=b=>{b.key==="Escape"&&r(),b.key==="ArrowLeft"&&o(y=>Math.max(0,y-1)),b.key==="ArrowRight"&&o(y=>Math.min(n.length-1,y+1))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[r,n.length]),_.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return r(),null;const u=n[s],d=ae.getArchivePhotoUrl(t,u),h=()=>{const m=document.createElement("a");m.href=d,m.download=`${e}_photo_${s+1}.jpg`,m.click()},p=()=>{i&&c(!0)};return a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[a.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:m=>m.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:h,children:[a.jsx(wi,{className:"w-4 h-4"}),"Download"]}),i&&a.jsx(Ne,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:a.jsx(ln,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-6 h-6"})})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&a.jsx("button",{onClick:()=>o(m=>m-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(Eh,{className:"w-8 h-8 text-white"})}),a.jsx("img",{src:d,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),so(m=>m+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(ks,{className:"w-8 h-8 text-white"})})]}),n.length>1&&a.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((m,b)=>a.jsx("button",{onClick:()=>o(b),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${b===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:a.jsx("img",{src:ae.getArchivePhotoUrl(t,m),alt:`Thumbnail ${b+1}`,className:"w-full h-full object-cover"})},m))})]}),l&&a.jsx(er,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(u),c(!1)},onCancel:()=>c(!1)})]})}function za(t){this.content=t}za.prototype={constructor:za,find:function(t){for(var e=0;e>1}};za.from=function(t){if(t instanceof za)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new za(e)};function Gee(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(r),s=e.child(r);if(i==s){n+=i.nodeSize;continue}if(!i.sameMarkup(s))return n;if(i.isText&&i.text!=s.text){for(let o=0;i.text[o]==s.text[o];o++)n++;return n}if(i.content.size||s.content.size){let o=Gee(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function qee(t,e,n,r){for(let i=t.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:n,b:r};let o=t.child(--i),l=e.child(--s),c=o.nodeSize;if(o==l){n-=c,r-=c;continue}if(!o.sameMarkup(l))return{a:n,b:r};if(o.isText&&o.text!=l.text){let u=0,d=Math.min(o.text.length,l.text.length);for(;ue&&r(c,i+l,s||null,o)!==!1&&c.content.size){let d=l+1;c.nodesBetween(Math.max(0,e-d),Math.min(c.content.size,n-d),r,i+d)}l=u}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let s="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let u=l.isText?l.text.slice(Math.max(e,c)-c,n-c):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&u||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=u},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),s=1);se)for(let s=0,o=0;oe&&((on)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,n-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,n-o-1))),r.push(l),i+=l.nodeSize),o=c}return new At(r,i)}cutByIndex(e,n){return e==n?At.empty:e==0&&n==this.content.length?this:new At(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new At(i,s)}addToStart(e){return new At([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new At(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let i=this.child(n),s=r+i.nodeSize;if(s>=e)return s==e?a1(n+1,s):a1(n,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return At.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new At(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return At.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),n.push(this),r=!0),n&&n.push(s)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;nr.type.rank-i.type.rank),n}};Lr.none=[];class gN extends Error{}class $t{constructor(e,n,r){this.content=e,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=Kee(this.content,e+this.openStart,n);return r&&new $t(r,this.openStart,this.openEnd)}removeBetween(e,n){return new $t(Wee(this.content,e+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,n){if(!n)return $t.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new $t(At.fromJSON(e,n.content),r,i)}static maxOpen(e,n=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)i++;return new $t(e,r,i)}}$t.empty=new $t(At.empty,0,0);function Wee(t,e,n){let{index:r,offset:i}=t.findIndex(e),s=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(i==e||s.isText){if(l!=n&&!t.child(o).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=o)throw new RangeError("Removing non-flat range");return t.replaceChild(r,s.copy(Wee(s.content,e-i-1,n-i-1)))}function Kee(t,e,n,r){let{index:i,offset:s}=t.findIndex(e),o=t.maybeChild(i);if(s==e||o.isText)return r&&!r.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=Kee(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function o6e(t,e,n){if(n.openStart>t.depth)throw new gN("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new gN("Inconsistent open depths");return Xee(t,e,n,0)}function Xee(t,e,n,r){let i=t.index(r),s=t.node(r);if(i==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function C0(t,e,n,r){let i=(e||t).node(n),s=0,o=e?e.index(n):i.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(rm(t.nodeAfter,r),s++));for(let l=s;li&&UD(t,e,i+1),o=r.depth>i&&UD(n,r,i+1),l=[];return C0(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(Yee(s,o),rm(im(s,Qee(t,e,n,r,i+1)),l)):(s&&rm(im(s,bN(t,e,i+1)),l),C0(e,n,i,l),o&&rm(im(o,bN(n,r,i+1)),l)),C0(r,null,i,l),new At(l)}function bN(t,e,n){let r=[];if(C0(null,t,n,r),t.depth>n){let i=UD(t,e,n+1);rm(im(i,bN(t,e,n+1)),r)}return C0(e,null,n,r),new At(r)}function l6e(t,e){let n=e.depth-t.openStart,i=e.node(n).copy(t.content);for(let s=n-1;s>=0;s--)i=e.node(s).copy(At.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class My{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(n);return r?e.child(n).cut(r):i}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,n){n=this.resolveDepth(n);let r=this.path[n*3],i=n==0?0:this.path[n*3-1]+1;for(let s=0;s0;n--)if(this.start(n)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!n||n(this.node(r))))return new xN(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],i=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),u=s-c;if(r.push(o,l,i+c),!u||(o=o.child(l),o.isText))break;s=u-1,i+=c+1}return new My(n,r,s)}static resolveCached(e,n){let r=Xq.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Zee(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=At.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=i;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let i=At.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Sh.prototype.text=void 0;class yN extends Sh{constructor(e,n,r,i){if(super(e,n,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Zee(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,n){return this.text.slice(e,n)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new yN(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new yN(this.type,this.attrs,e,this.marks)}cut(e=0,n=this.text.length){return e==0&&n==this.text.length?this:this.withText(this.text.slice(e,n))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Zee(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Em{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new h6e(e,n);if(r.next==null)return Em.empty;let i=Jee(r);r.next&&r.err("Unexpected trailing text");let s=y6e(x6e(i));return v6e(s,r),s}matchType(e){for(let n=0;nu.createAndFill()));for(let u=0;u=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` +`)}}Em.empty=new Em(!0);class h6e{constructor(e,n){this.string=e,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Jee(t){let e=[];do e.push(f6e(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function f6e(t){let e=[];do e.push(m6e(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function m6e(t){let e=b6e(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=p6e(t,e);else break;return e}function Yq(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function p6e(t,e){let n=Yq(t),r=n;return t.eat(",")&&(t.next!="}"?r=Yq(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function g6e(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let s in n){let o=n[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function b6e(t){if(t.eat("(")){let e=Jee(t);return t.eat(")")||t.err("Missing closing paren"),e}else if(/\W/.test(t.next))t.err("Unexpected token '"+t.next+"'");else{let e=g6e(t,t.next).map(n=>(t.inline==null?t.inline=n.isInline:t.inline!=n.isInline&&t.err("Mixing inline and block content"),{type:"name",value:n}));return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function x6e(t){let e=[[]];return i(s(t,0),n()),e;function n(){return e.push([])-1}function r(o,l,c){let u={term:c,to:l};return e[o].push(u),u}function i(o,l){o.forEach(c=>c.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((c,u)=>c.concat(s(u,l)),[]);if(o.type=="seq")for(let c=0;;c++){let u=s(o.exprs[c],l);if(c==o.exprs.length-1)return u;i(u,l=n())}else if(o.type=="star"){let c=n();return r(l,c),i(s(o.expr,c),c),[r(c)]}else if(o.type=="plus"){let c=n();return i(s(o.expr,l),c),i(s(o.expr,c),c),[r(c)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let c=l;for(let u=0;u{t[o].forEach(({term:l,to:c})=>{if(!l)return;let u;for(let d=0;d{u||i.push([l,u=[]]),u.indexOf(d)==-1&&u.push(d)})})});let s=e[r.join(",")]=new Em(r.indexOf(t.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:nte(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Sh(this,this.computeAttrs(e),At.from(n),Lr.setFrom(r))}createChecked(e=null,n,r){return n=At.from(n),this.checkContent(n),new Sh(this,this.computeAttrs(e),n,Lr.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=At.from(n),n.size){let o=this.contentMatch.fillBefore(n);if(!o)return null;n=o.append(n)}let i=this.contentMatch.matchFragment(n),s=i&&i.fillBefore(At.empty,!0);return s?new Sh(this,e,n.append(s),Lr.setFrom(r)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;nr[s]=new ate(s,n,o));let i=n.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function w6e(t,e,n){let r=n.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${s}`)}}class _6e{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?w6e(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class DM{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=ite(e,i.attrs),this.excluded=null;let s=tte(this.attrs);this.instance=s?new Lr(this,s):null}create(e=null){return!e&&this.instance?this.instance:new Lr(this,nte(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new DM(s,i++,n,o)),r}removeFromSet(e){for(var n=0;n-1}}class ste{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let i in e)n[i]=e[i];n.nodes=za.from(e.nodes),n.marks=za.from(e.marks||{}),this.nodes=Zq.compile(this.spec.nodes,this),this.marks=DM.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Em.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Jq(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Jq(this,o.split(" "))}this.nodeFromJSON=i=>Sh.fromJSON(this,i),this.markFromJSON=i=>Lr.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Zq){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(n,r,i)}text(e,n){let r=this.nodes.text;return new yN(r,r.defaultAttrs,e,Lr.setFrom(n))}mark(e,n){return typeof e=="string"&&(e=this.marks[e]),e.create(n)}nodeType(e){let n=this.nodes[e];if(!n)throw new RangeError("Unknown node type: "+e);return n}}function Jq(t,e){let n=[];for(let r=0;r-1)&&n.push(o=c)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function S6e(t){return t.tag!=null}function N6e(t){return t.style!=null}let P0=class HD{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(S6e(i))this.tags.push(i);else if(N6e(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,n={}){let r=new t7(this,n,!1);return r.addAll(e,Lr.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new t7(this,n,!0);return r.addAll(e,Lr.none,n.from,n.to),$t.maxOpen(r.finish())}matchTag(e,n,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=n))){if(o.getAttrs){let c=o.getAttrs(n);if(c===!1)continue;o.attrs=c||void 0}return o}}}static schemaRules(e){let n=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=n7(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=n7(o)),o.node||o.ignore||o.mark||(o.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new HD(e,HD.schemaRules(e)))}};const ote={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},k6e={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},lte={ol:!0,ul:!0},Ey=1,$D=2,j0=4;function e7(t,e,n){return e!=null?(e?Ey:0)|(e==="full"?$D:0):t&&t.whitespace=="pre"?Ey|$D:n&~j0}class s1{constructor(e,n,r,i,s,o){this.type=e,this.attrs=n,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=Lr.none,this.match=s||(o&j0?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(At.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&Ey)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let n=At.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(At.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!ote.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class t7{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=n.topNode,s,o=e7(null,n.preserveWhitespace,0)|(r?j0:0);i?s=new s1(i.type,i.attrs,Lr.none,!0,n.topMatch||i.type.contentMatch,o):r?s=new s1(null,null,Lr.none,!0,null,o):s=new s1(e.schema.topNodeType,null,Lr.none,!0,null,o),this.nodes=[s],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,n){e.nodeType==3?this.addTextNode(e,n):e.nodeType==1&&this.addElement(e,n)}addTextNode(e,n){let r=e.nodeValue,i=this.top,s=i.options&$D?"full":this.localPreserveWS||(i.options&Ey)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` +`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let c=0;c!c.clearMark(u)):n=n.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)l=c;else break}}return n}addElementByRule(e,n,r,i){let s,o;if(n.node)if(o=this.parser.schema.nodes[n.node],o.isLeaf)this.insertNode(o.create(n.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let c=this.enter(o,n.attrs||null,r,n.preserveWhitespace);c&&(s=!0,r=c)}else{let c=this.parser.schema.marks[n.mark];r=r.concat(c.create(n.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(c=>this.insertNode(c,r,!1));else{let c=e;typeof n.contentElement=="string"?c=e.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(e):n.contentElement&&(c=n.contentElement),this.findAround(e,c,!0),this.addAll(c,r),this.findAround(e,c,!1)}s&&this.sync(l)&&this.open--}addAll(e,n,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,n);this.findAtPoint(e,s)}findPlace(e,n,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let c=this.nodes[o],u=c.findWrapping(e);if(u&&(!i||i.length>u.length+l)&&(i=u,s=c,!u.length))break;if(c.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(u.type):r7(u.type,e))?(c=u.addToSet(c),!1):!0),this.nodes.push(new s1(e,n,c,i,null,l)),this.open++,r}closeExtra(e=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let n=this.open;n>=0;n--){if(this.nodes[n]==e)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=Ey)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let n=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,c)=>{for(;l>=0;l--){let u=n[l];if(u==""){if(l==n.length-1||l==0)continue;for(;c>=s;c--)if(o(l-1,c))return!0;return!1}else{let d=c>0||c==0&&i?this.nodes[c].type:r&&c>=s?r.node(c-s).type:null;if(!d||d.name!=u&&!d.isInGroup(u))return!1;c--}}return!0};return o(n.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let n=e.depth;n>=0;n--){let r=e.node(n).contentMatchAt(e.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function M6e(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&<e.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function E6e(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function n7(t){let e={};for(let n in t)e[n]=t[n];return e}function r7(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(t))continue;let s=[],o=l=>{s.push(l);for(let c=0;c{if(s.length||o.marks.length){let l=0,c=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,n);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,n,r={}){let i=this.marks[e.type.name];return i&&B1(_P(r),i(e,n),null,e.attrs)}static renderSpec(e,n,r=null,i){return B1(e,n,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new zm(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=i7(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return i7(e.marks)}}function i7(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function _P(t){return t.document||window.document}const a7=new WeakMap;function T6e(t){let e=a7.get(t);return e===void 0&&a7.set(t,e=A6e(t)),e}function A6e(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(n=i.slice(0,o),i=i.slice(o+1));let l,c=n?t.createElementNS(n,i):t.createElement(i),u=e[1],d=1;if(u&&typeof u=="object"&&u.nodeType==null&&!Array.isArray(u)){d=2;for(let h in u)if(u[h]!=null){let p=h.indexOf(" ");p>0?c.setAttributeNS(h.slice(0,p),h.slice(p+1),u[h]):h=="style"&&c.style?c.style.cssText=u[h]:c.setAttribute(h,u[h])}}for(let h=d;hd)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:m,contentDOM:b}=B1(t,p,n,r);if(c.appendChild(m),b){if(l)throw new RangeError("Multiple content holes");l=b}}}return{dom:c,contentDOM:l}}const cte=65535,ute=Math.pow(2,16);function C6e(t,e){return t+e*ute}function s7(t){return t&cte}function P6e(t){return(t-(t&cte))/ute}const dte=1,hte=2,H1=4,fte=8;class VD{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&fte)>0}get deletedBefore(){return(this.delInfo&(dte|H1))>0}get deletedAfter(){return(this.delInfo&(hte|H1))>0}get deletedAcross(){return(this.delInfo&H1)>0}}class bo{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&bo.empty)return bo.empty}recover(e){let n=0,r=s7(e);if(!this.inverted)for(let i=0;ie)break;let u=this.ranges[l+s],d=this.ranges[l+o],h=c+u;if(e<=h){let p=u?e==c?-1:e==h?1:n:n,m=c+i+(p<0?0:d);if(r)return m;let b=e==(n<0?c:h)?null:C6e(l/3,e-c),y=e==c?hte:e==h?dte:H1;return(n<0?e!=c:e!=h)&&(y|=fte),new VD(m,y,b)}i+=d-u}return r?e+i:new VD(e+i,0,null)}touches(e,n){let r=0,i=s7(n),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let u=this.ranges[l+s],d=c+u;if(e<=d&&l==i*3)return!0;r+=this.ranges[l+o]-u}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;n--){let i=e.getMirror(n);this.appendMap(e._maps[n].invert(),i!=null&&i>n?r-i-1:void 0)}}invert(){let e=new Ty;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let r=this.from;rs&&c!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),n.openStart,n.openEnd);return Hi.fromReplace(e,this.from,this.to,s)}invert(){return new Fl(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new uh(n.pos,r.pos,this.mark)}merge(e){return e instanceof uh&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new uh(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new uh(n.from,n.to,e.markFromJSON(n.mark))}}cs.jsonID("addMark",uh);class Fl extends cs{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=new $t(j4(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return Hi.fromReplace(e,this.from,this.to,r)}invert(){return new uh(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Fl(n.pos,r.pos,this.mark)}merge(e){return e instanceof Fl&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Fl(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new Fl(n.from,n.to,e.markFromJSON(n.mark))}}cs.jsonID("removeMark",Fl);class dh extends cs{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return Hi.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Hi.fromReplace(e,this.pos,this.pos+1,new $t(At.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let i=0;ir.pos?null:new _a(n.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new _a(n.from,n.to,n.gapFrom,n.gapTo,$t.fromJSON(e,n.slice),n.insert,!!n.structure)}}cs.jsonID("replaceAround",_a);function GD(t,e,n){let r=t.resolve(e),i=n-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function j6e(t,e,n,r){let i=[],s=[],o,l;t.doc.nodesBetween(e,n,(c,u,d)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&d.type.allowsMarkType(r.type)){let p=Math.max(u,e),m=Math.min(u+c.nodeSize,n),b=r.addToSet(h);for(let y=0;yt.step(c)),s.forEach(c=>t.step(c))}function D6e(t,e,n,r){let i=[],s=0;t.doc.nodesBetween(e,n,(o,l)=>{if(!o.isInline)return;s++;let c=null;if(r instanceof DM){let u=o.marks,d;for(;d=r.isInSet(u);)(c||(c=[])).push(d),u=d.removeFromSet(u)}else r?r.isInSet(o.marks)&&(c=[r]):c=o.marks;if(c&&c.length){let u=Math.min(l+o.nodeSize,n);for(let d=0;dt.step(new Fl(o.from,o.to,o.style)))}function D4(t,e,n,r=n.contentMatch,i=!0){let s=t.doc.nodeAt(e),o=[],l=e+1;for(let c=0;c=0;c--)t.step(o[c])}function R6e(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function Ub(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,s=0;;--r){let o=t.$from.node(r),l=t.$from.index(r)+i,c=t.$to.indexAfter(r)-s;if(rn;b--)y||r.index(b)>0?(y=!0,d=At.from(r.node(b).copy(d)),h++):c--;let p=At.empty,m=0;for(let b=s,y=!1;b>n;b--)y||i.after(b+1)=0;o--){if(r.size){let l=n[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=At.from(n[o].type.create(n[o].attrs,r))}let i=e.start,s=e.end;t.step(new _a(i,s,i,s,new $t(r,0,0),n.length,!0))}function z6e(t,e,n,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=t.steps.length;t.doc.nodesBetween(e,n,(o,l)=>{let c=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,c)&&U6e(t.doc,t.mapping.slice(s).map(l),r)){let u=null;if(r.schema.linebreakReplacement){let m=r.whitespace=="pre",b=!!r.contentMatch.matchType(r.schema.linebreakReplacement);m&&!b?u=!1:!m&&b&&(u=!0)}u===!1&&pte(t,o,l,s),D4(t,t.mapping.slice(s).map(l,1),r,void 0,u===null);let d=t.mapping.slice(s),h=d.map(l,1),p=d.map(l+o.nodeSize,1);return t.step(new _a(h,p,h+1,p-1,new $t(At.from(r.create(c,null,o.marks)),0,0),1,!0)),u===!0&&mte(t,o,l,s),!1}})}function mte(t,e,n,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let c=t.mapping.slice(r).map(n+1+s+o.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function pte(t,e,n,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=t.mapping.slice(r).map(n+1+s);t.replaceWith(o,o+1,e.type.schema.text(` +`))}})}function U6e(t,e,n){let r=t.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function B6e(t,e,n,r,i){let s=t.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");n||(n=s.type);let o=n.create(r,null,i||s.marks);if(s.isLeaf)return t.replaceWith(e,e+s.nodeSize,o);if(!n.validContent(s.content))throw new RangeError("Invalid content for node type "+n.name);t.step(new _a(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new $t(At.from(o),0,0),1,!0))}function Lu(t,e,n=1,r){let i=t.resolve(e),s=i.depth-n,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let u=i.depth-1,d=n-2;u>s;u--,d--){let h=i.node(u),p=i.index(u);if(h.type.spec.isolating)return!1;let m=h.content.cutByIndex(p,h.childCount),b=r&&r[d+1];b&&(m=m.replaceChild(0,b.type.create(b.attrs)));let y=r&&r[d]||h;if(!h.canReplace(p+1,h.childCount)||!y.type.validContent(m))return!1}let l=i.indexAfter(s),c=r&&r[0];return i.node(s).canReplaceWith(l,l,c?c.type:i.node(s+1).type)}function H6e(t,e,n=1,r){let i=t.doc.resolve(e),s=At.empty,o=At.empty;for(let l=i.depth,c=i.depth-n,u=n-1;l>c;l--,u--){s=At.from(i.node(l).copy(s));let d=r&&r[u];o=At.from(d?d.type.create(d.attrs,o):i.node(l).copy(o))}t.step(new va(e,e,new $t(s.append(o),n,n),!0))}function qh(t,e){let n=t.resolve(e),r=n.index();return gte(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function $6e(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&>e(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=n<0?r.before(i):r.after(i)}}function V6e(t,e,n){let r=null,{linebreakReplacement:i}=t.doc.type.schema,s=t.doc.resolve(e-n),o=s.node().type;if(i&&o.inlineContent){let d=o.whitespace=="pre",h=!!o.contentMatch.matchType(i);d&&!h?r=!1:!d&&h&&(r=!0)}let l=t.steps.length;if(r===!1){let d=t.doc.resolve(e+n);pte(t,d.node(),d.before(),l)}o.inlineContent&&D4(t,e+n-1,o,s.node().contentMatchAt(s.index()),r==null);let c=t.mapping.slice(l),u=c.map(e-n);if(t.step(new va(u,c.map(e+n,-1),$t.empty,!0)),r===!0){let d=t.doc.resolve(u);mte(t,d.node(),d.before(),t.steps.length)}return t}function G6e(t,e,n){let r=t.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),n))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,n))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,n))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,c=r.index(o)+(l>0?1:0),u=r.node(o),d=!1;if(s==1)d=u.canReplace(c,c,i);else{let h=u.contentMatchAt(c).findWrapping(i.firstChild.type);d=h&&u.canReplaceWith(c,c,h[0])}if(d)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function OM(t,e,n=e,r=$t.empty){if(e==n&&!r.size)return null;let i=t.resolve(e),s=t.resolve(n);return xte(i,s,r)?new va(e,n,r):new q6e(i,s,r).fit()}function xte(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class q6e{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=At.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=At.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let u=this.findFittable();u?this.placeNodes(u):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let c=new $t(s,o,l);return e>-1?new _a(r.pos,e,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new va(r.pos,i.pos,c):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}n=s.content}for(let n=1;n<=2;n++)for(let r=n==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=NP(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:c,match:u}=this.frontier[l],d,h=null;if(n==1&&(o?u.matchType(o.type)||(h=u.fillBefore(At.from(o),!1)):s&&c.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:h};if(n==2&&o&&(d=u.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:d};if(s&&u.matchType(s.type))break}}}openMore(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=NP(e,n);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new $t(e,n+1,Math.max(r,i.size+n>=e.size-r?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=NP(e,n);if(i.childCount<=1&&n>0){let s=e.size-n<=n+i.size;this.unplaced=new $t(p0(e,n-1,1),n-1,s?n-1:r)}else this.unplaced=new $t(p0(e,n,1),n,r)}placeNodes({sliceDepth:e,frontierDepth:n,parent:r,inject:i,wrap:s}){for(;this.depth>n;)this.closeFrontierNode();if(s)for(let y=0;y1||c==0||y.content.size)&&(h=x,d.push(yte(y.mark(p.allowedMarks(y.marks)),u==1?c:0,u==l.childCount?m:-1)))}let b=u==l.childCount;b||(m=-1),this.placed=g0(this.placed,n,At.from(d)),this.frontier[n].match=h,b&&m<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let y=0,x=l;y1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:i}=this.frontier[n],s=n=0;l--){let{match:c,type:u}=this.frontier[l],d=kP(e,l,u,c,!0);if(!d||d.childCount)continue e}return{depth:n,fit:o,move:s?e.doc.resolve(e.after(n+1)):e}}}}close(e){let n=this.findCloseLevel(e);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=g0(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,n=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=g0(this.placed,this.depth,At.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(At.empty,!0);n.childCount&&(this.placed=g0(this.placed,this.frontier.length,n))}}function p0(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(p0(t.firstChild.content,e-1,n)))}function g0(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(g0(t.lastChild.content,e-1,n)))}function NP(t,e){for(let n=0;n1&&(r=r.replaceChild(0,yte(r.firstChild,e-1,r.childCount==1?n-1:0))),e>0&&(r=t.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(At.empty,!0)))),t.copy(r)}function kP(t,e,n,r,i){let s=t.node(e),o=i?t.indexAfter(e):t.index(e);if(o==s.childCount&&!n.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!W6e(n,s.content,o)?l:null}function W6e(t,e,n){for(let r=n;r0;p--,m--){let b=i.node(p).type.spec;if(b.defining||b.definingAsContext||b.isolating)break;o.indexOf(p)>-1?l=p:i.before(p)==m&&o.splice(1,0,-p)}let c=o.indexOf(l),u=[],d=r.openStart;for(let p=r.content,m=0;;m++){let b=p.firstChild;if(u.push(b),m==r.openStart)break;p=b.content}for(let p=d-1;p>=0;p--){let m=u[p],b=K6e(m.type);if(b&&!m.sameMarkup(i.node(Math.abs(l)-1)))d=p;else if(b||!m.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let m=(p+d+1)%(r.openStart+1),b=u[m];if(b)for(let y=0;y=0&&(t.replace(e,n,r),!(t.steps.length>h));p--){let m=o[p];m<0||(e=i.before(m),n=s.after(m))}}function vte(t,e,n,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(t).append(t);t=o.append(s.matchFragment(o).fillBefore(At.empty,!0))}return t}function Y6e(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let i=G6e(t.doc,e,r.type);i!=null&&(e=n=i)}t.replaceRange(e,n,new $t(At.from(r),0,0))}function Q6e(t,e,n){let r=t.doc.resolve(e),i=t.doc.resolve(n),s=wte(r,i);for(let o=0;o0&&(c||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return t.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&n>r.end(o)&&i.end(o)-n!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return t.delete(r.before(o),n);t.delete(e,n)}function wte(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let i=r;i>=0;i--){let s=t.start(i);if(se.pos+(e.depth-i)||t.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==t.depth&&i==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&n.push(i)}return n}class Ig extends cs{constructor(e,n,r){super(),this.pos=e,this.attr=n,this.value=r}apply(e){let n=e.nodeAt(this.pos);if(!n)return Hi.fail("No node at attribute step's position");let r=Object.create(null);for(let s in n.attrs)r[s]=n.attrs[s];r[this.attr]=this.value;let i=n.type.create(r,null,n.marks);return Hi.fromReplace(e,this.pos,this.pos+1,new $t(At.from(i),0,n.isLeaf?0:1))}getMap(){return bo.empty}invert(e){return new Ig(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Ig(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Ig(n.pos,n.attr,n.value)}}cs.jsonID("attr",Ig);class Ay extends cs{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let i in e.attrs)n[i]=e.attrs[i];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return Hi.ok(r)}getMap(){return bo.empty}invert(e){return new Ay(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Ay(n.attr,n.value)}}cs.jsonID("docAttr",Ay);let db=class extends Error{};db=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};db.prototype=Object.create(Error.prototype);db.prototype.constructor=db;db.prototype.name="TransformError";class _te{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new Ty}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new db(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,r=$t.empty){let i=OM(this.doc,e,n,r);return i&&this.step(i),this}replaceWith(e,n,r){return this.replace(e,n,new $t(At.from(r),0,0))}delete(e,n){return this.replace(e,n,$t.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return X6e(this,e,n,r),this}replaceRangeWith(e,n,r){return Y6e(this,e,n,r),this}deleteRange(e,n){return Q6e(this,e,n),this}lift(e,n){return O6e(this,e,n),this}join(e,n=1){return V6e(this,e,n),this}wrap(e,n){return I6e(this,e,n),this}setBlockType(e,n=e,r,i=null){return z6e(this,e,n,r,i),this}setNodeMarkup(e,n,r=null,i){return B6e(this,e,n,r,i),this}setNodeAttribute(e,n,r){return this.step(new Ig(e,n,r)),this}setDocAttribute(e,n){return this.step(new Ay(e,n)),this}addNodeMark(e,n){return this.step(new dh(e,n)),this}removeNodeMark(e,n){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(n instanceof Lr)n.isInSet(r.marks)&&this.step(new Tm(e,n));else{let i=r.marks,s,o=[];for(;s=n.isInSet(i);)o.push(new Tm(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,n=1,r){return H6e(this,e,n,r),this}addMark(e,n,r){return j6e(this,e,n,r),this}removeMark(e,n,r){return D6e(this,e,n,r),this}clearIncompatible(e,n,r){return D4(this,e,n,r),this}}const MP=Object.create(null);class Fn{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new Z6e(e.min(n),e.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let n=0;n=0;s--){let o=n<0?hg(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):hg(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,n,r);if(o)return o}return null}static near(e,n=1){return this.findFrom(e,n)||this.findFrom(e,-n)||new ko(e.node(0))}static atStart(e){return hg(e,e,0,0,1)||new ko(e)}static atEnd(e){return hg(e,e,e.content.size,e.childCount,-1)||new ko(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=MP[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in MP)throw new RangeError("Duplicate use of selection JSON ID "+e);return MP[e]=n,n.prototype.jsonID=e,n}getBookmark(){return yn.between(this.$anchor,this.$head).getBookmark()}}Fn.prototype.visible=!0;class Z6e{constructor(e,n){this.$from=e,this.$to=n}}let l7=!1;function c7(t){!l7&&!t.parent.inlineContent&&(l7=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class yn extends Fn{constructor(e,n=e){c7(e),c7(n),super(e,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return Fn.near(r);let i=e.resolve(n.map(this.anchor));return new yn(i.parent.inlineContent?i:r,r)}replace(e,n=$t.empty){if(super.replace(e,n),n==$t.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof yn&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new LM(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new yn(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let i=e.resolve(n);return new this(i,r==n?i:e.resolve(r))}static between(e,n,r){let i=e.pos-n.pos;if((!r||i)&&(r=i>=0?1:-1),!n.parent.inlineContent){let s=Fn.findFrom(n,r,!0)||Fn.findFrom(n,-r,!0);if(s)n=s.$head;else return Fn.near(n,r)}return e.parent.inlineContent||(i==0?e=n:(e=(Fn.findFrom(e,-r,!0)||Fn.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&rn.isSelectable(l))return rn.create(t,n-(i<0?l.nodeSize:0))}else{let c=hg(t,l,n+i,i<0?l.childCount:0,i,s);if(c)return c}n+=l.nodeSize*i}return null}function u7(t,e,n){let r=t.steps.length-1;if(r{o==null&&(o=d)}),t.setSelection(Fn.near(t.doc.resolve(o),n))}const d7=1,o1=2,h7=4;class eHe extends _te{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=o1,this}ensureMarks(e){return Lr.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&o1)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~o1,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,n=!0){let r=this.selection;return n&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||Lr.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let i=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=n),!e)return this.deleteRange(n,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(n);s=r==n?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,i.text(e,s)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(Fn.near(this.selection.$to)),this}}setMeta(e,n){return this.meta[typeof e=="string"?e:e.key]=n,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=h7,this}get scrolledIntoView(){return(this.updated&h7)>0}}function f7(t,e){return!e||!t?t:t.bind(e)}class b0{constructor(e,n,r){this.name=e,this.init=f7(n.init,r),this.apply=f7(n.apply,r)}}const tHe=[new b0("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new b0("selection",{init(t,e){return t.selection||Fn.atStart(e.doc)},apply(t){return t.selection}}),new b0("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new b0("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class EP{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=tHe.slice(),n&&n.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new b0(r.key,r.spec.state,r))})}}class Ng{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,n=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(n[r]=s.toJSON.call(i,this[i.key]))}return n}static fromJSON(e,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new EP(e.schema,e.plugins),s=new Ng(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=Sh.fromJSON(e.schema,n.doc);else if(o.name=="selection")s.selection=Fn.fromJSON(s.doc,n.selection);else if(o.name=="storedMarks")n.storedMarks&&(s.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let c=r[l],u=c.spec.state;if(c.key==o.name&&u&&u.fromJSON&&Object.prototype.hasOwnProperty.call(n,l)){s[o.name]=u.fromJSON.call(c,e,n[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Ste(t,e,n){for(let r in t){let i=t[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ste(i,e,{})),n[r]=i}return n}class di{constructor(e){this.spec=e,this.props={},e.props&&Ste(e.props,this,this.props),this.key=e.key?e.key.key:Nte("plugin")}getState(e){return e[this.key]}}const TP=Object.create(null);function Nte(t){return t in TP?t+"$"+ ++TP[t]:(TP[t]=0,t+"$")}class ca{constructor(e="key"){this.key=Nte(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const L4=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function kte(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const Mte=(t,e,n)=>{let r=kte(t,n);if(!r)return!1;let i=F4(r);if(!i){let o=r.blockRange(),l=o&&Ub(o);return l==null?!1:(e&&e(t.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Ote(t,i,e,-1))return!0;if(r.parent.content.size==0&&(hb(s,"end")||rn.isSelectable(s)))for(let o=r.depth;;o--){let l=OM(t.doc,r.before(o),r.after(o),$t.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(t.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},nHe=(t,e,n)=>{let r=kte(t,n);if(!r)return!1;let i=F4(r);return i?Ete(t,i,e):!1},rHe=(t,e,n)=>{let r=Ate(t,n);if(!r)return!1;let i=I4(r);return i?Ete(t,i,e):!1};function Ete(t,e,n){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let d=i.lastChild;if(!d)return!1;i=d}let o=e.nodeAfter,l=o,c=e.pos+1;for(;!l.isTextblock;c++){if(l.type.spec.isolating)return!1;let d=l.firstChild;if(!d)return!1;l=d}let u=OM(t.doc,s,c,$t.empty);if(!u||u.from!=s||u instanceof va&&u.slice.size>=c-s)return!1;if(n){let d=t.tr.step(u);d.setSelection(yn.create(d.doc,s)),n(d.scrollIntoView())}return!0}function hb(t,e,n=!1){for(let r=t;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}const Tte=(t,e,n)=>{let{$head:r,empty:i}=t.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;s=F4(r)}let o=s&&s.nodeBefore;return!o||!rn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(rn.create(t.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function F4(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function Ate(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset{let r=Ate(t,n);if(!r)return!1;let i=I4(r);if(!i)return!1;let s=i.nodeAfter;if(Ote(t,i,e,1))return!0;if(r.parent.content.size==0&&(hb(s,"start")||rn.isSelectable(s))){let o=OM(t.doc,r.before(),r.after(),$t.empty);if(o&&o.slice.size{let{$head:r,empty:i}=t.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset=0;e--){let n=t.node(e);if(t.index(e)+1{let n=t.selection,r=n instanceof rn,i;if(r){if(n.node.isTextblock||!qh(t.doc,n.from))return!1;i=n.from}else if(i=RM(t.doc,n.from,-1),i==null)return!1;if(e){let s=t.tr.join(i);r&&s.setSelection(rn.create(s.doc,i-t.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},aHe=(t,e)=>{let n=t.selection,r;if(n instanceof rn){if(n.node.isTextblock||!qh(t.doc,n.to))return!1;r=n.to}else if(r=RM(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},sHe=(t,e)=>{let{$from:n,$to:r}=t.selection,i=n.blockRange(r),s=i&&Ub(i);return s==null?!1:(e&&e(t.tr.lift(i,s).scrollIntoView()),!0)},jte=(t,e)=>{let{$head:n,$anchor:r}=t.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(e&&e(t.tr.insertText(` +`).scrollIntoView()),!0)};function z4(t){for(let e=0;e{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),s=n.indexAfter(-1),o=z4(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=n.after(),c=t.tr.replaceWith(l,l,o.createAndFill());c.setSelection(Fn.near(c.doc.resolve(l),1)),e(c.scrollIntoView())}return!0},Dte=(t,e)=>{let n=t.selection,{$from:r,$to:i}=n;if(n instanceof ko||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=z4(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let s=n.before();if(Lu(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),i=r&&Ub(r);return i==null?!1:(e&&e(t.tr.lift(r,i).scrollIntoView()),!0)};function lHe(t){return(e,n)=>{let{$from:r,$to:i}=e.selection;if(e.selection instanceof rn&&e.selection.node.isBlock)return!r.parentOffset||!Lu(e.doc,r.pos)?!1:(n&&n(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let s=[],o,l,c=!1,u=!1;for(let m=r.depth;;m--)if(r.node(m).isBlock){c=r.end(m)==r.pos+(r.depth-m),u=r.start(m)==r.pos-(r.depth-m),l=z4(r.node(m-1).contentMatchAt(r.indexAfter(m-1))),s.unshift(c&&l?{type:l}:null),o=m;break}else{if(m==1)return!1;s.unshift(null)}let d=e.tr;(e.selection instanceof yn||e.selection instanceof ko)&&d.deleteSelection();let h=d.mapping.map(r.pos),p=Lu(d.doc,h,s.length,s);if(p||(s[0]=l?{type:l}:null,p=Lu(d.doc,h,s.length,s)),!p)return!1;if(d.split(h,s.length,s),!c&&u&&r.node(o).type!=l){let m=d.mapping.map(r.before(o)),b=d.doc.resolve(m);l&&r.node(o-1).canReplaceWith(b.index(),b.index()+1,l)&&d.setNodeMarkup(d.mapping.map(r.before(o)),l)}return n&&n(d.scrollIntoView()),!0}}const cHe=lHe(),uHe=(t,e)=>{let{$from:n,to:r}=t.selection,i,s=n.sharedDepth(r);return s==0?!1:(i=n.before(s),e&&e(t.tr.setSelection(rn.create(t.doc,i))),!0)};function dHe(t,e,n){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(n&&n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||qh(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function Ote(t,e,n,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,c=i.type.spec.isolating||s.type.spec.isolating;if(!c&&dHe(t,e,n))return!0;let u=!c&&e.parent.canReplace(e.index(),e.index()+1);if(u&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(n){let m=e.pos+s.nodeSize,b=At.empty;for(let v=o.length-1;v>=0;v--)b=At.from(o[v].create(null,b));b=At.from(i.copy(b));let y=t.tr.step(new _a(e.pos-1,m,e.pos,m,new $t(b,1,0),o.length,!0)),x=y.doc.resolve(m+2*o.length);x.nodeAfter&&x.nodeAfter.type==i.type&&qh(y.doc,x.pos)&&y.join(x.pos),n(y.scrollIntoView())}return!0}let d=s.type.spec.isolating||r>0&&c?null:Fn.findFrom(e,1),h=d&&d.$from.blockRange(d.$to),p=h&&Ub(h);if(p!=null&&p>=e.depth)return n&&n(t.tr.lift(h,p).scrollIntoView()),!0;if(u&&hb(s,"start",!0)&&hb(i,"end")){let m=i,b=[];for(;b.push(m),!m.isTextblock;)m=m.lastChild;let y=s,x=1;for(;!y.isTextblock;y=y.firstChild)x++;if(m.canReplace(m.childCount,m.childCount,y.content)){if(n){let v=At.empty;for(let N=b.length-1;N>=0;N--)v=At.from(b[N].copy(v));let S=t.tr.step(new _a(e.pos-b.length,e.pos+s.nodeSize,e.pos+x,e.pos+s.nodeSize-x,new $t(v,b.length,0),0,!0));n(S.scrollIntoView())}return!0}}return!1}function Lte(t){return function(e,n){let r=e.selection,i=t<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(n&&n(e.tr.setSelection(yn.create(e.doc,t<0?i.start(s):i.end(s)))),!0):!1}}const hHe=Lte(-1),fHe=Lte(1);function mHe(t,e=null){return function(n,r){let{$from:i,$to:s}=n.selection,o=i.blockRange(s),l=o&&R4(o,t,e);return l?(r&&r(n.tr.wrap(o,l).scrollIntoView()),!0):!1}}function m7(t,e=null){return function(n,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!c.isTextblock||c.hasMarkup(t,e)))if(c.type==t)i=!0;else{let d=n.doc.resolve(u),h=d.index();i=d.parent.canReplaceWith(h,h+1,t)}})}if(!i)return!1;if(r){let s=n.tr;for(let o=0;o=2&&e.$from.node(e.depth-1).type.compatibleContent(n)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let c=o.resolve(e.start-2);s=new xN(c,c,e.depth),e.endIndex=0;d--)s=At.from(n[d].type.create(n[d].attrs,s));t.step(new _a(e.start-(r?2:0),e.end,e.start,e.end,new $t(s,0,0),n.length,!0));let o=0;for(let d=0;do.childCount>0&&o.firstChild.type==t);return s?n?r.node(s.depth-1).type==t?yHe(e,n,t,s):vHe(e,n,s):!0:!1}}function yHe(t,e,n,r){let i=t.tr,s=r.end,o=r.$to.end(r.depth);sy;b--)m-=i.child(b).nodeSize,r.delete(m-1,m+1);let s=r.doc.resolve(n.start),o=s.nodeAfter;if(r.mapping.map(n.end)!=n.start+s.nodeAfter.nodeSize)return!1;let l=n.startIndex==0,c=n.endIndex==i.childCount,u=s.node(-1),d=s.index(-1);if(!u.canReplace(d+(l?0:1),d+1,o.content.append(c?At.empty:At.from(i))))return!1;let h=s.pos,p=h+o.nodeSize;return r.step(new _a(h-(l?1:0),p+(c?1:0),h+1,p-1,new $t((l?At.empty:At.from(i.copy(At.empty))).append(c?At.empty:At.from(i.copy(At.empty))),l?0:1,c?0:1),l?0:1)),e(r.scrollIntoView()),!0}function wHe(t){return function(e,n){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,u=>u.childCount>0&&u.firstChild.type==t);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,c=l.child(o-1);if(c.type!=t)return!1;if(n){let u=c.lastChild&&c.lastChild.type==l.type,d=At.from(u?t.create():null),h=new $t(At.from(t.create(null,At.from(l.type.create(null,d)))),u?3:1,0),p=s.start,m=s.end;n(e.tr.step(new _a(p-(u?3:1),m,p,m,h,1,!0)).scrollIntoView())}return!0}}const $a=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},fb=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let qD=null;const pu=function(t,e,n){let r=qD||(qD=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},_He=function(){qD=null},Am=function(t,e,n,r){return n&&(p7(t,e,n,r,-1)||p7(t,e,n,r,1))},SHe=/^(img|br|input|textarea|hr)$/i;function p7(t,e,n,r,i){for(var s;;){if(t==n&&e==r)return!0;if(e==(i<0?0:rl(t))){let o=t.parentNode;if(!o||o.nodeType!=1||_v(t)||SHe.test(t.nodeName)||t.contentEditable=="false")return!1;e=$a(t)+(i<0?0:1),t=o}else if(t.nodeType==1){let o=t.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else t=o,e=i<0?rl(t):0}else return!1}}function rl(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function NHe(t,e){for(;;){if(t.nodeType==3&&e)return t;if(t.nodeType==1&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=rl(t)}else if(t.parentNode&&!_v(t))e=$a(t),t=t.parentNode;else return null}}function kHe(t,e){for(;;){if(t.nodeType==3&&e2),Qo=mb||(Sc?/Mac/.test(Sc.platform):!1),AHe=Sc?/Win/.test(Sc.platform):!1,Eu=/Android \d/.test(Wh),Sv=!!g7&&"webkitFontSmoothing"in g7.documentElement.style,CHe=Sv?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function PHe(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function lu(t,e){return typeof t=="number"?t:t[e]}function jHe(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function b7(t,e,n){let r=t.someProp("scrollThreshold")||0,i=t.someProp("scrollMargin")||5,s=t.dom.ownerDocument;for(let o=n||t.dom;o;){if(o.nodeType!=1){o=fb(o);continue}let l=o,c=l==s.body,u=c?PHe(s):jHe(l),d=0,h=0;if(e.topu.bottom-lu(r,"bottom")&&(h=e.bottom-e.top>u.bottom-u.top?e.top+lu(i,"top")-u.top:e.bottom-u.bottom+lu(i,"bottom")),e.leftu.right-lu(r,"right")&&(d=e.right-u.right+lu(i,"right")),d||h)if(c)s.defaultView.scrollBy(d,h);else{let m=l.scrollLeft,b=l.scrollTop;h&&(l.scrollTop+=h),d&&(l.scrollLeft+=d);let y=l.scrollLeft-m,x=l.scrollTop-b;e={left:e.left-y,top:e.top-x,right:e.right-y,bottom:e.bottom-x}}let p=c?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(p))break;o=p=="absolute"?o.offsetParent:fb(o)}}function DHe(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=n+1;o=n-20){r=l,i=c.top;break}}return{refDOM:r,refTop:i,stack:zte(t.dom)}}function zte(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=fb(r));return e}function RHe({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;Ute(n,r==0?0:r-e)}function Ute(t,e){for(let n=0;n=l){o=Math.max(b.bottom,o),l=Math.min(b.top,l);let y=b.left>e.left?b.left-e.left:b.right=(b.left+b.right)/2?1:0));continue}}else b.top>e.top&&!c&&b.left<=e.left&&b.right>=e.left&&(c=d,u={left:Math.max(b.left,Math.min(b.right,e.left)),top:b.top});!n&&(e.left>=b.right&&e.top>=b.top||e.left>=b.left&&e.top>=b.bottom)&&(s=h+1)}}return!n&&c&&(n=c,i=u,r=0),n&&n.nodeType==3?LHe(n,i):!n||r&&n.nodeType==1?{node:t,offset:s}:Bte(n,i)}function LHe(t,e){let n=t.nodeValue.length,r=document.createRange();for(let i=0;i=(s.left+s.right)/2?1:0)}}return{node:t,offset:0}}function B4(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function FHe(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left(o.left+o.right)/2?1:-1}return t.docView.posFromDOM(r,i,s)}function zHe(t,e,n,r){let i=-1;for(let s=e,o=!1;s!=t.dom;){let l=t.docView.nearestDesc(s,!0),c;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((c=l.dom.getBoundingClientRect()).width||c.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&c.left>r.left||c.top>r.top?i=l.posBefore:(!o&&c.right-1?i:t.docView.posFromDOM(e,n,-1)}function Hte(t,e,n){let r=t.childNodes.length;if(r&&n.tope.top&&i++}let u;Sv&&i&&r.nodeType==1&&(u=r.childNodes[i-1]).nodeType==1&&u.contentEditable=="false"&&u.getBoundingClientRect().top>=e.top&&i--,r==t.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=t.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=zHe(t,r,i,e))}l==null&&(l=IHe(t,o,e));let c=t.docView.nearestDesc(o,!0);return{pos:l,inside:c?c.posAtStart-c.border:-1}}function x7(t){return t.top=0&&i==r.nodeValue.length?(c--,d=1):n<0?c--:u++,i0(Kd(pu(r,c,u),d),d<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(n<0||i==rl(r))){let c=r.childNodes[i-1];if(c.nodeType==1)return AP(c.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(n<0||i==rl(r))){let c=r.childNodes[i-1],u=c.nodeType==3?pu(c,rl(c)-(o?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(u)return i0(Kd(u,1),!1)}if(s==null&&i=0)}function i0(t,e){if(t.width==0)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function AP(t,e){if(t.height==0)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function Vte(t,e,n){let r=t.state,i=t.root.activeElement;r!=e&&t.updateState(e),i!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),i!=t.dom&&i&&i.focus()}}function HHe(t,e,n){let r=e.selection,i=n=="up"?r.$from:r.$to;return Vte(t,e,()=>{let{node:s}=t.docView.domFromPos(i.pos,n=="up"?-1:1);for(;;){let l=t.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=$te(t,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let c;if(l.nodeType==1)c=l.getClientRects();else if(l.nodeType==3)c=pu(l,0,l.nodeValue.length).getClientRects();else continue;for(let u=0;ud.top+1&&(n=="up"?o.top-d.top>(d.bottom-o.top)*2:d.bottom-o.bottom>(o.bottom-d.top)*2))return!1}}return!0})}const $He=/[\u0590-\u08ac]/;function VHe(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=t.domSelection();return l?!$He.test(r.parent.textContent)||!l.modify?n=="left"||n=="backward"?s:o:Vte(t,e,()=>{let{focusNode:c,focusOffset:u,anchorNode:d,anchorOffset:h}=t.domSelectionRange(),p=l.caretBidiLevel;l.modify("move",n,"character");let m=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:b,focusOffset:y}=t.domSelectionRange(),x=b&&!m.contains(b.nodeType==1?b:b.parentNode)||c==b&&u==y;try{l.collapse(d,h),c&&(c!=d||u!=h)&&l.extend&&l.extend(c,u)}catch{}return p!=null&&(l.caretBidiLevel=p),x}):r.pos==r.start()||r.pos==r.end()}let y7=null,v7=null,w7=!1;function GHe(t,e,n){return y7==e&&v7==n?w7:(y7=e,v7=n,w7=n=="up"||n=="down"?HHe(t,e,n):VHe(t,e,n))}const cl=0,_7=1,Vf=2,Nc=3;class Nv{constructor(e,n,r,i){this.parent=e,this.children=n,this.dom=r,this.contentDOM=i,this.dirty=cl,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,n,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let n=0;n$a(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&n==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!n||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let n=e.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(e,n,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;ne||o instanceof qte){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,n);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof Gte&&s.side>=0;r--);if(n<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&n&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,n):{node:this.contentDOM,offset:s?$a(s.dom)+1:0}}else{let s,o=!0;for(;s=r=d&&n<=u-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(e,n,d);e=o;for(let h=l;h>0;h--){let p=this.children[h-1];if(p.size&&p.dom.parentNode==this.contentDOM&&!p.emptyChildAt(1)){i=$a(p.dom)+1;break}e-=p.size}i==-1&&(i=0)}if(i>-1&&(u>n||l==this.children.length-1)){n=u;for(let d=l+1;db&&on){let b=l;l=c,c=b}let m=document.createRange();m.setEnd(c.node,c.offset),m.setStart(l.node,l.offset),u.removeAllRanges(),u.addRange(m)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,n){for(let r=0,i=0;i=r:er){let l=r+s.border,c=o-s.border;if(e>=l&&n<=c){this.dirty=e==r||n==o?Vf:_7,e==l&&n==c&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=Nc:s.markDirty(e-l,n-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Vf:Nc}r=o}this.dirty=Vf}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?Vf:_7;n.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!n.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.contentEditable="false",o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=n,this.widget=n,s=this}matchesWidget(e){return this.dirty==cl&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let n=this.widget.spec.stopEvent;return n?n(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class qHe extends Nv{constructor(e,n,r,i){super(e,[],n,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Cm extends Nv{constructor(e,n,r,i,s){super(e,[],r,i),this.mark=n,this.spec=s}static create(e,n,r,i){let s=i.nodeViews[n.type.name],o=s&&s(n,i,r);return(!o||!o.dom)&&(o=zm.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new Cm(e,n,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&Nc||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Nc&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=cl){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=QD(s,0,e,r));for(let l=0;l{if(!c)return o;if(c.parent)return c.parent.posBeforeChild(c)},r,i),d=u&&u.dom,h=u&&u.contentDOM;if(n.isText){if(!d)d=document.createTextNode(n.text);else if(d.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else d||({dom:d,contentDOM:h}=zm.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!h&&!n.isText&&d.nodeName!="BR"&&(d.hasAttribute("contenteditable")||(d.contentEditable="false"),n.type.spec.draggable&&(d.draggable=!0));let p=d;return d=Xte(d,r,n),u?c=new WHe(e,n,r,i,d,h||null,p,u,s,o+1):n.isText?new IM(e,n,r,i,d,p,s):new kh(e,n,r,i,d,h||null,p,s,o+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>At.empty)}return e}matchesNode(e,n,r){return this.dirty==cl&&e.eq(this.node)&&vN(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,n){let r=this.node.inlineContent,i=n,s=e.composing?this.localCompositionInfo(e,n):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,c=new XHe(this,o&&o.node,e);ZHe(this.node,this.innerDeco,(u,d,h)=>{u.spec.marks?c.syncToMarks(u.spec.marks,r,e):u.type.side>=0&&!h&&c.syncToMarks(d==this.node.childCount?Lr.none:this.node.child(d).marks,r,e),c.placeWidget(u,e,i)},(u,d,h,p)=>{c.syncToMarks(u.marks,r,e);let m;c.findNodeMatch(u,d,h,p)||l&&e.state.selection.from>i&&e.state.selection.to-1&&c.updateNodeAt(u,d,h,m,e)||c.updateNextNode(u,d,h,e,p,i)||c.addNode(u,d,h,e,i),i+=u.nodeSize}),c.syncToMarks([],r,e),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==Vf)&&(o&&this.protectLocalComposition(e,o),Wte(this.contentDOM,this.children,e),mb&&JHe(this.dom))}localCompositionInfo(e,n){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof yn)||rn+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=e$e(this.node.content,o,r-n,i-n);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:n,pos:r,text:i}){if(this.getDesc(n))return;let s=n;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new qHe(this,s,n,i);e.input.compositionNodes.push(o),this.children=QD(this.children,r,r+i.length,e,o)}update(e,n,r,i){return this.dirty==Nc||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,i),!0)}updateInner(e,n,r,i){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=cl}updateOuterDeco(e){if(vN(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Kte(this.dom,this.nodeDOM,YD(this.outerDeco,this.node,n),YD(e,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function S7(t,e,n,r,i){Xte(r,e,t);let s=new kh(void 0,t,e,n,r,r,r,i,0);return s.contentDOM&&s.updateChildren(i,0),s}class IM extends kh{constructor(e,n,r,i,s,o,l){super(e,n,r,i,s,null,o,l,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,n,r,i){return this.dirty==Nc||this.dirty!=cl&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=cl||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=cl,!0)}inParent(){let e=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,n,r){return e==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(e,n,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,n,r){let i=this.node.cut(e,n),s=document.createTextNode(i.text);return new IM(this.parent,i,this.outerDeco,this.innerDeco,s,s,r)}markDirty(e,n){super.markDirty(e,n),this.dom!=this.nodeDOM&&(e==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=Nc)}get domAtom(){return!1}isText(e){return this.node.text==e}}class qte extends Nv{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==cl&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class WHe extends kh{constructor(e,n,r,i,s,o,l,c,u,d){super(e,n,r,i,s,o,l,u,d),this.spec=c}update(e,n,r,i){if(this.dirty==Nc)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,n,r);return s&&this.updateInner(e,n,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,i){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function Wte(t,e,n){let r=t.firstChild,i=!1;for(let s=0;s>1,o=Math.min(s,e.length);for(;i-1)l>this.index&&(this.changed=!0,this.destroyBetween(this.index,l)),this.top=this.top.children[this.index];else{let c=Cm.create(this.top,e[s],n,r);this.top.children.splice(this.index,0,c),this.top=c,this.changed=!0}this.index=0,s++}}findNodeMatch(e,n,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,n,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,c=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let u=n.children[r-1];if(u instanceof Cm)n=u,r=u.children.length;else{l=u,r--;break}}else{if(n==e)break e;r=n.parent.children.indexOf(n),n=n.parent}let c=l.node;if(c){if(c!=t.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function QHe(t,e){return t.type.side-e.type.side}function ZHe(t,e,n,r){let i=e.locals(t),s=0;if(i.length==0){for(let u=0;us;)l.push(i[o++]);let b=s+p.nodeSize;if(p.isText){let x=b;o!x.inline):l.slice();r(p,y,e.forChild(s,p),m),s=b}}function JHe(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function e$e(t,e,n,r){for(let i=0,s=0;i=n){if(s>=r&&c.slice(r-e.length-l,r-l)==e)return r-e.length;let u=l=0&&u+e.length+l>=n)return l+u;if(n==r&&c.length>=r+e.length-l&&c.slice(r-l,r-l+e.length)==e)return r}}return-1}function QD(t,e,n,r,i){let s=[];for(let o=0,l=0;o=n||d<=e?s.push(c):(un&&s.push(c.slice(n-u,c.size,r)))}return s}function H4(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let i=t.docView.nearestDesc(n.focusNode),s=i&&i.size==0,o=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(o<0)return null;let l=r.resolve(o),c,u;if(FM(n)){for(c=o;i&&!i.node;)i=i.parent;let h=i.node;if(i&&h.isAtom&&rn.isSelectable(h)&&i.parent&&!(h.isInline&&MHe(n.focusNode,n.focusOffset,i.dom))){let p=i.posBefore;u=new rn(o==p?l:r.resolve(p))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=o,p=o;for(let m=0;m{(n.anchorNode!=r||n.anchorOffset!=i)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Yte(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function n$e(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,$a(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&Ks&&Nh<=11&&(n.disabled=!0,n.disabled=!1)}function Qte(t,e){if(e instanceof rn){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(T7(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else T7(t)}function T7(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function $4(t,e,n,r){return t.someProp("createSelectionBetween",i=>i(t,e,n))||yn.between(e,n,r)}function A7(t){return t.editable&&!t.hasFocus()?!1:Zte(t)}function Zte(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function r$e(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Am(e.node,e.offset,n.anchorNode,n.anchorOffset)}function ZD(t,e){let{$anchor:n,$head:r}=t.selection,i=e>0?n.max(r):n.min(r),s=i.parent.inlineContent?i.depth?t.doc.resolve(e>0?i.after():i.before()):null:i;return s&&Fn.findFrom(s,e)}function Jd(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function C7(t,e,n){let r=t.state.selection;if(r instanceof yn)if(n.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=t.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Jd(t,new yn(r.$anchor,o))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let i=ZD(t.state,e);return i&&i instanceof rn?Jd(t,i):!1}else if(!(Qo&&n.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=t.docView.descAt(l))&&!o.contentDOM?rn.isSelectable(s)?Jd(t,new rn(e<0?t.state.doc.resolve(i.pos-s.nodeSize):i)):Sv?Jd(t,new yn(t.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof rn&&r.node.isInline)return Jd(t,new yn(e>0?r.$to:r.$from));{let i=ZD(t.state,e);return i?Jd(t,i):!1}}}function wN(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function R0(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function ag(t,e){return e<0?i$e(t):a$e(t)}function i$e(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i,s,o=!1;for(ll&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let l=n.childNodes[r-1];if(R0(l,-1))i=n,s=--r;else if(l.nodeType==3)n=l,r=n.nodeValue.length;else break}}else{if(Jte(n))break;{let l=n.previousSibling;for(;l&&R0(l,-1);)i=n.parentNode,s=$a(l),l=l.previousSibling;if(l)n=l,r=wN(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}o?JD(t,n,r):i&&JD(t,i,s)}function a$e(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i=wN(n),s,o;for(;;)if(r{t.state==i&&Fu(t)},50)}function P7(t,e){let n=t.state.doc.resolve(e);if(!(ns||AHe)&&n.parent.inlineContent){let i=t.coordsAtPos(e);if(e>n.start()){let s=t.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function j7(t,e,n){let r=t.state.selection;if(r instanceof yn&&!r.empty||n.indexOf("s")>-1||Qo&&n.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let o=ZD(t.state,e);if(o&&o instanceof rn)return Jd(t,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof ko?Fn.near(o,e):Fn.findFrom(o,e);return l?Jd(t,l):!1}return!1}function D7(t,e){if(!(t.state.selection instanceof yn))return!0;let{$head:n,$anchor:r,empty:i}=t.state.selection;if(!n.sameParent(r))return!0;if(!i)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(s&&!s.isText){let o=t.state.tr;return e<0?o.delete(n.pos-s.nodeSize,n.pos):o.delete(n.pos,n.pos+s.nodeSize),t.dispatch(o),!0}return!1}function R7(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function l$e(t){if(!Ts||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&e.nodeType==1&&n==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;R7(t,r,"true"),setTimeout(()=>R7(t,r,"false"),20)}return!1}function c$e(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function u$e(t,e){let n=e.keyCode,r=c$e(e);if(n==8||Qo&&n==72&&r=="c")return D7(t,-1)||ag(t,-1);if(n==46&&!e.shiftKey||Qo&&n==68&&r=="c")return D7(t,1)||ag(t,1);if(n==13||n==27)return!0;if(n==37||Qo&&n==66&&r=="c"){let i=n==37?P7(t,t.state.selection.from)=="ltr"?-1:1:-1;return C7(t,i,r)||ag(t,i)}else if(n==39||Qo&&n==70&&r=="c"){let i=n==39?P7(t,t.state.selection.from)=="ltr"?1:-1:1;return C7(t,i,r)||ag(t,i)}else{if(n==38||Qo&&n==80&&r=="c")return j7(t,-1,r)||ag(t,-1);if(n==40||Qo&&n==78&&r=="c")return l$e(t)||j7(t,1,r)||ag(t,1);if(r==(Qo?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function V4(t,e){t.someProp("transformCopied",m=>{e=m(e,t)});let n=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let m=r.firstChild;n.push(m.type.name,m.attrs!=m.type.defaultAttrs?m.attrs:null),r=m.content}let o=t.someProp("clipboardSerializer")||zm.fromSchema(t.state.schema),l=ane(),c=l.createElement("div");c.appendChild(o.serializeFragment(r,{document:l}));let u=c.firstChild,d,h=0;for(;u&&u.nodeType==1&&(d=ine[u.nodeName.toLowerCase()]);){for(let m=d.length-1;m>=0;m--){let b=l.createElement(d[m]);for(;c.firstChild;)b.appendChild(c.firstChild);c.appendChild(b),h++}u=c.firstChild}u&&u.nodeType==1&&u.setAttribute("data-pm-slice",`${i} ${s}${h?` -${h}`:""} ${JSON.stringify(n)}`);let p=t.someProp("clipboardTextSerializer",m=>m(e,t))||e.content.textBetween(0,e.content.size,` `);return{dom:c,text:p,slice:e}}function ene(t,e,n,r,i){let s=i.parent.type.spec.code,o,l;if(!n&&!e)return null;let c=!!e&&(r||s||!n);if(c){if(t.someProp("transformPastedText",p=>{e=p(e,s||r,t)}),s)return l=new $t(At.from(t.state.schema.text(e.replace(/\r\n?/g,` -`))),0,0),t.someProp("transformPasted",p=>{l=p(l,t,!0)}),l;let h=t.someProp("clipboardTextParser",p=>p(e,i,r,t));if(h)l=h;else{let p=i.marks(),{schema:m}=t.state,b=zm.fromSchema(m);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(y=>{let x=o.appendChild(document.createElement("p"));y&&x.appendChild(b.serializeNode(m.text(y,p)))})}}else t.someProp("transformPastedHTML",h=>{n=h(n,t)}),o=f$e(n),Sv&&m$e(o);let u=o&&o.querySelector("[data-pm-slice]"),d=u&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(u.getAttribute("data-pm-slice")||"");if(d&&d[3])for(let h=+d[3];h>0;h--){let p=o.firstChild;for(;p&&p.nodeType!=1;)p=p.nextSibling;if(!p)break;o=p}if(l||(l=(t.someProp("clipboardParser")||t.someProp("domParser")||P0.fromSchema(t.state.schema)).parseSlice(o,{preserveWhitespace:!!(c||d),context:i,ruleFromNode(p){return p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!u$e.test(p.parentNode.nodeName)?{ignore:!0}:null}})),d)l=p$e(O7(l,+d[1],+d[2]),d[4]);else if(l=$t.maxOpen(d$e(l.content,i),!0),l.openStart||l.openEnd){let h=0,p=0;for(let m=l.content.firstChild;h{l=h(l,t,c)}),l}const u$e=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function d$e(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let i=e.node(n).contentMatchAt(e.index(n)),s,o=[];if(t.forEach(l=>{if(!o)return;let c=i.findWrapping(l.type),u;if(!c)return o=null;if(u=o.length&&s.length&&nne(c,s,l,o[o.length-1],0))o[o.length-1]=u;else{o.length&&(o[o.length-1]=rne(o[o.length-1],s.length));let d=tne(l,c);o.push(d),i=i.matchType(d.type),s=c}}),o)return At.from(o)}return t}function tne(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,At.from(t));return t}function nne(t,e,n,r,i){if(i1&&(s=0),i=n&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(At.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,o.copy(l))}function O7(t,e,n){return en})),PP.createHTML(t)):t}function f$e(t){let e=/^(\s*]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=ane().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(t),i;if((i=r&&ine[r[1].toLowerCase()])&&(t=i.map(s=>"<"+s+">").join("")+t+i.map(s=>"").reverse().join("")),n.innerHTML=h$e(t),i)for(let s=0;s=0;l-=2){let c=n.nodes[r[l]];if(!c||c.hasRequiredAttrs())break;i=At.from(c.create(r[l+1],i)),s++,o++}return new $t(i,s,o)}const As={},Cs={},g$e={touchstart:!0,touchmove:!0};class b$e{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function x$e(t){for(let e in As){let n=As[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{v$e(t,r)&&!G4(t,r)&&(t.editable||!(r.type in Cs))&&n(t,r)},g$e[e]?{passive:!0}:void 0)}Ts&&t.dom.addEventListener("input",()=>null),tR(t)}function hh(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function y$e(t){t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function tR(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>G4(t,r))})}function G4(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function v$e(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function w$e(t,e){!G4(t,e)&&As[e.type]&&(t.editable||!(e.type in Cs))&&As[e.type](t,e)}Cs.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!one(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Eu&&ns&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),mb&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();t.input.lastIOSEnter=r,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==r&&(t.someProp("handleKeyDown",i=>i(t,Lf(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||c$e(t,n)?n.preventDefault():hh(t,"key")};Cs.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};Cs.keypress=(t,e)=>{let n=e;if(one(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||Qo&&n.metaKey)return;if(t.someProp("handleKeyPress",i=>i(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof yn)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(n.charCode),s=()=>t.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!t.someProp("handleTextInput",o=>o(t,r.$from.pos,r.$to.pos,i,s))&&t.dispatch(s()),n.preventDefault()}};function zM(t){return{left:t.clientX,top:t.clientY}}function _$e(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function q4(t,e,n,r,i){if(r==-1)return!1;let s=t.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(t.someProp(e,l=>o>s.depth?l(t,n,s.nodeAfter,s.before(o),i,!0):l(t,n,s.node(o),s.before(o),i,!1)))return!0;return!1}function zg(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);r.setMeta("pointer",!0),t.dispatch(r)}function S$e(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&rn.isSelectable(r)?(zg(t,new rn(n)),!0):!1}function N$e(t,e){if(e==-1)return!1;let n=t.state.selection,r,i;n instanceof rn&&(r=n.node);let s=t.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(rn.isSelectable(l)){r&&n.$from.depth>0&&o>=n.$from.depth&&s.before(n.$from.depth+1)==n.$from.pos?i=s.before(n.$from.depth):i=s.before(o);break}}return i!=null?(zg(t,rn.create(t.state.doc,i)),!0):!1}function k$e(t,e,n,r,i){return q4(t,"handleClickOn",e,n,r)||t.someProp("handleClick",s=>s(t,e,r))||(i?N$e(t,n):S$e(t,n))}function M$e(t,e,n,r){return q4(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",i=>i(t,e,r))}function E$e(t,e,n,r){return q4(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",i=>i(t,e,r))||T$e(t,n,r)}function T$e(t,e,n){if(n.button!=0)return!1;let r=t.state.doc;if(e==-1)return r.inlineContent?(zg(t,yn.create(r,0,r.content.size)),!0):!1;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)zg(t,yn.create(r,l+1,l+1+o.content.size));else if(rn.isSelectable(o))zg(t,rn.create(r,l));else continue;return!0}}function W4(t){return _N(t)}const sne=Qo?"metaKey":"ctrlKey";As.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=W4(t),i=Date.now(),s="singleClick";i-t.input.lastClick.time<500&&_$e(n,t.input.lastClick)&&!n[sne]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?s="doubleClick":t.input.lastClick.type=="doubleClick"&&(s="tripleClick")),t.input.lastClick={time:i,x:n.clientX,y:n.clientY,type:s,button:n.button};let o=t.posAtCoords(zM(n));o&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new A$e(t,o,n,!!r)):(s=="doubleClick"?M$e:E$e)(t,o.pos,o.inside,n)?n.preventDefault():hh(t,"pointer"))};class A$e{constructor(e,n,r,i){this.view=e,this.pos=n,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!r[sne],this.allowDefault=r.shiftKey;let s,o;if(n.inside>-1)s=e.state.doc.nodeAt(n.inside),o=n.inside;else{let d=e.state.doc.resolve(n.pos);s=d.parent,o=d.depth?d.before():0}const l=i?null:r.target,c=l?e.docView.nearestDesc(l,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:u}=e.state;(r.button==0&&s.type.spec.draggable&&s.type.spec.selectable!==!1||u instanceof rn&&u.from<=o&&u.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&ll&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this)),hh(e,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>Fu(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(zM(e))),this.updateAllowDefault(e),this.allowDefault||!n?hh(this.view,"pointer"):k$e(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Ts&&this.mightDrag&&!this.mightDrag.node.isAtom||ns&&!this.view.state.selection.visible&&Math.min(Math.abs(n.pos-this.view.state.selection.from),Math.abs(n.pos-this.view.state.selection.to))<=2)?(zg(this.view,Fn.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):hh(this.view,"pointer")}move(e){this.updateAllowDefault(e),hh(this.view,"pointer"),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}}As.touchstart=t=>{t.input.lastTouch=Date.now(),W4(t),hh(t,"pointer")};As.touchmove=t=>{t.input.lastTouch=Date.now(),hh(t,"pointer")};As.contextmenu=t=>W4(t);function one(t,e){return t.composing?!0:Ts&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const C$e=Eu?5e3:-1;Cs.compositionstart=Cs.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof yn&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)))t.markCursor=t.state.storedMarks||n.marks(),_N(t,!0),t.markCursor=null;else if(_N(t,!e.selection.empty),ll&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=t.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}t.input.composing=!0}lne(t,C$e)};Cs.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=e.timeStamp,t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,lne(t,20))};function lne(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>_N(t),e))}function cne(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=j$e());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function P$e(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=SHe(e.focusNode,e.focusOffset),r=NHe(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let i=r.pmViewDesc,s=t.domObserver.lastChangedTextNode;if(n==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(t.input.compositionNode==r){let o=n.pmViewDesc;if(!(!o||!o.isText(n.nodeValue)))return r}}return n||r}function j$e(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function _N(t,e=!1){if(!(Eu&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),cne(t),e||t.docView&&t.docView.dirty){let n=H4(t),r=t.state.selection;return n&&!n.eq(r)?t.dispatch(t.state.tr.setSelection(n)):(t.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function D$e(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}const Cy=Ks&&Nh<15||mb&&AHe<604;As.copy=Cs.cut=(t,e)=>{let n=e,r=t.state.selection,i=n.type=="cut";if(r.empty)return;let s=Cy?null:n.clipboardData,o=r.content(),{dom:l,text:c}=V4(t,o);s?(n.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",c)):D$e(t,l),i&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function R$e(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function O$e(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?Py(t,r.value,null,i,e):Py(t,r.textContent,r.innerHTML,i,e)},50)}function Py(t,e,n,r,i){let s=ene(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",c=>c(t,i,s||$t.empty)))return!0;if(!s)return!1;let o=R$e(s),l=o?t.state.tr.replaceSelectionWith(o,r):t.state.tr.replaceSelection(s);return t.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function une(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Cs.paste=(t,e)=>{let n=e;if(t.composing&&!Eu)return;let r=Cy?null:n.clipboardData,i=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&Py(t,une(r),r.getData("text/html"),i,n)?n.preventDefault():O$e(t,n)};class dne{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}}const L$e=Qo?"altKey":"ctrlKey";function hne(t,e){let n=t.someProp("dragCopies",r=>!r(e));return n??!e[L$e]}As.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let i=t.state.selection,s=i.empty?null:t.posAtCoords(zM(n)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof rn?i.to-1:i.to))){if(r&&r.mightDrag)o=rn.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let h=t.docView.nearestDesc(n.target,!0);h&&h.node.type.spec.draggable&&h!=t.docView&&(o=rn.create(t.state.doc,h.posBefore))}}let l=(o||t.state.selection).content(),{dom:c,text:u,slice:d}=V4(t,l);(!n.dataTransfer.files.length||!ns||Ite>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Cy?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",Cy||n.dataTransfer.setData("text/plain",u),t.dragging=new dne(d,hne(t,n),o)};As.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};Cs.dragover=Cs.dragenter=(t,e)=>e.preventDefault();Cs.drop=(t,e)=>{let n=e,r=t.dragging;if(t.dragging=null,!n.dataTransfer)return;let i=t.posAtCoords(zM(n));if(!i)return;let s=t.state.doc.resolve(i.pos),o=r&&r.slice;o?t.someProp("transformPasted",b=>{o=b(o,t,!1)}):o=ene(t,une(n.dataTransfer),Cy?null:n.dataTransfer.getData("text/html"),!1,s);let l=!!(r&&hne(t,n));if(t.someProp("handleDrop",b=>b(t,n,o||$t.empty,l))){n.preventDefault();return}if(!o)return;n.preventDefault();let c=o?bte(t.state.doc,s.pos,o):s.pos;c==null&&(c=s.pos);let u=t.state.tr;if(l){let{node:b}=r;b?b.replace(u):u.deleteSelection()}let d=u.mapping.map(c),h=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,p=u.doc;if(h?u.replaceRangeWith(d,d,o.content.firstChild):u.replaceRange(d,d,o),u.doc.eq(p))return;let m=u.doc.resolve(d);if(h&&rn.isSelectable(o.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(o.content.firstChild))u.setSelection(new rn(m));else{let b=u.mapping.map(c);u.mapping.maps[u.mapping.maps.length-1].forEach((y,x,v,S)=>b=S),u.setSelection($4(t,m,u.doc.resolve(b)))}t.focus(),t.dispatch(u.setMeta("uiEvent","drop"))};As.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&Fu(t)},20))};As.blur=(t,e)=>{let n=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)};As.beforeinput=(t,e)=>{if(ns&&Eu&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:r}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=r||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",s=>s(t,Lf(8,"Backspace")))))return;let{$cursor:i}=t.state.selection;i&&i.pos>0&&t.dispatch(t.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let t in Cs)As[t]=Cs[t];function jy(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}class SN{constructor(e,n){this.toDOM=e,this.spec=n||am,this.side=this.spec.side||0}map(e,n,r,i){let{pos:s,deleted:o}=e.mapResult(n.from+i,this.side<0?-1:1);return o?null:new _s(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof SN&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&jy(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Mh{constructor(e,n){this.attrs=e,this.spec=n||am}map(e,n,r,i){let s=e.map(n.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(n.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new _s(s,o,this)}valid(e,n){return n.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,n-l,r,i+l,s)}}map(e,n,r){return this==Ja||e.maps.length==0?this:this.mapInner(e,n,0,0,r||am)}mapInner(e,n,r,i,s){let o;for(let l=0;l{let u=c+r,d;if(d=mne(n,l,u)){for(i||(i=this.children.slice());sl&&h.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+n.content.size;for(let l=0;ls&&c.type instanceof Mh){let u=Math.max(s,c.from)-s,d=Math.min(o,c.to)-s;ui.map(e,n,am));return ah.from(r)}forChild(e,n){if(n.isLeaf)return oi.empty;let r=[];for(let i=0;in instanceof oi)?e:e.reduce((n,r)=>n.concat(r instanceof oi?r:r.members),[]))}}forEachSet(e){for(let n=0;n{let x=y-b-(m-p);for(let v=0;vS+d-h)continue;let N=l[v]+d-h;m>=N?l[v+1]=p<=N?-2:-1:p>=d&&x&&(l[v]+=x,l[v+1]+=x)}h+=x}),d=n.maps[u].map(d,-1)}let c=!1;for(let u=0;u=r.content.size){c=!0;continue}let p=n.map(t[u+1]+s,-1),m=p-i,{index:b,offset:y}=r.content.findIndex(h),x=r.maybeChild(b);if(x&&y==h&&y+x.nodeSize==m){let v=l[u+2].mapInner(n,x,d+1,t[u]+s+1,o);v!=Ja?(l[u]=h,l[u+1]=m,l[u+2]=v):(l[u+1]=-2,c=!0)}else c=!0}if(c){let u=I$e(l,t,e,n,i,s,o),d=NN(u,r,0,o);e=d.local;for(let h=0;hn&&o.to{let u=mne(t,l,c+n);if(u){s=!0;let d=NN(u,l,n+c+1,r);d!=Ja&&i.push(c,c+l.nodeSize,d)}});let o=fne(s?pne(t):t,-n).sort(sm);for(let l=0;l0;)e++;t.splice(e,0,n)}function jP(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=Ja&&e.push(r)}),t.cursorWrapper&&e.push(oi.create(t.state.doc,[t.cursorWrapper.deco])),ah.from(e)}const z$e={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},U$e=Ks&&Nh<=11;class B$e{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class H$e{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new B$e,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),U$e&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,z$e)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let n=0;nthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(A7(this.view)){if(this.suppressingSelectionUpdates)return Fu(this.view);if(Ks&&Nh<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Am(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let n=new Set,r;for(let s=e.focusNode;s;s=fb(s))n.add(s);for(let s=e.anchorNode;s;s=fb(s))if(n.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let n=this.pendingRecords();n.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&A7(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,c=[];if(e.editable)for(let d=0;dh.nodeName=="BR");if(d.length==2){let[h,p]=d;h.parentNode&&h.parentNode.parentNode==p.parentNode?p.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let p of d){let m=p.parentNode;m&&m.nodeName=="LI"&&(!h||G$e(e,h)!=m)&&p.remove()}}}let u=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),$$e(e)),this.handleDOMChange(s,o,l,c),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Fu(e),this.currentSelection.set(r))}registerMutation(e,n){if(n.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let d=0;di;x--){let v=r.childNodes[x-1],S=v.pmViewDesc;if(v.nodeName=="BR"&&!S){s=x;break}if(!S||S.size)break}let h=t.state.doc,p=t.someProp("domParser")||P0.fromSchema(t.state.schema),m=h.resolve(o),b=null,y=p.parse(r,{topNode:m.parent,topMatch:m.parent.contentMatchAt(m.index()),topOpen:!0,from:i,to:s,preserveWhitespace:m.parent.type.whitespace=="pre"?"full":!0,findPositions:u,ruleFromNode:W$e,context:m});if(u&&u[0].pos!=null){let x=u[0].pos,v=u[1]&&u[1].pos;v==null&&(v=x),b={anchor:x+o,head:v+o}}return{doc:y,sel:b,from:o,to:l}}function W$e(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Ts&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(t.parentNode.lastChild==t||Ts&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}const K$e=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function X$e(t,e,n,r,i){let s=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let k=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,R=H4(t,k);if(R&&!t.state.selection.eq(R)){if(ns&&Eu&&t.input.lastKeyCode===13&&Date.now()-100P(t,Lf(13,"Enter"))))return;let C=t.state.tr.setSelection(R);k=="pointer"?C.setMeta("pointer",!0):k=="key"&&C.scrollIntoView(),s&&C.setMeta("composition",s),t.dispatch(C)}return}let o=t.state.doc.resolve(e),l=o.sharedDepth(n);e=o.before(l+1),n=t.state.doc.resolve(n).after(l+1);let c=t.state.selection,u=q$e(t,e,n),d=t.state.doc,h=d.slice(u.from,u.to),p,m;t.input.lastKeyCode===8&&Date.now()-100Date.now()-225||Eu)&&i.some(k=>k.nodeType==1&&!K$e.test(k.nodeName))&&(!b||b.endA>=b.endB)&&t.someProp("handleKeyDown",k=>k(t,Lf(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!b)if(r&&c instanceof yn&&!c.empty&&c.$head.sameParent(c.$anchor)&&!t.composing&&!(u.sel&&u.sel.anchor!=u.sel.head))b={start:c.from,endA:c.to,endB:c.to};else{if(u.sel){let k=B7(t,t.state.doc,u.sel);if(k&&!k.eq(t.state.selection)){let R=t.state.tr.setSelection(k);s&&R.setMeta("composition",s),t.dispatch(R)}}return}t.state.selection.fromt.state.selection.from&&b.start<=t.state.selection.from+2&&t.state.selection.from>=u.from?b.start=t.state.selection.from:b.endA=t.state.selection.to-2&&t.state.selection.to<=u.to&&(b.endB+=t.state.selection.to-b.endA,b.endA=t.state.selection.to)),Ks&&Nh<=11&&b.endB==b.start+1&&b.endA==b.start&&b.start>u.from&&u.doc.textBetween(b.start-u.from-1,b.start-u.from+1)=="  "&&(b.start--,b.endA--,b.endB--);let y=u.doc.resolveNoCache(b.start-u.from),x=u.doc.resolveNoCache(b.endB-u.from),v=d.resolve(b.start),S=y.sameParent(x)&&y.parent.inlineContent&&v.end()>=b.endA;if((mb&&t.input.lastIOSEnter>Date.now()-225&&(!S||i.some(k=>k.nodeName=="DIV"||k.nodeName=="P"))||!S&&y.posk(t,Lf(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>b.start&&Q$e(d,b.start,b.endA,y,x)&&t.someProp("handleKeyDown",k=>k(t,Lf(8,"Backspace")))){Eu&&ns&&t.domObserver.suppressSelectionUpdates();return}ns&&b.endB==b.start&&(t.input.lastChromeDelete=Date.now()),Eu&&!S&&y.start()!=x.start()&&x.parentOffset==0&&y.depth==x.depth&&u.sel&&u.sel.anchor==u.sel.head&&u.sel.head==b.endA&&(b.endB-=2,x=u.doc.resolveNoCache(b.endB-u.from),setTimeout(()=>{t.someProp("handleKeyDown",function(k){return k(t,Lf(13,"Enter"))})},20));let N=b.start,T=b.endA,M=k=>{let R=k||t.state.tr.replace(N,T,u.doc.slice(b.start-u.from,b.endB-u.from));if(u.sel){let C=B7(t,R.doc,u.sel);C&&!(ns&&t.composing&&C.empty&&(b.start!=b.endB||t.input.lastChromeDeleteFu(t),20));let k=M(t.state.tr.delete(N,T)),R=d.resolve(b.start).marksAcross(d.resolve(b.endA));R&&k.ensureMarks(R),t.dispatch(k)}else if(b.endA==b.endB&&(A=Y$e(y.parent.content.cut(y.parentOffset,x.parentOffset),v.parent.content.cut(v.parentOffset,b.endA-v.start())))){let k=M(t.state.tr);A.type=="add"?k.addMark(N,T,A.mark):k.removeMark(N,T,A.mark),t.dispatch(k)}else if(y.parent.child(y.index()).isText&&y.index()==x.index()-(x.textOffset?0:1)){let k=y.parent.textBetween(y.parentOffset,x.parentOffset),R=()=>M(t.state.tr.insertText(k,N,T));t.someProp("handleTextInput",C=>C(t,N,T,k,R))||t.dispatch(R())}else t.dispatch(M());else t.dispatch(M())}function B7(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:$4(t,e.resolve(n.anchor),e.resolve(n.head))}function Y$e(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,i=n,s=r,o,l,c;for(let d=0;dd.mark(l.addToSet(d.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",c=d=>d.mark(l.removeFromSet(d.marks));else return null;let u=[];for(let d=0;dn||DP(o,!0,!1)0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,i++,e=!1;if(n){let s=t.node(r).maybeChild(t.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function Z$e(t,e,n,r,i){let s=t.findDiffStart(e,n);if(s==null)return null;let{a:o,b:l}=t.findDiffEnd(e,n+t.size,n+e.size);if(i=="end"){let c=Math.max(0,s-Math.min(o,l));r-=o+c-s}if(o=o?s-r:0;s-=c,s&&s=l?s-r:0;s-=c,s&&s=56320&&e<=57343&&n>=55296&&n<=56319}class gne{constructor(e,n){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new b$e,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(W7),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=G7(this),V7(this),this.nodeViews=q7(this),this.docView=S7(this.state.doc,$7(this),jP(this),this.dom,this),this.domObserver=new H$e(this,(r,i,s,o)=>X$e(this,r,i,s,o)),this.domObserver.start(),x$e(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let n in e)this._props[n]=e[n];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&tR(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(W7),this.directPlugins=e.plugins),this.updateStateInner(e.state,n)}setProps(e){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in e)n[r]=e[r];this.update(n)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,n){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(cne(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=n.plugins;if(l||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let m=q7(this);eVe(m,this.nodeViews)&&(this.nodeViews=m,s=!0)}(l||n.handleDOMEvents!=this._props.handleDOMEvents)&&tR(this),this.editable=G7(this),V7(this);let c=jP(this),u=$7(this),d=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",h=s||!this.docView.matchesNode(e.doc,u,c);(h||!e.selection.eq(i.selection))&&(o=!0);let p=d=="preserve"&&o&&this.dom.style.overflowAnchor==null&&jHe(this);if(o){this.domObserver.stop();let m=h&&(Ks||ns)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&J$e(i.selection,e.selection);if(h){let b=ns?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=P$e(this)),(s||!this.docView.update(e.doc,u,c,this))&&(this.docView.updateOuterDeco(u),this.docView.destroy(),this.docView=S7(e.doc,u,c,this.dom,this)),b&&!this.trackWrites&&(m=!0)}m||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&n$e(this))?Fu(this,m):(Qte(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),d=="reset"?this.dom.scrollTop=0:d=="to selection"?this.scrollToSelection():p&&DHe(p)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof rn){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&b7(this,n.getBoundingClientRect(),e)}else b7(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let n=0;n0&&this.state.doc.nodeAt(s))==r.node&&(i=s)}this.dragging=new dne(e.slice,e.move,i<0?void 0:rn.create(this.state.doc,i))}someProp(e,n){let r=this._props&&this._props[e],i;if(r!=null&&(i=n?n(r):r))return i;for(let o=0;on.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return zHe(this,e)}coordsAtPos(e,n=1){return $te(this,e,n)}domAtPos(e,n=0){return this.docView.domFromPos(e,n)}nodeDOM(e){let n=this.docView.descAt(e);return n?n.nodeDOM:null}posAtDOM(e,n,r=-1){let i=this.docView.posFromDOM(e,n,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,n){return VHe(this,n||this.state,e)}pasteHTML(e,n){return Py(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return Py(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return V4(this,e)}destroy(){this.docView&&(y$e(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],jP(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,wHe())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return w$e(this,e)}domSelectionRange(){let e=this.domSelection();return e?Ts&&this.root.nodeType===11&&MHe(this.dom.ownerDocument)==this.dom&&V$e(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}gne.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function $7(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(t.state)),n)for(let r in n)r=="class"?e.class+=" "+n[r]:r=="style"?e.style=(e.style?e.style+";":"")+n[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(n[r]))}),e.translate||(e.translate="no"),[_s.node(0,t.state.doc.content.size,e)]}function V7(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:_s.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function G7(t){return!t.someProp("editable",e=>e(t.state)===!1)}function J$e(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}function q7(t){let e=Object.create(null);function n(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function eVe(t,e){let n=0,r=0;for(let i in t){if(t[i]!=e[i])return!0;n++}for(let i in e)r++;return n!=r}function W7(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var Uh={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},kN={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},tVe=typeof navigator<"u"&&/Mac/.test(navigator.platform),nVe=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Va=0;Va<10;Va++)Uh[48+Va]=Uh[96+Va]=String(Va);for(var Va=1;Va<=24;Va++)Uh[Va+111]="F"+Va;for(var Va=65;Va<=90;Va++)Uh[Va]=String.fromCharCode(Va+32),kN[Va]=String.fromCharCode(Va);for(var RP in Uh)kN.hasOwnProperty(RP)||(kN[RP]=Uh[RP]);function rVe(t){var e=tVe&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||nVe&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?kN:Uh)[t.keyCode]||t.key||"Unidentified";return n=="Esc"&&(n="Escape"),n=="Del"&&(n="Delete"),n=="Left"&&(n="ArrowLeft"),n=="Up"&&(n="ArrowUp"),n=="Right"&&(n="ArrowRight"),n=="Down"&&(n="ArrowDown"),n}const iVe=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),aVe=typeof navigator<"u"&&/Win/.test(navigator.platform);function sVe(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let r,i,s,o;for(let l=0;l{for(var n in e)cVe(t,n,{get:e[n],enumerable:!0})};function UM(t){const{state:e,transaction:n}=t;let{selection:r}=n,{doc:i}=n,{storedMarks:s}=n;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return s},get selection(){return r},get doc(){return i},get tr(){return r=n.selection,i=n.doc,s=n.storedMarks,n}}}var BM=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:e,state:n}=this,{view:r}=e,{tr:i}=n,s=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,l])=>[o,(...u)=>{const d=l(...u)(s);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(i),d}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,e=!0){const{rawCommands:n,editor:r,state:i}=this,{view:s}=r,o=[],l=!!t,c=t||i.tr,u=()=>(!l&&e&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&s.dispatch(c),o.every(h=>h===!0)),d={...Object.fromEntries(Object.entries(n).map(([h,p])=>[h,(...b)=>{const y=this.buildProps(c,e),x=p(...b)(y);return o.push(x),d}])),run:u};return d}createCan(t){const{rawCommands:e,state:n}=this,r=!1,i=t||n.tr,s=this.buildProps(i,r);return{...Object.fromEntries(Object.entries(e).map(([l,c])=>[l,(...u)=>c(...u)({...s,dispatch:void 0})])),chain:()=>this.createChain(i,r)}}buildProps(t,e=!0){const{rawCommands:n,editor:r,state:i}=this,{view:s}=r,o={tr:t,editor:r,view:s,state:UM({state:i,transaction:t}),dispatch:e?()=>{}:void 0,chain:()=>this.createChain(t,e),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(...u)=>c(...u)(o)]))}};return o}},xne={};Y4(xne,{blur:()=>uVe,clearContent:()=>dVe,clearNodes:()=>hVe,command:()=>fVe,createParagraphNear:()=>mVe,cut:()=>pVe,deleteCurrentNode:()=>gVe,deleteNode:()=>bVe,deleteRange:()=>xVe,deleteSelection:()=>yVe,enter:()=>vVe,exitCode:()=>wVe,extendMarkRange:()=>_Ve,first:()=>SVe,focus:()=>kVe,forEach:()=>MVe,insertContent:()=>EVe,insertContentAt:()=>CVe,joinBackward:()=>DVe,joinDown:()=>jVe,joinForward:()=>RVe,joinItemBackward:()=>OVe,joinItemForward:()=>LVe,joinTextblockBackward:()=>FVe,joinTextblockForward:()=>IVe,joinUp:()=>PVe,keyboardShortcut:()=>UVe,lift:()=>BVe,liftEmptyBlock:()=>HVe,liftListItem:()=>$Ve,newlineInCode:()=>VVe,resetAttributes:()=>GVe,scrollIntoView:()=>qVe,selectAll:()=>WVe,selectNodeBackward:()=>KVe,selectNodeForward:()=>XVe,selectParentNode:()=>YVe,selectTextblockEnd:()=>QVe,selectTextblockStart:()=>ZVe,setContent:()=>JVe,setMark:()=>bGe,setMeta:()=>xGe,setNode:()=>yGe,setNodeSelection:()=>vGe,setTextDirection:()=>wGe,setTextSelection:()=>_Ge,sinkListItem:()=>SGe,splitBlock:()=>NGe,splitListItem:()=>kGe,toggleList:()=>MGe,toggleMark:()=>EGe,toggleNode:()=>TGe,toggleWrap:()=>AGe,undoInputRule:()=>CGe,unsetAllMarks:()=>PGe,unsetMark:()=>jGe,unsetTextDirection:()=>DGe,updateAttributes:()=>RGe,wrapIn:()=>OGe,wrapInList:()=>LGe});var uVe=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window?.getSelection())==null||n.removeAllRanges())}),!0),dVe=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),hVe=()=>({state:t,tr:e,dispatch:n})=>{const{selection:r}=e,{ranges:i}=r;return n&&i.forEach(({$from:s,$to:o})=>{t.doc.nodesBetween(s.pos,o.pos,(l,c)=>{if(l.type.isText)return;const{doc:u,mapping:d}=e,h=u.resolve(d.map(c)),p=u.resolve(d.map(c+l.nodeSize)),m=h.blockRange(p);if(!m)return;const b=Ub(m);if(l.type.isTextblock){const{defaultType:y}=h.parent.contentMatchAt(h.index());e.setNodeMarkup(m.start,y)}(b||b===0)&&e.lift(m,b)})}),!0},fVe=t=>e=>t(e),mVe=()=>({state:t,dispatch:e})=>Dte(t,e),pVe=(t,e)=>({editor:n,tr:r})=>{const{state:i}=n,s=i.doc.slice(t.from,t.to);r.deleteRange(t.from,t.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new yn(r.doc.resolve(Math.max(o-1,0)))),!0},gVe=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,r=n.$anchor.node();if(r.content.size>0)return!1;const i=t.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const l=i.before(s),c=i.after(s);t.delete(l,c).scrollIntoView()}return!0}return!1};function qi(t,e){if(typeof t=="string"){if(!e.nodes[t])throw Error(`There is no node type named '${t}'. Maybe you forgot to add the extension?`);return e.nodes[t]}return t}var bVe=t=>({tr:e,state:n,dispatch:r})=>{const i=qi(t,n.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const c=s.before(o),u=s.after(o);e.delete(c,u).scrollIntoView()}return!0}return!1},xVe=t=>({tr:e,dispatch:n})=>{const{from:r,to:i}=t;return n&&e.delete(r,i),!0},yVe=()=>({state:t,dispatch:e})=>L4(t,e),vVe=()=>({commands:t})=>t.keyboardShortcut("Enter"),wVe=()=>({state:t,dispatch:e})=>sHe(t,e);function Q4(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function MN(t,e,n={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>n.strict?e[i]===t[i]:Q4(e[i])?e[i].test(t[i]):e[i]===t[i]):!0}function yne(t,e,n={}){return t.find(r=>r.type===e&&MN(Object.fromEntries(Object.keys(n).map(i=>[i,r.attrs[i]])),n))}function K7(t,e,n={}){return!!yne(t,e,n)}function Z4(t,e,n){var r;if(!t||!e)return;let i=t.parent.childAfter(t.parentOffset);if((!i.node||!i.node.marks.some(d=>d.type===e))&&(i=t.parent.childBefore(t.parentOffset)),!i.node||!i.node.marks.some(d=>d.type===e)||(n=n||((r=i.node.marks[0])==null?void 0:r.attrs),!yne([...i.node.marks],e,n)))return;let o=i.index,l=t.start()+i.offset,c=o+1,u=l+i.node.nodeSize;for(;o>0&&K7([...t.parent.child(o-1).marks],e,n);)o-=1,l-=t.parent.child(o).nodeSize;for(;c({tr:n,state:r,dispatch:i})=>{const s=id(t,r.schema),{doc:o,selection:l}=n,{$from:c,from:u,to:d}=l;if(i){const h=Z4(c,s,e);if(h&&h.from<=u&&h.to>=d){const p=yn.create(o,h.from,h.to);n.setSelection(p)}}return!0},SVe=t=>e=>{const n=typeof t=="function"?t(e):t;for(let r=0;r({editor:n,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(J4()||NVe())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),e?.scrollIntoView&&n.commands.scrollIntoView())})};if(r.hasFocus()&&t===null||t===!1)return!0;if(s&&t===null&&!vne(n.state.selection))return o(),!0;const l=wne(i.doc,t)||n.state.selection,c=n.state.selection.eq(l);return s&&(c||i.setSelection(l),c&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},MVe=(t,e)=>n=>t.every((r,i)=>e(r,{...n,index:i})),EVe=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),_ne=t=>{const e=t.childNodes;for(let n=e.length-1;n>=0;n-=1){const r=e[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?t.removeChild(r):r.nodeType===1&&_ne(r)}return t};function l1(t){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${t}`,n=new window.DOMParser().parseFromString(e,"text/html").body;return _ne(n)}function Dy(t,e,n){if(t instanceof Sh||t instanceof At)return t;n={slice:!0,parseOptions:{},...n};const r=typeof t=="object"&&t!==null,i=typeof t=="string";if(r)try{if(Array.isArray(t)&&t.length>0)return At.fromArray(t.map(l=>e.nodeFromJSON(l)));const o=e.nodeFromJSON(t);return n.errorOnInvalidContent&&o.check(),o}catch(s){if(n.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",t,"Error:",s),Dy("",e,n)}if(i){if(n.errorOnInvalidContent){let o=!1,l="";const c=new ste({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:u=>(o=!0,l=typeof u=="string"?u:u.outerHTML,null)}]}})});if(n.slice?P0.fromSchema(c).parseSlice(l1(t),n.parseOptions):P0.fromSchema(c).parse(l1(t),n.parseOptions),n.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=P0.fromSchema(e);return n.slice?s.parseSlice(l1(t),n.parseOptions).content:s.parse(l1(t),n.parseOptions)}return Dy("",e,n)}function TVe(t,e,n){const r=t.steps.length-1;if(r{o===0&&(o=d)}),t.setSelection(Fn.near(t.doc.resolve(o),n))}var AVe=t=>!("type"in t),CVe=(t,e,n)=>({tr:r,dispatch:i,editor:s})=>{var o;if(i){n={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let l;const c=x=>{s.emit("contentError",{editor:s,error:x,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},u={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{Dy(e,s.schema,{parseOptions:u,errorOnInvalidContent:!0})}catch(x){c(x)}try{l=Dy(e,s.schema,{parseOptions:u,errorOnInvalidContent:(o=n.errorOnInvalidContent)!=null?o:s.options.enableContentCheck})}catch(x){return c(x),!1}let{from:d,to:h}=typeof t=="number"?{from:t,to:t}:{from:t.from,to:t.to},p=!0,m=!0;if((AVe(l)?l:[l]).forEach(x=>{x.check(),p=p?x.isText&&x.marks.length===0:!1,m=m?x.isBlock:!1}),d===h&&m){const{parent:x}=r.doc.resolve(d);x.isTextblock&&!x.type.spec.code&&!x.childCount&&(d-=1,h+=1)}let y;if(p){if(Array.isArray(e))y=e.map(x=>x.text||"").join("");else if(e instanceof At){let x="";e.forEach(v=>{v.text&&(x+=v.text)}),y=x}else typeof e=="object"&&e&&e.text?y=e.text:y=e;r.insertText(y,d,h)}else{y=l;const x=r.doc.resolve(d),v=x.node(),S=x.parentOffset===0,N=v.isText||v.isTextblock,T=v.content.size>0;S&&N&&T&&(d=Math.max(0,d-1)),r.replaceWith(d,h,y)}n.updateSelection&&TVe(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:d,text:y}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:d,text:y})}return!0},PVe=()=>({state:t,dispatch:e})=>rHe(t,e),jVe=()=>({state:t,dispatch:e})=>iHe(t,e),DVe=()=>({state:t,dispatch:e})=>Mte(t,e),RVe=()=>({state:t,dispatch:e})=>Cte(t,e),OVe=()=>({state:t,dispatch:e,tr:n})=>{try{const r=RM(t.doc,t.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},LVe=()=>({state:t,dispatch:e,tr:n})=>{try{const r=RM(t.doc,t.selection.$from.pos,1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},FVe=()=>({state:t,dispatch:e})=>tHe(t,e),IVe=()=>({state:t,dispatch:e})=>nHe(t,e);function Sne(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function zVe(t){const e=t.split(/-(?!$)/);let n=e[e.length-1];n==="Space"&&(n=" ");let r,i,s,o;for(let l=0;l({editor:e,view:n,tr:r,dispatch:i})=>{const s=zVe(t).split(/-(?!$)/),o=s.find(u=>!["Alt","Ctrl","Meta","Shift"].includes(u)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),c=e.captureTransaction(()=>{n.someProp("handleKeyDown",u=>u(n,l))});return c?.steps.forEach(u=>{const d=u.map(r.mapping);d&&i&&r.maybeStep(d)}),!0};function Bh(t,e,n={}){const{from:r,to:i,empty:s}=t.selection,o=e?qi(e,t.schema):null,l=[];t.doc.nodesBetween(r,i,(h,p)=>{if(h.isText)return;const m=Math.max(r,p),b=Math.min(i,p+h.nodeSize);l.push({node:h,from:m,to:b})});const c=i-r,u=l.filter(h=>o?o.name===h.node.type.name:!0).filter(h=>MN(h.node.attrs,n,{strict:!1}));return s?!!u.length:u.reduce((h,p)=>h+p.to-p.from,0)>=c}var BVe=(t,e={})=>({state:n,dispatch:r})=>{const i=qi(t,n.schema);return Bh(n,i,e)?aHe(n,r):!1},HVe=()=>({state:t,dispatch:e})=>Rte(t,e),$Ve=t=>({state:e,dispatch:n})=>{const r=qi(t,e.schema);return bHe(r)(e,n)},VVe=()=>({state:t,dispatch:e})=>jte(t,e);function HM(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function X7(t,e){const n=typeof e=="string"?[e]:e;return Object.keys(t).reduce((r,i)=>(n.includes(i)||(r[i]=t[i]),r),{})}var GVe=(t,e)=>({tr:n,state:r,dispatch:i})=>{let s=null,o=null;const l=HM(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=qi(t,r.schema)),l==="mark"&&(o=id(t,r.schema));let c=!1;return n.selection.ranges.forEach(u=>{r.doc.nodesBetween(u.$from.pos,u.$to.pos,(d,h)=>{s&&s===d.type&&(c=!0,i&&n.setNodeMarkup(h,void 0,X7(d.attrs,e))),o&&d.marks.length&&d.marks.forEach(p=>{o===p.type&&(c=!0,i&&n.addMark(h,h+d.nodeSize,o.create(X7(p.attrs,e))))})})}),c},qVe=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),WVe=()=>({tr:t,dispatch:e})=>{if(e){const n=new ko(t.doc);t.setSelection(n)}return!0},KVe=()=>({state:t,dispatch:e})=>Tte(t,e),XVe=()=>({state:t,dispatch:e})=>Pte(t,e),YVe=()=>({state:t,dispatch:e})=>cHe(t,e),QVe=()=>({state:t,dispatch:e})=>hHe(t,e),ZVe=()=>({state:t,dispatch:e})=>dHe(t,e);function nR(t,e,n={},r={}){return Dy(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var JVe=(t,{errorOnInvalidContent:e,emitUpdate:n=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:c}=s;if(r.preserveWhitespace!=="full"){const u=nR(t,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});return o&&s.replaceWith(0,c.content.size,u).setMeta("preventUpdate",!n),!0}return o&&s.setMeta("preventUpdate",!n),l.insertContentAt({from:0,to:c.content.size},t,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function Nne(t,e){const n=id(e,t.schema),{from:r,to:i,empty:s}=t.selection,o=[];s?(t.storedMarks&&o.push(...t.storedMarks),o.push(...t.selection.$head.marks())):t.doc.nodesBetween(r,i,c=>{o.push(...c.marks)});const l=o.find(c=>c.type.name===n.name);return l?{...l.attrs}:{}}function kne(t,e){const n=new _te(t);return e.forEach(r=>{r.steps.forEach(i=>{n.step(i)})}),n}function eGe(t){for(let e=0;e{n(i)&&r.push({node:i,pos:s})}),r}function nGe(t,e){for(let n=t.depth;n>0;n-=1){const r=t.node(n);if(e(r))return{pos:n>0?t.before(n):0,start:t.start(n),depth:n,node:r}}}function $M(t){return e=>nGe(e.$from,t)}function tn(t,e,n){return t.config[e]===void 0&&t.parent?tn(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?tn(t.parent,e,n):null}):t.config[e]}function eF(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},r=tn(e,"addExtensions",n);return r?[e,...eF(r())]:e}).flat(10)}function tF(t,e){const n=zm.fromSchema(e).serializeFragment(t),i=document.implementation.createHTMLDocument().createElement("div");return i.appendChild(n),i.innerHTML}function Mne(t){return typeof t=="function"}function xr(t,e=void 0,...n){return Mne(t)?e?t.bind(e)(...n):t(...n):t}function rGe(t={}){return Object.keys(t).length===0&&t.constructor===Object}function pb(t){const e=t.filter(i=>i.type==="extension"),n=t.filter(i=>i.type==="node"),r=t.filter(i=>i.type==="mark");return{baseExtensions:e,nodeExtensions:n,markExtensions:r}}function Ene(t){const e=[],{nodeExtensions:n,markExtensions:r}=pb(t),i=[...n,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return t.forEach(o=>{const l={name:o.name,options:o.options,storage:o.storage,extensions:i},c=tn(o,"addGlobalAttributes",l);if(!c)return;c().forEach(d=>{d.types.forEach(h=>{Object.entries(d.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(o=>{const l={name:o.name,options:o.options,storage:o.storage},c=tn(o,"addAttributes",l);if(!c)return;const u=c();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:o.name,name:d,attribute:p})})}),e}function _i(...t){return t.filter(e=>!!e).reduce((e,n)=>{const r={...e};return Object.entries(n).forEach(([i,s])=>{if(!r[i]){r[i]=s;return}if(i==="class"){const l=s?String(s).split(" "):[],c=r[i]?r[i].split(" "):[],u=l.filter(d=>!c.includes(d));r[i]=[...c,...u].join(" ")}else if(i==="style"){const l=s?s.split(";").map(d=>d.trim()).filter(Boolean):[],c=r[i]?r[i].split(";").map(d=>d.trim()).filter(Boolean):[],u=new Map;c.forEach(d=>{const[h,p]=d.split(":").map(m=>m.trim());u.set(h,p)}),l.forEach(d=>{const[h,p]=d.split(":").map(m=>m.trim());u.set(h,p)}),r[i]=Array.from(u.entries()).map(([d,h])=>`${d}: ${h}`).join("; ")}else r[i]=s}),r},{})}function EN(t,e){return e.filter(n=>n.type===t.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(t.attrs)||{}:{[n.name]:t.attrs[n.name]}).reduce((n,r)=>_i(n,r),{})}function iGe(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function Y7(t,e){return"style"in t?t:{...t,getAttrs:n=>{const r=t.getAttrs?t.getAttrs(n):t.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(n):iGe(n.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Q7(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&rGe(n)?!1:n!=null))}function Z7(t){var e,n;const r={};return!((e=t?.attribute)!=null&&e.isRequired)&&"default"in(t?.attribute||{})&&(r.default=t.attribute.default),((n=t?.attribute)==null?void 0:n.validate)!==void 0&&(r.validate=t.attribute.validate),[t.name,r]}function aGe(t,e){var n;const r=Ene(t),{nodeExtensions:i,markExtensions:s}=pb(t),o=(n=i.find(u=>tn(u,"topNode")))==null?void 0:n.name,l=Object.fromEntries(i.map(u=>{const d=r.filter(v=>v.type===u.name),h={name:u.name,options:u.options,storage:u.storage,editor:e},p=t.reduce((v,S)=>{const N=tn(S,"extendNodeSchema",h);return{...v,...N?N(u):{}}},{}),m=Q7({...p,content:xr(tn(u,"content",h)),marks:xr(tn(u,"marks",h)),group:xr(tn(u,"group",h)),inline:xr(tn(u,"inline",h)),atom:xr(tn(u,"atom",h)),selectable:xr(tn(u,"selectable",h)),draggable:xr(tn(u,"draggable",h)),code:xr(tn(u,"code",h)),whitespace:xr(tn(u,"whitespace",h)),linebreakReplacement:xr(tn(u,"linebreakReplacement",h)),defining:xr(tn(u,"defining",h)),isolating:xr(tn(u,"isolating",h)),attrs:Object.fromEntries(d.map(Z7))}),b=xr(tn(u,"parseHTML",h));b&&(m.parseDOM=b.map(v=>Y7(v,d)));const y=tn(u,"renderHTML",h);y&&(m.toDOM=v=>y({node:v,HTMLAttributes:EN(v,d)}));const x=tn(u,"renderText",h);return x&&(m.toText=x),[u.name,m]})),c=Object.fromEntries(s.map(u=>{const d=r.filter(x=>x.type===u.name),h={name:u.name,options:u.options,storage:u.storage,editor:e},p=t.reduce((x,v)=>{const S=tn(v,"extendMarkSchema",h);return{...x,...S?S(u):{}}},{}),m=Q7({...p,inclusive:xr(tn(u,"inclusive",h)),excludes:xr(tn(u,"excludes",h)),group:xr(tn(u,"group",h)),spanning:xr(tn(u,"spanning",h)),code:xr(tn(u,"code",h)),attrs:Object.fromEntries(d.map(Z7))}),b=xr(tn(u,"parseHTML",h));b&&(m.parseDOM=b.map(x=>Y7(x,d)));const y=tn(u,"renderHTML",h);return y&&(m.toDOM=x=>y({mark:x,HTMLAttributes:EN(x,d)})),[u.name,m]}));return new ste({topNode:o,nodes:l,marks:c})}function sGe(t){const e=t.filter((n,r)=>t.indexOf(n)!==r);return Array.from(new Set(e))}function nF(t){return t.sort((n,r)=>{const i=tn(n,"priority")||100,s=tn(r,"priority")||100;return i>s?-1:ir.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Ane(t,e,n){const{from:r,to:i}=e,{blockSeparator:s=` +`))),0,0),t.someProp("transformPasted",p=>{l=p(l,t,!0)}),l;let h=t.someProp("clipboardTextParser",p=>p(e,i,r,t));if(h)l=h;else{let p=i.marks(),{schema:m}=t.state,b=zm.fromSchema(m);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(y=>{let x=o.appendChild(document.createElement("p"));y&&x.appendChild(b.serializeNode(m.text(y,p)))})}}else t.someProp("transformPastedHTML",h=>{n=h(n,t)}),o=m$e(n),Sv&&p$e(o);let u=o&&o.querySelector("[data-pm-slice]"),d=u&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(u.getAttribute("data-pm-slice")||"");if(d&&d[3])for(let h=+d[3];h>0;h--){let p=o.firstChild;for(;p&&p.nodeType!=1;)p=p.nextSibling;if(!p)break;o=p}if(l||(l=(t.someProp("clipboardParser")||t.someProp("domParser")||P0.fromSchema(t.state.schema)).parseSlice(o,{preserveWhitespace:!!(c||d),context:i,ruleFromNode(p){return p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!d$e.test(p.parentNode.nodeName)?{ignore:!0}:null}})),d)l=g$e(O7(l,+d[1],+d[2]),d[4]);else if(l=$t.maxOpen(h$e(l.content,i),!0),l.openStart||l.openEnd){let h=0,p=0;for(let m=l.content.firstChild;h{l=h(l,t,c)}),l}const d$e=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function h$e(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let i=e.node(n).contentMatchAt(e.index(n)),s,o=[];if(t.forEach(l=>{if(!o)return;let c=i.findWrapping(l.type),u;if(!c)return o=null;if(u=o.length&&s.length&&nne(c,s,l,o[o.length-1],0))o[o.length-1]=u;else{o.length&&(o[o.length-1]=rne(o[o.length-1],s.length));let d=tne(l,c);o.push(d),i=i.matchType(d.type),s=c}}),o)return At.from(o)}return t}function tne(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,At.from(t));return t}function nne(t,e,n,r,i){if(i1&&(s=0),i=n&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(At.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,o.copy(l))}function O7(t,e,n){return en})),PP.createHTML(t)):t}function m$e(t){let e=/^(\s*]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=ane().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(t),i;if((i=r&&ine[r[1].toLowerCase()])&&(t=i.map(s=>"<"+s+">").join("")+t+i.map(s=>"").reverse().join("")),n.innerHTML=f$e(t),i)for(let s=0;s=0;l-=2){let c=n.nodes[r[l]];if(!c||c.hasRequiredAttrs())break;i=At.from(c.create(r[l+1],i)),s++,o++}return new $t(i,s,o)}const As={},Cs={},b$e={touchstart:!0,touchmove:!0};class x$e{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function y$e(t){for(let e in As){let n=As[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{w$e(t,r)&&!G4(t,r)&&(t.editable||!(r.type in Cs))&&n(t,r)},b$e[e]?{passive:!0}:void 0)}Ts&&t.dom.addEventListener("input",()=>null),tR(t)}function hh(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function v$e(t){t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function tR(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>G4(t,r))})}function G4(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function w$e(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function _$e(t,e){!G4(t,e)&&As[e.type]&&(t.editable||!(e.type in Cs))&&As[e.type](t,e)}Cs.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!one(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Eu&&ns&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),mb&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();t.input.lastIOSEnter=r,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==r&&(t.someProp("handleKeyDown",i=>i(t,Lf(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||u$e(t,n)?n.preventDefault():hh(t,"key")};Cs.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};Cs.keypress=(t,e)=>{let n=e;if(one(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||Qo&&n.metaKey)return;if(t.someProp("handleKeyPress",i=>i(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof yn)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(n.charCode),s=()=>t.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!t.someProp("handleTextInput",o=>o(t,r.$from.pos,r.$to.pos,i,s))&&t.dispatch(s()),n.preventDefault()}};function zM(t){return{left:t.clientX,top:t.clientY}}function S$e(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function q4(t,e,n,r,i){if(r==-1)return!1;let s=t.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(t.someProp(e,l=>o>s.depth?l(t,n,s.nodeAfter,s.before(o),i,!0):l(t,n,s.node(o),s.before(o),i,!1)))return!0;return!1}function zg(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);r.setMeta("pointer",!0),t.dispatch(r)}function N$e(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&rn.isSelectable(r)?(zg(t,new rn(n)),!0):!1}function k$e(t,e){if(e==-1)return!1;let n=t.state.selection,r,i;n instanceof rn&&(r=n.node);let s=t.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(rn.isSelectable(l)){r&&n.$from.depth>0&&o>=n.$from.depth&&s.before(n.$from.depth+1)==n.$from.pos?i=s.before(n.$from.depth):i=s.before(o);break}}return i!=null?(zg(t,rn.create(t.state.doc,i)),!0):!1}function M$e(t,e,n,r,i){return q4(t,"handleClickOn",e,n,r)||t.someProp("handleClick",s=>s(t,e,r))||(i?k$e(t,n):N$e(t,n))}function E$e(t,e,n,r){return q4(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",i=>i(t,e,r))}function T$e(t,e,n,r){return q4(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",i=>i(t,e,r))||A$e(t,n,r)}function A$e(t,e,n){if(n.button!=0)return!1;let r=t.state.doc;if(e==-1)return r.inlineContent?(zg(t,yn.create(r,0,r.content.size)),!0):!1;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)zg(t,yn.create(r,l+1,l+1+o.content.size));else if(rn.isSelectable(o))zg(t,rn.create(r,l));else continue;return!0}}function W4(t){return _N(t)}const sne=Qo?"metaKey":"ctrlKey";As.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=W4(t),i=Date.now(),s="singleClick";i-t.input.lastClick.time<500&&S$e(n,t.input.lastClick)&&!n[sne]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?s="doubleClick":t.input.lastClick.type=="doubleClick"&&(s="tripleClick")),t.input.lastClick={time:i,x:n.clientX,y:n.clientY,type:s,button:n.button};let o=t.posAtCoords(zM(n));o&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new C$e(t,o,n,!!r)):(s=="doubleClick"?E$e:T$e)(t,o.pos,o.inside,n)?n.preventDefault():hh(t,"pointer"))};class C$e{constructor(e,n,r,i){this.view=e,this.pos=n,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!r[sne],this.allowDefault=r.shiftKey;let s,o;if(n.inside>-1)s=e.state.doc.nodeAt(n.inside),o=n.inside;else{let d=e.state.doc.resolve(n.pos);s=d.parent,o=d.depth?d.before():0}const l=i?null:r.target,c=l?e.docView.nearestDesc(l,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:u}=e.state;(r.button==0&&s.type.spec.draggable&&s.type.spec.selectable!==!1||u instanceof rn&&u.from<=o&&u.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&ll&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this)),hh(e,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>Fu(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(zM(e))),this.updateAllowDefault(e),this.allowDefault||!n?hh(this.view,"pointer"):M$e(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Ts&&this.mightDrag&&!this.mightDrag.node.isAtom||ns&&!this.view.state.selection.visible&&Math.min(Math.abs(n.pos-this.view.state.selection.from),Math.abs(n.pos-this.view.state.selection.to))<=2)?(zg(this.view,Fn.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):hh(this.view,"pointer")}move(e){this.updateAllowDefault(e),hh(this.view,"pointer"),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}}As.touchstart=t=>{t.input.lastTouch=Date.now(),W4(t),hh(t,"pointer")};As.touchmove=t=>{t.input.lastTouch=Date.now(),hh(t,"pointer")};As.contextmenu=t=>W4(t);function one(t,e){return t.composing?!0:Ts&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const P$e=Eu?5e3:-1;Cs.compositionstart=Cs.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof yn&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)))t.markCursor=t.state.storedMarks||n.marks(),_N(t,!0),t.markCursor=null;else if(_N(t,!e.selection.empty),ll&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=t.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}t.input.composing=!0}lne(t,P$e)};Cs.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=e.timeStamp,t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,lne(t,20))};function lne(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>_N(t),e))}function cne(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=D$e());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function j$e(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=NHe(e.focusNode,e.focusOffset),r=kHe(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let i=r.pmViewDesc,s=t.domObserver.lastChangedTextNode;if(n==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(t.input.compositionNode==r){let o=n.pmViewDesc;if(!(!o||!o.isText(n.nodeValue)))return r}}return n||r}function D$e(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function _N(t,e=!1){if(!(Eu&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),cne(t),e||t.docView&&t.docView.dirty){let n=H4(t),r=t.state.selection;return n&&!n.eq(r)?t.dispatch(t.state.tr.setSelection(n)):(t.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function R$e(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}const Cy=Ks&&Nh<15||mb&&CHe<604;As.copy=Cs.cut=(t,e)=>{let n=e,r=t.state.selection,i=n.type=="cut";if(r.empty)return;let s=Cy?null:n.clipboardData,o=r.content(),{dom:l,text:c}=V4(t,o);s?(n.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",c)):R$e(t,l),i&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function O$e(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function L$e(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?Py(t,r.value,null,i,e):Py(t,r.textContent,r.innerHTML,i,e)},50)}function Py(t,e,n,r,i){let s=ene(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",c=>c(t,i,s||$t.empty)))return!0;if(!s)return!1;let o=O$e(s),l=o?t.state.tr.replaceSelectionWith(o,r):t.state.tr.replaceSelection(s);return t.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function une(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Cs.paste=(t,e)=>{let n=e;if(t.composing&&!Eu)return;let r=Cy?null:n.clipboardData,i=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&Py(t,une(r),r.getData("text/html"),i,n)?n.preventDefault():L$e(t,n)};class dne{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}}const F$e=Qo?"altKey":"ctrlKey";function hne(t,e){let n=t.someProp("dragCopies",r=>!r(e));return n??!e[F$e]}As.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let i=t.state.selection,s=i.empty?null:t.posAtCoords(zM(n)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof rn?i.to-1:i.to))){if(r&&r.mightDrag)o=rn.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let h=t.docView.nearestDesc(n.target,!0);h&&h.node.type.spec.draggable&&h!=t.docView&&(o=rn.create(t.state.doc,h.posBefore))}}let l=(o||t.state.selection).content(),{dom:c,text:u,slice:d}=V4(t,l);(!n.dataTransfer.files.length||!ns||Ite>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Cy?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",Cy||n.dataTransfer.setData("text/plain",u),t.dragging=new dne(d,hne(t,n),o)};As.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};Cs.dragover=Cs.dragenter=(t,e)=>e.preventDefault();Cs.drop=(t,e)=>{let n=e,r=t.dragging;if(t.dragging=null,!n.dataTransfer)return;let i=t.posAtCoords(zM(n));if(!i)return;let s=t.state.doc.resolve(i.pos),o=r&&r.slice;o?t.someProp("transformPasted",b=>{o=b(o,t,!1)}):o=ene(t,une(n.dataTransfer),Cy?null:n.dataTransfer.getData("text/html"),!1,s);let l=!!(r&&hne(t,n));if(t.someProp("handleDrop",b=>b(t,n,o||$t.empty,l))){n.preventDefault();return}if(!o)return;n.preventDefault();let c=o?bte(t.state.doc,s.pos,o):s.pos;c==null&&(c=s.pos);let u=t.state.tr;if(l){let{node:b}=r;b?b.replace(u):u.deleteSelection()}let d=u.mapping.map(c),h=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,p=u.doc;if(h?u.replaceRangeWith(d,d,o.content.firstChild):u.replaceRange(d,d,o),u.doc.eq(p))return;let m=u.doc.resolve(d);if(h&&rn.isSelectable(o.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(o.content.firstChild))u.setSelection(new rn(m));else{let b=u.mapping.map(c);u.mapping.maps[u.mapping.maps.length-1].forEach((y,x,v,S)=>b=S),u.setSelection($4(t,m,u.doc.resolve(b)))}t.focus(),t.dispatch(u.setMeta("uiEvent","drop"))};As.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&Fu(t)},20))};As.blur=(t,e)=>{let n=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)};As.beforeinput=(t,e)=>{if(ns&&Eu&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:r}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=r||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",s=>s(t,Lf(8,"Backspace")))))return;let{$cursor:i}=t.state.selection;i&&i.pos>0&&t.dispatch(t.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let t in Cs)As[t]=Cs[t];function jy(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}class SN{constructor(e,n){this.toDOM=e,this.spec=n||am,this.side=this.spec.side||0}map(e,n,r,i){let{pos:s,deleted:o}=e.mapResult(n.from+i,this.side<0?-1:1);return o?null:new _s(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof SN&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&jy(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Mh{constructor(e,n){this.attrs=e,this.spec=n||am}map(e,n,r,i){let s=e.map(n.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(n.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new _s(s,o,this)}valid(e,n){return n.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,n-l,r,i+l,s)}}map(e,n,r){return this==Ja||e.maps.length==0?this:this.mapInner(e,n,0,0,r||am)}mapInner(e,n,r,i,s){let o;for(let l=0;l{let u=c+r,d;if(d=mne(n,l,u)){for(i||(i=this.children.slice());sl&&h.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+n.content.size;for(let l=0;ls&&c.type instanceof Mh){let u=Math.max(s,c.from)-s,d=Math.min(o,c.to)-s;ui.map(e,n,am));return ah.from(r)}forChild(e,n){if(n.isLeaf)return oi.empty;let r=[];for(let i=0;in instanceof oi)?e:e.reduce((n,r)=>n.concat(r instanceof oi?r:r.members),[]))}}forEachSet(e){for(let n=0;n{let x=y-b-(m-p);for(let v=0;vS+d-h)continue;let N=l[v]+d-h;m>=N?l[v+1]=p<=N?-2:-1:p>=d&&x&&(l[v]+=x,l[v+1]+=x)}h+=x}),d=n.maps[u].map(d,-1)}let c=!1;for(let u=0;u=r.content.size){c=!0;continue}let p=n.map(t[u+1]+s,-1),m=p-i,{index:b,offset:y}=r.content.findIndex(h),x=r.maybeChild(b);if(x&&y==h&&y+x.nodeSize==m){let v=l[u+2].mapInner(n,x,d+1,t[u]+s+1,o);v!=Ja?(l[u]=h,l[u+1]=m,l[u+2]=v):(l[u+1]=-2,c=!0)}else c=!0}if(c){let u=z$e(l,t,e,n,i,s,o),d=NN(u,r,0,o);e=d.local;for(let h=0;hn&&o.to{let u=mne(t,l,c+n);if(u){s=!0;let d=NN(u,l,n+c+1,r);d!=Ja&&i.push(c,c+l.nodeSize,d)}});let o=fne(s?pne(t):t,-n).sort(sm);for(let l=0;l0;)e++;t.splice(e,0,n)}function jP(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=Ja&&e.push(r)}),t.cursorWrapper&&e.push(oi.create(t.state.doc,[t.cursorWrapper.deco])),ah.from(e)}const U$e={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},B$e=Ks&&Nh<=11;class H$e{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class $$e{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new H$e,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),B$e&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,U$e)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let n=0;nthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(A7(this.view)){if(this.suppressingSelectionUpdates)return Fu(this.view);if(Ks&&Nh<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Am(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let n=new Set,r;for(let s=e.focusNode;s;s=fb(s))n.add(s);for(let s=e.anchorNode;s;s=fb(s))if(n.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let n=this.pendingRecords();n.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&A7(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,c=[];if(e.editable)for(let d=0;dh.nodeName=="BR");if(d.length==2){let[h,p]=d;h.parentNode&&h.parentNode.parentNode==p.parentNode?p.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let p of d){let m=p.parentNode;m&&m.nodeName=="LI"&&(!h||q$e(e,h)!=m)&&p.remove()}}}let u=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),V$e(e)),this.handleDOMChange(s,o,l,c),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Fu(e),this.currentSelection.set(r))}registerMutation(e,n){if(n.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let d=0;di;x--){let v=r.childNodes[x-1],S=v.pmViewDesc;if(v.nodeName=="BR"&&!S){s=x;break}if(!S||S.size)break}let h=t.state.doc,p=t.someProp("domParser")||P0.fromSchema(t.state.schema),m=h.resolve(o),b=null,y=p.parse(r,{topNode:m.parent,topMatch:m.parent.contentMatchAt(m.index()),topOpen:!0,from:i,to:s,preserveWhitespace:m.parent.type.whitespace=="pre"?"full":!0,findPositions:u,ruleFromNode:K$e,context:m});if(u&&u[0].pos!=null){let x=u[0].pos,v=u[1]&&u[1].pos;v==null&&(v=x),b={anchor:x+o,head:v+o}}return{doc:y,sel:b,from:o,to:l}}function K$e(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Ts&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(t.parentNode.lastChild==t||Ts&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}const X$e=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function Y$e(t,e,n,r,i){let s=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let k=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,R=H4(t,k);if(R&&!t.state.selection.eq(R)){if(ns&&Eu&&t.input.lastKeyCode===13&&Date.now()-100P(t,Lf(13,"Enter"))))return;let C=t.state.tr.setSelection(R);k=="pointer"?C.setMeta("pointer",!0):k=="key"&&C.scrollIntoView(),s&&C.setMeta("composition",s),t.dispatch(C)}return}let o=t.state.doc.resolve(e),l=o.sharedDepth(n);e=o.before(l+1),n=t.state.doc.resolve(n).after(l+1);let c=t.state.selection,u=W$e(t,e,n),d=t.state.doc,h=d.slice(u.from,u.to),p,m;t.input.lastKeyCode===8&&Date.now()-100Date.now()-225||Eu)&&i.some(k=>k.nodeType==1&&!X$e.test(k.nodeName))&&(!b||b.endA>=b.endB)&&t.someProp("handleKeyDown",k=>k(t,Lf(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!b)if(r&&c instanceof yn&&!c.empty&&c.$head.sameParent(c.$anchor)&&!t.composing&&!(u.sel&&u.sel.anchor!=u.sel.head))b={start:c.from,endA:c.to,endB:c.to};else{if(u.sel){let k=B7(t,t.state.doc,u.sel);if(k&&!k.eq(t.state.selection)){let R=t.state.tr.setSelection(k);s&&R.setMeta("composition",s),t.dispatch(R)}}return}t.state.selection.fromt.state.selection.from&&b.start<=t.state.selection.from+2&&t.state.selection.from>=u.from?b.start=t.state.selection.from:b.endA=t.state.selection.to-2&&t.state.selection.to<=u.to&&(b.endB+=t.state.selection.to-b.endA,b.endA=t.state.selection.to)),Ks&&Nh<=11&&b.endB==b.start+1&&b.endA==b.start&&b.start>u.from&&u.doc.textBetween(b.start-u.from-1,b.start-u.from+1)=="  "&&(b.start--,b.endA--,b.endB--);let y=u.doc.resolveNoCache(b.start-u.from),x=u.doc.resolveNoCache(b.endB-u.from),v=d.resolve(b.start),S=y.sameParent(x)&&y.parent.inlineContent&&v.end()>=b.endA;if((mb&&t.input.lastIOSEnter>Date.now()-225&&(!S||i.some(k=>k.nodeName=="DIV"||k.nodeName=="P"))||!S&&y.posk(t,Lf(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>b.start&&Z$e(d,b.start,b.endA,y,x)&&t.someProp("handleKeyDown",k=>k(t,Lf(8,"Backspace")))){Eu&&ns&&t.domObserver.suppressSelectionUpdates();return}ns&&b.endB==b.start&&(t.input.lastChromeDelete=Date.now()),Eu&&!S&&y.start()!=x.start()&&x.parentOffset==0&&y.depth==x.depth&&u.sel&&u.sel.anchor==u.sel.head&&u.sel.head==b.endA&&(b.endB-=2,x=u.doc.resolveNoCache(b.endB-u.from),setTimeout(()=>{t.someProp("handleKeyDown",function(k){return k(t,Lf(13,"Enter"))})},20));let N=b.start,T=b.endA,M=k=>{let R=k||t.state.tr.replace(N,T,u.doc.slice(b.start-u.from,b.endB-u.from));if(u.sel){let C=B7(t,R.doc,u.sel);C&&!(ns&&t.composing&&C.empty&&(b.start!=b.endB||t.input.lastChromeDeleteFu(t),20));let k=M(t.state.tr.delete(N,T)),R=d.resolve(b.start).marksAcross(d.resolve(b.endA));R&&k.ensureMarks(R),t.dispatch(k)}else if(b.endA==b.endB&&(A=Q$e(y.parent.content.cut(y.parentOffset,x.parentOffset),v.parent.content.cut(v.parentOffset,b.endA-v.start())))){let k=M(t.state.tr);A.type=="add"?k.addMark(N,T,A.mark):k.removeMark(N,T,A.mark),t.dispatch(k)}else if(y.parent.child(y.index()).isText&&y.index()==x.index()-(x.textOffset?0:1)){let k=y.parent.textBetween(y.parentOffset,x.parentOffset),R=()=>M(t.state.tr.insertText(k,N,T));t.someProp("handleTextInput",C=>C(t,N,T,k,R))||t.dispatch(R())}else t.dispatch(M());else t.dispatch(M())}function B7(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:$4(t,e.resolve(n.anchor),e.resolve(n.head))}function Q$e(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,i=n,s=r,o,l,c;for(let d=0;dd.mark(l.addToSet(d.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",c=d=>d.mark(l.removeFromSet(d.marks));else return null;let u=[];for(let d=0;dn||DP(o,!0,!1)0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,i++,e=!1;if(n){let s=t.node(r).maybeChild(t.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function J$e(t,e,n,r,i){let s=t.findDiffStart(e,n);if(s==null)return null;let{a:o,b:l}=t.findDiffEnd(e,n+t.size,n+e.size);if(i=="end"){let c=Math.max(0,s-Math.min(o,l));r-=o+c-s}if(o=o?s-r:0;s-=c,s&&s=l?s-r:0;s-=c,s&&s=56320&&e<=57343&&n>=55296&&n<=56319}class gne{constructor(e,n){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new x$e,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(W7),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=G7(this),V7(this),this.nodeViews=q7(this),this.docView=S7(this.state.doc,$7(this),jP(this),this.dom,this),this.domObserver=new $$e(this,(r,i,s,o)=>Y$e(this,r,i,s,o)),this.domObserver.start(),y$e(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let n in e)this._props[n]=e[n];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&tR(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(W7),this.directPlugins=e.plugins),this.updateStateInner(e.state,n)}setProps(e){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in e)n[r]=e[r];this.update(n)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,n){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(cne(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=n.plugins;if(l||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let m=q7(this);tVe(m,this.nodeViews)&&(this.nodeViews=m,s=!0)}(l||n.handleDOMEvents!=this._props.handleDOMEvents)&&tR(this),this.editable=G7(this),V7(this);let c=jP(this),u=$7(this),d=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",h=s||!this.docView.matchesNode(e.doc,u,c);(h||!e.selection.eq(i.selection))&&(o=!0);let p=d=="preserve"&&o&&this.dom.style.overflowAnchor==null&&DHe(this);if(o){this.domObserver.stop();let m=h&&(Ks||ns)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&eVe(i.selection,e.selection);if(h){let b=ns?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=j$e(this)),(s||!this.docView.update(e.doc,u,c,this))&&(this.docView.updateOuterDeco(u),this.docView.destroy(),this.docView=S7(e.doc,u,c,this.dom,this)),b&&!this.trackWrites&&(m=!0)}m||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&r$e(this))?Fu(this,m):(Qte(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),d=="reset"?this.dom.scrollTop=0:d=="to selection"?this.scrollToSelection():p&&RHe(p)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof rn){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&b7(this,n.getBoundingClientRect(),e)}else b7(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let n=0;n0&&this.state.doc.nodeAt(s))==r.node&&(i=s)}this.dragging=new dne(e.slice,e.move,i<0?void 0:rn.create(this.state.doc,i))}someProp(e,n){let r=this._props&&this._props[e],i;if(r!=null&&(i=n?n(r):r))return i;for(let o=0;on.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return UHe(this,e)}coordsAtPos(e,n=1){return $te(this,e,n)}domAtPos(e,n=0){return this.docView.domFromPos(e,n)}nodeDOM(e){let n=this.docView.descAt(e);return n?n.nodeDOM:null}posAtDOM(e,n,r=-1){let i=this.docView.posFromDOM(e,n,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,n){return GHe(this,n||this.state,e)}pasteHTML(e,n){return Py(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return Py(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return V4(this,e)}destroy(){this.docView&&(v$e(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],jP(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,_He())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return _$e(this,e)}domSelectionRange(){let e=this.domSelection();return e?Ts&&this.root.nodeType===11&&EHe(this.dom.ownerDocument)==this.dom&&G$e(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}gne.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function $7(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(t.state)),n)for(let r in n)r=="class"?e.class+=" "+n[r]:r=="style"?e.style=(e.style?e.style+";":"")+n[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(n[r]))}),e.translate||(e.translate="no"),[_s.node(0,t.state.doc.content.size,e)]}function V7(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:_s.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function G7(t){return!t.someProp("editable",e=>e(t.state)===!1)}function eVe(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}function q7(t){let e=Object.create(null);function n(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function tVe(t,e){let n=0,r=0;for(let i in t){if(t[i]!=e[i])return!0;n++}for(let i in e)r++;return n!=r}function W7(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var Uh={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},kN={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},nVe=typeof navigator<"u"&&/Mac/.test(navigator.platform),rVe=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Va=0;Va<10;Va++)Uh[48+Va]=Uh[96+Va]=String(Va);for(var Va=1;Va<=24;Va++)Uh[Va+111]="F"+Va;for(var Va=65;Va<=90;Va++)Uh[Va]=String.fromCharCode(Va+32),kN[Va]=String.fromCharCode(Va);for(var RP in Uh)kN.hasOwnProperty(RP)||(kN[RP]=Uh[RP]);function iVe(t){var e=nVe&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||rVe&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?kN:Uh)[t.keyCode]||t.key||"Unidentified";return n=="Esc"&&(n="Escape"),n=="Del"&&(n="Delete"),n=="Left"&&(n="ArrowLeft"),n=="Up"&&(n="ArrowUp"),n=="Right"&&(n="ArrowRight"),n=="Down"&&(n="ArrowDown"),n}const aVe=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),sVe=typeof navigator<"u"&&/Win/.test(navigator.platform);function oVe(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let r,i,s,o;for(let l=0;l{for(var n in e)uVe(t,n,{get:e[n],enumerable:!0})};function UM(t){const{state:e,transaction:n}=t;let{selection:r}=n,{doc:i}=n,{storedMarks:s}=n;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return s},get selection(){return r},get doc(){return i},get tr(){return r=n.selection,i=n.doc,s=n.storedMarks,n}}}var BM=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:e,state:n}=this,{view:r}=e,{tr:i}=n,s=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,l])=>[o,(...u)=>{const d=l(...u)(s);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(i),d}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,e=!0){const{rawCommands:n,editor:r,state:i}=this,{view:s}=r,o=[],l=!!t,c=t||i.tr,u=()=>(!l&&e&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&s.dispatch(c),o.every(h=>h===!0)),d={...Object.fromEntries(Object.entries(n).map(([h,p])=>[h,(...b)=>{const y=this.buildProps(c,e),x=p(...b)(y);return o.push(x),d}])),run:u};return d}createCan(t){const{rawCommands:e,state:n}=this,r=!1,i=t||n.tr,s=this.buildProps(i,r);return{...Object.fromEntries(Object.entries(e).map(([l,c])=>[l,(...u)=>c(...u)({...s,dispatch:void 0})])),chain:()=>this.createChain(i,r)}}buildProps(t,e=!0){const{rawCommands:n,editor:r,state:i}=this,{view:s}=r,o={tr:t,editor:r,view:s,state:UM({state:i,transaction:t}),dispatch:e?()=>{}:void 0,chain:()=>this.createChain(t,e),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(...u)=>c(...u)(o)]))}};return o}},xne={};Y4(xne,{blur:()=>dVe,clearContent:()=>hVe,clearNodes:()=>fVe,command:()=>mVe,createParagraphNear:()=>pVe,cut:()=>gVe,deleteCurrentNode:()=>bVe,deleteNode:()=>xVe,deleteRange:()=>yVe,deleteSelection:()=>vVe,enter:()=>wVe,exitCode:()=>_Ve,extendMarkRange:()=>SVe,first:()=>NVe,focus:()=>MVe,forEach:()=>EVe,insertContent:()=>TVe,insertContentAt:()=>PVe,joinBackward:()=>RVe,joinDown:()=>DVe,joinForward:()=>OVe,joinItemBackward:()=>LVe,joinItemForward:()=>FVe,joinTextblockBackward:()=>IVe,joinTextblockForward:()=>zVe,joinUp:()=>jVe,keyboardShortcut:()=>BVe,lift:()=>HVe,liftEmptyBlock:()=>$Ve,liftListItem:()=>VVe,newlineInCode:()=>GVe,resetAttributes:()=>qVe,scrollIntoView:()=>WVe,selectAll:()=>KVe,selectNodeBackward:()=>XVe,selectNodeForward:()=>YVe,selectParentNode:()=>QVe,selectTextblockEnd:()=>ZVe,selectTextblockStart:()=>JVe,setContent:()=>eGe,setMark:()=>xGe,setMeta:()=>yGe,setNode:()=>vGe,setNodeSelection:()=>wGe,setTextDirection:()=>_Ge,setTextSelection:()=>SGe,sinkListItem:()=>NGe,splitBlock:()=>kGe,splitListItem:()=>MGe,toggleList:()=>EGe,toggleMark:()=>TGe,toggleNode:()=>AGe,toggleWrap:()=>CGe,undoInputRule:()=>PGe,unsetAllMarks:()=>jGe,unsetMark:()=>DGe,unsetTextDirection:()=>RGe,updateAttributes:()=>OGe,wrapIn:()=>LGe,wrapInList:()=>FGe});var dVe=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window?.getSelection())==null||n.removeAllRanges())}),!0),hVe=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),fVe=()=>({state:t,tr:e,dispatch:n})=>{const{selection:r}=e,{ranges:i}=r;return n&&i.forEach(({$from:s,$to:o})=>{t.doc.nodesBetween(s.pos,o.pos,(l,c)=>{if(l.type.isText)return;const{doc:u,mapping:d}=e,h=u.resolve(d.map(c)),p=u.resolve(d.map(c+l.nodeSize)),m=h.blockRange(p);if(!m)return;const b=Ub(m);if(l.type.isTextblock){const{defaultType:y}=h.parent.contentMatchAt(h.index());e.setNodeMarkup(m.start,y)}(b||b===0)&&e.lift(m,b)})}),!0},mVe=t=>e=>t(e),pVe=()=>({state:t,dispatch:e})=>Dte(t,e),gVe=(t,e)=>({editor:n,tr:r})=>{const{state:i}=n,s=i.doc.slice(t.from,t.to);r.deleteRange(t.from,t.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new yn(r.doc.resolve(Math.max(o-1,0)))),!0},bVe=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,r=n.$anchor.node();if(r.content.size>0)return!1;const i=t.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const l=i.before(s),c=i.after(s);t.delete(l,c).scrollIntoView()}return!0}return!1};function qi(t,e){if(typeof t=="string"){if(!e.nodes[t])throw Error(`There is no node type named '${t}'. Maybe you forgot to add the extension?`);return e.nodes[t]}return t}var xVe=t=>({tr:e,state:n,dispatch:r})=>{const i=qi(t,n.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const c=s.before(o),u=s.after(o);e.delete(c,u).scrollIntoView()}return!0}return!1},yVe=t=>({tr:e,dispatch:n})=>{const{from:r,to:i}=t;return n&&e.delete(r,i),!0},vVe=()=>({state:t,dispatch:e})=>L4(t,e),wVe=()=>({commands:t})=>t.keyboardShortcut("Enter"),_Ve=()=>({state:t,dispatch:e})=>oHe(t,e);function Q4(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function MN(t,e,n={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>n.strict?e[i]===t[i]:Q4(e[i])?e[i].test(t[i]):e[i]===t[i]):!0}function yne(t,e,n={}){return t.find(r=>r.type===e&&MN(Object.fromEntries(Object.keys(n).map(i=>[i,r.attrs[i]])),n))}function K7(t,e,n={}){return!!yne(t,e,n)}function Z4(t,e,n){var r;if(!t||!e)return;let i=t.parent.childAfter(t.parentOffset);if((!i.node||!i.node.marks.some(d=>d.type===e))&&(i=t.parent.childBefore(t.parentOffset)),!i.node||!i.node.marks.some(d=>d.type===e)||(n=n||((r=i.node.marks[0])==null?void 0:r.attrs),!yne([...i.node.marks],e,n)))return;let o=i.index,l=t.start()+i.offset,c=o+1,u=l+i.node.nodeSize;for(;o>0&&K7([...t.parent.child(o-1).marks],e,n);)o-=1,l-=t.parent.child(o).nodeSize;for(;c({tr:n,state:r,dispatch:i})=>{const s=id(t,r.schema),{doc:o,selection:l}=n,{$from:c,from:u,to:d}=l;if(i){const h=Z4(c,s,e);if(h&&h.from<=u&&h.to>=d){const p=yn.create(o,h.from,h.to);n.setSelection(p)}}return!0},NVe=t=>e=>{const n=typeof t=="function"?t(e):t;for(let r=0;r({editor:n,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(J4()||kVe())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),e?.scrollIntoView&&n.commands.scrollIntoView())})};if(r.hasFocus()&&t===null||t===!1)return!0;if(s&&t===null&&!vne(n.state.selection))return o(),!0;const l=wne(i.doc,t)||n.state.selection,c=n.state.selection.eq(l);return s&&(c||i.setSelection(l),c&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},EVe=(t,e)=>n=>t.every((r,i)=>e(r,{...n,index:i})),TVe=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),_ne=t=>{const e=t.childNodes;for(let n=e.length-1;n>=0;n-=1){const r=e[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?t.removeChild(r):r.nodeType===1&&_ne(r)}return t};function l1(t){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${t}`,n=new window.DOMParser().parseFromString(e,"text/html").body;return _ne(n)}function Dy(t,e,n){if(t instanceof Sh||t instanceof At)return t;n={slice:!0,parseOptions:{},...n};const r=typeof t=="object"&&t!==null,i=typeof t=="string";if(r)try{if(Array.isArray(t)&&t.length>0)return At.fromArray(t.map(l=>e.nodeFromJSON(l)));const o=e.nodeFromJSON(t);return n.errorOnInvalidContent&&o.check(),o}catch(s){if(n.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",t,"Error:",s),Dy("",e,n)}if(i){if(n.errorOnInvalidContent){let o=!1,l="";const c=new ste({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:u=>(o=!0,l=typeof u=="string"?u:u.outerHTML,null)}]}})});if(n.slice?P0.fromSchema(c).parseSlice(l1(t),n.parseOptions):P0.fromSchema(c).parse(l1(t),n.parseOptions),n.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=P0.fromSchema(e);return n.slice?s.parseSlice(l1(t),n.parseOptions).content:s.parse(l1(t),n.parseOptions)}return Dy("",e,n)}function AVe(t,e,n){const r=t.steps.length-1;if(r{o===0&&(o=d)}),t.setSelection(Fn.near(t.doc.resolve(o),n))}var CVe=t=>!("type"in t),PVe=(t,e,n)=>({tr:r,dispatch:i,editor:s})=>{var o;if(i){n={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let l;const c=x=>{s.emit("contentError",{editor:s,error:x,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},u={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{Dy(e,s.schema,{parseOptions:u,errorOnInvalidContent:!0})}catch(x){c(x)}try{l=Dy(e,s.schema,{parseOptions:u,errorOnInvalidContent:(o=n.errorOnInvalidContent)!=null?o:s.options.enableContentCheck})}catch(x){return c(x),!1}let{from:d,to:h}=typeof t=="number"?{from:t,to:t}:{from:t.from,to:t.to},p=!0,m=!0;if((CVe(l)?l:[l]).forEach(x=>{x.check(),p=p?x.isText&&x.marks.length===0:!1,m=m?x.isBlock:!1}),d===h&&m){const{parent:x}=r.doc.resolve(d);x.isTextblock&&!x.type.spec.code&&!x.childCount&&(d-=1,h+=1)}let y;if(p){if(Array.isArray(e))y=e.map(x=>x.text||"").join("");else if(e instanceof At){let x="";e.forEach(v=>{v.text&&(x+=v.text)}),y=x}else typeof e=="object"&&e&&e.text?y=e.text:y=e;r.insertText(y,d,h)}else{y=l;const x=r.doc.resolve(d),v=x.node(),S=x.parentOffset===0,N=v.isText||v.isTextblock,T=v.content.size>0;S&&N&&T&&(d=Math.max(0,d-1)),r.replaceWith(d,h,y)}n.updateSelection&&AVe(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:d,text:y}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:d,text:y})}return!0},jVe=()=>({state:t,dispatch:e})=>iHe(t,e),DVe=()=>({state:t,dispatch:e})=>aHe(t,e),RVe=()=>({state:t,dispatch:e})=>Mte(t,e),OVe=()=>({state:t,dispatch:e})=>Cte(t,e),LVe=()=>({state:t,dispatch:e,tr:n})=>{try{const r=RM(t.doc,t.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},FVe=()=>({state:t,dispatch:e,tr:n})=>{try{const r=RM(t.doc,t.selection.$from.pos,1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},IVe=()=>({state:t,dispatch:e})=>nHe(t,e),zVe=()=>({state:t,dispatch:e})=>rHe(t,e);function Sne(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function UVe(t){const e=t.split(/-(?!$)/);let n=e[e.length-1];n==="Space"&&(n=" ");let r,i,s,o;for(let l=0;l({editor:e,view:n,tr:r,dispatch:i})=>{const s=UVe(t).split(/-(?!$)/),o=s.find(u=>!["Alt","Ctrl","Meta","Shift"].includes(u)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),c=e.captureTransaction(()=>{n.someProp("handleKeyDown",u=>u(n,l))});return c?.steps.forEach(u=>{const d=u.map(r.mapping);d&&i&&r.maybeStep(d)}),!0};function Bh(t,e,n={}){const{from:r,to:i,empty:s}=t.selection,o=e?qi(e,t.schema):null,l=[];t.doc.nodesBetween(r,i,(h,p)=>{if(h.isText)return;const m=Math.max(r,p),b=Math.min(i,p+h.nodeSize);l.push({node:h,from:m,to:b})});const c=i-r,u=l.filter(h=>o?o.name===h.node.type.name:!0).filter(h=>MN(h.node.attrs,n,{strict:!1}));return s?!!u.length:u.reduce((h,p)=>h+p.to-p.from,0)>=c}var HVe=(t,e={})=>({state:n,dispatch:r})=>{const i=qi(t,n.schema);return Bh(n,i,e)?sHe(n,r):!1},$Ve=()=>({state:t,dispatch:e})=>Rte(t,e),VVe=t=>({state:e,dispatch:n})=>{const r=qi(t,e.schema);return xHe(r)(e,n)},GVe=()=>({state:t,dispatch:e})=>jte(t,e);function HM(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function X7(t,e){const n=typeof e=="string"?[e]:e;return Object.keys(t).reduce((r,i)=>(n.includes(i)||(r[i]=t[i]),r),{})}var qVe=(t,e)=>({tr:n,state:r,dispatch:i})=>{let s=null,o=null;const l=HM(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=qi(t,r.schema)),l==="mark"&&(o=id(t,r.schema));let c=!1;return n.selection.ranges.forEach(u=>{r.doc.nodesBetween(u.$from.pos,u.$to.pos,(d,h)=>{s&&s===d.type&&(c=!0,i&&n.setNodeMarkup(h,void 0,X7(d.attrs,e))),o&&d.marks.length&&d.marks.forEach(p=>{o===p.type&&(c=!0,i&&n.addMark(h,h+d.nodeSize,o.create(X7(p.attrs,e))))})})}),c},WVe=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),KVe=()=>({tr:t,dispatch:e})=>{if(e){const n=new ko(t.doc);t.setSelection(n)}return!0},XVe=()=>({state:t,dispatch:e})=>Tte(t,e),YVe=()=>({state:t,dispatch:e})=>Pte(t,e),QVe=()=>({state:t,dispatch:e})=>uHe(t,e),ZVe=()=>({state:t,dispatch:e})=>fHe(t,e),JVe=()=>({state:t,dispatch:e})=>hHe(t,e);function nR(t,e,n={},r={}){return Dy(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var eGe=(t,{errorOnInvalidContent:e,emitUpdate:n=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:c}=s;if(r.preserveWhitespace!=="full"){const u=nR(t,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});return o&&s.replaceWith(0,c.content.size,u).setMeta("preventUpdate",!n),!0}return o&&s.setMeta("preventUpdate",!n),l.insertContentAt({from:0,to:c.content.size},t,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function Nne(t,e){const n=id(e,t.schema),{from:r,to:i,empty:s}=t.selection,o=[];s?(t.storedMarks&&o.push(...t.storedMarks),o.push(...t.selection.$head.marks())):t.doc.nodesBetween(r,i,c=>{o.push(...c.marks)});const l=o.find(c=>c.type.name===n.name);return l?{...l.attrs}:{}}function kne(t,e){const n=new _te(t);return e.forEach(r=>{r.steps.forEach(i=>{n.step(i)})}),n}function tGe(t){for(let e=0;e{n(i)&&r.push({node:i,pos:s})}),r}function rGe(t,e){for(let n=t.depth;n>0;n-=1){const r=t.node(n);if(e(r))return{pos:n>0?t.before(n):0,start:t.start(n),depth:n,node:r}}}function $M(t){return e=>rGe(e.$from,t)}function tn(t,e,n){return t.config[e]===void 0&&t.parent?tn(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?tn(t.parent,e,n):null}):t.config[e]}function eF(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},r=tn(e,"addExtensions",n);return r?[e,...eF(r())]:e}).flat(10)}function tF(t,e){const n=zm.fromSchema(e).serializeFragment(t),i=document.implementation.createHTMLDocument().createElement("div");return i.appendChild(n),i.innerHTML}function Mne(t){return typeof t=="function"}function xr(t,e=void 0,...n){return Mne(t)?e?t.bind(e)(...n):t(...n):t}function iGe(t={}){return Object.keys(t).length===0&&t.constructor===Object}function pb(t){const e=t.filter(i=>i.type==="extension"),n=t.filter(i=>i.type==="node"),r=t.filter(i=>i.type==="mark");return{baseExtensions:e,nodeExtensions:n,markExtensions:r}}function Ene(t){const e=[],{nodeExtensions:n,markExtensions:r}=pb(t),i=[...n,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return t.forEach(o=>{const l={name:o.name,options:o.options,storage:o.storage,extensions:i},c=tn(o,"addGlobalAttributes",l);if(!c)return;c().forEach(d=>{d.types.forEach(h=>{Object.entries(d.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(o=>{const l={name:o.name,options:o.options,storage:o.storage},c=tn(o,"addAttributes",l);if(!c)return;const u=c();Object.entries(u).forEach(([d,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:o.name,name:d,attribute:p})})}),e}function _i(...t){return t.filter(e=>!!e).reduce((e,n)=>{const r={...e};return Object.entries(n).forEach(([i,s])=>{if(!r[i]){r[i]=s;return}if(i==="class"){const l=s?String(s).split(" "):[],c=r[i]?r[i].split(" "):[],u=l.filter(d=>!c.includes(d));r[i]=[...c,...u].join(" ")}else if(i==="style"){const l=s?s.split(";").map(d=>d.trim()).filter(Boolean):[],c=r[i]?r[i].split(";").map(d=>d.trim()).filter(Boolean):[],u=new Map;c.forEach(d=>{const[h,p]=d.split(":").map(m=>m.trim());u.set(h,p)}),l.forEach(d=>{const[h,p]=d.split(":").map(m=>m.trim());u.set(h,p)}),r[i]=Array.from(u.entries()).map(([d,h])=>`${d}: ${h}`).join("; ")}else r[i]=s}),r},{})}function EN(t,e){return e.filter(n=>n.type===t.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(t.attrs)||{}:{[n.name]:t.attrs[n.name]}).reduce((n,r)=>_i(n,r),{})}function aGe(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function Y7(t,e){return"style"in t?t:{...t,getAttrs:n=>{const r=t.getAttrs?t.getAttrs(n):t.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(n):aGe(n.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Q7(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&iGe(n)?!1:n!=null))}function Z7(t){var e,n;const r={};return!((e=t?.attribute)!=null&&e.isRequired)&&"default"in(t?.attribute||{})&&(r.default=t.attribute.default),((n=t?.attribute)==null?void 0:n.validate)!==void 0&&(r.validate=t.attribute.validate),[t.name,r]}function sGe(t,e){var n;const r=Ene(t),{nodeExtensions:i,markExtensions:s}=pb(t),o=(n=i.find(u=>tn(u,"topNode")))==null?void 0:n.name,l=Object.fromEntries(i.map(u=>{const d=r.filter(v=>v.type===u.name),h={name:u.name,options:u.options,storage:u.storage,editor:e},p=t.reduce((v,S)=>{const N=tn(S,"extendNodeSchema",h);return{...v,...N?N(u):{}}},{}),m=Q7({...p,content:xr(tn(u,"content",h)),marks:xr(tn(u,"marks",h)),group:xr(tn(u,"group",h)),inline:xr(tn(u,"inline",h)),atom:xr(tn(u,"atom",h)),selectable:xr(tn(u,"selectable",h)),draggable:xr(tn(u,"draggable",h)),code:xr(tn(u,"code",h)),whitespace:xr(tn(u,"whitespace",h)),linebreakReplacement:xr(tn(u,"linebreakReplacement",h)),defining:xr(tn(u,"defining",h)),isolating:xr(tn(u,"isolating",h)),attrs:Object.fromEntries(d.map(Z7))}),b=xr(tn(u,"parseHTML",h));b&&(m.parseDOM=b.map(v=>Y7(v,d)));const y=tn(u,"renderHTML",h);y&&(m.toDOM=v=>y({node:v,HTMLAttributes:EN(v,d)}));const x=tn(u,"renderText",h);return x&&(m.toText=x),[u.name,m]})),c=Object.fromEntries(s.map(u=>{const d=r.filter(x=>x.type===u.name),h={name:u.name,options:u.options,storage:u.storage,editor:e},p=t.reduce((x,v)=>{const S=tn(v,"extendMarkSchema",h);return{...x,...S?S(u):{}}},{}),m=Q7({...p,inclusive:xr(tn(u,"inclusive",h)),excludes:xr(tn(u,"excludes",h)),group:xr(tn(u,"group",h)),spanning:xr(tn(u,"spanning",h)),code:xr(tn(u,"code",h)),attrs:Object.fromEntries(d.map(Z7))}),b=xr(tn(u,"parseHTML",h));b&&(m.parseDOM=b.map(x=>Y7(x,d)));const y=tn(u,"renderHTML",h);return y&&(m.toDOM=x=>y({mark:x,HTMLAttributes:EN(x,d)})),[u.name,m]}));return new ste({topNode:o,nodes:l,marks:c})}function oGe(t){const e=t.filter((n,r)=>t.indexOf(n)!==r);return Array.from(new Set(e))}function nF(t){return t.sort((n,r)=>{const i=tn(n,"priority")||100,s=tn(r,"priority")||100;return i>s?-1:ir.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Ane(t,e,n){const{from:r,to:i}=e,{blockSeparator:s=` -`,textSerializers:o={}}=n||{};let l="";return t.nodesBetween(r,i,(c,u,d,h)=>{var p;c.isBlock&&u>r&&(l+=s);const m=o?.[c.type.name];if(m)return d&&(l+=m({node:c,pos:u,parent:d,index:h,range:e})),!1;c.isText&&(l+=(p=c?.text)==null?void 0:p.slice(Math.max(r,u)-u,i-u))}),l}function oGe(t,e){const n={from:0,to:t.content.size};return Ane(t,n,e)}function Cne(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function lGe(t,e){const n=qi(e,t.schema),{from:r,to:i}=t.selection,s=[];t.doc.nodesBetween(r,i,l=>{s.push(l)});const o=s.reverse().find(l=>l.type.name===n.name);return o?{...o.attrs}:{}}function Pne(t,e){const n=HM(typeof e=="string"?e:e.name,t.schema);return n==="node"?lGe(t,e):n==="mark"?Nne(t,e):{}}function cGe(t,e=JSON.stringify){const n={};return t.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(n,i)?!1:n[i]=!0})}function uGe(t){const e=cGe(t);return e.length===1?e:e.filter((n,r)=>!e.filter((s,o)=>o!==r).some(s=>n.oldRange.from>=s.oldRange.from&&n.oldRange.to<=s.oldRange.to&&n.newRange.from>=s.newRange.from&&n.newRange.to<=s.newRange.to))}function jne(t){const{mapping:e,steps:n}=t,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,c)=>{o.push({from:l,to:c})});else{const{from:l,to:c}=n[s];if(l===void 0||c===void 0)return;o.push({from:l,to:c})}o.forEach(({from:l,to:c})=>{const u=e.slice(s).map(l,-1),d=e.slice(s).map(c),h=e.invert().map(u,-1),p=e.invert().map(d);r.push({oldRange:{from:h,to:p},newRange:{from:u,to:d}})})}),uGe(r)}function rF(t,e,n){const r=[];return t===e?n.resolve(t).marks().forEach(i=>{const s=n.resolve(t),o=Z4(s,i.type);o&&r.push({mark:i,...o})}):n.nodesBetween(t,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}var dGe=(t,e,n,r=20)=>{const i=t.doc.resolve(n);let s=r,o=null;for(;s>0&&o===null;){const l=i.node(s);l?.type.name===e?o=l:s-=1}return[o,s]};function LP(t,e){return e.nodes[t]||e.marks[t]||null}function $1(t,e,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const i=t.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}var hGe=(t,e=500)=>{let n="";const r=t.parentOffset;return t.parent.nodesBetween(Math.max(0,r-e),r,(i,s,o,l)=>{var c,u;const d=((u=(c=i.type.spec).toText)==null?void 0:u.call(c,{node:i,pos:s,parent:o,index:l}))||i.textContent||"%leaf%";n+=i.isAtom&&!i.isText?d:d.slice(0,Math.max(0,r-s))}),n};function rR(t,e,n={}){const{empty:r,ranges:i}=t.selection,s=e?id(e,t.schema):null;if(r)return!!(t.storedMarks||t.selection.$from.marks()).filter(h=>s?s.name===h.type.name:!0).find(h=>MN(h.attrs,n,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:h,$to:p})=>{const m=h.pos,b=p.pos;t.doc.nodesBetween(m,b,(y,x)=>{if(!y.isText&&!y.marks.length)return;const v=Math.max(m,x),S=Math.min(b,x+y.nodeSize),N=S-v;o+=N,l.push(...y.marks.map(T=>({mark:T,from:v,to:S})))})}),o===0)return!1;const c=l.filter(h=>s?s.name===h.mark.type.name:!0).filter(h=>MN(h.mark.attrs,n,{strict:!1})).reduce((h,p)=>h+p.to-p.from,0),u=l.filter(h=>s?h.mark.type!==s&&h.mark.type.excludes(s):!0).reduce((h,p)=>h+p.to-p.from,0);return(c>0?c+u:c)>=o}function fGe(t,e,n={}){if(!e)return Bh(t,null,n)||rR(t,null,n);const r=HM(e,t.schema);return r==="node"?Bh(t,e,n):r==="mark"?rR(t,e,n):!1}var mGe=(t,e)=>{const{$from:n,$to:r,$anchor:i}=t.selection;if(e){const s=$M(l=>l.type.name===e)(t.selection);if(!s)return!1;const o=t.doc.resolve(s.pos+1);return i.pos+1===o.end()}return!(r.parentOffset{const{$from:e,$to:n}=t.selection;return!(e.parentOffset>0||e.pos!==n.pos)};function J7(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function e9(t,e){const{nodeExtensions:n}=pb(e),r=n.find(o=>o.name===t);if(!r)return!1;const i={name:r.name,options:r.options,storage:r.storage},s=xr(tn(r,"group",i));return typeof s!="string"?!1:s.split(" ").includes("list")}function VM(t,{checkChildren:e=!0,ignoreWhitespace:n=!1}={}){var r;if(n){if(t.type.name==="hardBreak")return!0;if(t.isText)return/^\s*$/m.test((r=t.text)!=null?r:"")}if(t.isText)return!t.text;if(t.isAtom||t.isLeaf)return!1;if(t.content.childCount===0)return!0;if(e){let i=!0;return t.content.forEach(s=>{i!==!1&&(VM(s,{ignoreWhitespace:n,checkChildren:e})||(i=!1))}),i}return!1}function Dne(t){return t instanceof rn}function gGe(t,e,n){var r;const{selection:i}=e;let s=null;if(vne(i)&&(s=i.$cursor),s){const l=(r=t.storedMarks)!=null?r:s.marks();return s.parent.type.allowsMarkType(n)&&(!!n.isInSet(l)||!l.some(u=>u.type.excludes(n)))}const{ranges:o}=i;return o.some(({$from:l,$to:c})=>{let u=l.depth===0?t.doc.inlineContent&&t.doc.type.allowsMarkType(n):!1;return t.doc.nodesBetween(l.pos,c.pos,(d,h,p)=>{if(u)return!1;if(d.isInline){const m=!p||p.type.allowsMarkType(n),b=!!n.isInSet(d.marks)||!d.marks.some(y=>y.type.excludes(n));u=m&&b}return!u}),u})}var bGe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{const{selection:s}=n,{empty:o,ranges:l}=s,c=id(t,r.schema);if(i)if(o){const u=Nne(r,c);n.addStoredMark(c.create({...u,...e}))}else l.forEach(u=>{const d=u.$from.pos,h=u.$to.pos;r.doc.nodesBetween(d,h,(p,m)=>{const b=Math.max(m,d),y=Math.min(m+p.nodeSize,h);p.marks.find(v=>v.type===c)?p.marks.forEach(v=>{c===v.type&&n.addMark(b,y,c.create({...v.attrs,...e}))}):n.addMark(b,y,c.create(e))})});return gGe(r,n,c)},xGe=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),yGe=(t,e={})=>({state:n,dispatch:r,chain:i})=>{const s=qi(t,n.schema);let o;return n.selection.$anchor.sameParent(n.selection.$head)&&(o=n.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>m7(s,{...o,...e})(n)?!0:l.clearNodes()).command(({state:l})=>m7(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},vGe=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,i=qf(t,0,r.content.size),s=rn.create(r,i);e.setSelection(s)}return!0},wGe=(t,e)=>({tr:n,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&n.doc.nodesBetween(o,l,(c,u)=>{c.isText||n.setNodeMarkup(u,void 0,{...c.attrs,dir:t})}),!0},_Ge=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,{from:i,to:s}=typeof t=="number"?{from:t,to:t}:t,o=yn.atStart(r).from,l=yn.atEnd(r).to,c=qf(i,o,l),u=qf(s,o,l),d=yn.create(r,c,u);e.setSelection(d)}return!0},SGe=t=>({state:e,dispatch:n})=>{const r=qi(t,e.schema);return vHe(r)(e,n)};function t9(t,e){const n=t.storedMarks||t.selection.$to.parentOffset&&t.selection.$from.marks();if(n){const r=n.filter(i=>e?.includes(i.type.name));t.tr.ensureMarks(r)}}var NGe=({keepMarks:t=!0}={})=>({tr:e,state:n,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:c}=s,u=i.extensionManager.attributes,d=$1(u,l.node().type.name,l.node().attrs);if(s instanceof rn&&s.node.isBlock)return!l.parentOffset||!Lu(o,l.pos)?!1:(r&&(t&&t9(n,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const h=c.parentOffset===c.parent.content.size,p=l.depth===0?void 0:eGe(l.node(-1).contentMatchAt(l.indexAfter(-1)));let m=h&&p?[{type:p,attrs:d}]:void 0,b=Lu(e.doc,e.mapping.map(l.pos),1,m);if(!m&&!b&&Lu(e.doc,e.mapping.map(l.pos),1,p?[{type:p}]:void 0)&&(b=!0,m=p?[{type:p,attrs:d}]:void 0),r){if(b&&(s instanceof yn&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,m),p&&!h&&!l.parentOffset&&l.parent.type!==p)){const y=e.mapping.map(l.before()),x=e.doc.resolve(y);l.node(-1).canReplaceWith(x.index(),x.index()+1,p)&&e.setNodeMarkup(e.mapping.map(l.before()),p)}t&&t9(n,i.extensionManager.splittableMarks),e.scrollIntoView()}return b},kGe=(t,e={})=>({tr:n,state:r,dispatch:i,editor:s})=>{var o;const l=qi(t,r.schema),{$from:c,$to:u}=r.selection,d=r.selection.node;if(d&&d.isBlock||c.depth<2||!c.sameParent(u))return!1;const h=c.node(-1);if(h.type!==l)return!1;const p=s.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==l||c.index(-2)!==c.node(-2).childCount-1)return!1;if(i){let v=At.empty;const S=c.index(-1)?1:c.index(-2)?2:3;for(let R=c.depth-S;R>=c.depth-3;R-=1)v=At.from(c.node(R).copy(v));const N=c.indexAfter(-1){if(k>-1)return!1;R.isTextblock&&R.content.size===0&&(k=C+1)}),k>-1&&n.setSelection(yn.near(n.doc.resolve(k))),n.scrollIntoView()}return!0}const m=u.pos===c.end()?h.contentMatchAt(0).defaultType:null,b={...$1(p,h.type.name,h.attrs),...e},y={...$1(p,c.node().type.name,c.node().attrs),...e};n.delete(c.pos,u.pos);const x=m?[{type:l,attrs:b},{type:m,attrs:y}]:[{type:l,attrs:b}];if(!Lu(n.doc,c.pos,2))return!1;if(i){const{selection:v,storedMarks:S}=r,{splittableMarks:N}=s.extensionManager,T=S||v.$to.parentOffset&&v.$from.marks();if(n.split(c.pos,2,x).scrollIntoView(),!T||!i)return!0;const M=T.filter(A=>N.includes(A.type.name));n.ensureMarks(M)}return!0},FP=(t,e)=>{const n=$M(o=>o.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const i=t.doc.nodeAt(r);return n.node.type===i?.type&&qh(t.doc,n.pos)&&t.join(n.pos),!0},IP=(t,e)=>{const n=$M(o=>o.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const i=t.doc.nodeAt(r);return n.node.type===i?.type&&qh(t.doc,r)&&t.join(r),!0},MGe=(t,e,n,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:c,commands:u,can:d})=>{const{extensions:h,splittableMarks:p}=i.extensionManager,m=qi(t,o.schema),b=qi(e,o.schema),{selection:y,storedMarks:x}=o,{$from:v,$to:S}=y,N=v.blockRange(S),T=x||y.$to.parentOffset&&y.$from.marks();if(!N)return!1;const M=$M(A=>e9(A.type.name,h))(y);if(N.depth>=1&&M&&N.depth-M.depth<=1){if(M.node.type===m)return u.liftListItem(b);if(e9(M.node.type.name,h)&&m.validContent(M.node.content)&&l)return c().command(()=>(s.setNodeMarkup(M.pos,m),!0)).command(()=>FP(s,m)).command(()=>IP(s,m)).run()}return!n||!T||!l?c().command(()=>d().wrapInList(m,r)?!0:u.clearNodes()).wrapInList(m,r).command(()=>FP(s,m)).command(()=>IP(s,m)).run():c().command(()=>{const A=d().wrapInList(m,r),k=T.filter(R=>p.includes(R.type.name));return s.ensureMarks(k),A?!0:u.clearNodes()}).wrapInList(m,r).command(()=>FP(s,m)).command(()=>IP(s,m)).run()},EGe=(t,e={},n={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=n,o=id(t,r.schema);return rR(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},TGe=(t,e,n={})=>({state:r,commands:i})=>{const s=qi(t,r.schema),o=qi(e,r.schema),l=Bh(r,s,n);let c;return r.selection.$anchor.sameParent(r.selection.$head)&&(c=r.selection.$anchor.parent.attrs),l?i.setNode(o,c):i.setNode(s,{...c,...n})},AGe=(t,e={})=>({state:n,commands:r})=>{const i=qi(t,n.schema);return Bh(n,i,e)?r.lift(i):r.wrapIn(i,e)},CGe=()=>({state:t,dispatch:e})=>{const n=t.plugins;for(let r=0;r=0;c-=1)o.step(l.steps[c].invert(l.docs[c]));if(s.text){const c=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,t.schema.text(s.text,c))}else o.delete(s.from,s.to)}return!0}}return!1},PGe=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,{empty:r,ranges:i}=n;return r||e&&i.forEach(s=>{t.removeMark(s.$from.pos,s.$to.pos)}),!0},jGe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{var s;const{extendEmptyMarkRange:o=!1}=e,{selection:l}=n,c=id(t,r.schema),{$from:u,empty:d,ranges:h}=l;if(!i)return!0;if(d&&o){let{from:p,to:m}=l;const b=(s=u.marks().find(x=>x.type===c))==null?void 0:s.attrs,y=Z4(u,c,b);y&&(p=y.from,m=y.to),n.removeMark(p,m,c)}else h.forEach(p=>{n.removeMark(p.$from.pos,p.$to.pos,c)});return n.removeStoredMark(c),!0},DGe=t=>({tr:e,state:n,dispatch:r})=>{const{selection:i}=n;let s,o;return typeof t=="number"?(s=t,o=t):t&&"from"in t&&"to"in t?(s=t.from,o=t.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,c)=>{if(l.isText)return;const u={...l.attrs};delete u.dir,e.setNodeMarkup(c,void 0,u)}),!0},RGe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{let s=null,o=null;const l=HM(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=qi(t,r.schema)),l==="mark"&&(o=id(t,r.schema));let c=!1;return n.selection.ranges.forEach(u=>{const d=u.$from.pos,h=u.$to.pos;let p,m,b,y;n.selection.empty?r.doc.nodesBetween(d,h,(x,v)=>{s&&s===x.type&&(c=!0,b=Math.max(v,d),y=Math.min(v+x.nodeSize,h),p=v,m=x)}):r.doc.nodesBetween(d,h,(x,v)=>{v=d&&v<=h&&(s&&s===x.type&&(c=!0,i&&n.setNodeMarkup(v,void 0,{...x.attrs,...e})),o&&x.marks.length&&x.marks.forEach(S=>{if(o===S.type&&(c=!0,i)){const N=Math.max(v,d),T=Math.min(v+x.nodeSize,h);n.addMark(N,T,o.create({...S.attrs,...e}))}}))}),m&&(p!==void 0&&i&&n.setNodeMarkup(p,void 0,{...m.attrs,...e}),o&&m.marks.length&&m.marks.forEach(x=>{o===x.type&&i&&n.addMark(b,y,o.create({...x.attrs,...e}))}))}),c},OGe=(t,e={})=>({state:n,dispatch:r})=>{const i=qi(t,n.schema);return fHe(i,e)(n,r)},LGe=(t,e={})=>({state:n,dispatch:r})=>{const i=qi(t,n.schema);return mHe(i,e)(n,r)},FGe=class{constructor(){this.callbacks={}}on(t,e){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e),this}emit(t,...e){const n=this.callbacks[t];return n&&n.forEach(r=>r.apply(this,e)),this}off(t,e){const n=this.callbacks[t];return n&&(e?this.callbacks[t]=n.filter(r=>r!==e):delete this.callbacks[t]),this}once(t,e){const n=(...r)=>{this.off(t,n),e.apply(this,r)};return this.on(t,n)}removeAllListeners(){this.callbacks={}}},GM=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},IGe=(t,e)=>{if(Q4(e))return e.exec(t);const n=e(t);if(!n)return null;const r=[n.text];return r.index=n.index,r.input=t,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(n.replaceWith)),r};function c1(t){var e;const{editor:n,from:r,to:i,text:s,rules:o,plugin:l}=t,{view:c}=n;if(c.composing)return!1;const u=c.state.doc.resolve(r);if(u.parent.type.spec.code||(e=u.nodeBefore||u.nodeAfter)!=null&&e.marks.find(p=>p.type.spec.code))return!1;let d=!1;const h=hGe(u)+s;return o.forEach(p=>{if(d)return;const m=IGe(h,p.find);if(!m)return;const b=c.state.tr,y=UM({state:c.state,transaction:b}),x={from:r-(m[0].length-s.length),to:i},{commands:v,chain:S,can:N}=new BM({editor:n,state:y});p.handler({state:y,range:x,match:m,commands:v,chain:S,can:N})===null||!b.steps.length||(p.undoable&&b.setMeta(l,{transform:b,from:r,to:i,text:s}),c.dispatch(b),d=!0)}),d}function zGe(t){const{editor:e,rules:n}=t,r=new di({state:{init(){return null},apply(i,s,o){const l=i.getMeta(r);if(l)return l;const c=i.getMeta("applyInputRules");return!!c&&setTimeout(()=>{let{text:d}=c;typeof d=="string"?d=d:d=tF(At.from(d),o.schema);const{from:h}=c,p=h+d.length;c1({editor:e,from:h,to:p,text:d,rules:n,plugin:r})}),i.selectionSet||i.docChanged?null:s}},props:{handleTextInput(i,s,o,l){return c1({editor:e,from:s,to:o,text:l,rules:n,plugin:r})},handleDOMEvents:{compositionend:i=>(setTimeout(()=>{const{$cursor:s}=i.state.selection;s&&c1({editor:e,from:s.pos,to:s.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(i,s){if(s.key!=="Enter")return!1;const{$cursor:o}=i.state.selection;return o?c1({editor:e,from:o.pos,to:o.pos,text:` -`,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function UGe(t){return Object.prototype.toString.call(t).slice(8,-1)}function u1(t){return UGe(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function Rne(t,e){const n={...t};return u1(t)&&u1(e)&&Object.keys(e).forEach(r=>{u1(e[r])&&u1(t[r])?n[r]=Rne(t[r],e[r]):n[r]=e[r]}),n}var iF=class{constructor(t={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...t},this.name=this.config.name}get options(){return{...xr(tn(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...xr(tn(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>Rne(this.options,t)});return e.name=this.name,e.parent=this.parent,e}extend(t={}){const e=new this.constructor({...this.config,...t});return e.parent=this,this.child=e,e.name="name"in t?t.name:e.parent.name,e}},Kh=class One extends iF{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new One(n)}static handleExit({editor:e,mark:n}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const o=i.marks();if(!!!o.find(u=>u?.type.name===n.name))return!1;const c=o.find(u=>u?.type.name===n.name);return c&&r.removeStoredMark(c),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function BGe(t){return typeof t=="number"}var HGe=class{constructor(t){this.find=t.find,this.handler=t.handler}},$Ge=(t,e,n)=>{if(Q4(e))return[...t.matchAll(e)];const r=e(t,n);return r?r.map(i=>{const s=[i.text];return s.index=i.index,s.input=t,s.data=i.data,i.replaceWith&&(i.text.includes(i.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),s.push(i.replaceWith)),s}):[]};function VGe(t){const{editor:e,state:n,from:r,to:i,rule:s,pasteEvent:o,dropEvent:l}=t,{commands:c,chain:u,can:d}=new BM({editor:e,state:n}),h=[];return n.doc.nodesBetween(r,i,(m,b)=>{var y,x,v,S,N;if((x=(y=m.type)==null?void 0:y.spec)!=null&&x.code||!(m.isText||m.isTextblock||m.isInline))return;const T=(N=(S=(v=m.content)==null?void 0:v.size)!=null?S:m.nodeSize)!=null?N:0,M=Math.max(r,b),A=Math.min(i,b+T);if(M>=A)return;const k=m.isText?m.text||"":m.textBetween(M-b,A-b,void 0,"");$Ge(k,s.find,o).forEach(C=>{if(C.index===void 0)return;const P=M+C.index+1,U=P+C[0].length,F={from:n.tr.mapping.map(P),to:n.tr.mapping.map(U)},H=s.handler({state:n,range:F,match:C,commands:c,chain:u,can:d,pasteEvent:o,dropEvent:l});h.push(H)})}),h.every(m=>m!==null)}var d1=null,GGe=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function qGe(t){const{editor:e,rules:n}=t;let r=null,i=!1,s=!1,o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,l;try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}const c=({state:d,from:h,to:p,rule:m,pasteEvt:b})=>{const y=d.tr,x=UM({state:d,transaction:y});if(!(!VGe({editor:e,state:x,from:Math.max(h-1,0),to:p.b-1,rule:m,pasteEvent:b,dropEvent:l})||!y.steps.length)){try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}return o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,y}};return n.map(d=>new di({view(h){const p=b=>{var y;r=(y=h.dom.parentElement)!=null&&y.contains(b.target)?h.dom.parentElement:null,r&&(d1=e)},m=()=>{d1&&(d1=null)};return window.addEventListener("dragstart",p),window.addEventListener("dragend",m),{destroy(){window.removeEventListener("dragstart",p),window.removeEventListener("dragend",m)}}},props:{handleDOMEvents:{drop:(h,p)=>{if(s=r===h.dom.parentElement,l=p,!s){const m=d1;m?.isEditable&&setTimeout(()=>{const b=m.state.selection;b&&m.commands.deleteRange({from:b.from,to:b.to})},10)}return!1},paste:(h,p)=>{var m;const b=(m=p.clipboardData)==null?void 0:m.getData("text/html");return o=p,i=!!b?.includes("data-pm-slice"),!1}}},appendTransaction:(h,p,m)=>{const b=h[0],y=b.getMeta("uiEvent")==="paste"&&!i,x=b.getMeta("uiEvent")==="drop"&&!s,v=b.getMeta("applyPasteRules"),S=!!v;if(!y&&!x&&!S)return;if(S){let{text:M}=v;typeof M=="string"?M=M:M=tF(At.from(M),m.schema);const{from:A}=v,k=A+M.length,R=GGe(M);return c({rule:d,state:m,from:A,to:{b:k},pasteEvt:R})}const N=p.doc.content.findDiffStart(m.doc.content),T=p.doc.content.findDiffEnd(m.doc.content);if(!(!BGe(N)||!T||N===T.b))return c({rule:d,state:m,from:N,to:T,pasteEvt:o})}}))}var qM=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=Tne(t),this.schema=aGe(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((t,e)=>{const n={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:LP(e.name,this.schema)},r=tn(e,"addCommands",n);return r?{...t,...r()}:t},{})}get plugins(){const{editor:t}=this;return nF([...this.extensions].reverse()).flatMap(r=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:LP(r.name,this.schema)},s=[],o=tn(r,"addKeyboardShortcuts",i);let l={};if(r.type==="mark"&&tn(r,"exitable",i)&&(l.ArrowRight=()=>Kh.handleExit({editor:t,mark:r})),o){const p=Object.fromEntries(Object.entries(o()).map(([m,b])=>[m,()=>b({editor:t})]));l={...l,...p}}const c=lVe(l);s.push(c);const u=tn(r,"addInputRules",i);if(J7(r,t.options.enableInputRules)&&u){const p=u();if(p&&p.length){const m=zGe({editor:t,rules:p}),b=Array.isArray(m)?m:[m];s.push(...b)}}const d=tn(r,"addPasteRules",i);if(J7(r,t.options.enablePasteRules)&&d){const p=d();if(p&&p.length){const m=qGe({editor:t,rules:p});s.push(...m)}}const h=tn(r,"addProseMirrorPlugins",i);if(h){const p=h();s.push(...p)}return s})}get attributes(){return Ene(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=pb(this.extensions);return Object.fromEntries(e.filter(n=>!!tn(n,"addNodeView")).map(n=>{const r=this.attributes.filter(c=>c.type===n.name),i={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:qi(n.name,this.schema)},s=tn(n,"addNodeView",i);if(!s)return[];const o=s();if(!o)return[];const l=(c,u,d,h,p)=>{const m=EN(c,r);return o({node:c,view:u,getPos:d,decorations:h,innerDecorations:p,editor:t,extension:n,HTMLAttributes:m})};return[n.name,l]}))}get markViews(){const{editor:t}=this,{markExtensions:e}=pb(this.extensions);return Object.fromEntries(e.filter(n=>!!tn(n,"addMarkView")).map(n=>{const r=this.attributes.filter(l=>l.type===n.name),i={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:id(n.name,this.schema)},s=tn(n,"addMarkView",i);if(!s)return[];const o=(l,c,u)=>{const d=EN(l,r);return s()({mark:l,view:c,inline:u,editor:t,extension:n,HTMLAttributes:d,updateAttributes:h=>{oqe(l,t,h)}})};return[n.name,o]}))}setupExtensions(){const t=this.extensions;this.editor.extensionStorage=Object.fromEntries(t.map(e=>[e.name,e.storage])),t.forEach(e=>{var n;const r={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:LP(e.name,this.schema)};e.type==="mark"&&((n=xr(tn(e,"keepOnSplit",r)))==null||n)&&this.splittableMarks.push(e.name);const i=tn(e,"onBeforeCreate",r),s=tn(e,"onCreate",r),o=tn(e,"onUpdate",r),l=tn(e,"onSelectionUpdate",r),c=tn(e,"onTransaction",r),u=tn(e,"onFocus",r),d=tn(e,"onBlur",r),h=tn(e,"onDestroy",r);i&&this.editor.on("beforeCreate",i),s&&this.editor.on("create",s),o&&this.editor.on("update",o),l&&this.editor.on("selectionUpdate",l),c&&this.editor.on("transaction",c),u&&this.editor.on("focus",u),d&&this.editor.on("blur",d),h&&this.editor.on("destroy",h)})}};qM.resolve=Tne;qM.sort=nF;qM.flatten=eF;var WGe={};Y4(WGe,{ClipboardTextSerializer:()=>Fne,Commands:()=>Ine,Delete:()=>zne,Drop:()=>Une,Editable:()=>Bne,FocusEvents:()=>$ne,Keymap:()=>Vne,Paste:()=>Gne,Tabindex:()=>qne,TextDirection:()=>Wne,focusEventsPluginKey:()=>Hne});var Dr=class Lne extends iF{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new Lne(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},Fne=Dr.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new di({key:new ca("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:t}=this,{state:e,schema:n}=t,{doc:r,selection:i}=e,{ranges:s}=i,o=Math.min(...s.map(d=>d.$from.pos)),l=Math.max(...s.map(d=>d.$to.pos)),c=Cne(n);return Ane(r,{from:o,to:l},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),Ine=Dr.create({name:"commands",addCommands(){return{...xne}}}),zne=Dr.create({name:"delete",onUpdate({transaction:t,appendedTransactions:e}){var n,r,i;const s=()=>{var o,l,c,u;if((u=(c=(l=(o=this.editor.options.coreExtensionOptions)==null?void 0:o.delete)==null?void 0:l.filterTransaction)==null?void 0:c.call(l,t))!=null?u:t.getMeta("y-sync$"))return;const d=kne(t.before,[t,...e]);jne(d).forEach(m=>{d.mapping.mapResult(m.oldRange.from).deletedAfter&&d.mapping.mapResult(m.oldRange.to).deletedBefore&&d.before.nodesBetween(m.oldRange.from,m.oldRange.to,(b,y)=>{const x=y+b.nodeSize-2,v=m.oldRange.from<=y&&x<=m.oldRange.to;this.editor.emit("delete",{type:"node",node:b,from:y,to:x,newFrom:d.mapping.map(y),newTo:d.mapping.map(x),deletedRange:m.oldRange,newRange:m.newRange,partial:!v,editor:this.editor,transaction:t,combinedTransform:d})})});const p=d.mapping;d.steps.forEach((m,b)=>{var y,x;if(m instanceof Fl){const v=p.slice(b).map(m.from,-1),S=p.slice(b).map(m.to),N=p.invert().map(v,-1),T=p.invert().map(S),M=(y=d.doc.nodeAt(v-1))==null?void 0:y.marks.some(k=>k.eq(m.mark)),A=(x=d.doc.nodeAt(S))==null?void 0:x.marks.some(k=>k.eq(m.mark));this.editor.emit("delete",{type:"mark",mark:m.mark,from:m.from,to:m.to,deletedRange:{from:N,to:T},newRange:{from:v,to:S},partial:!!(A||M),editor:this.editor,transaction:t,combinedTransform:d})}})};(i=(r=(n=this.editor.options.coreExtensionOptions)==null?void 0:n.delete)==null?void 0:r.async)==null||i?setTimeout(s,0):s()}}),Une=Dr.create({name:"drop",addProseMirrorPlugins(){return[new di({key:new ca("tiptapDrop"),props:{handleDrop:(t,e,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:r})}}})]}}),Bne=Dr.create({name:"editable",addProseMirrorPlugins(){return[new di({key:new ca("editable"),props:{editable:()=>this.editor.options.editable}})]}}),Hne=new ca("focusEvents"),$ne=Dr.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new di({key:Hne,props:{handleDOMEvents:{focus:(e,n)=>{t.isFocused=!0;const r=t.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,n)=>{t.isFocused=!1;const r=t.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),Vne=Dr.create({name:"keymap",addKeyboardShortcuts(){const t=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:c,doc:u}=l,{empty:d,$anchor:h}=c,{pos:p,parent:m}=h,b=h.parent.isTextblock&&p>0?l.doc.resolve(p-1):h,y=b.parent.type.spec.isolating,x=h.pos-h.parentOffset,v=y&&b.parent.childCount===1?x===h.pos:Fn.atStart(u).from===p;return!d||!m.type.isTextblock||m.textContent.length||!v||v&&h.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:t,"Mod-Backspace":t,"Shift-Backspace":t,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":t,"Alt-Backspace":t,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return J4()||Sne()?s:i},addProseMirrorPlugins(){return[new di({key:new ca("clearDocument"),appendTransaction:(t,e,n)=>{if(t.some(y=>y.getMeta("composition")))return;const r=t.some(y=>y.docChanged)&&!e.doc.eq(n.doc),i=t.some(y=>y.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,c=Fn.atStart(e.doc).from,u=Fn.atEnd(e.doc).to;if(s||!(o===c&&l===u)||!VM(n.doc))return;const p=n.tr,m=UM({state:n,transaction:p}),{commands:b}=new BM({editor:this.editor,state:m});if(b.clearNodes(),!!p.steps.length)return p}})]}}),Gne=Dr.create({name:"paste",addProseMirrorPlugins(){return[new di({key:new ca("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),qne=Dr.create({name:"tabindex",addProseMirrorPlugins(){return[new di({key:new ca("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),Wne=Dr.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=pb(this.extensions);return[{types:t.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const n=e.getAttribute("dir");return n&&(n==="ltr"||n==="rtl"||n==="auto")?n:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new di({key:new ca("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),KGe=class mg{constructor(e,n,r=!1,i=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=n,this.currentNode=i}get name(){return this.node.type.name}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!=null?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let n=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}n=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:n,to:r},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1),n=this.resolvedPos.doc.resolve(e);return new mg(n,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new mg(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new mg(e,this.editor)}get children(){const e=[];return this.node.content.forEach((n,r)=>{const i=n.isBlock&&!n.isTextblock,s=n.isAtom&&!n.isText,o=this.pos+r+(s?0:1);if(o<0||o>this.resolvedPos.doc.nodeSize-2)return;const l=this.resolvedPos.doc.resolve(o);if(!i&&l.depth<=this.depth)return;const c=new mg(l,this.editor,i,i?n:null);i&&(c.actualDepth=this.depth+1),e.push(new mg(l,this.editor,i,i?n:null))}),e}get firstChild(){return this.children[0]||null}get lastChild(){const e=this.children;return e[e.length-1]||null}closest(e,n={}){let r=null,i=this.parent;for(;i&&!r;){if(i.node.type.name===e)if(Object.keys(n).length>0){const s=i.node.attrs,o=Object.keys(n);for(let l=0;l{r&&i.length>0||(o.node.type.name===e&&s.every(c=>n[c]===o.node.attrs[c])&&i.push(o),!(r&&i.length>0)&&(i=i.concat(o.querySelectorAll(e,n,r))))}),i}setAttribute(e){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(n)}},XGe=`.ProseMirror { +`,textSerializers:o={}}=n||{};let l="";return t.nodesBetween(r,i,(c,u,d,h)=>{var p;c.isBlock&&u>r&&(l+=s);const m=o?.[c.type.name];if(m)return d&&(l+=m({node:c,pos:u,parent:d,index:h,range:e})),!1;c.isText&&(l+=(p=c?.text)==null?void 0:p.slice(Math.max(r,u)-u,i-u))}),l}function lGe(t,e){const n={from:0,to:t.content.size};return Ane(t,n,e)}function Cne(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function cGe(t,e){const n=qi(e,t.schema),{from:r,to:i}=t.selection,s=[];t.doc.nodesBetween(r,i,l=>{s.push(l)});const o=s.reverse().find(l=>l.type.name===n.name);return o?{...o.attrs}:{}}function Pne(t,e){const n=HM(typeof e=="string"?e:e.name,t.schema);return n==="node"?cGe(t,e):n==="mark"?Nne(t,e):{}}function uGe(t,e=JSON.stringify){const n={};return t.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(n,i)?!1:n[i]=!0})}function dGe(t){const e=uGe(t);return e.length===1?e:e.filter((n,r)=>!e.filter((s,o)=>o!==r).some(s=>n.oldRange.from>=s.oldRange.from&&n.oldRange.to<=s.oldRange.to&&n.newRange.from>=s.newRange.from&&n.newRange.to<=s.newRange.to))}function jne(t){const{mapping:e,steps:n}=t,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,c)=>{o.push({from:l,to:c})});else{const{from:l,to:c}=n[s];if(l===void 0||c===void 0)return;o.push({from:l,to:c})}o.forEach(({from:l,to:c})=>{const u=e.slice(s).map(l,-1),d=e.slice(s).map(c),h=e.invert().map(u,-1),p=e.invert().map(d);r.push({oldRange:{from:h,to:p},newRange:{from:u,to:d}})})}),dGe(r)}function rF(t,e,n){const r=[];return t===e?n.resolve(t).marks().forEach(i=>{const s=n.resolve(t),o=Z4(s,i.type);o&&r.push({mark:i,...o})}):n.nodesBetween(t,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}var hGe=(t,e,n,r=20)=>{const i=t.doc.resolve(n);let s=r,o=null;for(;s>0&&o===null;){const l=i.node(s);l?.type.name===e?o=l:s-=1}return[o,s]};function LP(t,e){return e.nodes[t]||e.marks[t]||null}function $1(t,e,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const i=t.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}var fGe=(t,e=500)=>{let n="";const r=t.parentOffset;return t.parent.nodesBetween(Math.max(0,r-e),r,(i,s,o,l)=>{var c,u;const d=((u=(c=i.type.spec).toText)==null?void 0:u.call(c,{node:i,pos:s,parent:o,index:l}))||i.textContent||"%leaf%";n+=i.isAtom&&!i.isText?d:d.slice(0,Math.max(0,r-s))}),n};function rR(t,e,n={}){const{empty:r,ranges:i}=t.selection,s=e?id(e,t.schema):null;if(r)return!!(t.storedMarks||t.selection.$from.marks()).filter(h=>s?s.name===h.type.name:!0).find(h=>MN(h.attrs,n,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:h,$to:p})=>{const m=h.pos,b=p.pos;t.doc.nodesBetween(m,b,(y,x)=>{if(!y.isText&&!y.marks.length)return;const v=Math.max(m,x),S=Math.min(b,x+y.nodeSize),N=S-v;o+=N,l.push(...y.marks.map(T=>({mark:T,from:v,to:S})))})}),o===0)return!1;const c=l.filter(h=>s?s.name===h.mark.type.name:!0).filter(h=>MN(h.mark.attrs,n,{strict:!1})).reduce((h,p)=>h+p.to-p.from,0),u=l.filter(h=>s?h.mark.type!==s&&h.mark.type.excludes(s):!0).reduce((h,p)=>h+p.to-p.from,0);return(c>0?c+u:c)>=o}function mGe(t,e,n={}){if(!e)return Bh(t,null,n)||rR(t,null,n);const r=HM(e,t.schema);return r==="node"?Bh(t,e,n):r==="mark"?rR(t,e,n):!1}var pGe=(t,e)=>{const{$from:n,$to:r,$anchor:i}=t.selection;if(e){const s=$M(l=>l.type.name===e)(t.selection);if(!s)return!1;const o=t.doc.resolve(s.pos+1);return i.pos+1===o.end()}return!(r.parentOffset{const{$from:e,$to:n}=t.selection;return!(e.parentOffset>0||e.pos!==n.pos)};function J7(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function e9(t,e){const{nodeExtensions:n}=pb(e),r=n.find(o=>o.name===t);if(!r)return!1;const i={name:r.name,options:r.options,storage:r.storage},s=xr(tn(r,"group",i));return typeof s!="string"?!1:s.split(" ").includes("list")}function VM(t,{checkChildren:e=!0,ignoreWhitespace:n=!1}={}){var r;if(n){if(t.type.name==="hardBreak")return!0;if(t.isText)return/^\s*$/m.test((r=t.text)!=null?r:"")}if(t.isText)return!t.text;if(t.isAtom||t.isLeaf)return!1;if(t.content.childCount===0)return!0;if(e){let i=!0;return t.content.forEach(s=>{i!==!1&&(VM(s,{ignoreWhitespace:n,checkChildren:e})||(i=!1))}),i}return!1}function Dne(t){return t instanceof rn}function bGe(t,e,n){var r;const{selection:i}=e;let s=null;if(vne(i)&&(s=i.$cursor),s){const l=(r=t.storedMarks)!=null?r:s.marks();return s.parent.type.allowsMarkType(n)&&(!!n.isInSet(l)||!l.some(u=>u.type.excludes(n)))}const{ranges:o}=i;return o.some(({$from:l,$to:c})=>{let u=l.depth===0?t.doc.inlineContent&&t.doc.type.allowsMarkType(n):!1;return t.doc.nodesBetween(l.pos,c.pos,(d,h,p)=>{if(u)return!1;if(d.isInline){const m=!p||p.type.allowsMarkType(n),b=!!n.isInSet(d.marks)||!d.marks.some(y=>y.type.excludes(n));u=m&&b}return!u}),u})}var xGe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{const{selection:s}=n,{empty:o,ranges:l}=s,c=id(t,r.schema);if(i)if(o){const u=Nne(r,c);n.addStoredMark(c.create({...u,...e}))}else l.forEach(u=>{const d=u.$from.pos,h=u.$to.pos;r.doc.nodesBetween(d,h,(p,m)=>{const b=Math.max(m,d),y=Math.min(m+p.nodeSize,h);p.marks.find(v=>v.type===c)?p.marks.forEach(v=>{c===v.type&&n.addMark(b,y,c.create({...v.attrs,...e}))}):n.addMark(b,y,c.create(e))})});return bGe(r,n,c)},yGe=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),vGe=(t,e={})=>({state:n,dispatch:r,chain:i})=>{const s=qi(t,n.schema);let o;return n.selection.$anchor.sameParent(n.selection.$head)&&(o=n.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>m7(s,{...o,...e})(n)?!0:l.clearNodes()).command(({state:l})=>m7(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},wGe=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,i=qf(t,0,r.content.size),s=rn.create(r,i);e.setSelection(s)}return!0},_Ge=(t,e)=>({tr:n,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&n.doc.nodesBetween(o,l,(c,u)=>{c.isText||n.setNodeMarkup(u,void 0,{...c.attrs,dir:t})}),!0},SGe=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,{from:i,to:s}=typeof t=="number"?{from:t,to:t}:t,o=yn.atStart(r).from,l=yn.atEnd(r).to,c=qf(i,o,l),u=qf(s,o,l),d=yn.create(r,c,u);e.setSelection(d)}return!0},NGe=t=>({state:e,dispatch:n})=>{const r=qi(t,e.schema);return wHe(r)(e,n)};function t9(t,e){const n=t.storedMarks||t.selection.$to.parentOffset&&t.selection.$from.marks();if(n){const r=n.filter(i=>e?.includes(i.type.name));t.tr.ensureMarks(r)}}var kGe=({keepMarks:t=!0}={})=>({tr:e,state:n,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:c}=s,u=i.extensionManager.attributes,d=$1(u,l.node().type.name,l.node().attrs);if(s instanceof rn&&s.node.isBlock)return!l.parentOffset||!Lu(o,l.pos)?!1:(r&&(t&&t9(n,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const h=c.parentOffset===c.parent.content.size,p=l.depth===0?void 0:tGe(l.node(-1).contentMatchAt(l.indexAfter(-1)));let m=h&&p?[{type:p,attrs:d}]:void 0,b=Lu(e.doc,e.mapping.map(l.pos),1,m);if(!m&&!b&&Lu(e.doc,e.mapping.map(l.pos),1,p?[{type:p}]:void 0)&&(b=!0,m=p?[{type:p,attrs:d}]:void 0),r){if(b&&(s instanceof yn&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,m),p&&!h&&!l.parentOffset&&l.parent.type!==p)){const y=e.mapping.map(l.before()),x=e.doc.resolve(y);l.node(-1).canReplaceWith(x.index(),x.index()+1,p)&&e.setNodeMarkup(e.mapping.map(l.before()),p)}t&&t9(n,i.extensionManager.splittableMarks),e.scrollIntoView()}return b},MGe=(t,e={})=>({tr:n,state:r,dispatch:i,editor:s})=>{var o;const l=qi(t,r.schema),{$from:c,$to:u}=r.selection,d=r.selection.node;if(d&&d.isBlock||c.depth<2||!c.sameParent(u))return!1;const h=c.node(-1);if(h.type!==l)return!1;const p=s.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==l||c.index(-2)!==c.node(-2).childCount-1)return!1;if(i){let v=At.empty;const S=c.index(-1)?1:c.index(-2)?2:3;for(let R=c.depth-S;R>=c.depth-3;R-=1)v=At.from(c.node(R).copy(v));const N=c.indexAfter(-1){if(k>-1)return!1;R.isTextblock&&R.content.size===0&&(k=C+1)}),k>-1&&n.setSelection(yn.near(n.doc.resolve(k))),n.scrollIntoView()}return!0}const m=u.pos===c.end()?h.contentMatchAt(0).defaultType:null,b={...$1(p,h.type.name,h.attrs),...e},y={...$1(p,c.node().type.name,c.node().attrs),...e};n.delete(c.pos,u.pos);const x=m?[{type:l,attrs:b},{type:m,attrs:y}]:[{type:l,attrs:b}];if(!Lu(n.doc,c.pos,2))return!1;if(i){const{selection:v,storedMarks:S}=r,{splittableMarks:N}=s.extensionManager,T=S||v.$to.parentOffset&&v.$from.marks();if(n.split(c.pos,2,x).scrollIntoView(),!T||!i)return!0;const M=T.filter(A=>N.includes(A.type.name));n.ensureMarks(M)}return!0},FP=(t,e)=>{const n=$M(o=>o.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const i=t.doc.nodeAt(r);return n.node.type===i?.type&&qh(t.doc,n.pos)&&t.join(n.pos),!0},IP=(t,e)=>{const n=$M(o=>o.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const i=t.doc.nodeAt(r);return n.node.type===i?.type&&qh(t.doc,r)&&t.join(r),!0},EGe=(t,e,n,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:c,commands:u,can:d})=>{const{extensions:h,splittableMarks:p}=i.extensionManager,m=qi(t,o.schema),b=qi(e,o.schema),{selection:y,storedMarks:x}=o,{$from:v,$to:S}=y,N=v.blockRange(S),T=x||y.$to.parentOffset&&y.$from.marks();if(!N)return!1;const M=$M(A=>e9(A.type.name,h))(y);if(N.depth>=1&&M&&N.depth-M.depth<=1){if(M.node.type===m)return u.liftListItem(b);if(e9(M.node.type.name,h)&&m.validContent(M.node.content)&&l)return c().command(()=>(s.setNodeMarkup(M.pos,m),!0)).command(()=>FP(s,m)).command(()=>IP(s,m)).run()}return!n||!T||!l?c().command(()=>d().wrapInList(m,r)?!0:u.clearNodes()).wrapInList(m,r).command(()=>FP(s,m)).command(()=>IP(s,m)).run():c().command(()=>{const A=d().wrapInList(m,r),k=T.filter(R=>p.includes(R.type.name));return s.ensureMarks(k),A?!0:u.clearNodes()}).wrapInList(m,r).command(()=>FP(s,m)).command(()=>IP(s,m)).run()},TGe=(t,e={},n={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=n,o=id(t,r.schema);return rR(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},AGe=(t,e,n={})=>({state:r,commands:i})=>{const s=qi(t,r.schema),o=qi(e,r.schema),l=Bh(r,s,n);let c;return r.selection.$anchor.sameParent(r.selection.$head)&&(c=r.selection.$anchor.parent.attrs),l?i.setNode(o,c):i.setNode(s,{...c,...n})},CGe=(t,e={})=>({state:n,commands:r})=>{const i=qi(t,n.schema);return Bh(n,i,e)?r.lift(i):r.wrapIn(i,e)},PGe=()=>({state:t,dispatch:e})=>{const n=t.plugins;for(let r=0;r=0;c-=1)o.step(l.steps[c].invert(l.docs[c]));if(s.text){const c=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,t.schema.text(s.text,c))}else o.delete(s.from,s.to)}return!0}}return!1},jGe=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,{empty:r,ranges:i}=n;return r||e&&i.forEach(s=>{t.removeMark(s.$from.pos,s.$to.pos)}),!0},DGe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{var s;const{extendEmptyMarkRange:o=!1}=e,{selection:l}=n,c=id(t,r.schema),{$from:u,empty:d,ranges:h}=l;if(!i)return!0;if(d&&o){let{from:p,to:m}=l;const b=(s=u.marks().find(x=>x.type===c))==null?void 0:s.attrs,y=Z4(u,c,b);y&&(p=y.from,m=y.to),n.removeMark(p,m,c)}else h.forEach(p=>{n.removeMark(p.$from.pos,p.$to.pos,c)});return n.removeStoredMark(c),!0},RGe=t=>({tr:e,state:n,dispatch:r})=>{const{selection:i}=n;let s,o;return typeof t=="number"?(s=t,o=t):t&&"from"in t&&"to"in t?(s=t.from,o=t.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,c)=>{if(l.isText)return;const u={...l.attrs};delete u.dir,e.setNodeMarkup(c,void 0,u)}),!0},OGe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{let s=null,o=null;const l=HM(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=qi(t,r.schema)),l==="mark"&&(o=id(t,r.schema));let c=!1;return n.selection.ranges.forEach(u=>{const d=u.$from.pos,h=u.$to.pos;let p,m,b,y;n.selection.empty?r.doc.nodesBetween(d,h,(x,v)=>{s&&s===x.type&&(c=!0,b=Math.max(v,d),y=Math.min(v+x.nodeSize,h),p=v,m=x)}):r.doc.nodesBetween(d,h,(x,v)=>{v=d&&v<=h&&(s&&s===x.type&&(c=!0,i&&n.setNodeMarkup(v,void 0,{...x.attrs,...e})),o&&x.marks.length&&x.marks.forEach(S=>{if(o===S.type&&(c=!0,i)){const N=Math.max(v,d),T=Math.min(v+x.nodeSize,h);n.addMark(N,T,o.create({...S.attrs,...e}))}}))}),m&&(p!==void 0&&i&&n.setNodeMarkup(p,void 0,{...m.attrs,...e}),o&&m.marks.length&&m.marks.forEach(x=>{o===x.type&&i&&n.addMark(b,y,o.create({...x.attrs,...e}))}))}),c},LGe=(t,e={})=>({state:n,dispatch:r})=>{const i=qi(t,n.schema);return mHe(i,e)(n,r)},FGe=(t,e={})=>({state:n,dispatch:r})=>{const i=qi(t,n.schema);return pHe(i,e)(n,r)},IGe=class{constructor(){this.callbacks={}}on(t,e){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e),this}emit(t,...e){const n=this.callbacks[t];return n&&n.forEach(r=>r.apply(this,e)),this}off(t,e){const n=this.callbacks[t];return n&&(e?this.callbacks[t]=n.filter(r=>r!==e):delete this.callbacks[t]),this}once(t,e){const n=(...r)=>{this.off(t,n),e.apply(this,r)};return this.on(t,n)}removeAllListeners(){this.callbacks={}}},GM=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},zGe=(t,e)=>{if(Q4(e))return e.exec(t);const n=e(t);if(!n)return null;const r=[n.text];return r.index=n.index,r.input=t,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(n.replaceWith)),r};function c1(t){var e;const{editor:n,from:r,to:i,text:s,rules:o,plugin:l}=t,{view:c}=n;if(c.composing)return!1;const u=c.state.doc.resolve(r);if(u.parent.type.spec.code||(e=u.nodeBefore||u.nodeAfter)!=null&&e.marks.find(p=>p.type.spec.code))return!1;let d=!1;const h=fGe(u)+s;return o.forEach(p=>{if(d)return;const m=zGe(h,p.find);if(!m)return;const b=c.state.tr,y=UM({state:c.state,transaction:b}),x={from:r-(m[0].length-s.length),to:i},{commands:v,chain:S,can:N}=new BM({editor:n,state:y});p.handler({state:y,range:x,match:m,commands:v,chain:S,can:N})===null||!b.steps.length||(p.undoable&&b.setMeta(l,{transform:b,from:r,to:i,text:s}),c.dispatch(b),d=!0)}),d}function UGe(t){const{editor:e,rules:n}=t,r=new di({state:{init(){return null},apply(i,s,o){const l=i.getMeta(r);if(l)return l;const c=i.getMeta("applyInputRules");return!!c&&setTimeout(()=>{let{text:d}=c;typeof d=="string"?d=d:d=tF(At.from(d),o.schema);const{from:h}=c,p=h+d.length;c1({editor:e,from:h,to:p,text:d,rules:n,plugin:r})}),i.selectionSet||i.docChanged?null:s}},props:{handleTextInput(i,s,o,l){return c1({editor:e,from:s,to:o,text:l,rules:n,plugin:r})},handleDOMEvents:{compositionend:i=>(setTimeout(()=>{const{$cursor:s}=i.state.selection;s&&c1({editor:e,from:s.pos,to:s.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(i,s){if(s.key!=="Enter")return!1;const{$cursor:o}=i.state.selection;return o?c1({editor:e,from:o.pos,to:o.pos,text:` +`,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function BGe(t){return Object.prototype.toString.call(t).slice(8,-1)}function u1(t){return BGe(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function Rne(t,e){const n={...t};return u1(t)&&u1(e)&&Object.keys(e).forEach(r=>{u1(e[r])&&u1(t[r])?n[r]=Rne(t[r],e[r]):n[r]=e[r]}),n}var iF=class{constructor(t={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...t},this.name=this.config.name}get options(){return{...xr(tn(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...xr(tn(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>Rne(this.options,t)});return e.name=this.name,e.parent=this.parent,e}extend(t={}){const e=new this.constructor({...this.config,...t});return e.parent=this,this.child=e,e.name="name"in t?t.name:e.parent.name,e}},Kh=class One extends iF{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new One(n)}static handleExit({editor:e,mark:n}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const o=i.marks();if(!!!o.find(u=>u?.type.name===n.name))return!1;const c=o.find(u=>u?.type.name===n.name);return c&&r.removeStoredMark(c),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function HGe(t){return typeof t=="number"}var $Ge=class{constructor(t){this.find=t.find,this.handler=t.handler}},VGe=(t,e,n)=>{if(Q4(e))return[...t.matchAll(e)];const r=e(t,n);return r?r.map(i=>{const s=[i.text];return s.index=i.index,s.input=t,s.data=i.data,i.replaceWith&&(i.text.includes(i.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),s.push(i.replaceWith)),s}):[]};function GGe(t){const{editor:e,state:n,from:r,to:i,rule:s,pasteEvent:o,dropEvent:l}=t,{commands:c,chain:u,can:d}=new BM({editor:e,state:n}),h=[];return n.doc.nodesBetween(r,i,(m,b)=>{var y,x,v,S,N;if((x=(y=m.type)==null?void 0:y.spec)!=null&&x.code||!(m.isText||m.isTextblock||m.isInline))return;const T=(N=(S=(v=m.content)==null?void 0:v.size)!=null?S:m.nodeSize)!=null?N:0,M=Math.max(r,b),A=Math.min(i,b+T);if(M>=A)return;const k=m.isText?m.text||"":m.textBetween(M-b,A-b,void 0,"");VGe(k,s.find,o).forEach(C=>{if(C.index===void 0)return;const P=M+C.index+1,U=P+C[0].length,F={from:n.tr.mapping.map(P),to:n.tr.mapping.map(U)},H=s.handler({state:n,range:F,match:C,commands:c,chain:u,can:d,pasteEvent:o,dropEvent:l});h.push(H)})}),h.every(m=>m!==null)}var d1=null,qGe=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function WGe(t){const{editor:e,rules:n}=t;let r=null,i=!1,s=!1,o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,l;try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}const c=({state:d,from:h,to:p,rule:m,pasteEvt:b})=>{const y=d.tr,x=UM({state:d,transaction:y});if(!(!GGe({editor:e,state:x,from:Math.max(h-1,0),to:p.b-1,rule:m,pasteEvent:b,dropEvent:l})||!y.steps.length)){try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}return o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,y}};return n.map(d=>new di({view(h){const p=b=>{var y;r=(y=h.dom.parentElement)!=null&&y.contains(b.target)?h.dom.parentElement:null,r&&(d1=e)},m=()=>{d1&&(d1=null)};return window.addEventListener("dragstart",p),window.addEventListener("dragend",m),{destroy(){window.removeEventListener("dragstart",p),window.removeEventListener("dragend",m)}}},props:{handleDOMEvents:{drop:(h,p)=>{if(s=r===h.dom.parentElement,l=p,!s){const m=d1;m?.isEditable&&setTimeout(()=>{const b=m.state.selection;b&&m.commands.deleteRange({from:b.from,to:b.to})},10)}return!1},paste:(h,p)=>{var m;const b=(m=p.clipboardData)==null?void 0:m.getData("text/html");return o=p,i=!!b?.includes("data-pm-slice"),!1}}},appendTransaction:(h,p,m)=>{const b=h[0],y=b.getMeta("uiEvent")==="paste"&&!i,x=b.getMeta("uiEvent")==="drop"&&!s,v=b.getMeta("applyPasteRules"),S=!!v;if(!y&&!x&&!S)return;if(S){let{text:M}=v;typeof M=="string"?M=M:M=tF(At.from(M),m.schema);const{from:A}=v,k=A+M.length,R=qGe(M);return c({rule:d,state:m,from:A,to:{b:k},pasteEvt:R})}const N=p.doc.content.findDiffStart(m.doc.content),T=p.doc.content.findDiffEnd(m.doc.content);if(!(!HGe(N)||!T||N===T.b))return c({rule:d,state:m,from:N,to:T,pasteEvt:o})}}))}var qM=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=Tne(t),this.schema=sGe(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((t,e)=>{const n={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:LP(e.name,this.schema)},r=tn(e,"addCommands",n);return r?{...t,...r()}:t},{})}get plugins(){const{editor:t}=this;return nF([...this.extensions].reverse()).flatMap(r=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:LP(r.name,this.schema)},s=[],o=tn(r,"addKeyboardShortcuts",i);let l={};if(r.type==="mark"&&tn(r,"exitable",i)&&(l.ArrowRight=()=>Kh.handleExit({editor:t,mark:r})),o){const p=Object.fromEntries(Object.entries(o()).map(([m,b])=>[m,()=>b({editor:t})]));l={...l,...p}}const c=cVe(l);s.push(c);const u=tn(r,"addInputRules",i);if(J7(r,t.options.enableInputRules)&&u){const p=u();if(p&&p.length){const m=UGe({editor:t,rules:p}),b=Array.isArray(m)?m:[m];s.push(...b)}}const d=tn(r,"addPasteRules",i);if(J7(r,t.options.enablePasteRules)&&d){const p=d();if(p&&p.length){const m=WGe({editor:t,rules:p});s.push(...m)}}const h=tn(r,"addProseMirrorPlugins",i);if(h){const p=h();s.push(...p)}return s})}get attributes(){return Ene(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=pb(this.extensions);return Object.fromEntries(e.filter(n=>!!tn(n,"addNodeView")).map(n=>{const r=this.attributes.filter(c=>c.type===n.name),i={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:qi(n.name,this.schema)},s=tn(n,"addNodeView",i);if(!s)return[];const o=s();if(!o)return[];const l=(c,u,d,h,p)=>{const m=EN(c,r);return o({node:c,view:u,getPos:d,decorations:h,innerDecorations:p,editor:t,extension:n,HTMLAttributes:m})};return[n.name,l]}))}get markViews(){const{editor:t}=this,{markExtensions:e}=pb(this.extensions);return Object.fromEntries(e.filter(n=>!!tn(n,"addMarkView")).map(n=>{const r=this.attributes.filter(l=>l.type===n.name),i={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:id(n.name,this.schema)},s=tn(n,"addMarkView",i);if(!s)return[];const o=(l,c,u)=>{const d=EN(l,r);return s()({mark:l,view:c,inline:u,editor:t,extension:n,HTMLAttributes:d,updateAttributes:h=>{lqe(l,t,h)}})};return[n.name,o]}))}setupExtensions(){const t=this.extensions;this.editor.extensionStorage=Object.fromEntries(t.map(e=>[e.name,e.storage])),t.forEach(e=>{var n;const r={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:LP(e.name,this.schema)};e.type==="mark"&&((n=xr(tn(e,"keepOnSplit",r)))==null||n)&&this.splittableMarks.push(e.name);const i=tn(e,"onBeforeCreate",r),s=tn(e,"onCreate",r),o=tn(e,"onUpdate",r),l=tn(e,"onSelectionUpdate",r),c=tn(e,"onTransaction",r),u=tn(e,"onFocus",r),d=tn(e,"onBlur",r),h=tn(e,"onDestroy",r);i&&this.editor.on("beforeCreate",i),s&&this.editor.on("create",s),o&&this.editor.on("update",o),l&&this.editor.on("selectionUpdate",l),c&&this.editor.on("transaction",c),u&&this.editor.on("focus",u),d&&this.editor.on("blur",d),h&&this.editor.on("destroy",h)})}};qM.resolve=Tne;qM.sort=nF;qM.flatten=eF;var KGe={};Y4(KGe,{ClipboardTextSerializer:()=>Fne,Commands:()=>Ine,Delete:()=>zne,Drop:()=>Une,Editable:()=>Bne,FocusEvents:()=>$ne,Keymap:()=>Vne,Paste:()=>Gne,Tabindex:()=>qne,TextDirection:()=>Wne,focusEventsPluginKey:()=>Hne});var Dr=class Lne extends iF{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new Lne(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},Fne=Dr.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new di({key:new ca("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:t}=this,{state:e,schema:n}=t,{doc:r,selection:i}=e,{ranges:s}=i,o=Math.min(...s.map(d=>d.$from.pos)),l=Math.max(...s.map(d=>d.$to.pos)),c=Cne(n);return Ane(r,{from:o,to:l},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),Ine=Dr.create({name:"commands",addCommands(){return{...xne}}}),zne=Dr.create({name:"delete",onUpdate({transaction:t,appendedTransactions:e}){var n,r,i;const s=()=>{var o,l,c,u;if((u=(c=(l=(o=this.editor.options.coreExtensionOptions)==null?void 0:o.delete)==null?void 0:l.filterTransaction)==null?void 0:c.call(l,t))!=null?u:t.getMeta("y-sync$"))return;const d=kne(t.before,[t,...e]);jne(d).forEach(m=>{d.mapping.mapResult(m.oldRange.from).deletedAfter&&d.mapping.mapResult(m.oldRange.to).deletedBefore&&d.before.nodesBetween(m.oldRange.from,m.oldRange.to,(b,y)=>{const x=y+b.nodeSize-2,v=m.oldRange.from<=y&&x<=m.oldRange.to;this.editor.emit("delete",{type:"node",node:b,from:y,to:x,newFrom:d.mapping.map(y),newTo:d.mapping.map(x),deletedRange:m.oldRange,newRange:m.newRange,partial:!v,editor:this.editor,transaction:t,combinedTransform:d})})});const p=d.mapping;d.steps.forEach((m,b)=>{var y,x;if(m instanceof Fl){const v=p.slice(b).map(m.from,-1),S=p.slice(b).map(m.to),N=p.invert().map(v,-1),T=p.invert().map(S),M=(y=d.doc.nodeAt(v-1))==null?void 0:y.marks.some(k=>k.eq(m.mark)),A=(x=d.doc.nodeAt(S))==null?void 0:x.marks.some(k=>k.eq(m.mark));this.editor.emit("delete",{type:"mark",mark:m.mark,from:m.from,to:m.to,deletedRange:{from:N,to:T},newRange:{from:v,to:S},partial:!!(A||M),editor:this.editor,transaction:t,combinedTransform:d})}})};(i=(r=(n=this.editor.options.coreExtensionOptions)==null?void 0:n.delete)==null?void 0:r.async)==null||i?setTimeout(s,0):s()}}),Une=Dr.create({name:"drop",addProseMirrorPlugins(){return[new di({key:new ca("tiptapDrop"),props:{handleDrop:(t,e,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:r})}}})]}}),Bne=Dr.create({name:"editable",addProseMirrorPlugins(){return[new di({key:new ca("editable"),props:{editable:()=>this.editor.options.editable}})]}}),Hne=new ca("focusEvents"),$ne=Dr.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new di({key:Hne,props:{handleDOMEvents:{focus:(e,n)=>{t.isFocused=!0;const r=t.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,n)=>{t.isFocused=!1;const r=t.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),Vne=Dr.create({name:"keymap",addKeyboardShortcuts(){const t=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:c,doc:u}=l,{empty:d,$anchor:h}=c,{pos:p,parent:m}=h,b=h.parent.isTextblock&&p>0?l.doc.resolve(p-1):h,y=b.parent.type.spec.isolating,x=h.pos-h.parentOffset,v=y&&b.parent.childCount===1?x===h.pos:Fn.atStart(u).from===p;return!d||!m.type.isTextblock||m.textContent.length||!v||v&&h.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:t,"Mod-Backspace":t,"Shift-Backspace":t,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":t,"Alt-Backspace":t,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return J4()||Sne()?s:i},addProseMirrorPlugins(){return[new di({key:new ca("clearDocument"),appendTransaction:(t,e,n)=>{if(t.some(y=>y.getMeta("composition")))return;const r=t.some(y=>y.docChanged)&&!e.doc.eq(n.doc),i=t.some(y=>y.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,c=Fn.atStart(e.doc).from,u=Fn.atEnd(e.doc).to;if(s||!(o===c&&l===u)||!VM(n.doc))return;const p=n.tr,m=UM({state:n,transaction:p}),{commands:b}=new BM({editor:this.editor,state:m});if(b.clearNodes(),!!p.steps.length)return p}})]}}),Gne=Dr.create({name:"paste",addProseMirrorPlugins(){return[new di({key:new ca("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),qne=Dr.create({name:"tabindex",addProseMirrorPlugins(){return[new di({key:new ca("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),Wne=Dr.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=pb(this.extensions);return[{types:t.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const n=e.getAttribute("dir");return n&&(n==="ltr"||n==="rtl"||n==="auto")?n:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new di({key:new ca("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),XGe=class mg{constructor(e,n,r=!1,i=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=n,this.currentNode=i}get name(){return this.node.type.name}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!=null?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let n=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}n=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:n,to:r},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1),n=this.resolvedPos.doc.resolve(e);return new mg(n,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new mg(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new mg(e,this.editor)}get children(){const e=[];return this.node.content.forEach((n,r)=>{const i=n.isBlock&&!n.isTextblock,s=n.isAtom&&!n.isText,o=this.pos+r+(s?0:1);if(o<0||o>this.resolvedPos.doc.nodeSize-2)return;const l=this.resolvedPos.doc.resolve(o);if(!i&&l.depth<=this.depth)return;const c=new mg(l,this.editor,i,i?n:null);i&&(c.actualDepth=this.depth+1),e.push(new mg(l,this.editor,i,i?n:null))}),e}get firstChild(){return this.children[0]||null}get lastChild(){const e=this.children;return e[e.length-1]||null}closest(e,n={}){let r=null,i=this.parent;for(;i&&!r;){if(i.node.type.name===e)if(Object.keys(n).length>0){const s=i.node.attrs,o=Object.keys(n);for(let l=0;l{r&&i.length>0||(o.node.type.name===e&&s.every(c=>n[c]===o.node.attrs[c])&&i.push(o),!(r&&i.length>0)&&(i=i.concat(o.querySelectorAll(e,n,r))))}),i}setAttribute(e){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(n)}},YGe=`.ProseMirror { position: relative; } @@ -8590,15 +8590,15 @@ img.ProseMirror-separator { .ProseMirror-focused .ProseMirror-gapcursor { display: block; -}`;function YGe(t,e,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const i=document.createElement("style");return e&&i.setAttribute("nonce",e),i.setAttribute("data-tiptap-style",""),i.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(i),i}var QGe=class extends FGe{constructor(t={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:r})=>{throw r},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.setOptions(t),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:r,slice:i,moved:s})=>this.options.onDrop(r,i,s)),this.on("paste",({event:r,slice:i})=>this.options.onPaste(r,i)),this.on("delete",this.options.onDelete);const e=this.createDoc(),n=wne(e,this.options.autofocus);this.editorState=Ng.create({doc:e,schema:this.schema,selection:n||void 0}),this.options.element&&this.mount(this.options.element)}mount(t){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(t),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){const t=this.editorView.dom;t?.editor&&delete t.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(t){console.warn("Failed to remove CSS element:",t)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=YGe(XGe,this.options.injectNonce))}setOptions(t={}){this.options={...this.options,...t},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(t,e=!0){this.setOptions({editable:t}),e&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:t=>{this.editorState=t},dispatch:t=>{this.dispatchTransaction(t)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(t,e)=>{if(this.editorView)return this.editorView[e];if(e==="state")return this.editorState;if(e in t)return Reflect.get(t,e);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${e}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(t,e){const n=Mne(e)?e(t,[...this.state.plugins]):[...this.state.plugins,t],r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}unregisterPlugin(t){if(this.isDestroyed)return;const e=this.state.plugins;let n=e;if([].concat(t).forEach(i=>{const s=typeof i=="string"?`${i}$`:i.key;n=n.filter(o=>!o.key.startsWith(s))}),e.length===n.length)return;const r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}createExtensionManager(){var t,e;const r=[...this.options.enableCoreExtensions?[Bne,Fne.configure({blockSeparator:(e=(t=this.options.coreExtensionOptions)==null?void 0:t.clipboardTextSerializer)==null?void 0:e.blockSeparator}),Ine,$ne,Vne,qne,Une,Gne,zne,Wne.configure({direction:this.options.textDirection})].filter(i=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[i.name]!==!1:!0):[],...this.options.extensions].filter(i=>["extension","node","mark"].includes(i?.type));this.extensionManager=new qM(r,this)}createCommandManager(){this.commandManager=new BM({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let t;try{t=nR(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(e){if(!(e instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(e.message))throw e;this.emit("contentError",{editor:this,error:e,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(n=>n.name!=="collaboration"),this.createExtensionManager()}}),t=nR(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return t}createView(t){var e;this.editorView=new gne(t,{...this.options.editorProps,attributes:{role:"textbox",...(e=this.options.editorProps)==null?void 0:e.attributes},dispatchTransaction:this.dispatchTransaction.bind(this),state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const n=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(n),this.prependClass(),this.injectCSS();const r=this.view.dom;r.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(t){this.isCapturingTransaction=!0,t(),this.isCapturingTransaction=!1;const e=this.capturedTransaction;return this.capturedTransaction=null,e}dispatchTransaction(t){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=t;return}t.steps.forEach(u=>{var d;return(d=this.capturedTransaction)==null?void 0:d.step(u)});return}const{state:e,transactions:n}=this.state.applyTransaction(t),r=!this.state.selection.eq(e.selection),i=n.includes(t),s=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:t,nextState:e}),!i)return;this.view.updateState(e),this.emit("transaction",{editor:this,transaction:t,appendedTransactions:n.slice(1)}),r&&this.emit("selectionUpdate",{editor:this,transaction:t});const o=n.findLast(u=>u.getMeta("focus")||u.getMeta("blur")),l=o?.getMeta("focus"),c=o?.getMeta("blur");l&&this.emit("focus",{editor:this,event:l.event,transaction:o}),c&&this.emit("blur",{editor:this,event:c.event,transaction:o}),!(t.getMeta("preventUpdate")||!n.some(u=>u.docChanged)||s.doc.eq(e.doc))&&this.emit("update",{editor:this,transaction:t,appendedTransactions:n.slice(1)})}getAttributes(t){return Pne(this.state,t)}isActive(t,e){const n=typeof t=="string"?t:null,r=typeof t=="string"?e:t;return fGe(this.state,n,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return tF(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:e=` +}`;function QGe(t,e,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const i=document.createElement("style");return e&&i.setAttribute("nonce",e),i.setAttribute("data-tiptap-style",""),i.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(i),i}var ZGe=class extends IGe{constructor(t={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:r})=>{throw r},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.setOptions(t),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:r,slice:i,moved:s})=>this.options.onDrop(r,i,s)),this.on("paste",({event:r,slice:i})=>this.options.onPaste(r,i)),this.on("delete",this.options.onDelete);const e=this.createDoc(),n=wne(e,this.options.autofocus);this.editorState=Ng.create({doc:e,schema:this.schema,selection:n||void 0}),this.options.element&&this.mount(this.options.element)}mount(t){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(t),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){const t=this.editorView.dom;t?.editor&&delete t.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(t){console.warn("Failed to remove CSS element:",t)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=QGe(YGe,this.options.injectNonce))}setOptions(t={}){this.options={...this.options,...t},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(t,e=!0){this.setOptions({editable:t}),e&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:t=>{this.editorState=t},dispatch:t=>{this.dispatchTransaction(t)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(t,e)=>{if(this.editorView)return this.editorView[e];if(e==="state")return this.editorState;if(e in t)return Reflect.get(t,e);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${e}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(t,e){const n=Mne(e)?e(t,[...this.state.plugins]):[...this.state.plugins,t],r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}unregisterPlugin(t){if(this.isDestroyed)return;const e=this.state.plugins;let n=e;if([].concat(t).forEach(i=>{const s=typeof i=="string"?`${i}$`:i.key;n=n.filter(o=>!o.key.startsWith(s))}),e.length===n.length)return;const r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}createExtensionManager(){var t,e;const r=[...this.options.enableCoreExtensions?[Bne,Fne.configure({blockSeparator:(e=(t=this.options.coreExtensionOptions)==null?void 0:t.clipboardTextSerializer)==null?void 0:e.blockSeparator}),Ine,$ne,Vne,qne,Une,Gne,zne,Wne.configure({direction:this.options.textDirection})].filter(i=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[i.name]!==!1:!0):[],...this.options.extensions].filter(i=>["extension","node","mark"].includes(i?.type));this.extensionManager=new qM(r,this)}createCommandManager(){this.commandManager=new BM({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let t;try{t=nR(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(e){if(!(e instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(e.message))throw e;this.emit("contentError",{editor:this,error:e,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(n=>n.name!=="collaboration"),this.createExtensionManager()}}),t=nR(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return t}createView(t){var e;this.editorView=new gne(t,{...this.options.editorProps,attributes:{role:"textbox",...(e=this.options.editorProps)==null?void 0:e.attributes},dispatchTransaction:this.dispatchTransaction.bind(this),state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const n=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(n),this.prependClass(),this.injectCSS();const r=this.view.dom;r.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(t){this.isCapturingTransaction=!0,t(),this.isCapturingTransaction=!1;const e=this.capturedTransaction;return this.capturedTransaction=null,e}dispatchTransaction(t){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=t;return}t.steps.forEach(u=>{var d;return(d=this.capturedTransaction)==null?void 0:d.step(u)});return}const{state:e,transactions:n}=this.state.applyTransaction(t),r=!this.state.selection.eq(e.selection),i=n.includes(t),s=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:t,nextState:e}),!i)return;this.view.updateState(e),this.emit("transaction",{editor:this,transaction:t,appendedTransactions:n.slice(1)}),r&&this.emit("selectionUpdate",{editor:this,transaction:t});const o=n.findLast(u=>u.getMeta("focus")||u.getMeta("blur")),l=o?.getMeta("focus"),c=o?.getMeta("blur");l&&this.emit("focus",{editor:this,event:l.event,transaction:o}),c&&this.emit("blur",{editor:this,event:c.event,transaction:o}),!(t.getMeta("preventUpdate")||!n.some(u=>u.docChanged)||s.doc.eq(e.doc))&&this.emit("update",{editor:this,transaction:t,appendedTransactions:n.slice(1)})}getAttributes(t){return Pne(this.state,t)}isActive(t,e){const n=typeof t=="string"?t:null,r=typeof t=="string"?e:t;return mGe(this.state,n,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return tF(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:e=` -`,textSerializers:n={}}=t||{};return oGe(this.state.doc,{blockSeparator:e,textSerializers:{...Cne(this.schema),...n}})}get isEmpty(){return VM(this.state.doc)}destroy(){this.emit("destroy"),this.unmount(),this.removeAllListeners()}get isDestroyed(){var t,e;return(e=(t=this.editorView)==null?void 0:t.isDestroyed)!=null?e:!0}$node(t,e){var n;return((n=this.$doc)==null?void 0:n.querySelector(t,e))||null}$nodes(t,e){var n;return((n=this.$doc)==null?void 0:n.querySelectorAll(t,e))||null}$pos(t){const e=this.state.doc.resolve(t);return new KGe(e,this)}get $doc(){return this.$pos(0)}};function gb(t){return new GM({find:t.find,handler:({state:e,range:n,match:r})=>{const i=xr(t.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const c=l.search(/\S/),u=n.from+l.indexOf(o),d=u+o.length;if(rF(n.from,n.to,e.doc).filter(m=>m.mark.type.excluded.find(y=>y===t.type&&y!==m.mark.type)).filter(m=>m.to>u).length)return null;dn.from&&s.delete(n.from+c,u);const p=n.from+c+o.length;s.addMark(n.from+c,p,t.type.create(i||{})),s.removeStoredMark(t.type)}},undoable:t.undoable})}function Kne(t){return new GM({find:t.find,handler:({state:e,range:n,match:r})=>{const i=xr(t.getAttributes,void 0,r)||{},{tr:s}=e,o=n.from;let l=n.to;const c=t.type.create(i);if(r[1]){const u=r[0].lastIndexOf(r[1]);let d=o+u;d>l?d=l:l=d+r[1].length;const h=r[0][r[0].length-1];s.insertText(h,o+r[0].length-1),s.replaceWith(d,l,c)}else if(r[0]){const u=t.type.isInline?o:o-1;s.insert(u,t.type.create(i)).delete(s.mapping.map(o),s.mapping.map(l))}s.scrollIntoView()},undoable:t.undoable})}function iR(t){return new GM({find:t.find,handler:({state:e,range:n,match:r})=>{const i=e.doc.resolve(n.from),s=xr(t.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),t.type))return null;e.tr.delete(n.from,n.to).setBlockType(n.from,n.from,t.type,s)},undoable:t.undoable})}function bb(t){return new GM({find:t.find,handler:({state:e,range:n,match:r,chain:i})=>{const s=xr(t.getAttributes,void 0,r)||{},o=e.tr.delete(n.from,n.to),c=o.doc.resolve(n.from).blockRange(),u=c&&R4(c,t.type,s);if(!u)return null;if(o.wrap(c,u),t.keepMarks&&t.editor){const{selection:h,storedMarks:p}=e,{splittableMarks:m}=t.editor.extensionManager,b=p||h.$to.parentOffset&&h.$from.marks();if(b){const y=b.filter(x=>m.includes(x.type.name));o.ensureMarks(y)}}if(t.keepAttributes){const h=t.type.name==="bulletList"||t.type.name==="orderedList"?"listItem":"taskList";i().updateAttributes(h,s).run()}const d=o.doc.resolve(n.from-1).nodeBefore;d&&d.type===t.type&&qh(o.doc,n.from-1)&&(!t.joinPredicate||t.joinPredicate(r,d))&&o.join(n.from-1)},undoable:t.undoable})}var ZGe=t=>"touches"in t,JGe=class{constructor(t){this.directions=["bottom-left","bottom-right","top-left","top-right"],this.minSize={height:8,width:8},this.preserveAspectRatio=!1,this.classNames={container:"",wrapper:"",handle:"",resizing:""},this.initialWidth=0,this.initialHeight=0,this.aspectRatio=1,this.isResizing=!1,this.activeHandle=null,this.startX=0,this.startY=0,this.startWidth=0,this.startHeight=0,this.isShiftKeyPressed=!1,this.handleMouseMove=o=>{if(!this.isResizing||!this.activeHandle)return;const l=o.clientX-this.startX,c=o.clientY-this.startY;this.handleResize(l,c)},this.handleTouchMove=o=>{if(!this.isResizing||!this.activeHandle)return;const l=o.touches[0];if(!l)return;const c=l.clientX-this.startX,u=l.clientY-this.startY;this.handleResize(c,u)},this.handleMouseUp=()=>{if(!this.isResizing)return;const o=this.element.offsetWidth,l=this.element.offsetHeight;this.onCommit(o,l),this.isResizing=!1,this.activeHandle=null,this.container.dataset.resizeState="false",this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)},this.handleKeyDown=o=>{o.key==="Shift"&&(this.isShiftKeyPressed=!0)},this.handleKeyUp=o=>{o.key==="Shift"&&(this.isShiftKeyPressed=!1)};var e,n,r,i,s;this.node=t.node,this.element=t.element,this.contentElement=t.contentElement,this.getPos=t.getPos,this.onResize=t.onResize,this.onCommit=t.onCommit,this.onUpdate=t.onUpdate,(e=t.options)!=null&&e.min&&(this.minSize={...this.minSize,...t.options.min}),(n=t.options)!=null&&n.max&&(this.maxSize=t.options.max),(r=t?.options)!=null&&r.directions&&(this.directions=t.options.directions),(i=t.options)!=null&&i.preserveAspectRatio&&(this.preserveAspectRatio=t.options.preserveAspectRatio),(s=t.options)!=null&&s.className&&(this.classNames={container:t.options.className.container||"",wrapper:t.options.className.wrapper||"",handle:t.options.className.handle||"",resizing:t.options.className.resizing||""}),this.wrapper=this.createWrapper(),this.container=this.createContainer(),this.applyInitialSize(),this.attachHandles()}get dom(){return this.container}get contentDOM(){return this.contentElement}update(t,e,n){return t.type!==this.node.type?!1:(this.node=t,this.onUpdate?this.onUpdate(t,e,n):!0)}destroy(){this.isResizing&&(this.container.dataset.resizeState="false",this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp),this.isResizing=!1,this.activeHandle=null),this.container.remove()}createContainer(){const t=document.createElement("div");return t.dataset.resizeContainer="",t.dataset.node=this.node.type.name,t.style.display="flex",t.style.justifyContent="flex-start",t.style.alignItems="flex-start",this.classNames.container&&(t.className=this.classNames.container),t.appendChild(this.wrapper),t}createWrapper(){const t=document.createElement("div");return t.style.position="relative",t.style.display="block",t.dataset.resizeWrapper="",this.classNames.wrapper&&(t.className=this.classNames.wrapper),t.appendChild(this.element),t}createHandle(t){const e=document.createElement("div");return e.dataset.resizeHandle=t,e.style.position="absolute",this.classNames.handle&&(e.className=this.classNames.handle),e}positionHandle(t,e){const n=e.includes("top"),r=e.includes("bottom"),i=e.includes("left"),s=e.includes("right");n&&(t.style.top="0"),r&&(t.style.bottom="0"),i&&(t.style.left="0"),s&&(t.style.right="0"),(e==="top"||e==="bottom")&&(t.style.left="0",t.style.right="0"),(e==="left"||e==="right")&&(t.style.top="0",t.style.bottom="0")}attachHandles(){this.directions.forEach(t=>{const e=this.createHandle(t);this.positionHandle(e,t),e.addEventListener("mousedown",n=>this.handleResizeStart(n,t)),e.addEventListener("touchstart",n=>this.handleResizeStart(n,t)),this.wrapper.appendChild(e)})}applyInitialSize(){const t=this.node.attrs.width,e=this.node.attrs.height;t?(this.element.style.width=`${t}px`,this.initialWidth=t):this.initialWidth=this.element.offsetWidth,e?(this.element.style.height=`${e}px`,this.initialHeight=e):this.initialHeight=this.element.offsetHeight,this.initialWidth>0&&this.initialHeight>0&&(this.aspectRatio=this.initialWidth/this.initialHeight)}handleResizeStart(t,e){t.preventDefault(),t.stopPropagation(),this.isResizing=!0,this.activeHandle=e,ZGe(t)?(this.startX=t.touches[0].clientX,this.startY=t.touches[0].clientY):(this.startX=t.clientX,this.startY=t.clientY),this.startWidth=this.element.offsetWidth,this.startHeight=this.element.offsetHeight,this.startWidth>0&&this.startHeight>0&&(this.aspectRatio=this.startWidth/this.startHeight),this.getPos(),this.container.dataset.resizeState="true",this.classNames.resizing&&this.container.classList.add(this.classNames.resizing),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("touchmove",this.handleTouchMove),document.addEventListener("mouseup",this.handleMouseUp),document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}handleResize(t,e){if(!this.activeHandle)return;const n=this.preserveAspectRatio||this.isShiftKeyPressed,{width:r,height:i}=this.calculateNewDimensions(this.activeHandle,t,e),s=this.applyConstraints(r,i,n);this.element.style.width=`${s.width}px`,this.element.style.height=`${s.height}px`,this.onResize&&this.onResize(s.width,s.height)}calculateNewDimensions(t,e,n){let r=this.startWidth,i=this.startHeight;const s=t.includes("right"),o=t.includes("left"),l=t.includes("bottom"),c=t.includes("top");return s?r=this.startWidth+e:o&&(r=this.startWidth-e),l?i=this.startHeight+n:c&&(i=this.startHeight-n),(t==="right"||t==="left")&&(r=this.startWidth+(s?e:-e)),(t==="top"||t==="bottom")&&(i=this.startHeight+(l?n:-n)),this.preserveAspectRatio||this.isShiftKeyPressed?this.applyAspectRatio(r,i,t):{width:r,height:i}}applyConstraints(t,e,n){var r,i,s,o;if(!n){let u=Math.max(this.minSize.width,t),d=Math.max(this.minSize.height,e);return(r=this.maxSize)!=null&&r.width&&(u=Math.min(this.maxSize.width,u)),(i=this.maxSize)!=null&&i.height&&(d=Math.min(this.maxSize.height,d)),{width:u,height:d}}let l=t,c=e;return lthis.maxSize.width&&(l=this.maxSize.width,c=l/this.aspectRatio),(o=this.maxSize)!=null&&o.height&&c>this.maxSize.height&&(c=this.maxSize.height,l=c*this.aspectRatio),{width:l,height:c}}applyAspectRatio(t,e,n){const r=n==="left"||n==="right",i=n==="top"||n==="bottom";return r?{width:t,height:t/this.aspectRatio}:i?{width:e*this.aspectRatio,height:e}:{width:t,height:t/this.aspectRatio}}};function eqe(t,e){const{selection:n}=t,{$from:r}=n;if(n instanceof rn){const s=r.index();return r.parent.canReplaceWith(s,s+1,e)}let i=r.depth;for(;i>=0;){const s=r.index(i);if(r.node(i).contentMatchAt(s).matchType(e))return!0;i-=1}return!1}var tqe={};Y4(tqe,{createAtomBlockMarkdownSpec:()=>nqe,createBlockMarkdownSpec:()=>rqe,createInlineMarkdownSpec:()=>sqe,parseAttributes:()=>aF,parseIndentedBlocks:()=>aR,renderNestedMarkdownContent:()=>oF,serializeAttributes:()=>sF});function aF(t){if(!t?.trim())return{};const e={},n=[],r=t.replace(/["']([^"']*)["']/g,u=>(n.push(u),`__QUOTED_${n.length-1}__`)),i=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(i){const u=i.map(d=>d.trim().slice(1));e.class=u.join(" ")}const s=r.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);s&&(e.id=s[1]);const o=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(r.matchAll(o)).forEach(([,u,d])=>{var h;const p=parseInt(((h=d.match(/__QUOTED_(\d+)__/))==null?void 0:h[1])||"0",10),m=n[p];m&&(e[u]=m.slice(1,-1))});const c=r.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return c&&c.split(/\s+/).filter(Boolean).forEach(d=>{d.match(/^[a-zA-Z][\w-]*$/)&&(e[d]=!0)}),e}function sF(t){if(!t||Object.keys(t).length===0)return"";const e=[];return t.class&&String(t.class).split(/\s+/).filter(Boolean).forEach(r=>e.push(`.${r}`)),t.id&&e.push(`#${t.id}`),Object.entries(t).forEach(([n,r])=>{n==="class"||n==="id"||(r===!0?e.push(n):r!==!1&&r!=null&&e.push(`${n}="${String(r)}"`))}),e.join(" ")}function nqe(t){const{nodeName:e,name:n,parseAttributes:r=aF,serializeAttributes:i=sF,defaultAttributes:s={},requiredAttributes:o=[],allowedAttributes:l}=t,c=n||e,u=d=>{if(!l)return d;const h={};return l.forEach(p=>{p in d&&(h[p]=d[p])}),h};return{parseMarkdown:(d,h)=>{const p={...s,...d.attributes};return h.createNode(e,p,[])},markdownTokenizer:{name:e,level:"block",start(d){var h;const p=new RegExp(`^:::${c}(?:\\s|$)`,"m"),m=(h=d.match(p))==null?void 0:h.index;return m!==void 0?m:-1},tokenize(d,h,p){const m=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),b=d.match(m);if(!b)return;const y=b[1]||"",x=r(y);if(!o.find(S=>!(S in x)))return{type:e,raw:b[0],attributes:x}}},renderMarkdown:d=>{const h=u(d.attrs||{}),p=i(h),m=p?` {${p}}`:"";return`:::${c}${m} :::`}}}function rqe(t){const{nodeName:e,name:n,getContent:r,parseAttributes:i=aF,serializeAttributes:s=sF,defaultAttributes:o={},content:l="block",allowedAttributes:c}=t,u=n||e,d=h=>{if(!c)return h;const p={};return c.forEach(m=>{m in h&&(p[m]=h[m])}),p};return{parseMarkdown:(h,p)=>{let m;if(r){const y=r(h);m=typeof y=="string"?[{type:"text",text:y}]:y}else l==="block"?m=p.parseChildren(h.tokens||[]):m=p.parseInline(h.tokens||[]);const b={...o,...h.attributes};return p.createNode(e,b,m)},markdownTokenizer:{name:e,level:"block",start(h){var p;const m=new RegExp(`^:::${u}`,"m"),b=(p=h.match(m))==null?void 0:p.index;return b!==void 0?b:-1},tokenize(h,p,m){var b;const y=new RegExp(`^:::${u}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),x=h.match(y);if(!x)return;const[v,S=""]=x,N=i(S);let T=1;const M=v.length;let A="";const k=/^:::([\w-]*)(\s.*)?/gm,R=h.slice(M);for(k.lastIndex=0;;){const C=k.exec(R);if(C===null)break;const P=C.index,U=C[1];if(!((b=C[2])!=null&&b.endsWith(":::"))){if(U)T+=1;else if(T-=1,T===0){const F=R.slice(0,P);A=F.trim();const H=h.slice(0,M+P+C[0].length);let D=[];if(A)if(l==="block")for(D=m.blockTokens(F),D.forEach($=>{$.text&&(!$.tokens||$.tokens.length===0)&&($.tokens=m.inlineTokens($.text))});D.length>0;){const $=D[D.length-1];if($.type==="paragraph"&&(!$.text||$.text.trim()===""))D.pop();else break}else D=m.inlineTokens(A);return{type:e,raw:H,attributes:N,content:A,tokens:D}}}}}},renderMarkdown:(h,p)=>{const m=d(h.attrs||{}),b=s(m),y=b?` {${b}}`:"",x=p.renderChildren(h.content||[],` +`,textSerializers:n={}}=t||{};return lGe(this.state.doc,{blockSeparator:e,textSerializers:{...Cne(this.schema),...n}})}get isEmpty(){return VM(this.state.doc)}destroy(){this.emit("destroy"),this.unmount(),this.removeAllListeners()}get isDestroyed(){var t,e;return(e=(t=this.editorView)==null?void 0:t.isDestroyed)!=null?e:!0}$node(t,e){var n;return((n=this.$doc)==null?void 0:n.querySelector(t,e))||null}$nodes(t,e){var n;return((n=this.$doc)==null?void 0:n.querySelectorAll(t,e))||null}$pos(t){const e=this.state.doc.resolve(t);return new XGe(e,this)}get $doc(){return this.$pos(0)}};function gb(t){return new GM({find:t.find,handler:({state:e,range:n,match:r})=>{const i=xr(t.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const c=l.search(/\S/),u=n.from+l.indexOf(o),d=u+o.length;if(rF(n.from,n.to,e.doc).filter(m=>m.mark.type.excluded.find(y=>y===t.type&&y!==m.mark.type)).filter(m=>m.to>u).length)return null;dn.from&&s.delete(n.from+c,u);const p=n.from+c+o.length;s.addMark(n.from+c,p,t.type.create(i||{})),s.removeStoredMark(t.type)}},undoable:t.undoable})}function Kne(t){return new GM({find:t.find,handler:({state:e,range:n,match:r})=>{const i=xr(t.getAttributes,void 0,r)||{},{tr:s}=e,o=n.from;let l=n.to;const c=t.type.create(i);if(r[1]){const u=r[0].lastIndexOf(r[1]);let d=o+u;d>l?d=l:l=d+r[1].length;const h=r[0][r[0].length-1];s.insertText(h,o+r[0].length-1),s.replaceWith(d,l,c)}else if(r[0]){const u=t.type.isInline?o:o-1;s.insert(u,t.type.create(i)).delete(s.mapping.map(o),s.mapping.map(l))}s.scrollIntoView()},undoable:t.undoable})}function iR(t){return new GM({find:t.find,handler:({state:e,range:n,match:r})=>{const i=e.doc.resolve(n.from),s=xr(t.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),t.type))return null;e.tr.delete(n.from,n.to).setBlockType(n.from,n.from,t.type,s)},undoable:t.undoable})}function bb(t){return new GM({find:t.find,handler:({state:e,range:n,match:r,chain:i})=>{const s=xr(t.getAttributes,void 0,r)||{},o=e.tr.delete(n.from,n.to),c=o.doc.resolve(n.from).blockRange(),u=c&&R4(c,t.type,s);if(!u)return null;if(o.wrap(c,u),t.keepMarks&&t.editor){const{selection:h,storedMarks:p}=e,{splittableMarks:m}=t.editor.extensionManager,b=p||h.$to.parentOffset&&h.$from.marks();if(b){const y=b.filter(x=>m.includes(x.type.name));o.ensureMarks(y)}}if(t.keepAttributes){const h=t.type.name==="bulletList"||t.type.name==="orderedList"?"listItem":"taskList";i().updateAttributes(h,s).run()}const d=o.doc.resolve(n.from-1).nodeBefore;d&&d.type===t.type&&qh(o.doc,n.from-1)&&(!t.joinPredicate||t.joinPredicate(r,d))&&o.join(n.from-1)},undoable:t.undoable})}var JGe=t=>"touches"in t,eqe=class{constructor(t){this.directions=["bottom-left","bottom-right","top-left","top-right"],this.minSize={height:8,width:8},this.preserveAspectRatio=!1,this.classNames={container:"",wrapper:"",handle:"",resizing:""},this.initialWidth=0,this.initialHeight=0,this.aspectRatio=1,this.isResizing=!1,this.activeHandle=null,this.startX=0,this.startY=0,this.startWidth=0,this.startHeight=0,this.isShiftKeyPressed=!1,this.handleMouseMove=o=>{if(!this.isResizing||!this.activeHandle)return;const l=o.clientX-this.startX,c=o.clientY-this.startY;this.handleResize(l,c)},this.handleTouchMove=o=>{if(!this.isResizing||!this.activeHandle)return;const l=o.touches[0];if(!l)return;const c=l.clientX-this.startX,u=l.clientY-this.startY;this.handleResize(c,u)},this.handleMouseUp=()=>{if(!this.isResizing)return;const o=this.element.offsetWidth,l=this.element.offsetHeight;this.onCommit(o,l),this.isResizing=!1,this.activeHandle=null,this.container.dataset.resizeState="false",this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)},this.handleKeyDown=o=>{o.key==="Shift"&&(this.isShiftKeyPressed=!0)},this.handleKeyUp=o=>{o.key==="Shift"&&(this.isShiftKeyPressed=!1)};var e,n,r,i,s;this.node=t.node,this.element=t.element,this.contentElement=t.contentElement,this.getPos=t.getPos,this.onResize=t.onResize,this.onCommit=t.onCommit,this.onUpdate=t.onUpdate,(e=t.options)!=null&&e.min&&(this.minSize={...this.minSize,...t.options.min}),(n=t.options)!=null&&n.max&&(this.maxSize=t.options.max),(r=t?.options)!=null&&r.directions&&(this.directions=t.options.directions),(i=t.options)!=null&&i.preserveAspectRatio&&(this.preserveAspectRatio=t.options.preserveAspectRatio),(s=t.options)!=null&&s.className&&(this.classNames={container:t.options.className.container||"",wrapper:t.options.className.wrapper||"",handle:t.options.className.handle||"",resizing:t.options.className.resizing||""}),this.wrapper=this.createWrapper(),this.container=this.createContainer(),this.applyInitialSize(),this.attachHandles()}get dom(){return this.container}get contentDOM(){return this.contentElement}update(t,e,n){return t.type!==this.node.type?!1:(this.node=t,this.onUpdate?this.onUpdate(t,e,n):!0)}destroy(){this.isResizing&&(this.container.dataset.resizeState="false",this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp),this.isResizing=!1,this.activeHandle=null),this.container.remove()}createContainer(){const t=document.createElement("div");return t.dataset.resizeContainer="",t.dataset.node=this.node.type.name,t.style.display="flex",t.style.justifyContent="flex-start",t.style.alignItems="flex-start",this.classNames.container&&(t.className=this.classNames.container),t.appendChild(this.wrapper),t}createWrapper(){const t=document.createElement("div");return t.style.position="relative",t.style.display="block",t.dataset.resizeWrapper="",this.classNames.wrapper&&(t.className=this.classNames.wrapper),t.appendChild(this.element),t}createHandle(t){const e=document.createElement("div");return e.dataset.resizeHandle=t,e.style.position="absolute",this.classNames.handle&&(e.className=this.classNames.handle),e}positionHandle(t,e){const n=e.includes("top"),r=e.includes("bottom"),i=e.includes("left"),s=e.includes("right");n&&(t.style.top="0"),r&&(t.style.bottom="0"),i&&(t.style.left="0"),s&&(t.style.right="0"),(e==="top"||e==="bottom")&&(t.style.left="0",t.style.right="0"),(e==="left"||e==="right")&&(t.style.top="0",t.style.bottom="0")}attachHandles(){this.directions.forEach(t=>{const e=this.createHandle(t);this.positionHandle(e,t),e.addEventListener("mousedown",n=>this.handleResizeStart(n,t)),e.addEventListener("touchstart",n=>this.handleResizeStart(n,t)),this.wrapper.appendChild(e)})}applyInitialSize(){const t=this.node.attrs.width,e=this.node.attrs.height;t?(this.element.style.width=`${t}px`,this.initialWidth=t):this.initialWidth=this.element.offsetWidth,e?(this.element.style.height=`${e}px`,this.initialHeight=e):this.initialHeight=this.element.offsetHeight,this.initialWidth>0&&this.initialHeight>0&&(this.aspectRatio=this.initialWidth/this.initialHeight)}handleResizeStart(t,e){t.preventDefault(),t.stopPropagation(),this.isResizing=!0,this.activeHandle=e,JGe(t)?(this.startX=t.touches[0].clientX,this.startY=t.touches[0].clientY):(this.startX=t.clientX,this.startY=t.clientY),this.startWidth=this.element.offsetWidth,this.startHeight=this.element.offsetHeight,this.startWidth>0&&this.startHeight>0&&(this.aspectRatio=this.startWidth/this.startHeight),this.getPos(),this.container.dataset.resizeState="true",this.classNames.resizing&&this.container.classList.add(this.classNames.resizing),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("touchmove",this.handleTouchMove),document.addEventListener("mouseup",this.handleMouseUp),document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}handleResize(t,e){if(!this.activeHandle)return;const n=this.preserveAspectRatio||this.isShiftKeyPressed,{width:r,height:i}=this.calculateNewDimensions(this.activeHandle,t,e),s=this.applyConstraints(r,i,n);this.element.style.width=`${s.width}px`,this.element.style.height=`${s.height}px`,this.onResize&&this.onResize(s.width,s.height)}calculateNewDimensions(t,e,n){let r=this.startWidth,i=this.startHeight;const s=t.includes("right"),o=t.includes("left"),l=t.includes("bottom"),c=t.includes("top");return s?r=this.startWidth+e:o&&(r=this.startWidth-e),l?i=this.startHeight+n:c&&(i=this.startHeight-n),(t==="right"||t==="left")&&(r=this.startWidth+(s?e:-e)),(t==="top"||t==="bottom")&&(i=this.startHeight+(l?n:-n)),this.preserveAspectRatio||this.isShiftKeyPressed?this.applyAspectRatio(r,i,t):{width:r,height:i}}applyConstraints(t,e,n){var r,i,s,o;if(!n){let u=Math.max(this.minSize.width,t),d=Math.max(this.minSize.height,e);return(r=this.maxSize)!=null&&r.width&&(u=Math.min(this.maxSize.width,u)),(i=this.maxSize)!=null&&i.height&&(d=Math.min(this.maxSize.height,d)),{width:u,height:d}}let l=t,c=e;return lthis.maxSize.width&&(l=this.maxSize.width,c=l/this.aspectRatio),(o=this.maxSize)!=null&&o.height&&c>this.maxSize.height&&(c=this.maxSize.height,l=c*this.aspectRatio),{width:l,height:c}}applyAspectRatio(t,e,n){const r=n==="left"||n==="right",i=n==="top"||n==="bottom";return r?{width:t,height:t/this.aspectRatio}:i?{width:e*this.aspectRatio,height:e}:{width:t,height:t/this.aspectRatio}}};function tqe(t,e){const{selection:n}=t,{$from:r}=n;if(n instanceof rn){const s=r.index();return r.parent.canReplaceWith(s,s+1,e)}let i=r.depth;for(;i>=0;){const s=r.index(i);if(r.node(i).contentMatchAt(s).matchType(e))return!0;i-=1}return!1}var nqe={};Y4(nqe,{createAtomBlockMarkdownSpec:()=>rqe,createBlockMarkdownSpec:()=>iqe,createInlineMarkdownSpec:()=>oqe,parseAttributes:()=>aF,parseIndentedBlocks:()=>aR,renderNestedMarkdownContent:()=>oF,serializeAttributes:()=>sF});function aF(t){if(!t?.trim())return{};const e={},n=[],r=t.replace(/["']([^"']*)["']/g,u=>(n.push(u),`__QUOTED_${n.length-1}__`)),i=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(i){const u=i.map(d=>d.trim().slice(1));e.class=u.join(" ")}const s=r.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);s&&(e.id=s[1]);const o=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(r.matchAll(o)).forEach(([,u,d])=>{var h;const p=parseInt(((h=d.match(/__QUOTED_(\d+)__/))==null?void 0:h[1])||"0",10),m=n[p];m&&(e[u]=m.slice(1,-1))});const c=r.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return c&&c.split(/\s+/).filter(Boolean).forEach(d=>{d.match(/^[a-zA-Z][\w-]*$/)&&(e[d]=!0)}),e}function sF(t){if(!t||Object.keys(t).length===0)return"";const e=[];return t.class&&String(t.class).split(/\s+/).filter(Boolean).forEach(r=>e.push(`.${r}`)),t.id&&e.push(`#${t.id}`),Object.entries(t).forEach(([n,r])=>{n==="class"||n==="id"||(r===!0?e.push(n):r!==!1&&r!=null&&e.push(`${n}="${String(r)}"`))}),e.join(" ")}function rqe(t){const{nodeName:e,name:n,parseAttributes:r=aF,serializeAttributes:i=sF,defaultAttributes:s={},requiredAttributes:o=[],allowedAttributes:l}=t,c=n||e,u=d=>{if(!l)return d;const h={};return l.forEach(p=>{p in d&&(h[p]=d[p])}),h};return{parseMarkdown:(d,h)=>{const p={...s,...d.attributes};return h.createNode(e,p,[])},markdownTokenizer:{name:e,level:"block",start(d){var h;const p=new RegExp(`^:::${c}(?:\\s|$)`,"m"),m=(h=d.match(p))==null?void 0:h.index;return m!==void 0?m:-1},tokenize(d,h,p){const m=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),b=d.match(m);if(!b)return;const y=b[1]||"",x=r(y);if(!o.find(S=>!(S in x)))return{type:e,raw:b[0],attributes:x}}},renderMarkdown:d=>{const h=u(d.attrs||{}),p=i(h),m=p?` {${p}}`:"";return`:::${c}${m} :::`}}}function iqe(t){const{nodeName:e,name:n,getContent:r,parseAttributes:i=aF,serializeAttributes:s=sF,defaultAttributes:o={},content:l="block",allowedAttributes:c}=t,u=n||e,d=h=>{if(!c)return h;const p={};return c.forEach(m=>{m in h&&(p[m]=h[m])}),p};return{parseMarkdown:(h,p)=>{let m;if(r){const y=r(h);m=typeof y=="string"?[{type:"text",text:y}]:y}else l==="block"?m=p.parseChildren(h.tokens||[]):m=p.parseInline(h.tokens||[]);const b={...o,...h.attributes};return p.createNode(e,b,m)},markdownTokenizer:{name:e,level:"block",start(h){var p;const m=new RegExp(`^:::${u}`,"m"),b=(p=h.match(m))==null?void 0:p.index;return b!==void 0?b:-1},tokenize(h,p,m){var b;const y=new RegExp(`^:::${u}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),x=h.match(y);if(!x)return;const[v,S=""]=x,N=i(S);let T=1;const M=v.length;let A="";const k=/^:::([\w-]*)(\s.*)?/gm,R=h.slice(M);for(k.lastIndex=0;;){const C=k.exec(R);if(C===null)break;const P=C.index,U=C[1];if(!((b=C[2])!=null&&b.endsWith(":::"))){if(U)T+=1;else if(T-=1,T===0){const F=R.slice(0,P);A=F.trim();const H=h.slice(0,M+P+C[0].length);let D=[];if(A)if(l==="block")for(D=m.blockTokens(F),D.forEach($=>{$.text&&(!$.tokens||$.tokens.length===0)&&($.tokens=m.inlineTokens($.text))});D.length>0;){const $=D[D.length-1];if($.type==="paragraph"&&(!$.text||$.text.trim()===""))D.pop();else break}else D=m.inlineTokens(A);return{type:e,raw:H,attributes:N,content:A,tokens:D}}}}}},renderMarkdown:(h,p)=>{const m=d(h.attrs||{}),b=s(m),y=b?` {${b}}`:"",x=p.renderChildren(h.content||[],` `);return`:::${u}${y} ${x} -:::`}}}function iqe(t){if(!t.trim())return{};const e={},n=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let r=n.exec(t);for(;r!==null;){const[,i,s,o]=r;e[i]=s||o,r=n.exec(t)}return e}function aqe(t){return Object.entries(t).filter(([,e])=>e!=null).map(([e,n])=>`${e}="${n}"`).join(" ")}function sqe(t){const{nodeName:e,name:n,getContent:r,parseAttributes:i=iqe,serializeAttributes:s=aqe,defaultAttributes:o={},selfClosing:l=!1,allowedAttributes:c}=t,u=n||e,d=p=>{if(!c)return p;const m={};return c.forEach(b=>{b in p&&(m[b]=p[b])}),m},h=u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(p,m)=>{const b={...o,...p.attributes};if(l)return m.createNode(e,b);const y=r?r(p):p.content||"";return y?m.createNode(e,b,[m.createTextNode(y)]):m.createNode(e,b,[])},markdownTokenizer:{name:e,level:"inline",start(p){const m=l?new RegExp(`\\[${h}\\s*[^\\]]*\\]`):new RegExp(`\\[${h}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${h}\\]`),b=p.match(m),y=b?.index;return y!==void 0?y:-1},tokenize(p,m,b){const y=l?new RegExp(`^\\[${h}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${h}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${h}\\]`),x=p.match(y);if(!x)return;let v="",S="";if(l){const[,T]=x;S=T}else{const[,T,M]=x;S=T,v=M||""}const N=i(S.trim());return{type:e,raw:x[0],content:v.trim(),attributes:N}}},renderMarkdown:p=>{let m="";r?m=r(p):p.content&&p.content.length>0&&(m=p.content.filter(v=>v.type==="text").map(v=>v.text).join(""));const b=d(p.attrs||{}),y=s(b),x=y?` ${y}`:"";return l?`[${u}${x}]`:`[${u}${x}]${m}[/${u}]`}}}function aR(t,e,n){var r,i,s,o;const l=t.split(` +:::`}}}function aqe(t){if(!t.trim())return{};const e={},n=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let r=n.exec(t);for(;r!==null;){const[,i,s,o]=r;e[i]=s||o,r=n.exec(t)}return e}function sqe(t){return Object.entries(t).filter(([,e])=>e!=null).map(([e,n])=>`${e}="${n}"`).join(" ")}function oqe(t){const{nodeName:e,name:n,getContent:r,parseAttributes:i=aqe,serializeAttributes:s=sqe,defaultAttributes:o={},selfClosing:l=!1,allowedAttributes:c}=t,u=n||e,d=p=>{if(!c)return p;const m={};return c.forEach(b=>{b in p&&(m[b]=p[b])}),m},h=u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(p,m)=>{const b={...o,...p.attributes};if(l)return m.createNode(e,b);const y=r?r(p):p.content||"";return y?m.createNode(e,b,[m.createTextNode(y)]):m.createNode(e,b,[])},markdownTokenizer:{name:e,level:"inline",start(p){const m=l?new RegExp(`\\[${h}\\s*[^\\]]*\\]`):new RegExp(`\\[${h}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${h}\\]`),b=p.match(m),y=b?.index;return y!==void 0?y:-1},tokenize(p,m,b){const y=l?new RegExp(`^\\[${h}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${h}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${h}\\]`),x=p.match(y);if(!x)return;let v="",S="";if(l){const[,T]=x;S=T}else{const[,T,M]=x;S=T,v=M||""}const N=i(S.trim());return{type:e,raw:x[0],content:v.trim(),attributes:N}}},renderMarkdown:p=>{let m="";r?m=r(p):p.content&&p.content.length>0&&(m=p.content.filter(v=>v.type==="text").map(v=>v.text).join(""));const b=d(p.attrs||{}),y=s(b),x=y?` ${y}`:"";return l?`[${u}${x}]`:`[${u}${x}]${m}[/${u}]`}}}function aR(t,e,n){var r,i,s,o;const l=t.split(` `),c=[];let u="",d=0;const h=e.baseIndentSize||2;for(;d0)break;if(p.trim()===""){d+=1,u=`${u}${p} `;continue}else return}const b=e.extractItemData(m),{indentLevel:y,mainContent:x}=b;u=`${u}${p} `;const v=[x];for(d+=1;dP.trim()!=="");if(k===-1)break;if((((i=(r=l[d+1+k].match(/^(\s*)/))==null?void 0:r[1])==null?void 0:i.length)||0)>y){v.push(M),u=`${u}${M} @@ -8607,11 +8607,11 @@ ${x} `);M.trim()&&(e.customNestedParser?S=e.customNestedParser(M):S=n.blockTokens(M))}const T=e.createToken(b,S);c.push(T)}if(c.length!==0)return{items:c,raw:u}}function oF(t,e,n,r){if(!t||!Array.isArray(t.content))return"";const i=typeof n=="function"?n(r):n,[s,...o]=t.content,l=e.renderChildren([s]),c=[`${i}${l}`];return o&&o.length>0&&o.forEach(u=>{const d=e.renderChildren([u]);if(d){const h=d.split(` `).map(p=>p?e.indent(p):"").join(` `);c.push(h)}}),c.join(` -`)}function oqe(t,e,n={}){const{state:r}=e,{doc:i,tr:s}=r,o=t;i.descendants((l,c)=>{const u=s.mapping.map(c),d=s.mapping.map(c)+l.nodeSize;let h=null;if(l.marks.forEach(m=>{if(m!==o)return!1;h=m}),!h)return;let p=!1;if(Object.keys(n).forEach(m=>{n[m]!==h.attrs[m]&&(p=!0)}),p){const m=t.type.create({...t.attrs,...n});s.removeMark(u,d,t.type),s.addMark(u,d,m)}}),s.docChanged&&e.view.dispatch(s)}var Zs=class Xne extends iF{constructor(){super(...arguments),this.type="node"}static create(e={}){const n=typeof e=="function"?e():e;return new Xne(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function Pm(t){return new HGe({find:t.find,handler:({state:e,range:n,match:r,pasteEvent:i})=>{const s=xr(t.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],c=r[0];let u=n.to;if(l){const d=c.search(/\S/),h=n.from+c.indexOf(l),p=h+l.length;if(rF(n.from,n.to,e.doc).filter(b=>b.mark.type.excluded.find(x=>x===t.type&&x!==b.mark.type)).filter(b=>b.to>h).length)return null;pn.from&&o.delete(n.from+d,h),u=n.from+d+l.length,o.addMark(n.from+d,u,t.type.create(s||{})),o.removeStoredMark(t.type)}}})}var zP,n9;function lqe(){return n9||(n9=1,zP=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,i,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!t(e[i],n[i]))return!1;return!0}if(e instanceof Map&&n instanceof Map){if(e.size!==n.size)return!1;for(i of e.entries())if(!n.has(i[0]))return!1;for(i of e.entries())if(!t(i[1],n.get(i[0])))return!1;return!0}if(e instanceof Set&&n instanceof Set){if(e.size!==n.size)return!1;for(i of e.entries())if(!n.has(i[0]))return!1;return!0}if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(n)){if(r=e.length,r!=n.length)return!1;for(i=r;i--!==0;)if(e[i]!==n[i])return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[i]))return!1;for(i=r;i--!==0;){var o=s[i];if(!(o==="_owner"&&e.$$typeof)&&!t(e[o],n[o]))return!1}return!0}return e!==e&&n!==n}),zP}var cqe=lqe();const uqe=gl(cqe);var dqe=(...t)=>e=>{t.forEach(n=>{typeof n=="function"?n(e):n&&(n.current=e)})},hqe=({contentComponent:t})=>{const e=MR.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getServerSnapshot);return a.jsx(a.Fragment,{children:Object.values(e)})};function fqe(){const t=new Set;let e={};return{subscribe(n){return t.add(n),()=>{t.delete(n)}},getSnapshot(){return e},getServerSnapshot(){return e},setRenderer(n,r){e={...e,[n]:Gle.createPortal(r.reactElement,r.element,n)},t.forEach(i=>i())},removeRenderer(n){const r={...e};delete r[n],e=r,t.forEach(i=>i())}}}var mqe=class extends ei.Component{constructor(t){var e;super(t),this.editorContentRef=ei.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!((e=t.editor)!=null&&e.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){const t=this.props.editor;if(t&&!t.isDestroyed&&t.options.element){if(t.contentComponent)return;const e=this.editorContentRef.current;e.append(t.view.dom),t.setOptions({element:e}),t.contentComponent=fqe(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=t.contentComponent.subscribe(()=>{this.setState(n=>n.hasContentComponentInitialized?n:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),t.createNodeViews(),this.initialized=!0}}componentWillUnmount(){var t;const e=this.props.editor;if(e){this.initialized=!1,e.isDestroyed||e.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),e.contentComponent=null;try{if(!((t=e.view.dom)!=null&&t.firstChild))return;const n=document.createElement("div");n.append(e.view.dom),e.setOptions({element:n})}catch{}}}render(){const{editor:t,innerRef:e,...n}=this.props;return a.jsxs(a.Fragment,{children:[a.jsx("div",{ref:dqe(e,this.editorContentRef),...n}),t?.contentComponent&&a.jsx(hqe,{contentComponent:t.contentComponent})]})}},pqe=_.forwardRef((t,e)=>{const n=ei.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[t.editor]);return ei.createElement(mqe,{key:n,innerRef:e,...t})}),gqe=ei.memo(pqe),bqe=typeof window<"u"?_.useLayoutEffect:_.useEffect,xqe=class{constructor(t){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=t,this.lastSnapshot={editor:t,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}watch(t){if(this.editor=t,this.editor){const e=()=>{this.transactionNumber+=1,this.subscribers.forEach(r=>r())},n=this.editor;return n.on("transaction",e),()=>{n.off("transaction",e)}}}};function yqe(t){var e;const[n]=_.useState(()=>new xqe(t.editor)),r=nY.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,t.selector,(e=t.equalityFn)!=null?e:uqe);return bqe(()=>n.watch(t.editor),[t.editor,n]),_.useDebugValue(r),r}var vqe=!1,sR=typeof window>"u",wqe=sR||!!(typeof window<"u"&&window.next),_qe=class Yne{constructor(e){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=e,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(e){this.editor=e,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(n=>n())}getInitialEditor(){return this.options.current.immediatelyRender===void 0?sR||wqe?null:this.createEditor():(this.options.current.immediatelyRender,this.options.current.immediatelyRender?this.createEditor():null)}createEditor(){const e={...this.options.current,onBeforeCreate:(...r)=>{var i,s;return(s=(i=this.options.current).onBeforeCreate)==null?void 0:s.call(i,...r)},onBlur:(...r)=>{var i,s;return(s=(i=this.options.current).onBlur)==null?void 0:s.call(i,...r)},onCreate:(...r)=>{var i,s;return(s=(i=this.options.current).onCreate)==null?void 0:s.call(i,...r)},onDestroy:(...r)=>{var i,s;return(s=(i=this.options.current).onDestroy)==null?void 0:s.call(i,...r)},onFocus:(...r)=>{var i,s;return(s=(i=this.options.current).onFocus)==null?void 0:s.call(i,...r)},onSelectionUpdate:(...r)=>{var i,s;return(s=(i=this.options.current).onSelectionUpdate)==null?void 0:s.call(i,...r)},onTransaction:(...r)=>{var i,s;return(s=(i=this.options.current).onTransaction)==null?void 0:s.call(i,...r)},onUpdate:(...r)=>{var i,s;return(s=(i=this.options.current).onUpdate)==null?void 0:s.call(i,...r)},onContentError:(...r)=>{var i,s;return(s=(i=this.options.current).onContentError)==null?void 0:s.call(i,...r)},onDrop:(...r)=>{var i,s;return(s=(i=this.options.current).onDrop)==null?void 0:s.call(i,...r)},onPaste:(...r)=>{var i,s;return(s=(i=this.options.current).onPaste)==null?void 0:s.call(i,...r)},onDelete:(...r)=>{var i,s;return(s=(i=this.options.current).onDelete)==null?void 0:s.call(i,...r)}};return new QGe(e)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(e){return this.subscriptions.add(e),()=>{this.subscriptions.delete(e)}}static compareOptions(e,n){return Object.keys(e).every(r=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(r)?!0:r==="extensions"&&e.extensions&&n.extensions?e.extensions.length!==n.extensions.length?!1:e.extensions.every((i,s)=>{var o;return i===((o=n.extensions)==null?void 0:o[s])}):e[r]===n[r])}onRender(e){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&e.length===0?Yne.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(e),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(e){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=e;return}if(this.previousDeps.length===e.length&&this.previousDeps.every((r,i)=>r===e[i]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=e}scheduleDestroy(){const e=this.instanceId,n=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===e){n&&n.setOptions(this.options.current);return}n&&!n.isDestroyed&&(n.destroy(),this.instanceId===e&&this.setEditor(null))},1)}};function Sqe(t={},e=[]){const n=_.useRef(t);n.current=t;const[r]=_.useState(()=>new _qe(n)),i=MR.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return _.useDebugValue(i),_.useEffect(r.onRender(e)),yqe({editor:i,selector:({transactionNumber:s})=>t.shouldRerenderOnTransaction===!1||t.shouldRerenderOnTransaction===void 0?null:t.immediatelyRender&&s===0?0:s+1}),i}var Nqe=_.createContext({editor:null});Nqe.Consumer;var kqe=_.createContext({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),Mqe=()=>_.useContext(kqe);ei.forwardRef((t,e)=>{const{onDragStart:n}=Mqe(),r=t.as||"div";return a.jsx(r,{...t,ref:e,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...t.style}})});ei.createContext({markViewContentRef:()=>{}});var TN=(t,e)=>{if(t==="slot")return 0;if(t instanceof Function)return t(e);const{children:n,...r}=e??{};if(t==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[t,r,n]},Eqe=/^\s*>\s$/,Tqe=Zs.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:t}){return TN("blockquote",{..._i(this.options.HTMLAttributes,t),children:TN("slot",{})})},parseMarkdown:(t,e)=>e.createNode("blockquote",void 0,e.parseChildren(t.tokens||[])),renderMarkdown:(t,e)=>{if(!t.content)return"";const n=">",r=[];return t.content.forEach(i=>{const l=e.renderChildren([i]).split(` +`)}function lqe(t,e,n={}){const{state:r}=e,{doc:i,tr:s}=r,o=t;i.descendants((l,c)=>{const u=s.mapping.map(c),d=s.mapping.map(c)+l.nodeSize;let h=null;if(l.marks.forEach(m=>{if(m!==o)return!1;h=m}),!h)return;let p=!1;if(Object.keys(n).forEach(m=>{n[m]!==h.attrs[m]&&(p=!0)}),p){const m=t.type.create({...t.attrs,...n});s.removeMark(u,d,t.type),s.addMark(u,d,m)}}),s.docChanged&&e.view.dispatch(s)}var Zs=class Xne extends iF{constructor(){super(...arguments),this.type="node"}static create(e={}){const n=typeof e=="function"?e():e;return new Xne(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function Pm(t){return new $Ge({find:t.find,handler:({state:e,range:n,match:r,pasteEvent:i})=>{const s=xr(t.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],c=r[0];let u=n.to;if(l){const d=c.search(/\S/),h=n.from+c.indexOf(l),p=h+l.length;if(rF(n.from,n.to,e.doc).filter(b=>b.mark.type.excluded.find(x=>x===t.type&&x!==b.mark.type)).filter(b=>b.to>h).length)return null;pn.from&&o.delete(n.from+d,h),u=n.from+d+l.length,o.addMark(n.from+d,u,t.type.create(s||{})),o.removeStoredMark(t.type)}}})}var zP,n9;function cqe(){return n9||(n9=1,zP=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,i,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!t(e[i],n[i]))return!1;return!0}if(e instanceof Map&&n instanceof Map){if(e.size!==n.size)return!1;for(i of e.entries())if(!n.has(i[0]))return!1;for(i of e.entries())if(!t(i[1],n.get(i[0])))return!1;return!0}if(e instanceof Set&&n instanceof Set){if(e.size!==n.size)return!1;for(i of e.entries())if(!n.has(i[0]))return!1;return!0}if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(n)){if(r=e.length,r!=n.length)return!1;for(i=r;i--!==0;)if(e[i]!==n[i])return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[i]))return!1;for(i=r;i--!==0;){var o=s[i];if(!(o==="_owner"&&e.$$typeof)&&!t(e[o],n[o]))return!1}return!0}return e!==e&&n!==n}),zP}var uqe=cqe();const dqe=gl(uqe);var hqe=(...t)=>e=>{t.forEach(n=>{typeof n=="function"?n(e):n&&(n.current=e)})},fqe=({contentComponent:t})=>{const e=MR.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getServerSnapshot);return a.jsx(a.Fragment,{children:Object.values(e)})};function mqe(){const t=new Set;let e={};return{subscribe(n){return t.add(n),()=>{t.delete(n)}},getSnapshot(){return e},getServerSnapshot(){return e},setRenderer(n,r){e={...e,[n]:Gle.createPortal(r.reactElement,r.element,n)},t.forEach(i=>i())},removeRenderer(n){const r={...e};delete r[n],e=r,t.forEach(i=>i())}}}var pqe=class extends ei.Component{constructor(t){var e;super(t),this.editorContentRef=ei.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!((e=t.editor)!=null&&e.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){const t=this.props.editor;if(t&&!t.isDestroyed&&t.options.element){if(t.contentComponent)return;const e=this.editorContentRef.current;e.append(t.view.dom),t.setOptions({element:e}),t.contentComponent=mqe(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=t.contentComponent.subscribe(()=>{this.setState(n=>n.hasContentComponentInitialized?n:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),t.createNodeViews(),this.initialized=!0}}componentWillUnmount(){var t;const e=this.props.editor;if(e){this.initialized=!1,e.isDestroyed||e.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),e.contentComponent=null;try{if(!((t=e.view.dom)!=null&&t.firstChild))return;const n=document.createElement("div");n.append(e.view.dom),e.setOptions({element:n})}catch{}}}render(){const{editor:t,innerRef:e,...n}=this.props;return a.jsxs(a.Fragment,{children:[a.jsx("div",{ref:hqe(e,this.editorContentRef),...n}),t?.contentComponent&&a.jsx(fqe,{contentComponent:t.contentComponent})]})}},gqe=_.forwardRef((t,e)=>{const n=ei.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[t.editor]);return ei.createElement(pqe,{key:n,innerRef:e,...t})}),bqe=ei.memo(gqe),xqe=typeof window<"u"?_.useLayoutEffect:_.useEffect,yqe=class{constructor(t){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=t,this.lastSnapshot={editor:t,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}watch(t){if(this.editor=t,this.editor){const e=()=>{this.transactionNumber+=1,this.subscribers.forEach(r=>r())},n=this.editor;return n.on("transaction",e),()=>{n.off("transaction",e)}}}};function vqe(t){var e;const[n]=_.useState(()=>new yqe(t.editor)),r=nY.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,t.selector,(e=t.equalityFn)!=null?e:dqe);return xqe(()=>n.watch(t.editor),[t.editor,n]),_.useDebugValue(r),r}var wqe=!1,sR=typeof window>"u",_qe=sR||!!(typeof window<"u"&&window.next),Sqe=class Yne{constructor(e){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=e,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(e){this.editor=e,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(n=>n())}getInitialEditor(){return this.options.current.immediatelyRender===void 0?sR||_qe?null:this.createEditor():(this.options.current.immediatelyRender,this.options.current.immediatelyRender?this.createEditor():null)}createEditor(){const e={...this.options.current,onBeforeCreate:(...r)=>{var i,s;return(s=(i=this.options.current).onBeforeCreate)==null?void 0:s.call(i,...r)},onBlur:(...r)=>{var i,s;return(s=(i=this.options.current).onBlur)==null?void 0:s.call(i,...r)},onCreate:(...r)=>{var i,s;return(s=(i=this.options.current).onCreate)==null?void 0:s.call(i,...r)},onDestroy:(...r)=>{var i,s;return(s=(i=this.options.current).onDestroy)==null?void 0:s.call(i,...r)},onFocus:(...r)=>{var i,s;return(s=(i=this.options.current).onFocus)==null?void 0:s.call(i,...r)},onSelectionUpdate:(...r)=>{var i,s;return(s=(i=this.options.current).onSelectionUpdate)==null?void 0:s.call(i,...r)},onTransaction:(...r)=>{var i,s;return(s=(i=this.options.current).onTransaction)==null?void 0:s.call(i,...r)},onUpdate:(...r)=>{var i,s;return(s=(i=this.options.current).onUpdate)==null?void 0:s.call(i,...r)},onContentError:(...r)=>{var i,s;return(s=(i=this.options.current).onContentError)==null?void 0:s.call(i,...r)},onDrop:(...r)=>{var i,s;return(s=(i=this.options.current).onDrop)==null?void 0:s.call(i,...r)},onPaste:(...r)=>{var i,s;return(s=(i=this.options.current).onPaste)==null?void 0:s.call(i,...r)},onDelete:(...r)=>{var i,s;return(s=(i=this.options.current).onDelete)==null?void 0:s.call(i,...r)}};return new ZGe(e)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(e){return this.subscriptions.add(e),()=>{this.subscriptions.delete(e)}}static compareOptions(e,n){return Object.keys(e).every(r=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(r)?!0:r==="extensions"&&e.extensions&&n.extensions?e.extensions.length!==n.extensions.length?!1:e.extensions.every((i,s)=>{var o;return i===((o=n.extensions)==null?void 0:o[s])}):e[r]===n[r])}onRender(e){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&e.length===0?Yne.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(e),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(e){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=e;return}if(this.previousDeps.length===e.length&&this.previousDeps.every((r,i)=>r===e[i]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=e}scheduleDestroy(){const e=this.instanceId,n=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===e){n&&n.setOptions(this.options.current);return}n&&!n.isDestroyed&&(n.destroy(),this.instanceId===e&&this.setEditor(null))},1)}};function Nqe(t={},e=[]){const n=_.useRef(t);n.current=t;const[r]=_.useState(()=>new Sqe(n)),i=MR.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return _.useDebugValue(i),_.useEffect(r.onRender(e)),vqe({editor:i,selector:({transactionNumber:s})=>t.shouldRerenderOnTransaction===!1||t.shouldRerenderOnTransaction===void 0?null:t.immediatelyRender&&s===0?0:s+1}),i}var kqe=_.createContext({editor:null});kqe.Consumer;var Mqe=_.createContext({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),Eqe=()=>_.useContext(Mqe);ei.forwardRef((t,e)=>{const{onDragStart:n}=Eqe(),r=t.as||"div";return a.jsx(r,{...t,ref:e,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...t.style}})});ei.createContext({markViewContentRef:()=>{}});var TN=(t,e)=>{if(t==="slot")return 0;if(t instanceof Function)return t(e);const{children:n,...r}=e??{};if(t==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[t,r,n]},Tqe=/^\s*>\s$/,Aqe=Zs.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:t}){return TN("blockquote",{..._i(this.options.HTMLAttributes,t),children:TN("slot",{})})},parseMarkdown:(t,e)=>e.createNode("blockquote",void 0,e.parseChildren(t.tokens||[])),renderMarkdown:(t,e)=>{if(!t.content)return"";const n=">",r=[];return t.content.forEach(i=>{const l=e.renderChildren([i]).split(` `).map(c=>c.trim()===""?n:`${n} ${c}`);r.push(l.join(` `))}),r.join(` ${n} -`)},addCommands(){return{setBlockquote:()=>({commands:t})=>t.wrapIn(this.name),toggleBlockquote:()=>({commands:t})=>t.toggleWrap(this.name),unsetBlockquote:()=>({commands:t})=>t.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote()}},addInputRules(){return[bb({find:Eqe,type:this.type})]}}),Aqe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,Cqe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,Pqe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,jqe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,Dqe=Kh.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:t=>t.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:t=>t.type.name===this.name},{style:"font-weight",getAttrs:t=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}]},renderHTML({HTMLAttributes:t}){return TN("strong",{..._i(this.options.HTMLAttributes,t),children:TN("slot",{})})},markdownTokenName:"strong",parseMarkdown:(t,e)=>e.applyMark("bold",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`**${e.renderChildren(t)}**`,addCommands(){return{setBold:()=>({commands:t})=>t.setMark(this.name),toggleBold:()=>({commands:t})=>t.toggleMark(this.name),unsetBold:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[gb({find:Aqe,type:this.type}),gb({find:Pqe,type:this.type})]},addPasteRules(){return[Pm({find:Cqe,type:this.type}),Pm({find:jqe,type:this.type})]}}),Rqe=/(^|[^`])`([^`]+)`(?!`)$/,Oqe=/(^|[^`])`([^`]+)`(?!`)/g,Lqe=Kh.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:t}){return["code",_i(this.options.HTMLAttributes,t),0]},markdownTokenName:"codespan",parseMarkdown:(t,e)=>e.applyMark("code",[{type:"text",text:t.text||""}]),renderMarkdown:(t,e)=>t.content?`\`${e.renderChildren(t.content)}\``:"",addCommands(){return{setCode:()=>({commands:t})=>t.setMark(this.name),toggleCode:()=>({commands:t})=>t.toggleMark(this.name),unsetCode:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[gb({find:Rqe,type:this.type})]},addPasteRules(){return[Pm({find:Oqe,type:this.type})]}}),UP=4,Fqe=/^```([a-z]+)?[\s\n]$/,Iqe=/^~~~([a-z]+)?[\s\n]$/,zqe=Zs.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:UP,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:t=>{var e;const{languageClassPrefix:n}=this.options;if(!n)return null;const s=[...((e=t.firstElementChild)==null?void 0:e.classList)||[]].filter(o=>o.startsWith(n)).map(o=>o.replace(n,""))[0];return s||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:t,HTMLAttributes:e}){return["pre",_i(this.options.HTMLAttributes,e),["code",{class:t.attrs.language?this.options.languageClassPrefix+t.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(t,e)=>{var n;return((n=t.raw)==null?void 0:n.startsWith("```"))===!1&&t.codeBlockStyle!=="indented"?[]:e.createNode("codeBlock",{language:t.lang||null},t.text?[e.createTextNode(t.text)]:[])},renderMarkdown:(t,e)=>{var n;let r="";const i=((n=t.attrs)==null?void 0:n.language)||"";return t.content?r=[`\`\`\`${i}`,e.renderChildren(t.content),"```"].join(` +`)},addCommands(){return{setBlockquote:()=>({commands:t})=>t.wrapIn(this.name),toggleBlockquote:()=>({commands:t})=>t.toggleWrap(this.name),unsetBlockquote:()=>({commands:t})=>t.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote()}},addInputRules(){return[bb({find:Tqe,type:this.type})]}}),Cqe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,Pqe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,jqe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,Dqe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,Rqe=Kh.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:t=>t.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:t=>t.type.name===this.name},{style:"font-weight",getAttrs:t=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}]},renderHTML({HTMLAttributes:t}){return TN("strong",{..._i(this.options.HTMLAttributes,t),children:TN("slot",{})})},markdownTokenName:"strong",parseMarkdown:(t,e)=>e.applyMark("bold",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`**${e.renderChildren(t)}**`,addCommands(){return{setBold:()=>({commands:t})=>t.setMark(this.name),toggleBold:()=>({commands:t})=>t.toggleMark(this.name),unsetBold:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[gb({find:Cqe,type:this.type}),gb({find:jqe,type:this.type})]},addPasteRules(){return[Pm({find:Pqe,type:this.type}),Pm({find:Dqe,type:this.type})]}}),Oqe=/(^|[^`])`([^`]+)`(?!`)$/,Lqe=/(^|[^`])`([^`]+)`(?!`)/g,Fqe=Kh.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:t}){return["code",_i(this.options.HTMLAttributes,t),0]},markdownTokenName:"codespan",parseMarkdown:(t,e)=>e.applyMark("code",[{type:"text",text:t.text||""}]),renderMarkdown:(t,e)=>t.content?`\`${e.renderChildren(t.content)}\``:"",addCommands(){return{setCode:()=>({commands:t})=>t.setMark(this.name),toggleCode:()=>({commands:t})=>t.toggleMark(this.name),unsetCode:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[gb({find:Oqe,type:this.type})]},addPasteRules(){return[Pm({find:Lqe,type:this.type})]}}),UP=4,Iqe=/^```([a-z]+)?[\s\n]$/,zqe=/^~~~([a-z]+)?[\s\n]$/,Uqe=Zs.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:UP,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:t=>{var e;const{languageClassPrefix:n}=this.options;if(!n)return null;const s=[...((e=t.firstElementChild)==null?void 0:e.classList)||[]].filter(o=>o.startsWith(n)).map(o=>o.replace(n,""))[0];return s||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:t,HTMLAttributes:e}){return["pre",_i(this.options.HTMLAttributes,e),["code",{class:t.attrs.language?this.options.languageClassPrefix+t.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(t,e)=>{var n;return((n=t.raw)==null?void 0:n.startsWith("```"))===!1&&t.codeBlockStyle!=="indented"?[]:e.createNode("codeBlock",{language:t.lang||null},t.text?[e.createTextNode(t.text)]:[])},renderMarkdown:(t,e)=>{var n;let r="";const i=((n=t.attrs)==null?void 0:n.language)||"";return t.content?r=[`\`\`\`${i}`,e.renderChildren(t.content),"```"].join(` `):r=`\`\`\`${i} \`\`\``,r},addCommands(){return{setCodeBlock:t=>({commands:e})=>e.setNode(this.name,t),toggleCodeBlock:t=>({commands:e})=>e.toggleNode(this.name,"paragraph",t)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:t,$anchor:e}=this.editor.state.selection,n=e.pos===1;return!t||e.parent.type.name!==this.name?!1:n||!e.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=(e=this.options.tabSize)!=null?e:UP,{state:r}=t,{selection:i}=r,{$from:s,empty:o}=i;if(s.parent.type!==this.type)return!1;const l=" ".repeat(n);return o?t.commands.insertContent(l):t.commands.command(({tr:c})=>{const{from:u,to:d}=i,m=r.doc.textBetween(u,d,` @@ -8627,46 +8627,46 @@ ${n} `).map(m=>{var b;const y=((b=m.match(/^ */))==null?void 0:b[0])||"",x=Math.min(y.length,n);return m.slice(x)}).join(` `);return l.replaceWith(c,u,r.schema.text(p)),!0})},Enter:({editor:t})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:e}=t,{selection:n}=e,{$from:r,empty:i}=n;if(!i||r.parent.type!==this.type)return!1;const s=r.parentOffset===r.parent.nodeSize-2,o=r.parent.textContent.endsWith(` -`);return!s||!o?!1:t.chain().command(({tr:l})=>(l.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:t})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=t,{selection:n,doc:r}=e,{$from:i,empty:s}=n;if(!s||i.parent.type!==this.type||!(i.parentOffset===i.parent.nodeSize-2))return!1;const l=i.after();return l===void 0?!1:r.nodeAt(l)?t.commands.command(({tr:u})=>(u.setSelection(Fn.near(r.resolve(l))),!0)):t.commands.exitCode()}}},addInputRules(){return[iR({find:Fqe,type:this.type,getAttributes:t=>({language:t[1]})}),iR({find:Iqe,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new di({key:new ca("codeBlockVSCodeHandler"),props:{handlePaste:(t,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;const n=e.clipboardData.getData("text/plain"),r=e.clipboardData.getData("vscode-editor-data"),i=r?JSON.parse(r):void 0,s=i?.mode;if(!n||!s)return!1;const{tr:o,schema:l}=t.state,c=l.text(n.replace(/\r\n?/g,` -`));return o.replaceSelectionWith(this.type.create({language:s},c)),o.selection.$from.parent.type!==this.type&&o.setSelection(yn.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),t.dispatch(o),!0}}})]}}),Uqe=Zs.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` +`);return!s||!o?!1:t.chain().command(({tr:l})=>(l.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:t})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=t,{selection:n,doc:r}=e,{$from:i,empty:s}=n;if(!s||i.parent.type!==this.type||!(i.parentOffset===i.parent.nodeSize-2))return!1;const l=i.after();return l===void 0?!1:r.nodeAt(l)?t.commands.command(({tr:u})=>(u.setSelection(Fn.near(r.resolve(l))),!0)):t.commands.exitCode()}}},addInputRules(){return[iR({find:Iqe,type:this.type,getAttributes:t=>({language:t[1]})}),iR({find:zqe,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new di({key:new ca("codeBlockVSCodeHandler"),props:{handlePaste:(t,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;const n=e.clipboardData.getData("text/plain"),r=e.clipboardData.getData("vscode-editor-data"),i=r?JSON.parse(r):void 0,s=i?.mode;if(!n||!s)return!1;const{tr:o,schema:l}=t.state,c=l.text(n.replace(/\r\n?/g,` +`));return o.replaceSelectionWith(this.type.create({language:s},c)),o.selection.$from.parent.type!==this.type&&o.setSelection(yn.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),t.dispatch(o),!0}}})]}}),Bqe=Zs.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` -`):""}),Bqe=Zs.create({name:"hardBreak",markdownTokenName:"br",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:t}){return["br",_i(this.options.HTMLAttributes,t)]},renderText(){return` +`):""}),Hqe=Zs.create({name:"hardBreak",markdownTokenName:"br",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:t}){return["br",_i(this.options.HTMLAttributes,t)]},renderText(){return` `},renderMarkdown:()=>` -`,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:t,chain:e,state:n,editor:r})=>t.first([()=>t.exitCode(),()=>t.command(()=>{const{selection:i,storedMarks:s}=n;if(i.$from.parent.type.spec.isolating)return!1;const{keepMarks:o}=this.options,{splittableMarks:l}=r.extensionManager,c=s||i.$to.parentOffset&&i.$from.marks();return e().insertContent({type:this.name}).command(({tr:u,dispatch:d})=>{if(d&&c&&o){const h=c.filter(p=>l.includes(p.type.name));u.ensureMarks(h)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),Hqe=Zs.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(t=>({tag:`h${t}`,attrs:{level:t}}))},renderHTML({node:t,HTMLAttributes:e}){return[`h${this.options.levels.includes(t.attrs.level)?t.attrs.level:this.options.levels[0]}`,_i(this.options.HTMLAttributes,e),0]},parseMarkdown:(t,e)=>e.createNode("heading",{level:t.depth||1},e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>{var n;const r=(n=t.attrs)!=null&&n.level?parseInt(t.attrs.level,10):1,i="#".repeat(r);return t.content?`${i} ${e.renderChildren(t.content)}`:""},addCommands(){return{setHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.setNode(this.name,t):!1,toggleHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.toggleNode(this.name,"paragraph",t):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((t,e)=>({...t,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(t=>iR({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),$qe=Zs.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:t}){return["hr",_i(this.options.HTMLAttributes,t)]},markdownTokenName:"hr",parseMarkdown:(t,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!eqe(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:r}=n,i=t();return Dne(n)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:s,tr:o,dispatch:l})=>{if(l){const{$to:c}=o.selection,u=c.end();if(c.nodeAfter)c.nodeAfter.isTextblock?o.setSelection(yn.create(o.doc,c.pos+1)):c.nodeAfter.isBlock?o.setSelection(rn.create(o.doc,c.pos)):o.setSelection(yn.create(o.doc,c.pos));else{const d=s.schema.nodes[this.options.nextNodeType]||c.parent.type.contentMatch.defaultType,h=d?.create();h&&(o.insert(u,h),o.setSelection(yn.create(o.doc,u+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Kne({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),Vqe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Gqe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,qqe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Wqe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,Kqe=Kh.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:t=>t.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:t=>t.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:t}){return["em",_i(this.options.HTMLAttributes,t),0]},addCommands(){return{setItalic:()=>({commands:t})=>t.setMark(this.name),toggleItalic:()=>({commands:t})=>t.toggleMark(this.name),unsetItalic:()=>({commands:t})=>t.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(t,e)=>e.applyMark("italic",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`*${e.renderChildren(t)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[gb({find:Vqe,type:this.type}),gb({find:qqe,type:this.type})]},addPasteRules(){return[Pm({find:Gqe,type:this.type}),Pm({find:Wqe,type:this.type})]}});const Xqe="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",Yqe="ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2",oR="numeric",lR="ascii",cR="alpha",O0="asciinumeric",x0="alphanumeric",uR="domain",Qne="emoji",Qqe="scheme",Zqe="slashscheme",BP="whitespace";function Jqe(t,e){return t in e||(e[t]=[]),e[t]}function Wf(t,e,n){e[oR]&&(e[O0]=!0,e[x0]=!0),e[lR]&&(e[O0]=!0,e[cR]=!0),e[O0]&&(e[x0]=!0),e[cR]&&(e[x0]=!0),e[x0]&&(e[uR]=!0),e[Qne]&&(e[uR]=!0);for(const r in e){const i=Jqe(r,n);i.indexOf(t)<0&&i.push(t)}}function e7e(t,e){const n={};for(const r in e)e[r].indexOf(t)>=0&&(n[r]=!0);return n}function $s(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}$s.groups={};$s.prototype={accepts(){return!!this.t},go(t){const e=this,n=e.j[t];if(n)return n;for(let r=0;rt.ta(e,n,r,i),mi=(t,e,n,r,i)=>t.tr(e,n,r,i),r9=(t,e,n,r,i)=>t.ts(e,n,r,i),Pt=(t,e,n,r,i)=>t.tt(e,n,r,i),mu="WORD",dR="UWORD",Zne="ASCIINUMERICAL",Jne="ALPHANUMERICAL",Ry="LOCALHOST",hR="TLD",fR="UTLD",V1="SCHEME",pg="SLASH_SCHEME",lF="NUM",mR="WS",cF="NL",L0="OPENBRACE",F0="CLOSEBRACE",AN="OPENBRACKET",CN="CLOSEBRACKET",PN="OPENPAREN",jN="CLOSEPAREN",DN="OPENANGLEBRACKET",RN="CLOSEANGLEBRACKET",ON="FULLWIDTHLEFTPAREN",LN="FULLWIDTHRIGHTPAREN",FN="LEFTCORNERBRACKET",IN="RIGHTCORNERBRACKET",zN="LEFTWHITECORNERBRACKET",UN="RIGHTWHITECORNERBRACKET",BN="FULLWIDTHLESSTHAN",HN="FULLWIDTHGREATERTHAN",$N="AMPERSAND",VN="APOSTROPHE",GN="ASTERISK",eh="AT",qN="BACKSLASH",WN="BACKTICK",KN="CARET",sh="COLON",uF="COMMA",XN="DOLLAR",Jl="DOT",YN="EQUALS",dF="EXCLAMATION",Ko="HYPHEN",I0="PERCENT",QN="PIPE",ZN="PLUS",JN="POUND",z0="QUERY",hF="QUOTE",ere="FULLWIDTHMIDDLEDOT",fF="SEMI",ec="SLASH",U0="TILDE",ek="UNDERSCORE",tre="EMOJI",tk="SYM";var nre=Object.freeze({__proto__:null,ALPHANUMERICAL:Jne,AMPERSAND:$N,APOSTROPHE:VN,ASCIINUMERICAL:Zne,ASTERISK:GN,AT:eh,BACKSLASH:qN,BACKTICK:WN,CARET:KN,CLOSEANGLEBRACKET:RN,CLOSEBRACE:F0,CLOSEBRACKET:CN,CLOSEPAREN:jN,COLON:sh,COMMA:uF,DOLLAR:XN,DOT:Jl,EMOJI:tre,EQUALS:YN,EXCLAMATION:dF,FULLWIDTHGREATERTHAN:HN,FULLWIDTHLEFTPAREN:ON,FULLWIDTHLESSTHAN:BN,FULLWIDTHMIDDLEDOT:ere,FULLWIDTHRIGHTPAREN:LN,HYPHEN:Ko,LEFTCORNERBRACKET:FN,LEFTWHITECORNERBRACKET:zN,LOCALHOST:Ry,NL:cF,NUM:lF,OPENANGLEBRACKET:DN,OPENBRACE:L0,OPENBRACKET:AN,OPENPAREN:PN,PERCENT:I0,PIPE:QN,PLUS:ZN,POUND:JN,QUERY:z0,QUOTE:hF,RIGHTCORNERBRACKET:IN,RIGHTWHITECORNERBRACKET:UN,SCHEME:V1,SEMI:fF,SLASH:ec,SLASH_SCHEME:pg,SYM:tk,TILDE:U0,TLD:hR,UNDERSCORE:ek,UTLD:fR,UWORD:dR,WORD:mu,WS:mR});const cu=/[a-z]/,a0=new RegExp("\\p{L}","u"),HP=new RegExp("\\p{Emoji}","u"),uu=/\d/,$P=/\s/,i9="\r",VP=` -`,t7e="️",n7e="‍",GP="";let h1=null,f1=null;function r7e(t=[]){const e={};$s.groups=e;const n=new $s;h1==null&&(h1=a9(Xqe)),f1==null&&(f1=a9(Yqe)),Pt(n,"'",VN),Pt(n,"{",L0),Pt(n,"}",F0),Pt(n,"[",AN),Pt(n,"]",CN),Pt(n,"(",PN),Pt(n,")",jN),Pt(n,"<",DN),Pt(n,">",RN),Pt(n,"(",ON),Pt(n,")",LN),Pt(n,"「",FN),Pt(n,"」",IN),Pt(n,"『",zN),Pt(n,"』",UN),Pt(n,"<",BN),Pt(n,">",HN),Pt(n,"&",$N),Pt(n,"*",GN),Pt(n,"@",eh),Pt(n,"`",WN),Pt(n,"^",KN),Pt(n,":",sh),Pt(n,",",uF),Pt(n,"$",XN),Pt(n,".",Jl),Pt(n,"=",YN),Pt(n,"!",dF),Pt(n,"-",Ko),Pt(n,"%",I0),Pt(n,"|",QN),Pt(n,"+",ZN),Pt(n,"#",JN),Pt(n,"?",z0),Pt(n,'"',hF),Pt(n,"/",ec),Pt(n,";",fF),Pt(n,"~",U0),Pt(n,"_",ek),Pt(n,"\\",qN),Pt(n,"・",ere);const r=mi(n,uu,lF,{[oR]:!0});mi(r,uu,r);const i=mi(r,cu,Zne,{[O0]:!0}),s=mi(r,a0,Jne,{[x0]:!0}),o=mi(n,cu,mu,{[lR]:!0});mi(o,uu,i),mi(o,cu,o),mi(i,uu,i),mi(i,cu,i);const l=mi(n,a0,dR,{[cR]:!0});mi(l,cu),mi(l,uu,s),mi(l,a0,l),mi(s,uu,s),mi(s,cu),mi(s,a0,s);const c=Pt(n,VP,cF,{[BP]:!0}),u=Pt(n,i9,mR,{[BP]:!0}),d=mi(n,$P,mR,{[BP]:!0});Pt(n,GP,d),Pt(u,VP,c),Pt(u,GP,d),mi(u,$P,d),Pt(d,i9),Pt(d,VP),mi(d,$P,d),Pt(d,GP,d);const h=mi(n,HP,tre,{[Qne]:!0});Pt(h,"#"),mi(h,HP,h),Pt(h,t7e,h);const p=Pt(h,n7e);Pt(p,"#"),mi(p,HP,h);const m=[[cu,o],[uu,i]],b=[[cu,null],[a0,l],[uu,s]];for(let y=0;yy[0]>x[0]?1:-1);for(let y=0;y=0?S[uR]=!0:cu.test(x)?uu.test(x)?S[O0]=!0:S[lR]=!0:S[oR]=!0,r9(n,x,x,S)}return r9(n,"localhost",Ry,{ascii:!0}),n.jd=new $s(tk),{start:n,tokens:Object.assign({groups:e},nre)}}function rre(t,e){const n=i7e(e.replace(/[A-Z]/g,l=>l.toLowerCase())),r=n.length,i=[];let s=0,o=0;for(;o=0&&(h+=n[o].length,p++),u+=n[o].length,s+=n[o].length,o++;s-=h,o-=p,u-=h,i.push({t:d.t,v:e.slice(s-u,s),s:s-u,e:s})}return i}function i7e(t){const e=[],n=t.length;let r=0;for(;r56319||r+1===n||(s=t.charCodeAt(r+1))<56320||s>57343?t[r]:t.slice(r,r+2);e.push(o),r+=o.length}return e}function qd(t,e,n,r,i){let s;const o=e.length;for(let l=0;l=0;)s++;if(s>0){e.push(n.join(""));for(let o=parseInt(t.substring(r,r+s),10);o>0;o--)n.pop();r+=s}else n.push(t[r]),r++}return e}const Oy={defaultProtocol:"http",events:null,format:s9,formatHref:s9,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function mF(t,e=null){let n=Object.assign({},Oy);t&&(n=Object.assign(n,t instanceof mF?t.o:t));const r=n.ignoreTags,i=[];for(let s=0;sn?r.substring(0,n)+"…":r},toFormattedHref(t){return t.get("formatHref",this.toHref(t.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(t=Oy.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(t),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(t){return{type:this.t,value:this.toFormattedString(t),isLink:this.isLink,href:this.toFormattedHref(t),start:this.startIndex(),end:this.endIndex()}},validate(t){return t.get("validate",this.toString(),this)},render(t){const e=this,n=this.toHref(t.get("defaultProtocol")),r=t.get("formatHref",n,this),i=t.get("tagName",n,e),s=this.toFormattedString(t),o={},l=t.get("className",n,e),c=t.get("target",n,e),u=t.get("rel",n,e),d=t.getObj("attributes",n,e),h=t.getObj("events",n,e);return o.href=r,l&&(o.class=l),c&&(o.target=c),u&&(o.rel=u),d&&Object.assign(o,d),{tagName:i,attributes:o,content:s,eventListeners:h}}};function WM(t,e){class n extends ire{constructor(i,s){super(i,s),this.t=t}}for(const r in e)n.prototype[r]=e[r];return n.t=t,n}const o9=WM("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),l9=WM("text"),a7e=WM("nl"),m1=WM("url",{isLink:!0,toHref(t=Oy.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==Ry&&t[1].t===sh}}),Go=t=>new $s(t);function s7e({groups:t}){const e=t.domain.concat([$N,GN,eh,qN,WN,KN,XN,YN,Ko,lF,I0,QN,ZN,JN,ec,tk,U0,ek]),n=[VN,sh,uF,Jl,dF,I0,z0,hF,fF,DN,RN,L0,F0,CN,AN,PN,jN,ON,LN,FN,IN,zN,UN,BN,HN],r=[$N,VN,GN,qN,WN,KN,XN,YN,Ko,L0,F0,I0,QN,ZN,JN,z0,ec,tk,U0,ek],i=Go(),s=Pt(i,U0);Dn(s,r,s),Dn(s,t.domain,s);const o=Go(),l=Go(),c=Go();Dn(i,t.domain,o),Dn(i,t.scheme,l),Dn(i,t.slashscheme,c),Dn(o,r,s),Dn(o,t.domain,o);const u=Pt(o,eh);Pt(s,eh,u),Pt(l,eh,u),Pt(c,eh,u);const d=Pt(s,Jl);Dn(d,r,s),Dn(d,t.domain,s);const h=Go();Dn(u,t.domain,h),Dn(h,t.domain,h);const p=Pt(h,Jl);Dn(p,t.domain,h);const m=Go(o9);Dn(p,t.tld,m),Dn(p,t.utld,m),Pt(u,Ry,m);const b=Pt(h,Ko);Pt(b,Ko,b),Dn(b,t.domain,h),Dn(m,t.domain,h),Pt(m,Jl,p),Pt(m,Ko,b);const y=Pt(m,sh);Dn(y,t.numeric,o9);const x=Pt(o,Ko),v=Pt(o,Jl);Pt(x,Ko,x),Dn(x,t.domain,o),Dn(v,r,s),Dn(v,t.domain,o);const S=Go(m1);Dn(v,t.tld,S),Dn(v,t.utld,S),Dn(S,t.domain,o),Dn(S,r,s),Pt(S,Jl,v),Pt(S,Ko,x),Pt(S,eh,u);const N=Pt(S,sh),T=Go(m1);Dn(N,t.numeric,T);const M=Go(m1),A=Go();Dn(M,e,M),Dn(M,n,A),Dn(A,e,M),Dn(A,n,A),Pt(S,ec,M),Pt(T,ec,M);const k=Pt(l,sh),R=Pt(c,sh),C=Pt(R,ec),P=Pt(C,ec);Dn(l,t.domain,o),Pt(l,Jl,v),Pt(l,Ko,x),Dn(c,t.domain,o),Pt(c,Jl,v),Pt(c,Ko,x),Dn(k,t.domain,M),Pt(k,ec,M),Pt(k,z0,M),Dn(P,t.domain,M),Dn(P,e,M),Pt(P,ec,M);const U=[[L0,F0],[AN,CN],[PN,jN],[DN,RN],[ON,LN],[FN,IN],[zN,UN],[BN,HN]];for(let F=0;F=0&&p++,i++,d++;if(p<0)i-=d,i0&&(s.push(qP(l9,e,o)),o=[]),i-=p,d-=p;const m=h.t,b=n.slice(i-d,i);s.push(qP(m,e,b))}}return o.length>0&&s.push(qP(l9,e,o)),s}function qP(t,e,n){const r=n[0].s,i=n[n.length-1].e,s=e.slice(r,i);return new t(s,n)}const l7e=typeof console<"u"&&console&&console.warn||(()=>{}),c7e="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Wr={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function u7e(){return $s.groups={},Wr.scanner=null,Wr.parser=null,Wr.tokenQueue=[],Wr.pluginQueue=[],Wr.customSchemes=[],Wr.initialized=!1,Wr}function c9(t,e=!1){if(Wr.initialized&&l7e(`linkifyjs: already initialized - will not register custom scheme "${t}" ${c7e}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error(`linkifyjs: incorrect scheme format. +`,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:t,chain:e,state:n,editor:r})=>t.first([()=>t.exitCode(),()=>t.command(()=>{const{selection:i,storedMarks:s}=n;if(i.$from.parent.type.spec.isolating)return!1;const{keepMarks:o}=this.options,{splittableMarks:l}=r.extensionManager,c=s||i.$to.parentOffset&&i.$from.marks();return e().insertContent({type:this.name}).command(({tr:u,dispatch:d})=>{if(d&&c&&o){const h=c.filter(p=>l.includes(p.type.name));u.ensureMarks(h)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),$qe=Zs.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(t=>({tag:`h${t}`,attrs:{level:t}}))},renderHTML({node:t,HTMLAttributes:e}){return[`h${this.options.levels.includes(t.attrs.level)?t.attrs.level:this.options.levels[0]}`,_i(this.options.HTMLAttributes,e),0]},parseMarkdown:(t,e)=>e.createNode("heading",{level:t.depth||1},e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>{var n;const r=(n=t.attrs)!=null&&n.level?parseInt(t.attrs.level,10):1,i="#".repeat(r);return t.content?`${i} ${e.renderChildren(t.content)}`:""},addCommands(){return{setHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.setNode(this.name,t):!1,toggleHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.toggleNode(this.name,"paragraph",t):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((t,e)=>({...t,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(t=>iR({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),Vqe=Zs.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:t}){return["hr",_i(this.options.HTMLAttributes,t)]},markdownTokenName:"hr",parseMarkdown:(t,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!tqe(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:r}=n,i=t();return Dne(n)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:s,tr:o,dispatch:l})=>{if(l){const{$to:c}=o.selection,u=c.end();if(c.nodeAfter)c.nodeAfter.isTextblock?o.setSelection(yn.create(o.doc,c.pos+1)):c.nodeAfter.isBlock?o.setSelection(rn.create(o.doc,c.pos)):o.setSelection(yn.create(o.doc,c.pos));else{const d=s.schema.nodes[this.options.nextNodeType]||c.parent.type.contentMatch.defaultType,h=d?.create();h&&(o.insert(u,h),o.setSelection(yn.create(o.doc,u+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Kne({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),Gqe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,qqe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Wqe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Kqe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,Xqe=Kh.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:t=>t.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:t=>t.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:t}){return["em",_i(this.options.HTMLAttributes,t),0]},addCommands(){return{setItalic:()=>({commands:t})=>t.setMark(this.name),toggleItalic:()=>({commands:t})=>t.toggleMark(this.name),unsetItalic:()=>({commands:t})=>t.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(t,e)=>e.applyMark("italic",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`*${e.renderChildren(t)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[gb({find:Gqe,type:this.type}),gb({find:Wqe,type:this.type})]},addPasteRules(){return[Pm({find:qqe,type:this.type}),Pm({find:Kqe,type:this.type})]}});const Yqe="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",Qqe="ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2",oR="numeric",lR="ascii",cR="alpha",O0="asciinumeric",x0="alphanumeric",uR="domain",Qne="emoji",Zqe="scheme",Jqe="slashscheme",BP="whitespace";function e7e(t,e){return t in e||(e[t]=[]),e[t]}function Wf(t,e,n){e[oR]&&(e[O0]=!0,e[x0]=!0),e[lR]&&(e[O0]=!0,e[cR]=!0),e[O0]&&(e[x0]=!0),e[cR]&&(e[x0]=!0),e[x0]&&(e[uR]=!0),e[Qne]&&(e[uR]=!0);for(const r in e){const i=e7e(r,n);i.indexOf(t)<0&&i.push(t)}}function t7e(t,e){const n={};for(const r in e)e[r].indexOf(t)>=0&&(n[r]=!0);return n}function $s(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}$s.groups={};$s.prototype={accepts(){return!!this.t},go(t){const e=this,n=e.j[t];if(n)return n;for(let r=0;rt.ta(e,n,r,i),mi=(t,e,n,r,i)=>t.tr(e,n,r,i),r9=(t,e,n,r,i)=>t.ts(e,n,r,i),Pt=(t,e,n,r,i)=>t.tt(e,n,r,i),mu="WORD",dR="UWORD",Zne="ASCIINUMERICAL",Jne="ALPHANUMERICAL",Ry="LOCALHOST",hR="TLD",fR="UTLD",V1="SCHEME",pg="SLASH_SCHEME",lF="NUM",mR="WS",cF="NL",L0="OPENBRACE",F0="CLOSEBRACE",AN="OPENBRACKET",CN="CLOSEBRACKET",PN="OPENPAREN",jN="CLOSEPAREN",DN="OPENANGLEBRACKET",RN="CLOSEANGLEBRACKET",ON="FULLWIDTHLEFTPAREN",LN="FULLWIDTHRIGHTPAREN",FN="LEFTCORNERBRACKET",IN="RIGHTCORNERBRACKET",zN="LEFTWHITECORNERBRACKET",UN="RIGHTWHITECORNERBRACKET",BN="FULLWIDTHLESSTHAN",HN="FULLWIDTHGREATERTHAN",$N="AMPERSAND",VN="APOSTROPHE",GN="ASTERISK",eh="AT",qN="BACKSLASH",WN="BACKTICK",KN="CARET",sh="COLON",uF="COMMA",XN="DOLLAR",Jl="DOT",YN="EQUALS",dF="EXCLAMATION",Ko="HYPHEN",I0="PERCENT",QN="PIPE",ZN="PLUS",JN="POUND",z0="QUERY",hF="QUOTE",ere="FULLWIDTHMIDDLEDOT",fF="SEMI",ec="SLASH",U0="TILDE",ek="UNDERSCORE",tre="EMOJI",tk="SYM";var nre=Object.freeze({__proto__:null,ALPHANUMERICAL:Jne,AMPERSAND:$N,APOSTROPHE:VN,ASCIINUMERICAL:Zne,ASTERISK:GN,AT:eh,BACKSLASH:qN,BACKTICK:WN,CARET:KN,CLOSEANGLEBRACKET:RN,CLOSEBRACE:F0,CLOSEBRACKET:CN,CLOSEPAREN:jN,COLON:sh,COMMA:uF,DOLLAR:XN,DOT:Jl,EMOJI:tre,EQUALS:YN,EXCLAMATION:dF,FULLWIDTHGREATERTHAN:HN,FULLWIDTHLEFTPAREN:ON,FULLWIDTHLESSTHAN:BN,FULLWIDTHMIDDLEDOT:ere,FULLWIDTHRIGHTPAREN:LN,HYPHEN:Ko,LEFTCORNERBRACKET:FN,LEFTWHITECORNERBRACKET:zN,LOCALHOST:Ry,NL:cF,NUM:lF,OPENANGLEBRACKET:DN,OPENBRACE:L0,OPENBRACKET:AN,OPENPAREN:PN,PERCENT:I0,PIPE:QN,PLUS:ZN,POUND:JN,QUERY:z0,QUOTE:hF,RIGHTCORNERBRACKET:IN,RIGHTWHITECORNERBRACKET:UN,SCHEME:V1,SEMI:fF,SLASH:ec,SLASH_SCHEME:pg,SYM:tk,TILDE:U0,TLD:hR,UNDERSCORE:ek,UTLD:fR,UWORD:dR,WORD:mu,WS:mR});const cu=/[a-z]/,a0=new RegExp("\\p{L}","u"),HP=new RegExp("\\p{Emoji}","u"),uu=/\d/,$P=/\s/,i9="\r",VP=` +`,n7e="️",r7e="‍",GP="";let h1=null,f1=null;function i7e(t=[]){const e={};$s.groups=e;const n=new $s;h1==null&&(h1=a9(Yqe)),f1==null&&(f1=a9(Qqe)),Pt(n,"'",VN),Pt(n,"{",L0),Pt(n,"}",F0),Pt(n,"[",AN),Pt(n,"]",CN),Pt(n,"(",PN),Pt(n,")",jN),Pt(n,"<",DN),Pt(n,">",RN),Pt(n,"(",ON),Pt(n,")",LN),Pt(n,"「",FN),Pt(n,"」",IN),Pt(n,"『",zN),Pt(n,"』",UN),Pt(n,"<",BN),Pt(n,">",HN),Pt(n,"&",$N),Pt(n,"*",GN),Pt(n,"@",eh),Pt(n,"`",WN),Pt(n,"^",KN),Pt(n,":",sh),Pt(n,",",uF),Pt(n,"$",XN),Pt(n,".",Jl),Pt(n,"=",YN),Pt(n,"!",dF),Pt(n,"-",Ko),Pt(n,"%",I0),Pt(n,"|",QN),Pt(n,"+",ZN),Pt(n,"#",JN),Pt(n,"?",z0),Pt(n,'"',hF),Pt(n,"/",ec),Pt(n,";",fF),Pt(n,"~",U0),Pt(n,"_",ek),Pt(n,"\\",qN),Pt(n,"・",ere);const r=mi(n,uu,lF,{[oR]:!0});mi(r,uu,r);const i=mi(r,cu,Zne,{[O0]:!0}),s=mi(r,a0,Jne,{[x0]:!0}),o=mi(n,cu,mu,{[lR]:!0});mi(o,uu,i),mi(o,cu,o),mi(i,uu,i),mi(i,cu,i);const l=mi(n,a0,dR,{[cR]:!0});mi(l,cu),mi(l,uu,s),mi(l,a0,l),mi(s,uu,s),mi(s,cu),mi(s,a0,s);const c=Pt(n,VP,cF,{[BP]:!0}),u=Pt(n,i9,mR,{[BP]:!0}),d=mi(n,$P,mR,{[BP]:!0});Pt(n,GP,d),Pt(u,VP,c),Pt(u,GP,d),mi(u,$P,d),Pt(d,i9),Pt(d,VP),mi(d,$P,d),Pt(d,GP,d);const h=mi(n,HP,tre,{[Qne]:!0});Pt(h,"#"),mi(h,HP,h),Pt(h,n7e,h);const p=Pt(h,r7e);Pt(p,"#"),mi(p,HP,h);const m=[[cu,o],[uu,i]],b=[[cu,null],[a0,l],[uu,s]];for(let y=0;yy[0]>x[0]?1:-1);for(let y=0;y=0?S[uR]=!0:cu.test(x)?uu.test(x)?S[O0]=!0:S[lR]=!0:S[oR]=!0,r9(n,x,x,S)}return r9(n,"localhost",Ry,{ascii:!0}),n.jd=new $s(tk),{start:n,tokens:Object.assign({groups:e},nre)}}function rre(t,e){const n=a7e(e.replace(/[A-Z]/g,l=>l.toLowerCase())),r=n.length,i=[];let s=0,o=0;for(;o=0&&(h+=n[o].length,p++),u+=n[o].length,s+=n[o].length,o++;s-=h,o-=p,u-=h,i.push({t:d.t,v:e.slice(s-u,s),s:s-u,e:s})}return i}function a7e(t){const e=[],n=t.length;let r=0;for(;r56319||r+1===n||(s=t.charCodeAt(r+1))<56320||s>57343?t[r]:t.slice(r,r+2);e.push(o),r+=o.length}return e}function qd(t,e,n,r,i){let s;const o=e.length;for(let l=0;l=0;)s++;if(s>0){e.push(n.join(""));for(let o=parseInt(t.substring(r,r+s),10);o>0;o--)n.pop();r+=s}else n.push(t[r]),r++}return e}const Oy={defaultProtocol:"http",events:null,format:s9,formatHref:s9,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function mF(t,e=null){let n=Object.assign({},Oy);t&&(n=Object.assign(n,t instanceof mF?t.o:t));const r=n.ignoreTags,i=[];for(let s=0;sn?r.substring(0,n)+"…":r},toFormattedHref(t){return t.get("formatHref",this.toHref(t.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(t=Oy.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(t),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(t){return{type:this.t,value:this.toFormattedString(t),isLink:this.isLink,href:this.toFormattedHref(t),start:this.startIndex(),end:this.endIndex()}},validate(t){return t.get("validate",this.toString(),this)},render(t){const e=this,n=this.toHref(t.get("defaultProtocol")),r=t.get("formatHref",n,this),i=t.get("tagName",n,e),s=this.toFormattedString(t),o={},l=t.get("className",n,e),c=t.get("target",n,e),u=t.get("rel",n,e),d=t.getObj("attributes",n,e),h=t.getObj("events",n,e);return o.href=r,l&&(o.class=l),c&&(o.target=c),u&&(o.rel=u),d&&Object.assign(o,d),{tagName:i,attributes:o,content:s,eventListeners:h}}};function WM(t,e){class n extends ire{constructor(i,s){super(i,s),this.t=t}}for(const r in e)n.prototype[r]=e[r];return n.t=t,n}const o9=WM("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),l9=WM("text"),s7e=WM("nl"),m1=WM("url",{isLink:!0,toHref(t=Oy.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==Ry&&t[1].t===sh}}),Go=t=>new $s(t);function o7e({groups:t}){const e=t.domain.concat([$N,GN,eh,qN,WN,KN,XN,YN,Ko,lF,I0,QN,ZN,JN,ec,tk,U0,ek]),n=[VN,sh,uF,Jl,dF,I0,z0,hF,fF,DN,RN,L0,F0,CN,AN,PN,jN,ON,LN,FN,IN,zN,UN,BN,HN],r=[$N,VN,GN,qN,WN,KN,XN,YN,Ko,L0,F0,I0,QN,ZN,JN,z0,ec,tk,U0,ek],i=Go(),s=Pt(i,U0);Dn(s,r,s),Dn(s,t.domain,s);const o=Go(),l=Go(),c=Go();Dn(i,t.domain,o),Dn(i,t.scheme,l),Dn(i,t.slashscheme,c),Dn(o,r,s),Dn(o,t.domain,o);const u=Pt(o,eh);Pt(s,eh,u),Pt(l,eh,u),Pt(c,eh,u);const d=Pt(s,Jl);Dn(d,r,s),Dn(d,t.domain,s);const h=Go();Dn(u,t.domain,h),Dn(h,t.domain,h);const p=Pt(h,Jl);Dn(p,t.domain,h);const m=Go(o9);Dn(p,t.tld,m),Dn(p,t.utld,m),Pt(u,Ry,m);const b=Pt(h,Ko);Pt(b,Ko,b),Dn(b,t.domain,h),Dn(m,t.domain,h),Pt(m,Jl,p),Pt(m,Ko,b);const y=Pt(m,sh);Dn(y,t.numeric,o9);const x=Pt(o,Ko),v=Pt(o,Jl);Pt(x,Ko,x),Dn(x,t.domain,o),Dn(v,r,s),Dn(v,t.domain,o);const S=Go(m1);Dn(v,t.tld,S),Dn(v,t.utld,S),Dn(S,t.domain,o),Dn(S,r,s),Pt(S,Jl,v),Pt(S,Ko,x),Pt(S,eh,u);const N=Pt(S,sh),T=Go(m1);Dn(N,t.numeric,T);const M=Go(m1),A=Go();Dn(M,e,M),Dn(M,n,A),Dn(A,e,M),Dn(A,n,A),Pt(S,ec,M),Pt(T,ec,M);const k=Pt(l,sh),R=Pt(c,sh),C=Pt(R,ec),P=Pt(C,ec);Dn(l,t.domain,o),Pt(l,Jl,v),Pt(l,Ko,x),Dn(c,t.domain,o),Pt(c,Jl,v),Pt(c,Ko,x),Dn(k,t.domain,M),Pt(k,ec,M),Pt(k,z0,M),Dn(P,t.domain,M),Dn(P,e,M),Pt(P,ec,M);const U=[[L0,F0],[AN,CN],[PN,jN],[DN,RN],[ON,LN],[FN,IN],[zN,UN],[BN,HN]];for(let F=0;F=0&&p++,i++,d++;if(p<0)i-=d,i0&&(s.push(qP(l9,e,o)),o=[]),i-=p,d-=p;const m=h.t,b=n.slice(i-d,i);s.push(qP(m,e,b))}}return o.length>0&&s.push(qP(l9,e,o)),s}function qP(t,e,n){const r=n[0].s,i=n[n.length-1].e,s=e.slice(r,i);return new t(s,n)}const c7e=typeof console<"u"&&console&&console.warn||(()=>{}),u7e="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Wr={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function d7e(){return $s.groups={},Wr.scanner=null,Wr.parser=null,Wr.tokenQueue=[],Wr.pluginQueue=[],Wr.customSchemes=[],Wr.initialized=!1,Wr}function c9(t,e=!1){if(Wr.initialized&&c7e(`linkifyjs: already initialized - will not register custom scheme "${t}" ${u7e}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error(`linkifyjs: incorrect scheme format. 1. Must only contain digits, lowercase ASCII letters or "-" 2. Cannot start or end with "-" -3. "-" cannot repeat`);Wr.customSchemes.push([t,e])}function d7e(){Wr.scanner=r7e(Wr.customSchemes);for(let t=0;t{const i=e.some(u=>u.docChanged)&&!n.doc.eq(r.doc),s=e.some(u=>u.getMeta("preventAutolink"));if(!i||s)return;const{tr:o}=r,l=kne(n.doc,[...e]);if(jne(l).forEach(({newRange:u})=>{const d=tGe(r.doc,u,m=>m.isTextblock);let h,p;if(d.length>1)h=d[0],p=r.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(d.length){const m=r.doc.textBetween(u.from,u.to," "," ");if(!f7e.test(m))return;h=d[0],p=r.doc.textBetween(h.pos,u.to,void 0," ")}if(h&&p){const m=p.split(h7e).filter(Boolean);if(m.length<=0)return!1;const b=m[m.length-1],y=h.pos+p.lastIndexOf(b);if(!b)return!1;const x=pF(b).map(v=>v.toObject(t.defaultProtocol));if(!p7e(x))return!1;x.filter(v=>v.isLink).map(v=>({...v,from:y+v.start+1,to:y+v.end+1})).filter(v=>r.schema.marks.code?!r.doc.rangeHasMark(v.from,v.to,r.schema.marks.code):!0).filter(v=>t.validate(v.value)).filter(v=>t.shouldAutoLink(v.value)).forEach(v=>{rF(v.from,v.to,r.doc).some(S=>S.mark.type===t.type)||o.addMark(v.from,v.to,t.type.create({href:v.href}))})}}),!!o.steps.length)return o}})}function b7e(t){return new di({key:new ca("handleClickLink"),props:{handleClick:(e,n,r)=>{var i,s;if(r.button!==0||!e.editable)return!1;let o=null;if(r.target instanceof HTMLAnchorElement)o=r.target;else{let d=r.target;const h=[];for(;d.nodeName!=="DIV";)h.push(d),d=d.parentNode;o=h.find(p=>p.nodeName==="A")}if(!o)return!1;const l=Pne(e.state,t.type.name),c=(i=o?.href)!=null?i:l.href,u=(s=o?.target)!=null?s:l.target;return t.enableClickSelection&&t.editor.commands.extendMarkRange(t.type.name),o&&c?(window.open(c,u),!0):!1}}})}function x7e(t){return new di({key:new ca("handlePasteLink"),props:{handlePaste:(e,n,r)=>{const{shouldAutoLink:i}=t,{state:s}=e,{selection:o}=s,{empty:l}=o;if(l)return!1;let c="";r.content.forEach(d=>{c+=d.textContent});const u=are(c,{defaultProtocol:t.defaultProtocol}).find(d=>d.isLink&&d.value===c);return!c||!u||i!==void 0&&!i(u.href)?!1:t.editor.commands.setMark(t.type,{href:u.href})}}})}function Nf(t,e){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(r=>{const i=typeof r=="string"?r:r.scheme;i&&n.push(i)}),!t||t.replace(m7e,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var sre=Kh.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(t=>{if(typeof t=="string"){c9(t);return}c9(t.scheme,t.optionalSlashes)})},onDestroy(){u7e()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(t,e)=>!!Nf(t,e.protocols),validate:t=>!!t,shouldAutoLink:t=>!!t}},addAttributes(){return{href:{default:null,parseHTML(t){return t.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class}}},parseHTML(){return[{tag:"a[href]",getAttrs:t=>{const e=t.getAttribute("href");return!e||!this.options.isAllowedUri(e,{defaultValidate:n=>!!Nf(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:t}){return this.options.isAllowedUri(t.href,{defaultValidate:e=>!!Nf(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",_i(this.options.HTMLAttributes,t),0]:["a",_i(this.options.HTMLAttributes,{...t,href:""}),0]},markdownTokenName:"link",parseMarkdown:(t,e)=>e.applyMark("link",e.parseInline(t.tokens||[]),{href:t.href,title:t.title||null}),renderMarkdown:(t,e)=>{var n;const r=((n=t.attrs)==null?void 0:n.href)||"";return`[${e.renderChildren(t)}](${r})`},addCommands(){return{setLink:t=>({chain:e})=>{const{href:n}=t;return this.options.isAllowedUri(n,{defaultValidate:r=>!!Nf(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,t).setMeta("preventAutolink",!0).run():!1},toggleLink:t=>({chain:e})=>{const{href:n}=t||{};return n&&!this.options.isAllowedUri(n,{defaultValidate:r=>!!Nf(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:e().toggleMark(this.name,t,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:t})=>t().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[Pm({find:t=>{const e=[];if(t){const{protocols:n,defaultProtocol:r}=this.options,i=are(t).filter(s=>s.isLink&&this.options.isAllowedUri(s.value,{defaultValidate:o=>!!Nf(o,n),protocols:n,defaultProtocol:r}));i.length&&i.forEach(s=>{this.options.shouldAutoLink(s.value)&&e.push({text:s.value,data:{href:s.href},index:s.start})})}return e},type:this.type,getAttributes:t=>{var e;return{href:(e=t.data)==null?void 0:e.href}}})]},addProseMirrorPlugins(){const t=[],{protocols:e,defaultProtocol:n}=this.options;return this.options.autolink&&t.push(g7e({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:i=>!!Nf(i,e),protocols:e,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&t.push(b7e({type:this.type,editor:this.editor,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&t.push(x7e({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),t}}),y7e=sre,v7e=Object.defineProperty,w7e=(t,e)=>{for(var n in e)v7e(t,n,{get:e[n],enumerable:!0})},_7e="listItem",u9="textStyle",d9=/^\s*([-+*])\s$/,ore=Zs.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:t}){return["ul",_i(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>t.type!=="list"||t.ordered?[]:{type:"bulletList",content:t.items?e.parseChildren(t.items):[]},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` -`):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(_7e,this.editor.getAttributes(u9)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let t=bb({find:d9,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(t=bb({find:d9,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(u9),editor:this.editor})),[t]}}),lre=Zs.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:t}){return["li",_i(this.options.HTMLAttributes,t),0]},markdownTokenName:"list_item",parseMarkdown:(t,e)=>{if(t.type!=="list_item")return[];let n=[];if(t.tokens&&t.tokens.length>0)if(t.tokens.some(i=>i.type==="paragraph"))n=e.parseChildren(t.tokens);else{const i=t.tokens[0];if(i&&i.type==="text"&&i.tokens&&i.tokens.length>0){if(n=[{type:"paragraph",content:e.parseInline(i.tokens)}],t.tokens.length>1){const o=t.tokens.slice(1),l=e.parseChildren(o);n.push(...l)}}else n=e.parseChildren(t.tokens)}return n.length===0&&(n=[{type:"paragraph",content:[]}]),{type:"listItem",content:n}},renderMarkdown:(t,e,n)=>oF(t,e,r=>r.parentType==="bulletList"?"- ":r.parentType==="orderedList"?`${r.index+1}. `:"- ",n),addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),S7e={};w7e(S7e,{findListItemPos:()=>kv,getNextListDepth:()=>bF,handleBackspace:()=>pR,handleDelete:()=>gR,hasListBefore:()=>cre,hasListItemAfter:()=>N7e,hasListItemBefore:()=>ure,listItemHasSubList:()=>dre,nextListIsDeeper:()=>hre,nextListIsHigher:()=>fre});var kv=(t,e)=>{const{$from:n}=e.selection,r=qi(t,e.schema);let i=null,s=n.depth,o=n.pos,l=null;for(;s>0&&l===null;)i=n.node(s),i.type===r?l=s:(s-=1,o-=1);return l===null?null:{$pos:e.doc.resolve(o),depth:l}},bF=(t,e)=>{const n=kv(t,e);if(!n)return!1;const[,r]=dGe(e,t,n.$pos.pos+4);return r},cre=(t,e,n)=>{const{$anchor:r}=t.selection,i=Math.max(0,r.pos-2),s=t.doc.resolve(i).node();return!(!s||!n.includes(s.type.name))},ure=(t,e)=>{var n;const{$anchor:r}=e.selection,i=e.doc.resolve(r.pos-2);return!(i.index()===0||((n=i.nodeBefore)==null?void 0:n.type.name)!==t)},dre=(t,e,n)=>{if(!n)return!1;const r=qi(t,e.schema);let i=!1;return n.descendants(s=>{s.type===r&&(i=!0)}),i},pR=(t,e,n)=>{if(t.commands.undoInputRule())return!0;if(t.state.selection.from!==t.state.selection.to)return!1;if(!Bh(t.state,e)&&cre(t.state,e,n)){const{$anchor:l}=t.state.selection,c=t.state.doc.resolve(l.before()-1),u=[];c.node().descendants((p,m)=>{p.type.name===e&&u.push({node:p,pos:m})});const d=u.at(-1);if(!d)return!1;const h=t.state.doc.resolve(c.start()+d.pos+1);return t.chain().cut({from:l.start()-1,to:l.end()+1},h.end()).joinForward().run()}if(!Bh(t.state,e)||!pGe(t.state))return!1;const r=kv(e,t.state);if(!r)return!1;const s=t.state.doc.resolve(r.$pos.pos-2).node(r.depth),o=dre(e,t.state,s);return ure(e,t.state)&&!o?t.commands.joinItemBackward():t.chain().liftListItem(e).run()},hre=(t,e)=>{const n=bF(t,e),r=kv(t,e);return!r||!n?!1:n>r.depth},fre=(t,e)=>{const n=bF(t,e),r=kv(t,e);return!r||!n?!1:n{if(!Bh(t.state,e)||!mGe(t.state,e))return!1;const{selection:n}=t.state,{$from:r,$to:i}=n;return!n.empty&&r.sameParent(i)?!1:hre(e,t.state)?t.chain().focus(t.state.selection.from+4).lift(e).joinBackward().run():fre(e,t.state)?t.chain().joinForward().joinBackward().run():t.commands.joinItemForward()},N7e=(t,e)=>{var n;const{$anchor:r}=e.selection,i=e.doc.resolve(r.pos-r.parentOffset-2);return!(i.index()===i.parent.childCount-1||((n=i.nodeAfter)==null?void 0:n.type.name)!==t)},mre=Dr.create({name:"listKeymap",addOptions(){return{listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}},addKeyboardShortcuts(){return{Delete:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n})=>{t.state.schema.nodes[n]!==void 0&&gR(t,n)&&(e=!0)}),e},"Mod-Delete":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n})=>{t.state.schema.nodes[n]!==void 0&&gR(t,n)&&(e=!0)}),e},Backspace:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{t.state.schema.nodes[n]!==void 0&&pR(t,n,r)&&(e=!0)}),e},"Mod-Backspace":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{t.state.schema.nodes[n]!==void 0&&pR(t,n,r)&&(e=!0)}),e}}}}),h9=/^(\s*)(\d+)\.\s+(.*)$/,k7e=/^\s/;function M7e(t){const e=[];let n=0,r=0;for(;n{const i=e.some(u=>u.docChanged)&&!n.doc.eq(r.doc),s=e.some(u=>u.getMeta("preventAutolink"));if(!i||s)return;const{tr:o}=r,l=kne(n.doc,[...e]);if(jne(l).forEach(({newRange:u})=>{const d=nGe(r.doc,u,m=>m.isTextblock);let h,p;if(d.length>1)h=d[0],p=r.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(d.length){const m=r.doc.textBetween(u.from,u.to," "," ");if(!m7e.test(m))return;h=d[0],p=r.doc.textBetween(h.pos,u.to,void 0," ")}if(h&&p){const m=p.split(f7e).filter(Boolean);if(m.length<=0)return!1;const b=m[m.length-1],y=h.pos+p.lastIndexOf(b);if(!b)return!1;const x=pF(b).map(v=>v.toObject(t.defaultProtocol));if(!g7e(x))return!1;x.filter(v=>v.isLink).map(v=>({...v,from:y+v.start+1,to:y+v.end+1})).filter(v=>r.schema.marks.code?!r.doc.rangeHasMark(v.from,v.to,r.schema.marks.code):!0).filter(v=>t.validate(v.value)).filter(v=>t.shouldAutoLink(v.value)).forEach(v=>{rF(v.from,v.to,r.doc).some(S=>S.mark.type===t.type)||o.addMark(v.from,v.to,t.type.create({href:v.href}))})}}),!!o.steps.length)return o}})}function x7e(t){return new di({key:new ca("handleClickLink"),props:{handleClick:(e,n,r)=>{var i,s;if(r.button!==0||!e.editable)return!1;let o=null;if(r.target instanceof HTMLAnchorElement)o=r.target;else{let d=r.target;const h=[];for(;d.nodeName!=="DIV";)h.push(d),d=d.parentNode;o=h.find(p=>p.nodeName==="A")}if(!o)return!1;const l=Pne(e.state,t.type.name),c=(i=o?.href)!=null?i:l.href,u=(s=o?.target)!=null?s:l.target;return t.enableClickSelection&&t.editor.commands.extendMarkRange(t.type.name),o&&c?(window.open(c,u),!0):!1}}})}function y7e(t){return new di({key:new ca("handlePasteLink"),props:{handlePaste:(e,n,r)=>{const{shouldAutoLink:i}=t,{state:s}=e,{selection:o}=s,{empty:l}=o;if(l)return!1;let c="";r.content.forEach(d=>{c+=d.textContent});const u=are(c,{defaultProtocol:t.defaultProtocol}).find(d=>d.isLink&&d.value===c);return!c||!u||i!==void 0&&!i(u.href)?!1:t.editor.commands.setMark(t.type,{href:u.href})}}})}function Nf(t,e){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(r=>{const i=typeof r=="string"?r:r.scheme;i&&n.push(i)}),!t||t.replace(p7e,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var sre=Kh.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(t=>{if(typeof t=="string"){c9(t);return}c9(t.scheme,t.optionalSlashes)})},onDestroy(){d7e()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(t,e)=>!!Nf(t,e.protocols),validate:t=>!!t,shouldAutoLink:t=>!!t}},addAttributes(){return{href:{default:null,parseHTML(t){return t.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class}}},parseHTML(){return[{tag:"a[href]",getAttrs:t=>{const e=t.getAttribute("href");return!e||!this.options.isAllowedUri(e,{defaultValidate:n=>!!Nf(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:t}){return this.options.isAllowedUri(t.href,{defaultValidate:e=>!!Nf(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",_i(this.options.HTMLAttributes,t),0]:["a",_i(this.options.HTMLAttributes,{...t,href:""}),0]},markdownTokenName:"link",parseMarkdown:(t,e)=>e.applyMark("link",e.parseInline(t.tokens||[]),{href:t.href,title:t.title||null}),renderMarkdown:(t,e)=>{var n;const r=((n=t.attrs)==null?void 0:n.href)||"";return`[${e.renderChildren(t)}](${r})`},addCommands(){return{setLink:t=>({chain:e})=>{const{href:n}=t;return this.options.isAllowedUri(n,{defaultValidate:r=>!!Nf(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,t).setMeta("preventAutolink",!0).run():!1},toggleLink:t=>({chain:e})=>{const{href:n}=t||{};return n&&!this.options.isAllowedUri(n,{defaultValidate:r=>!!Nf(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:e().toggleMark(this.name,t,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:t})=>t().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[Pm({find:t=>{const e=[];if(t){const{protocols:n,defaultProtocol:r}=this.options,i=are(t).filter(s=>s.isLink&&this.options.isAllowedUri(s.value,{defaultValidate:o=>!!Nf(o,n),protocols:n,defaultProtocol:r}));i.length&&i.forEach(s=>{this.options.shouldAutoLink(s.value)&&e.push({text:s.value,data:{href:s.href},index:s.start})})}return e},type:this.type,getAttributes:t=>{var e;return{href:(e=t.data)==null?void 0:e.href}}})]},addProseMirrorPlugins(){const t=[],{protocols:e,defaultProtocol:n}=this.options;return this.options.autolink&&t.push(b7e({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:i=>!!Nf(i,e),protocols:e,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&t.push(x7e({type:this.type,editor:this.editor,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&t.push(y7e({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),t}}),v7e=sre,w7e=Object.defineProperty,_7e=(t,e)=>{for(var n in e)w7e(t,n,{get:e[n],enumerable:!0})},S7e="listItem",u9="textStyle",d9=/^\s*([-+*])\s$/,ore=Zs.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:t}){return["ul",_i(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>t.type!=="list"||t.ordered?[]:{type:"bulletList",content:t.items?e.parseChildren(t.items):[]},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` +`):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(S7e,this.editor.getAttributes(u9)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let t=bb({find:d9,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(t=bb({find:d9,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(u9),editor:this.editor})),[t]}}),lre=Zs.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:t}){return["li",_i(this.options.HTMLAttributes,t),0]},markdownTokenName:"list_item",parseMarkdown:(t,e)=>{if(t.type!=="list_item")return[];let n=[];if(t.tokens&&t.tokens.length>0)if(t.tokens.some(i=>i.type==="paragraph"))n=e.parseChildren(t.tokens);else{const i=t.tokens[0];if(i&&i.type==="text"&&i.tokens&&i.tokens.length>0){if(n=[{type:"paragraph",content:e.parseInline(i.tokens)}],t.tokens.length>1){const o=t.tokens.slice(1),l=e.parseChildren(o);n.push(...l)}}else n=e.parseChildren(t.tokens)}return n.length===0&&(n=[{type:"paragraph",content:[]}]),{type:"listItem",content:n}},renderMarkdown:(t,e,n)=>oF(t,e,r=>r.parentType==="bulletList"?"- ":r.parentType==="orderedList"?`${r.index+1}. `:"- ",n),addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),N7e={};_7e(N7e,{findListItemPos:()=>kv,getNextListDepth:()=>bF,handleBackspace:()=>pR,handleDelete:()=>gR,hasListBefore:()=>cre,hasListItemAfter:()=>k7e,hasListItemBefore:()=>ure,listItemHasSubList:()=>dre,nextListIsDeeper:()=>hre,nextListIsHigher:()=>fre});var kv=(t,e)=>{const{$from:n}=e.selection,r=qi(t,e.schema);let i=null,s=n.depth,o=n.pos,l=null;for(;s>0&&l===null;)i=n.node(s),i.type===r?l=s:(s-=1,o-=1);return l===null?null:{$pos:e.doc.resolve(o),depth:l}},bF=(t,e)=>{const n=kv(t,e);if(!n)return!1;const[,r]=hGe(e,t,n.$pos.pos+4);return r},cre=(t,e,n)=>{const{$anchor:r}=t.selection,i=Math.max(0,r.pos-2),s=t.doc.resolve(i).node();return!(!s||!n.includes(s.type.name))},ure=(t,e)=>{var n;const{$anchor:r}=e.selection,i=e.doc.resolve(r.pos-2);return!(i.index()===0||((n=i.nodeBefore)==null?void 0:n.type.name)!==t)},dre=(t,e,n)=>{if(!n)return!1;const r=qi(t,e.schema);let i=!1;return n.descendants(s=>{s.type===r&&(i=!0)}),i},pR=(t,e,n)=>{if(t.commands.undoInputRule())return!0;if(t.state.selection.from!==t.state.selection.to)return!1;if(!Bh(t.state,e)&&cre(t.state,e,n)){const{$anchor:l}=t.state.selection,c=t.state.doc.resolve(l.before()-1),u=[];c.node().descendants((p,m)=>{p.type.name===e&&u.push({node:p,pos:m})});const d=u.at(-1);if(!d)return!1;const h=t.state.doc.resolve(c.start()+d.pos+1);return t.chain().cut({from:l.start()-1,to:l.end()+1},h.end()).joinForward().run()}if(!Bh(t.state,e)||!gGe(t.state))return!1;const r=kv(e,t.state);if(!r)return!1;const s=t.state.doc.resolve(r.$pos.pos-2).node(r.depth),o=dre(e,t.state,s);return ure(e,t.state)&&!o?t.commands.joinItemBackward():t.chain().liftListItem(e).run()},hre=(t,e)=>{const n=bF(t,e),r=kv(t,e);return!r||!n?!1:n>r.depth},fre=(t,e)=>{const n=bF(t,e),r=kv(t,e);return!r||!n?!1:n{if(!Bh(t.state,e)||!pGe(t.state,e))return!1;const{selection:n}=t.state,{$from:r,$to:i}=n;return!n.empty&&r.sameParent(i)?!1:hre(e,t.state)?t.chain().focus(t.state.selection.from+4).lift(e).joinBackward().run():fre(e,t.state)?t.chain().joinForward().joinBackward().run():t.commands.joinItemForward()},k7e=(t,e)=>{var n;const{$anchor:r}=e.selection,i=e.doc.resolve(r.pos-r.parentOffset-2);return!(i.index()===i.parent.childCount-1||((n=i.nodeAfter)==null?void 0:n.type.name)!==t)},mre=Dr.create({name:"listKeymap",addOptions(){return{listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}},addKeyboardShortcuts(){return{Delete:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n})=>{t.state.schema.nodes[n]!==void 0&&gR(t,n)&&(e=!0)}),e},"Mod-Delete":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n})=>{t.state.schema.nodes[n]!==void 0&&gR(t,n)&&(e=!0)}),e},Backspace:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{t.state.schema.nodes[n]!==void 0&&pR(t,n,r)&&(e=!0)}),e},"Mod-Backspace":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{t.state.schema.nodes[n]!==void 0&&pR(t,n,r)&&(e=!0)}),e}}}}),h9=/^(\s*)(\d+)\.\s+(.*)$/,M7e=/^\s/;function E7e(t){const e=[];let n=0,r=0;for(;ne;)p.push(t[h]),h+=1;if(p.length>0){const m=Math.min(...p.map(y=>y.indent)),b=pre(p,m,n);u.push({type:"list",ordered:!0,start:p[0].number,items:b,raw:p.map(y=>y.raw).join(` -`)})}i.push({type:"list_item",raw:o.raw,tokens:u}),s=h}else s+=1}return i}function E7e(t,e){return t.map(n=>{if(n.type!=="list_item")return e.parseChildren([n])[0];const r=[];return n.tokens&&n.tokens.length>0&&n.tokens.forEach(i=>{if(i.type==="paragraph"||i.type==="list"||i.type==="blockquote"||i.type==="code")r.push(...e.parseChildren([i]));else if(i.type==="text"&&i.tokens){const s=e.parseChildren([i]);r.push({type:"paragraph",content:s})}else{const s=e.parseChildren([i]);s.length>0&&r.push(...s)}}),{type:"listItem",content:r}})}var T7e="listItem",f9="textStyle",m9=/^(\d+)\.\s$/,gre=Zs.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:t=>t.hasAttribute("start")?parseInt(t.getAttribute("start")||"",10):1},type:{default:null,parseHTML:t=>t.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:t}){const{start:e,...n}=t;return e===1?["ol",_i(this.options.HTMLAttributes,n),0]:["ol",_i(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>{if(t.type!=="list"||!t.ordered)return[];const n=t.start||1,r=t.items?E7e(t.items,e):[];return n!==1?{type:"orderedList",attrs:{start:n},content:r}:{type:"orderedList",content:r}},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` +`)})}i.push({type:"list_item",raw:o.raw,tokens:u}),s=h}else s+=1}return i}function T7e(t,e){return t.map(n=>{if(n.type!=="list_item")return e.parseChildren([n])[0];const r=[];return n.tokens&&n.tokens.length>0&&n.tokens.forEach(i=>{if(i.type==="paragraph"||i.type==="list"||i.type==="blockquote"||i.type==="code")r.push(...e.parseChildren([i]));else if(i.type==="text"&&i.tokens){const s=e.parseChildren([i]);r.push({type:"paragraph",content:s})}else{const s=e.parseChildren([i]);s.length>0&&r.push(...s)}}),{type:"listItem",content:r}})}var A7e="listItem",f9="textStyle",m9=/^(\d+)\.\s$/,gre=Zs.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:t=>t.hasAttribute("start")?parseInt(t.getAttribute("start")||"",10):1},type:{default:null,parseHTML:t=>t.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:t}){const{start:e,...n}=t;return e===1?["ol",_i(this.options.HTMLAttributes,n),0]:["ol",_i(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>{if(t.type!=="list"||!t.ordered)return[];const n=t.start||1,r=t.items?T7e(t.items,e):[];return n!==1?{type:"orderedList",attrs:{start:n},content:r}:{type:"orderedList",content:r}},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` `):"",markdownTokenizer:{name:"orderedList",level:"block",start:t=>{const e=t.match(/^(\s*)(\d+)\.\s+/),n=e?.index;return n!==void 0?n:-1},tokenize:(t,e,n)=>{var r;const i=t.split(` -`),[s,o]=M7e(i);if(s.length===0)return;const l=pre(s,0,n);return l.length===0?void 0:{type:"list",ordered:!0,start:((r=s[0])==null?void 0:r.number)||1,items:l,raw:i.slice(0,o).join(` -`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(T7e,this.editor.getAttributes(f9)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let t=bb({find:m9,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:(e,n)=>n.childCount+n.attrs.start===+e[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(t=bb({find:m9,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(f9)}),joinPredicate:(e,n)=>n.childCount+n.attrs.start===+e[1],editor:this.editor})),[t]}}),A7e=/^\s*(\[([( |x])?\])\s$/,C7e=Zs.create({name:"taskItem",addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}},content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:t=>{const e=t.getAttribute("data-checked");return e===""||e==="true"},renderHTML:t=>({"data-checked":t.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51}]},renderHTML({node:t,HTMLAttributes:e}){return["li",_i(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:t.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(t,e)=>{const n=[];if(t.tokens&&t.tokens.length>0?n.push(e.createNode("paragraph",{},e.parseInline(t.tokens))):t.text?n.push(e.createNode("paragraph",{},[e.createNode("text",{text:t.text})])):n.push(e.createNode("paragraph",{},[])),t.nestedTokens&&t.nestedTokens.length>0){const r=e.parseChildren(t.nestedTokens);n.push(...r)}return e.createNode("taskItem",{checked:t.checked||!1},n)},renderMarkdown:(t,e)=>{var n;const i=`- [${(n=t.attrs)!=null&&n.checked?"x":" "}] `;return oF(t,e,i)},addKeyboardShortcuts(){const t={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...t,Tab:()=>this.editor.commands.sinkListItem(this.name)}:t},addNodeView(){return({node:t,HTMLAttributes:e,getPos:n,editor:r})=>{const i=document.createElement("li"),s=document.createElement("label"),o=document.createElement("span"),l=document.createElement("input"),c=document.createElement("div"),u=d=>{var h,p;l.ariaLabel=((p=(h=this.options.a11y)==null?void 0:h.checkboxLabel)==null?void 0:p.call(h,d,l.checked))||`Task item checkbox for ${d.textContent||"empty task item"}`};return u(t),s.contentEditable="false",l.type="checkbox",l.addEventListener("mousedown",d=>d.preventDefault()),l.addEventListener("change",d=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){l.checked=!l.checked;return}const{checked:h}=d.target;r.isEditable&&typeof n=="function"&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:p})=>{const m=n();if(typeof m!="number")return!1;const b=p.doc.nodeAt(m);return p.setNodeMarkup(m,void 0,{...b?.attrs,checked:h}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(t,h)||(l.checked=!l.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([d,h])=>{i.setAttribute(d,h)}),i.dataset.checked=t.attrs.checked,l.checked=t.attrs.checked,s.append(l,o),i.append(s,c),Object.entries(e).forEach(([d,h])=>{i.setAttribute(d,h)}),{dom:i,contentDOM:c,update:d=>d.type!==this.type?!1:(i.dataset.checked=d.attrs.checked,l.checked=d.attrs.checked,u(d),!0)}}},addInputRules(){return[bb({find:A7e,type:this.type,getAttributes:t=>({checked:t[t.length-1]==="x"})})]}}),P7e=Zs.create({name:"taskList",addOptions(){return{itemTypeName:"taskItem",HTMLAttributes:{}}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:t}){return["ul",_i(this.options.HTMLAttributes,t,{"data-type":this.name}),0]},parseMarkdown:(t,e)=>e.createNode("taskList",{},e.parseChildren(t.items||[])),renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` -`):"",markdownTokenizer:{name:"taskList",level:"block",start(t){var e;const n=(e=t.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))==null?void 0:e.index;return n!==void 0?n:-1},tokenize(t,e,n){const r=s=>{const o=aR(s,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:l=>({indentLevel:l[1].length,mainContent:l[4],checked:l[3].toLowerCase()==="x"}),createToken:(l,c)=>({type:"taskItem",raw:"",mainContent:l.mainContent,indentLevel:l.indentLevel,checked:l.checked,text:l.mainContent,tokens:n.inlineTokens(l.mainContent),nestedTokens:c}),customNestedParser:r},n);return o?[{type:"taskList",raw:o.raw,items:o.items}]:n.blockTokens(s)},i=aR(t,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:s=>({indentLevel:s[1].length,mainContent:s[4],checked:s[3].toLowerCase()==="x"}),createToken:(s,o)=>({type:"taskItem",raw:"",mainContent:s.mainContent,indentLevel:s.indentLevel,checked:s.checked,text:s.mainContent,tokens:n.inlineTokens(s.mainContent),nestedTokens:o}),customNestedParser:r},n);if(i)return{type:"taskList",raw:i.raw,items:i.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:t})=>t.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});Dr.create({name:"listKit",addExtensions(){const t=[];return this.options.bulletList!==!1&&t.push(ore.configure(this.options.bulletList)),this.options.listItem!==!1&&t.push(lre.configure(this.options.listItem)),this.options.listKeymap!==!1&&t.push(mre.configure(this.options.listKeymap)),this.options.orderedList!==!1&&t.push(gre.configure(this.options.orderedList)),this.options.taskItem!==!1&&t.push(C7e.configure(this.options.taskItem)),this.options.taskList!==!1&&t.push(P7e.configure(this.options.taskList)),t}});var j7e=Zs.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",_i(this.options.HTMLAttributes,t),0]},parseMarkdown:(t,e)=>{const n=t.tokens||[];return n.length===1&&n[0].type==="image"?e.parseChildren([n[0]]):e.createNode("paragraph",void 0,e.parseInline(n))},renderMarkdown:(t,e)=>!t||!Array.isArray(t.content)?"":e.renderChildren(t.content),addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),D7e=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,R7e=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,O7e=Kh.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:t=>t.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:t}){return["s",_i(this.options.HTMLAttributes,t),0]},markdownTokenName:"del",parseMarkdown:(t,e)=>e.applyMark("strike",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`~~${e.renderChildren(t)}~~`,addCommands(){return{setStrike:()=>({commands:t})=>t.setMark(this.name),toggleStrike:()=>({commands:t})=>t.toggleMark(this.name),unsetStrike:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[gb({find:D7e,type:this.type})]},addPasteRules(){return[Pm({find:R7e,type:this.type})]}}),L7e=Zs.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),bre=Kh.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:t=>t.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:t}){return["u",_i(this.options.HTMLAttributes,t),0]},parseMarkdown(t,e){return e.applyMark(this.name||"underline",e.parseInline(t.tokens||[]))},renderMarkdown(t,e){return`++${e.renderChildren(t)}++`},markdownTokenizer:{name:"underline",level:"inline",start(t){return t.indexOf("++")},tokenize(t,e,n){const i=/^(\+\+)([\s\S]+?)(\+\+)/.exec(t);if(!i)return;const s=i[2].trim();return{type:"underline",raw:i[0],text:s,tokens:n.inlineTokens(s)}}},addCommands(){return{setUnderline:()=>({commands:t})=>t.setMark(this.name),toggleUnderline:()=>({commands:t})=>t.toggleMark(this.name),unsetUnderline:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}}),F7e=bre;function I7e(t={}){return new di({view(e){return new z7e(e,t)}})}class z7e{constructor(e,n){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(i=>{let s=o=>{this[i](o)};return e.dom.addEventListener(i,s),{name:i,handler:s}})}destroy(){this.handlers.forEach(({name:e,handler:n})=>this.editorView.dom.removeEventListener(e,n))}update(e,n){this.cursorPos!=null&&n.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),n=!e.parent.inlineContent,r,i=this.editorView.dom,s=i.getBoundingClientRect(),o=s.width/i.offsetWidth,l=s.height/i.offsetHeight;if(n){let h=e.nodeBefore,p=e.nodeAfter;if(h||p){let m=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(m){let b=m.getBoundingClientRect(),y=h?b.bottom:b.top;h&&p&&(y=(y+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let x=this.width/2*l;r={left:b.left,right:b.right,top:y-x,bottom:y+x}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),p=this.width/2*o;r={left:h.left-p,right:h.left+p,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let u,d;if(!c||c==document.body&&getComputedStyle(c).position=="static")u=-pageXOffset,d=-pageYOffset;else{let h=c.getBoundingClientRect(),p=h.width/c.offsetWidth,m=h.height/c.offsetHeight;u=h.left-c.scrollLeft*p,d=h.top-c.scrollTop*m}this.element.style.left=(r.left-u)/o+"px",this.element.style.top=(r.top-d)/l+"px",this.element.style.width=(r.right-r.left)/o+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),i=r&&r.type.spec.disableDropCursor,s=typeof i=="function"?i(this.editorView,n,e):i;if(n&&!s){let o=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=bte(this.editorView.state.doc,o,this.editorView.dragging.slice);l!=null&&(o=l)}this.setCursor(o),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}}class bi extends Fn{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return bi.valid(r)?new bi(r):Fn.near(r)}content(){return $t.empty}eq(e){return e instanceof bi&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new bi(e.resolve(n.pos))}getBookmark(){return new xF(this.anchor)}static valid(e){let n=e.parent;if(n.isTextblock||!U7e(e)||!B7e(e))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let i=n.contentMatchAt(e.index()).defaultType;return i&&i.isTextblock}static findGapCursorFrom(e,n,r=!1){e:for(;;){if(!r&&bi.valid(e))return e;let i=e.pos,s=null;for(let o=e.depth;;o--){let l=e.node(o);if(n>0?e.indexAfter(o)0){s=l.child(n>0?e.indexAfter(o):e.index(o)-1);break}else if(o==0)return null;i+=n;let c=e.doc.resolve(i);if(bi.valid(c))return c}for(;;){let o=n>0?s.firstChild:s.lastChild;if(!o){if(s.isAtom&&!s.isText&&!rn.isSelectable(s)){e=e.doc.resolve(i+s.nodeSize*n),r=!1;continue e}break}s=o,i+=n;let l=e.doc.resolve(i);if(bi.valid(l))return l}return null}}}bi.prototype.visible=!1;bi.findFrom=bi.findGapCursorFrom;Fn.jsonID("gapcursor",bi);class xF{constructor(e){this.pos=e}map(e){return new xF(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return bi.valid(n)?new bi(n):Fn.near(n)}}function xre(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function U7e(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(n-1);;i=i.lastChild){if(i.childCount==0&&!i.inlineContent||xre(i.type))return!0;if(i.inlineContent)return!1}}return!0}function B7e(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(n);;i=i.firstChild){if(i.childCount==0&&!i.inlineContent||xre(i.type))return!0;if(i.inlineContent)return!1}}return!0}function H7e(){return new di({props:{decorations:q7e,createSelectionBetween(t,e,n){return e.pos==n.pos&&bi.valid(n)?new bi(n):null},handleClick:V7e,handleKeyDown:$7e,handleDOMEvents:{beforeinput:G7e}}})}const $7e=bne({ArrowLeft:p1("horiz",-1),ArrowRight:p1("horiz",1),ArrowUp:p1("vert",-1),ArrowDown:p1("vert",1)});function p1(t,e){const n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,i,s){let o=r.selection,l=e>0?o.$to:o.$from,c=o.empty;if(o instanceof yn){if(!s.endOfTextblock(n)||l.depth==0)return!1;c=!1,l=r.doc.resolve(e>0?l.after():l.before())}let u=bi.findGapCursorFrom(l,e,c);return u?(i&&i(r.tr.setSelection(new bi(u))),!0):!1}}function V7e(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!bi.valid(r))return!1;let i=t.posAtCoords({left:n.clientX,top:n.clientY});return i&&i.inside>-1&&rn.isSelectable(t.state.doc.nodeAt(i.inside))?!1:(t.dispatch(t.state.tr.setSelection(new bi(r))),!0)}function G7e(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof bi))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let i=At.empty;for(let o=r.length-1;o>=0;o--)i=At.from(r[o].createAndFill(null,i));let s=t.state.tr.replace(n.pos,n.pos,new $t(i,0,0));return s.setSelection(yn.near(s.doc.resolve(n.pos+1))),t.dispatch(s),!1}function q7e(t){if(!(t.selection instanceof bi))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",oi.create(t.doc,[_s.widget(t.selection.head,e,{key:"gapcursor"})])}var nk=200,Sa=function(){};Sa.prototype.append=function(e){return e.length?(e=Sa.from(e),!this.length&&e||e.length=n?Sa.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))};Sa.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};Sa.prototype.forEach=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(e,n,r,0):this.forEachInvertedInner(e,n,r,0)};Sa.prototype.map=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},n,r),i};Sa.from=function(e){return e instanceof Sa?e:e&&e.length?new yre(e):Sa.empty};var yre=(function(t){function e(r){t.call(this),this.values=r}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var c=s;c=o;c--)if(i(this.values[c],l+c)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=nk)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=nk)return new e(i.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(e.prototype,n),e})(Sa);Sa.empty=new yre([]);var W7e=(function(t){function e(n,r){t.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.depth)+1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(Sa);const K7e=500;class Rl{constructor(e,n){this.items=e,this.eventCount=n}popEvent(e,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;n&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,c,u=[],d=[];return this.items.forEach((h,p)=>{if(!h.step){i||(i=this.remapping(r,p+1),s=i.maps.length),s--,d.push(h);return}if(i){d.push(new tc(h.map));let m=h.step.map(i.slice(s)),b;m&&o.maybeStep(m).doc&&(b=o.mapping.maps[o.mapping.maps.length-1],u.push(new tc(b,void 0,void 0,u.length+d.length))),s--,b&&i.appendMap(b,s)}else o.maybeStep(h.step);if(h.selection)return l=i?h.selection.map(i.slice(s)):h.selection,c=new Rl(this.items.slice(0,r).append(d.reverse().concat(u)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:o,selection:l}}addTransform(e,n,r,i){let s=[],o=this.eventCount,l=this.items,c=!i&&l.length?l.get(l.length-1):null;for(let d=0;dY7e&&(l=X7e(l,u),o-=u),new Rl(l.append(s),o)}remapping(e,n){let r=new Ty;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,n),r}addMaps(e){return this.eventCount==0?this:new Rl(this.items.append(e.map(n=>new tc(n))),this.eventCount)}rebased(e,n){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-n),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(p=>{p.selection&&l--},i);let c=n;this.items.forEach(p=>{let m=s.getMirror(--c);if(m==null)return;o=Math.min(o,m);let b=s.maps[m];if(p.step){let y=e.steps[m].invert(e.docs[m]),x=p.selection&&p.selection.map(s.slice(c+1,m));x&&l++,r.push(new tc(b,y,x))}else r.push(new tc(b))},i);let u=[];for(let p=n;pK7e&&(h=h.compress(this.items.length-r.length)),h}emptyItemCount(){let e=0;return this.items.forEach(n=>{n.step||e++}),e}compress(e=this.items.length){let n=this.remapping(0,e),r=n.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let c=o.step.map(n.slice(r)),u=c&&c.getMap();if(r--,u&&n.appendMap(u,r),c){let d=o.selection&&o.selection.map(n.slice(r));d&&s++;let h=new tc(u.invert(),c,d),p,m=i.length-1;(p=i.length&&i[m].merge(h))?i[m]=p:i.push(h)}}else o.map&&r--},this.items.length,0),new Rl(Sa.from(i.reverse()),s)}}Rl.empty=new Rl(Sa.empty,0);function X7e(t,e){let n;return t.forEach((r,i)=>{if(r.selection&&e--==0)return n=i,!1}),t.slice(n)}class tc{constructor(e,n,r,i){this.map=e,this.step=n,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let n=e.step.merge(this.step);if(n)return new tc(n.getMap().invert(),n,this.selection)}}}class th{constructor(e,n,r,i,s){this.done=e,this.undone=n,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const Y7e=20;function Q7e(t,e,n,r){let i=n.getMeta(om),s;if(i)return i.historyState;n.getMeta(e9e)&&(t=new th(t.done,t.undone,null,0,-1));let o=n.getMeta("appendedTransaction");if(n.steps.length==0)return t;if(o&&o.getMeta(om))return o.getMeta(om).redo?new th(t.done.addTransform(n,void 0,r,G1(e)),t.undone,p9(n.mapping.maps),t.prevTime,t.prevComposition):new th(t.done,t.undone.addTransform(n,void 0,r,G1(e)),null,t.prevTime,t.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=n.getMeta("composition"),c=t.prevTime==0||!o&&t.prevComposition!=l&&(t.prevTime<(n.time||0)-r.newGroupDelay||!Z7e(n,t.prevRanges)),u=o?WP(t.prevRanges,n.mapping):p9(n.mapping.maps);return new th(t.done.addTransform(n,c?e.selection.getBookmark():void 0,r,G1(e)),Rl.empty,u,n.time,l??t.prevComposition)}else return(s=n.getMeta("rebased"))?new th(t.done.rebased(n,s),t.undone.rebased(n,s),WP(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new th(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),WP(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function Z7e(t,e){if(!e)return!1;if(!t.docChanged)return!0;let n=!1;return t.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(n=!0)}),n}function p9(t){let e=[];for(let n=t.length-1;n>=0&&e.length==0;n--)t[n].forEach((r,i,s,o)=>e.push(s,o));return e}function WP(t,e){if(!t)return null;let n=[];for(let r=0;r{let i=om.getState(n);if(!i||(t?i.undone:i.done).eventCount==0)return!1;if(r){let s=J7e(i,n,t);s&&r(e?s.scrollIntoView():s)}return!0}}const wre=vre(!1,!0),_re=vre(!0,!0);Dr.create({name:"characterCount",addOptions(){return{limit:null,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=t=>{const e=t?.node||this.editor.state.doc;if((t?.mode||this.options.mode)==="textSize"){const r=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(r)}return e.nodeSize},this.storage.words=t=>{const e=t?.node||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new di({key:new ca("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;const i=this.options.limit;if(i==null||i===0){t=!0;return}const s=this.storage.characters({node:r.doc});if(s>i){const o=s-i,l=0,c=o;console.warn(`[CharacterCount] Initial content exceeded limit of ${i} characters. Content was automatically trimmed.`);const u=r.tr.deleteRange(l,c);return t=!0,u}t=!0},filterTransaction:(e,n)=>{const r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;const i=this.storage.characters({node:n.doc}),s=this.storage.characters({node:e.doc});if(s<=r||i>r&&s>r&&s<=i)return!0;if(i>r&&s>r&&s>i||!e.getMeta("paste"))return!1;const l=e.selection.$head.pos,c=s-r,u=l-c,d=l;return e.deleteRange(u,d),!(this.storage.characters({node:e.doc})>r)}})]}});var n9e=Dr.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[I7e(this.options)]}});Dr.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new di({key:new ca("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:i}=e,s=[];if(!n||!r)return oi.create(t,[]);let o=0;this.options.mode==="deepest"&&t.descendants((c,u)=>{if(c.isText)return;if(!(i>=u&&i<=u+c.nodeSize-1))return!1;o+=1});let l=0;return t.descendants((c,u)=>{if(c.isText||!(i>=u&&i<=u+c.nodeSize-1))return!1;if(l+=1,this.options.mode==="deepest"&&o-l>0||this.options.mode==="shallowest"&&l>1)return this.options.mode==="deepest";s.push(_s.node(u,u+c.nodeSize,{class:this.options.className}))}),oi.create(t,s)}}})]}});var r9e=Dr.create({name:"gapCursor",addProseMirrorPlugins(){return[H7e()]},extendNodeSchema(t){var e;const n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=xr(tn(t,"allowGapCursor",n)))!=null?e:null}}});Dr.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[new di({key:new ca("placeholder"),props:{decorations:({doc:t,selection:e})=>{const n=this.editor.isEditable||!this.options.showOnlyWhenEditable,{anchor:r}=e,i=[];if(!n)return null;const s=this.editor.isEmpty;return t.descendants((o,l)=>{const c=r>=l&&r<=l+o.nodeSize,u=!o.isLeaf&&VM(o);if((c||!this.options.showOnlyCurrent)&&u){const d=[this.options.emptyNodeClass];s&&d.push(this.options.emptyEditorClass);const h=_s.node(l,l+o.nodeSize,{class:d.join(" "),"data-placeholder":typeof this.options.placeholder=="function"?this.options.placeholder({editor:this.editor,node:o,pos:l,hasAnchor:c}):this.options.placeholder});i.push(h)}return this.options.includeChildren}),oi.create(t,i)}}})]}});Dr.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:t,options:e}=this;return[new di({key:new ca("selection"),props:{decorations(n){return n.selection.empty||t.isFocused||!t.isEditable||Dne(n.selection)||t.view.dragging?null:oi.create(n.doc,[_s.inline(n.selection.from,n.selection.to,{class:e.className})])}}})]}});function b9({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||e?.type===t}var i9e=Dr.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;const e=new ca(this.name),n=this.options.node||((t=this.editor.schema.topNodeType.contentMatch.defaultType)==null?void 0:t.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,i])=>i).filter(i=>(this.options.notAfter||[]).concat(n).includes(i.name));return[new di({key:e,appendTransaction:(i,s,o)=>{const{doc:l,tr:c,schema:u}=o,d=e.getState(o),h=l.content.size,p=u.nodes[n];if(d)return c.insert(h,p.create())},state:{init:(i,s)=>{const o=s.tr.doc.lastChild;return!b9({node:o,types:r})},apply:(i,s)=>{if(!i.docChanged||i.getMeta("__uniqueIDTransaction"))return s;const o=i.doc.lastChild;return!b9({node:o,types:r})}}})]}}),a9e=Dr.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>wre(t,e),redo:()=>({state:t,dispatch:e})=>_re(t,e)}},addProseMirrorPlugins(){return[t9e(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}}),s9e=Dr.create({name:"starterKit",addExtensions(){var t,e,n,r;const i=[];return this.options.bold!==!1&&i.push(Dqe.configure(this.options.bold)),this.options.blockquote!==!1&&i.push(Tqe.configure(this.options.blockquote)),this.options.bulletList!==!1&&i.push(ore.configure(this.options.bulletList)),this.options.code!==!1&&i.push(Lqe.configure(this.options.code)),this.options.codeBlock!==!1&&i.push(zqe.configure(this.options.codeBlock)),this.options.document!==!1&&i.push(Uqe.configure(this.options.document)),this.options.dropcursor!==!1&&i.push(n9e.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&i.push(r9e.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&i.push(Bqe.configure(this.options.hardBreak)),this.options.heading!==!1&&i.push(Hqe.configure(this.options.heading)),this.options.undoRedo!==!1&&i.push(a9e.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&i.push($qe.configure(this.options.horizontalRule)),this.options.italic!==!1&&i.push(Kqe.configure(this.options.italic)),this.options.listItem!==!1&&i.push(lre.configure(this.options.listItem)),this.options.listKeymap!==!1&&i.push(mre.configure((t=this.options)==null?void 0:t.listKeymap)),this.options.link!==!1&&i.push(sre.configure((e=this.options)==null?void 0:e.link)),this.options.orderedList!==!1&&i.push(gre.configure(this.options.orderedList)),this.options.paragraph!==!1&&i.push(j7e.configure(this.options.paragraph)),this.options.strike!==!1&&i.push(O7e.configure(this.options.strike)),this.options.text!==!1&&i.push(L7e.configure(this.options.text)),this.options.underline!==!1&&i.push(bre.configure((n=this.options)==null?void 0:n.underline)),this.options.trailingNode!==!1&&i.push(i9e.configure((r=this.options)==null?void 0:r.trailingNode)),i}}),o9e=s9e,l9e=Dr.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:t=>{const e=t.style.textAlign;return this.options.alignments.includes(e)?e:this.options.defaultAlignment},renderHTML:t=>t.textAlign?{style:`text-align: ${t.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:t=>({commands:e})=>this.options.alignments.includes(t)?this.options.types.map(n=>e.updateAttributes(n,{textAlign:t})).some(n=>n):!1,unsetTextAlign:()=>({commands:t})=>this.options.types.map(e=>t.resetAttributes(e,"textAlign")).some(e=>e),toggleTextAlign:t=>({editor:e,commands:n})=>this.options.alignments.includes(t)?e.isActive({textAlign:t})?n.unsetTextAlign():n.setTextAlign(t):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),c9e=l9e,u9e=20,Sre=(t,e=0)=>{const n=[];return!t.children.length||e>u9e||Array.from(t.children).forEach(r=>{r.tagName==="SPAN"?n.push(r):r.children.length&&n.push(...Sre(r,e+1))}),n},d9e=t=>{if(!t.children.length)return;const e=Sre(t);e&&e.forEach(n=>{var r,i;const s=n.getAttribute("style"),o=(i=(r=n.parentElement)==null?void 0:r.closest("span"))==null?void 0:i.getAttribute("style");n.setAttribute("style",`${o};${s}`)})},Nre=Kh.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!0}},parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&d9e(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",_i(this.options.HTMLAttributes,t),0]},addCommands(){return{toggleTextStyle:t=>({commands:e})=>e.toggleMark(this.name,t),removeEmptyTextStyle:()=>({tr:t})=>{const{selection:e}=t;return t.doc.nodesBetween(e.from,e.to,(n,r)=>{if(n.isTextblock)return!0;n.marks.filter(i=>i.type===this.type).some(i=>Object.values(i.attrs).some(s=>!!s))||t.removeMark(r,r+n.nodeSize,this.type)}),!0}}}}),h9e=Dr.create({name:"backgroundColor",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{backgroundColor:{default:null,parseHTML:t=>{var e;const n=t.getAttribute("style");if(n){const r=n.split(";").map(i=>i.trim()).filter(Boolean);for(let i=r.length-1;i>=0;i-=1){const s=r[i].split(":");if(s.length>=2){const o=s[0].trim().toLowerCase(),l=s.slice(1).join(":").trim();if(o==="background-color")return l.replace(/['"]+/g,"")}}}return(e=t.style.backgroundColor)==null?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.backgroundColor?{style:`background-color: ${t.backgroundColor}`}:{}}}}]},addCommands(){return{setBackgroundColor:t=>({chain:e})=>e().setMark("textStyle",{backgroundColor:t}).run(),unsetBackgroundColor:()=>({chain:t})=>t().setMark("textStyle",{backgroundColor:null}).removeEmptyTextStyle().run()}}}),kre=Dr.create({name:"color",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:t=>{var e;const n=t.getAttribute("style");if(n){const r=n.split(";").map(i=>i.trim()).filter(Boolean);for(let i=r.length-1;i>=0;i-=1){const s=r[i].split(":");if(s.length>=2){const o=s[0].trim().toLowerCase(),l=s.slice(1).join(":").trim();if(o==="color")return l.replace(/['"]+/g,"")}}}return(e=t.style.color)==null?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.color?{style:`color: ${t.color}`}:{}}}}]},addCommands(){return{setColor:t=>({chain:e})=>e().setMark("textStyle",{color:t}).run(),unsetColor:()=>({chain:t})=>t().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()}}}),f9e=Dr.create({name:"fontFamily",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontFamily:{default:null,parseHTML:t=>t.style.fontFamily,renderHTML:t=>t.fontFamily?{style:`font-family: ${t.fontFamily}`}:{}}}}]},addCommands(){return{setFontFamily:t=>({chain:e})=>e().setMark("textStyle",{fontFamily:t}).run(),unsetFontFamily:()=>({chain:t})=>t().setMark("textStyle",{fontFamily:null}).removeEmptyTextStyle().run()}}}),m9e=Dr.create({name:"fontSize",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:t=>t.style.fontSize,renderHTML:t=>t.fontSize?{style:`font-size: ${t.fontSize}`}:{}}}}]},addCommands(){return{setFontSize:t=>({chain:e})=>e().setMark("textStyle",{fontSize:t}).run(),unsetFontSize:()=>({chain:t})=>t().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()}}}),p9e=Dr.create({name:"lineHeight",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{lineHeight:{default:null,parseHTML:t=>t.style.lineHeight,renderHTML:t=>t.lineHeight?{style:`line-height: ${t.lineHeight}`}:{}}}}]},addCommands(){return{setLineHeight:t=>({chain:e})=>e().setMark("textStyle",{lineHeight:t}).run(),unsetLineHeight:()=>({chain:t})=>t().setMark("textStyle",{lineHeight:null}).removeEmptyTextStyle().run()}}});Dr.create({name:"textStyleKit",addExtensions(){const t=[];return this.options.backgroundColor!==!1&&t.push(h9e.configure(this.options.backgroundColor)),this.options.color!==!1&&t.push(kre.configure(this.options.color)),this.options.fontFamily!==!1&&t.push(f9e.configure(this.options.fontFamily)),this.options.fontSize!==!1&&t.push(m9e.configure(this.options.fontSize)),this.options.lineHeight!==!1&&t.push(p9e.configure(this.options.lineHeight)),this.options.textStyle!==!1&&t.push(Nre.configure(this.options.textStyle)),t}});var g9e=kre,b9e=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,x9e=Zs.create({name:"image",addOptions(){return{inline:!1,allowBase64:!1,HTMLAttributes:{},resize:!1}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},alt:{default:null},title:{default:null},width:{default:null},height:{default:null}}},parseHTML(){return[{tag:this.options.allowBase64?"img[src]":'img[src]:not([src^="data:"])'}]},renderHTML({HTMLAttributes:t}){return["img",_i(this.options.HTMLAttributes,t)]},parseMarkdown:(t,e)=>e.createNode("image",{src:t.href,title:t.title,alt:t.text}),renderMarkdown:t=>{var e,n,r,i,s,o;const l=(n=(e=t.attrs)==null?void 0:e.src)!=null?n:"",c=(i=(r=t.attrs)==null?void 0:r.alt)!=null?i:"",u=(o=(s=t.attrs)==null?void 0:s.title)!=null?o:"";return u?`![${c}](${l} "${u}")`:`![${c}](${l})`},addNodeView(){if(!this.options.resize||!this.options.resize.enabled||typeof document>"u"||!this.editor.isEditable)return null;const{directions:t,minWidth:e,minHeight:n,alwaysPreserveAspectRatio:r}=this.options.resize;return({node:i,getPos:s,HTMLAttributes:o})=>{const l=document.createElement("img");Object.entries(o).forEach(([d,h])=>{if(h!=null)switch(d){case"width":case"height":break;default:l.setAttribute(d,h);break}}),l.src=o.src;const c=new JGe({element:l,node:i,getPos:s,onResize:(d,h)=>{l.style.width=`${d}px`,l.style.height=`${h}px`},onCommit:(d,h)=>{const p=s();p!==void 0&&this.editor.chain().setNodeSelection(p).updateAttributes(this.name,{width:d,height:h}).run()},onUpdate:(d,h,p)=>d.type===i.type,options:{directions:t,min:{width:e,height:n},preserveAspectRatio:r===!0}}),u=c.dom;return u.style.visibility="hidden",u.style.pointerEvents="none",l.onload=()=>{u.style.visibility="",u.style.pointerEvents=""},c}},addCommands(){return{setImage:t=>({commands:e})=>e.insertContent({type:this.name,attrs:t})}},addInputRules(){return[Kne({find:b9e,type:this.type,getAttributes:t=>{const[,,e,n,r]=t;return{src:n,alt:e,title:r}}})]}}),y9e=x9e;function bR({content:t,onChange:e,placeholder:n}){const{t:r}=Yt(),i=Sqe({extensions:[o9e.configure({heading:!1,codeBlock:!1,code:!1}),F7e,y7e.configure({openOnClick:!1,HTMLAttributes:{target:"_blank",rel:"noopener noreferrer"}}),c9e.configure({types:["paragraph"]}),Nre,g9e,y9e.configure({HTMLAttributes:{style:"max-width: 100%; height: auto;"}})],content:t,onUpdate:({editor:l})=>{e(l.getHTML())},editorProps:{attributes:{class:"prose prose-invert prose-sm max-w-none focus:outline-none min-h-[120px] px-3 py-2",placeholder:n||""}}});if(!i)return null;const s=({onClick:l,isActive:c=!1,children:u,title:d})=>a.jsx("button",{type:"button",onClick:l,title:d,className:`p-1.5 rounded hover:bg-bambu-dark-tertiary transition-colors ${c?"bg-bambu-dark-tertiary text-bambu-green":"text-bambu-gray"}`,children:u}),o=()=>{const l=window.prompt("Enter URL:");l&&i.chain().focus().setLink({href:l}).run()};return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden bg-bambu-dark",children:[a.jsxs("div",{className:"flex items-center gap-0.5 p-1.5 border-b border-bambu-dark-tertiary bg-bambu-dark-secondary",children:[a.jsx(s,{onClick:()=>i.chain().focus().toggleBold().run(),isActive:i.isActive("bold"),title:r("richTextEditor.bold"),children:a.jsx(Bce,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().toggleItalic().run(),isActive:i.isActive("italic"),title:r("richTextEditor.italic"),children:a.jsx(jde,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().toggleUnderline().run(),isActive:i.isActive("underline"),title:r("richTextEditor.underline"),children:a.jsx(wfe,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),a.jsx(s,{onClick:()=>i.chain().focus().toggleBulletList().run(),isActive:i.isActive("bulletList"),title:r("richTextEditor.bulletList"),children:a.jsx(_k,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().toggleOrderedList().run(),isActive:i.isActive("orderedList"),title:r("richTextEditor.numberedList"),children:a.jsx(FW,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),a.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("left").run(),isActive:i.isActive({textAlign:"left"}),title:r("richTextEditor.alignLeft"),children:a.jsx(ffe,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("center").run(),isActive:i.isActive({textAlign:"center"}),title:r("richTextEditor.alignCenter"),children:a.jsx(cfe,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("right").run(),isActive:i.isActive({textAlign:"right"}),title:r("richTextEditor.alignRight"),children:a.jsx(dfe,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),a.jsx(s,{onClick:o,isActive:i.isActive("link"),title:r("richTextEditor.addLink"),children:a.jsx($y,{className:"w-4 h-4"})}),i.isActive("link")&&a.jsx(s,{onClick:()=>i.chain().focus().unsetLink().run(),title:r("richTextEditor.removeLink"),children:a.jsx(WR,{className:"w-4 h-4"})})]}),a.jsx(gqe,{editor:i})]})}function Mre({archiveId:t,archiveName:e,onClose:n}){const r=an(),[i,s]=_.useState(!1),[o,l]=_.useState(null),[c,u]=_.useState({}),{data:d,isLoading:h,error:p}=it({queryKey:["archive-project-page",t],queryFn:()=>ae.getArchiveProjectPage(t)}),m=dt({mutationFn:M=>ae.updateArchiveProjectPage(t,M),onSuccess:()=>{r.invalidateQueries({queryKey:["archive-project-page",t]}),s(!1),u({})}});_.useEffect(()=>{const M=A=>{A.key==="Escape"&&(o!==null?l(null):i?v():n())};return document.addEventListener("keydown",M),()=>document.removeEventListener("keydown",M)},[o,i,n]);const b=[...d?.model_pictures||[],...d?.profile_pictures||[]],y=()=>{u({title:d?.title||"",description:d?.description||"",designer:d?.designer||"",license:d?.license||"",profile_title:d?.profile_title||"",profile_description:d?.profile_description||""}),s(!0)},x=()=>{m.mutate(c)},v=()=>{s(!1),u({})},S=M=>{const A=["p","br","b","strong","i","em","u","a","ul","ol","li","figure","img"],k=new DOMParser().parseFromString(M,"text/html"),R=C=>{if(C.nodeType===Node.TEXT_NODE)return C.textContent||"";if(C.nodeType===Node.ELEMENT_NODE){const P=C,U=P.tagName.toLowerCase();if(!A.includes(U))return Array.from(P.childNodes).map(R).join("");let F="";if(U==="a"&&P.getAttribute("href")){const D=P.getAttribute("href");D?.toLowerCase().startsWith("http")&&(F=` href="${D}" target="_blank" rel="noopener noreferrer"`)}if(U==="img"){const D=P.getAttribute("src");if(!D?.toLowerCase().startsWith("http"))return"";F=` src="${D}" style="max-width: 100%; height: auto;"`}const H=Array.from(P.childNodes).map(R).join("");return["br","img"].includes(U)?`<${U}${F} />`:`<${U}${F}>${H}`}return""};return Array.from(k.body.childNodes).map(R).join("")},N=d&&(d.title||d.description||d.designer||d.profile_title||b.length>0),T=M=>{M.target===M.currentTarget&&n()};return a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:T,children:[a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(ys,{className:"w-5 h-5 text-bambu-green"}),a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Project Page",e&&a.jsxs("span",{className:"text-bambu-gray ml-2",children:["- ",e]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[!i&&N&&a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:y,children:[a.jsx(dm,{className:"w-4 h-4 mr-1"}),"Edit"]}),i&&a.jsxs(a.Fragment,{children:[a.jsx(Ne,{variant:"ghost",size:"sm",onClick:v,children:"Cancel"}),a.jsxs(Ne,{variant:"primary",size:"sm",onClick:x,disabled:m.isPending,children:[a.jsx(vs,{className:"w-4 h-4 mr-1"}),"Save"]})]}),a.jsx("button",{onClick:n,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-6",children:[h&&a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-bambu-green border-t-transparent"})}),p&&a.jsx("div",{className:"text-red-400 text-center py-12",children:"Failed to load project page data"}),d&&!N&&a.jsxs("div",{className:"text-bambu-gray text-center py-12",children:[a.jsx(ys,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),a.jsx("p",{children:"No project page data found in this 3MF file."}),a.jsx("p",{className:"text-sm mt-2",children:"Project pages are typically included in files downloaded from MakerWorld."})]}),d&&N&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"space-y-4",children:[i?a.jsx("input",{type:"text",value:c.title||"",onChange:M=>u({...c,title:M.target.value}),placeholder:"Title",className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-4 py-2 text-white text-xl font-semibold"}):d.title&&a.jsx("h3",{className:"text-xl font-semibold text-white",children:d.title}),a.jsxs("div",{className:"flex flex-wrap gap-4 text-sm",children:[i?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx($u,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c.designer||"",onChange:M=>u({...c,designer:M.target.value}),placeholder:"Designer",className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"})]}):d.designer&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx($u,{className:"w-4 h-4"}),a.jsx("span",{children:d.designer}),d.designer_user_id&&a.jsx("a",{href:`https://makerworld.com/en/@${d.designer_user_id}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline",children:a.jsx(Xr,{className:"w-3 h-3"})})]}),d.creation_date&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx(ti,{className:"w-4 h-4"}),a.jsx("span",{children:d.creation_date})]}),i?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ys,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c.license||"",onChange:M=>u({...c,license:M.target.value}),placeholder:"License",className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"})]}):d.license&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx(ys,{className:"w-4 h-4"}),a.jsx("span",{children:d.license})]}),d.origin&&a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark rounded text-bambu-gray",children:d.origin})]})]}),(d.description||i)&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide",children:"Description"}),i?a.jsx(bR,{content:c.description||"",onChange:M=>u({...c,description:M}),placeholder:"Enter description..."}):a.jsx("div",{className:"prose prose-invert prose-sm max-w-none text-bambu-gray-light",dangerouslySetInnerHTML:{__html:S(d.description||"")}})]}),(d.profile_title||d.profile_description||i)&&a.jsxs("div",{className:"space-y-2 p-4 bg-bambu-dark rounded-lg",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide",children:"Print Profile"}),i?a.jsxs("div",{className:"space-y-2",children:[a.jsx("input",{type:"text",value:c.profile_title||"",onChange:M=>u({...c,profile_title:M.target.value}),placeholder:"Profile Title",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-white"}),a.jsx(bR,{content:c.profile_description||"",onChange:M=>u({...c,profile_description:M}),placeholder:"Profile description..."})]}):a.jsxs(a.Fragment,{children:[d.profile_title&&a.jsx("p",{className:"text-white font-medium",children:d.profile_title}),d.profile_description&&a.jsx("div",{className:"prose prose-invert prose-sm max-w-none text-bambu-gray-light",dangerouslySetInnerHTML:{__html:S(d.profile_description)}}),d.profile_user_name&&a.jsxs("p",{className:"text-sm text-bambu-gray",children:["by ",d.profile_user_name]})]})]}),b.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide flex items-center gap-2",children:[a.jsx(Uu,{className:"w-4 h-4"}),"Images (",b.length,")"]}),a.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2",children:b.map((M,A)=>a.jsx("button",{onClick:()=>l(A),className:"aspect-square rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",children:a.jsx("img",{src:M.url,alt:M.name,className:"w-full h-full object-cover"})},M.path))})]}),d.design_model_id&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("a",{href:`https://makerworld.com/en/models/${d.design_model_id}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-bambu-green hover:underline",children:[a.jsx(Xr,{className:"w-4 h-4"}),"View on MakerWorld"]})})]})]})]}),o!==null&&b[o]&&a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-60",onClick:()=>l(null),children:[a.jsx("button",{onClick:M=>{M.stopPropagation(),l(Math.max(0,o-1))},disabled:o===0,className:"absolute left-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary disabled:opacity-30",children:a.jsx(Eh,{className:"w-6 h-6 text-white"})}),a.jsx("img",{src:b[o].url,alt:b[o].name,className:"max-w-[90vw] max-h-[90vh] object-contain",onClick:M=>M.stopPropagation()}),a.jsx("button",{onClick:M=>{M.stopPropagation(),l(Math.min(b.length-1,o+1))},disabled:o===b.length-1,className:"absolute right-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary disabled:opacity-30",children:a.jsx(ks,{className:"w-6 h-6 text-white"})}),a.jsx("button",{onClick:()=>l(null),className:"absolute top-4 right-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary",children:a.jsx(Lt,{className:"w-6 h-6 text-white"})}),a.jsxs("div",{className:"absolute bottom-4 text-white text-sm",children:[o+1," / ",b.length]})]})]})}const v9e=[.25,.5,.75,1,1.5,2,3,4];function sg(t){const e=Math.floor(t/60),n=Math.floor(t%60);return`${e}:${n.toString().padStart(2,"0")}`}function w9e({archiveId:t,timelapseSrc:e,onClose:n,onSave:r}){const{showToast:i}=Tn(),s=_.useRef(null),o=_.useRef(null),[l,c]=_.useState(!1),[u,d]=_.useState(0),[h,p]=_.useState(0),[m,b]=_.useState(0),[y,x]=_.useState(0),[v,S]=_.useState(1),[N,T]=_.useState(null),[M,A]=_.useState(null),[k,R]=_.useState(.8),[C,P]=_.useState(!1),{data:U,isLoading:F}=it({queryKey:["timelapse-info",t],queryFn:()=>ae.getTimelapseInfo(t)}),{data:H}=it({queryKey:["timelapse-thumbnails",t],queryFn:()=>ae.getTimelapseThumbnails(t,15)}),D=dt({mutationFn:()=>ae.processTimelapse(t,{trimStart:m,trimEnd:y,speed:v,saveMode:"replace"},N||void 0),onSuccess:B=>{i(B.message,"success"),r?.(),n()},onError:B=>{i(B.message||"Processing failed","error")}});_.useEffect(()=>{U?.duration&&y===0&&x(U.duration)},[U?.duration,y]),_.useEffect(()=>{const B=W=>{W.key==="Escape"&&n()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[n]),_.useEffect(()=>{const B=s.current;if(!B)return;const W=()=>{const fe=B.currentTime;d(fe),fe>=y&&(B.currentTime=m)},J=()=>{p(B.duration),y===0&&x(B.duration)},ne=()=>c(!0),me=()=>c(!1);return B.addEventListener("timeupdate",W),B.addEventListener("durationchange",J),B.addEventListener("play",ne),B.addEventListener("pause",me),()=>{B.removeEventListener("timeupdate",W),B.removeEventListener("durationchange",J),B.removeEventListener("play",ne),B.removeEventListener("pause",me)}},[m,y]),_.useEffect(()=>{const B=o.current,W=s.current;!B||!W||!M||(B.currentTime=W.currentTime,B.playbackRate=W.playbackRate,l&&!C?B.play().catch(()=>{}):B.pause())},[l,M,C]),_.useEffect(()=>{o.current&&(o.current.volume=C?0:k)},[k,C]),_.useEffect(()=>{s.current&&(s.current.playbackRate=v),o.current&&(o.current.playbackRate=v)},[v]);const $=_.useCallback(()=>{const B=s.current;B&&(l?B.pause():(B.currentTime{const W=s.current;W&&(W.currentTime=Math.max(m,Math.min(y,B)))},I=B=>{const W=B.target.files?.[0];W&&(M&&URL.revokeObjectURL(M),T(W),A(URL.createObjectURL(W)))},K=()=>{M&&URL.revokeObjectURL(M),T(null),A(null)};_.useEffect(()=>()=>{M&&URL.revokeObjectURL(M)},[M]);const Q=y-m,oe=Q/v;return F?a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:a.jsxs("div",{className:"flex items-center gap-3 text-white",children:[a.jsx(ct,{className:"w-6 h-6 animate-spin"}),"Loading video info..."]})}):a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:a.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl max-w-5xl w-full mx-4 max-h-[90vh] overflow-hidden flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ph,{className:"w-5 h-5 text-bambu-green"}),"Edit Timelapse"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ne,{variant:"primary",size:"sm",onClick:()=>D.mutate(),disabled:D.isPending,children:D.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(vs,{className:"w-4 h-4"}),"Save"]})}),a.jsx("button",{onClick:n,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[a.jsxs("div",{className:"relative",children:[a.jsx("video",{ref:s,src:e,className:"w-full rounded-lg bg-black",onClick:$,muted:!!M}),!l&&a.jsx("button",{onClick:$,className:"absolute inset-0 flex items-center justify-center bg-black/30 hover:bg-black/40 transition-colors",children:a.jsx("div",{className:"p-4 bg-bambu-green rounded-full",children:a.jsx(Eo,{className:"w-8 h-8 text-white"})})}),M&&a.jsx("audio",{ref:o,src:M,loop:!0})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(Fhe,{className:"w-4 h-4"}),a.jsx("span",{children:"Trim"}),a.jsxs("span",{className:"ml-auto",children:[sg(m)," - ",sg(y)," (",sg(Q),")"]})]}),a.jsxs("div",{className:"relative h-16 bg-bambu-dark rounded-lg overflow-hidden",children:[a.jsx("div",{className:"absolute inset-0 flex",children:H?.thumbnails.map((B,W)=>a.jsx("div",{className:"flex-1 bg-cover bg-center",style:{backgroundImage:`url(data:image/jpeg;base64,${B})`}},W))}),a.jsx("div",{className:"absolute inset-y-0 left-0 bg-black/60",style:{width:`${m/h*100}%`}}),a.jsx("div",{className:"absolute inset-y-0 right-0 bg-black/60",style:{width:`${(h-y)/h*100}%`}}),a.jsx("div",{className:"absolute inset-y-0 border-2 border-bambu-green",style:{left:`${m/h*100}%`,right:`${(h-y)/h*100}%`}}),a.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-white shadow-lg",style:{left:`${u/h*100}%`}}),a.jsx("input",{type:"range",min:0,max:h,step:.1,value:m,onChange:B=>{const W=parseFloat(B.target.value);W{const W=parseFloat(B.target.value);W>m+1&&x(W)},className:"absolute inset-0 w-full opacity-0 cursor-ew-resize",style:{clipPath:"inset(0 0 0 50%)"}})]}),a.jsx("input",{type:"range",min:0,max:h,step:.1,value:u,onChange:B=>G(parseFloat(B.target.value)),className:`w-full h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer +`),[s,o]=E7e(i);if(s.length===0)return;const l=pre(s,0,n);return l.length===0?void 0:{type:"list",ordered:!0,start:((r=s[0])==null?void 0:r.number)||1,items:l,raw:i.slice(0,o).join(` +`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(A7e,this.editor.getAttributes(f9)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let t=bb({find:m9,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:(e,n)=>n.childCount+n.attrs.start===+e[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(t=bb({find:m9,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(f9)}),joinPredicate:(e,n)=>n.childCount+n.attrs.start===+e[1],editor:this.editor})),[t]}}),C7e=/^\s*(\[([( |x])?\])\s$/,P7e=Zs.create({name:"taskItem",addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}},content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:t=>{const e=t.getAttribute("data-checked");return e===""||e==="true"},renderHTML:t=>({"data-checked":t.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51}]},renderHTML({node:t,HTMLAttributes:e}){return["li",_i(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:t.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(t,e)=>{const n=[];if(t.tokens&&t.tokens.length>0?n.push(e.createNode("paragraph",{},e.parseInline(t.tokens))):t.text?n.push(e.createNode("paragraph",{},[e.createNode("text",{text:t.text})])):n.push(e.createNode("paragraph",{},[])),t.nestedTokens&&t.nestedTokens.length>0){const r=e.parseChildren(t.nestedTokens);n.push(...r)}return e.createNode("taskItem",{checked:t.checked||!1},n)},renderMarkdown:(t,e)=>{var n;const i=`- [${(n=t.attrs)!=null&&n.checked?"x":" "}] `;return oF(t,e,i)},addKeyboardShortcuts(){const t={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...t,Tab:()=>this.editor.commands.sinkListItem(this.name)}:t},addNodeView(){return({node:t,HTMLAttributes:e,getPos:n,editor:r})=>{const i=document.createElement("li"),s=document.createElement("label"),o=document.createElement("span"),l=document.createElement("input"),c=document.createElement("div"),u=d=>{var h,p;l.ariaLabel=((p=(h=this.options.a11y)==null?void 0:h.checkboxLabel)==null?void 0:p.call(h,d,l.checked))||`Task item checkbox for ${d.textContent||"empty task item"}`};return u(t),s.contentEditable="false",l.type="checkbox",l.addEventListener("mousedown",d=>d.preventDefault()),l.addEventListener("change",d=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){l.checked=!l.checked;return}const{checked:h}=d.target;r.isEditable&&typeof n=="function"&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:p})=>{const m=n();if(typeof m!="number")return!1;const b=p.doc.nodeAt(m);return p.setNodeMarkup(m,void 0,{...b?.attrs,checked:h}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(t,h)||(l.checked=!l.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([d,h])=>{i.setAttribute(d,h)}),i.dataset.checked=t.attrs.checked,l.checked=t.attrs.checked,s.append(l,o),i.append(s,c),Object.entries(e).forEach(([d,h])=>{i.setAttribute(d,h)}),{dom:i,contentDOM:c,update:d=>d.type!==this.type?!1:(i.dataset.checked=d.attrs.checked,l.checked=d.attrs.checked,u(d),!0)}}},addInputRules(){return[bb({find:C7e,type:this.type,getAttributes:t=>({checked:t[t.length-1]==="x"})})]}}),j7e=Zs.create({name:"taskList",addOptions(){return{itemTypeName:"taskItem",HTMLAttributes:{}}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:t}){return["ul",_i(this.options.HTMLAttributes,t,{"data-type":this.name}),0]},parseMarkdown:(t,e)=>e.createNode("taskList",{},e.parseChildren(t.items||[])),renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` +`):"",markdownTokenizer:{name:"taskList",level:"block",start(t){var e;const n=(e=t.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))==null?void 0:e.index;return n!==void 0?n:-1},tokenize(t,e,n){const r=s=>{const o=aR(s,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:l=>({indentLevel:l[1].length,mainContent:l[4],checked:l[3].toLowerCase()==="x"}),createToken:(l,c)=>({type:"taskItem",raw:"",mainContent:l.mainContent,indentLevel:l.indentLevel,checked:l.checked,text:l.mainContent,tokens:n.inlineTokens(l.mainContent),nestedTokens:c}),customNestedParser:r},n);return o?[{type:"taskList",raw:o.raw,items:o.items}]:n.blockTokens(s)},i=aR(t,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:s=>({indentLevel:s[1].length,mainContent:s[4],checked:s[3].toLowerCase()==="x"}),createToken:(s,o)=>({type:"taskItem",raw:"",mainContent:s.mainContent,indentLevel:s.indentLevel,checked:s.checked,text:s.mainContent,tokens:n.inlineTokens(s.mainContent),nestedTokens:o}),customNestedParser:r},n);if(i)return{type:"taskList",raw:i.raw,items:i.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:t})=>t.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});Dr.create({name:"listKit",addExtensions(){const t=[];return this.options.bulletList!==!1&&t.push(ore.configure(this.options.bulletList)),this.options.listItem!==!1&&t.push(lre.configure(this.options.listItem)),this.options.listKeymap!==!1&&t.push(mre.configure(this.options.listKeymap)),this.options.orderedList!==!1&&t.push(gre.configure(this.options.orderedList)),this.options.taskItem!==!1&&t.push(P7e.configure(this.options.taskItem)),this.options.taskList!==!1&&t.push(j7e.configure(this.options.taskList)),t}});var D7e=Zs.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",_i(this.options.HTMLAttributes,t),0]},parseMarkdown:(t,e)=>{const n=t.tokens||[];return n.length===1&&n[0].type==="image"?e.parseChildren([n[0]]):e.createNode("paragraph",void 0,e.parseInline(n))},renderMarkdown:(t,e)=>!t||!Array.isArray(t.content)?"":e.renderChildren(t.content),addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),R7e=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,O7e=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,L7e=Kh.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:t=>t.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:t}){return["s",_i(this.options.HTMLAttributes,t),0]},markdownTokenName:"del",parseMarkdown:(t,e)=>e.applyMark("strike",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`~~${e.renderChildren(t)}~~`,addCommands(){return{setStrike:()=>({commands:t})=>t.setMark(this.name),toggleStrike:()=>({commands:t})=>t.toggleMark(this.name),unsetStrike:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[gb({find:R7e,type:this.type})]},addPasteRules(){return[Pm({find:O7e,type:this.type})]}}),F7e=Zs.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),bre=Kh.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:t=>t.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:t}){return["u",_i(this.options.HTMLAttributes,t),0]},parseMarkdown(t,e){return e.applyMark(this.name||"underline",e.parseInline(t.tokens||[]))},renderMarkdown(t,e){return`++${e.renderChildren(t)}++`},markdownTokenizer:{name:"underline",level:"inline",start(t){return t.indexOf("++")},tokenize(t,e,n){const i=/^(\+\+)([\s\S]+?)(\+\+)/.exec(t);if(!i)return;const s=i[2].trim();return{type:"underline",raw:i[0],text:s,tokens:n.inlineTokens(s)}}},addCommands(){return{setUnderline:()=>({commands:t})=>t.setMark(this.name),toggleUnderline:()=>({commands:t})=>t.toggleMark(this.name),unsetUnderline:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}}),I7e=bre;function z7e(t={}){return new di({view(e){return new U7e(e,t)}})}class U7e{constructor(e,n){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(i=>{let s=o=>{this[i](o)};return e.dom.addEventListener(i,s),{name:i,handler:s}})}destroy(){this.handlers.forEach(({name:e,handler:n})=>this.editorView.dom.removeEventListener(e,n))}update(e,n){this.cursorPos!=null&&n.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),n=!e.parent.inlineContent,r,i=this.editorView.dom,s=i.getBoundingClientRect(),o=s.width/i.offsetWidth,l=s.height/i.offsetHeight;if(n){let h=e.nodeBefore,p=e.nodeAfter;if(h||p){let m=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(m){let b=m.getBoundingClientRect(),y=h?b.bottom:b.top;h&&p&&(y=(y+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let x=this.width/2*l;r={left:b.left,right:b.right,top:y-x,bottom:y+x}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),p=this.width/2*o;r={left:h.left-p,right:h.left+p,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let u,d;if(!c||c==document.body&&getComputedStyle(c).position=="static")u=-pageXOffset,d=-pageYOffset;else{let h=c.getBoundingClientRect(),p=h.width/c.offsetWidth,m=h.height/c.offsetHeight;u=h.left-c.scrollLeft*p,d=h.top-c.scrollTop*m}this.element.style.left=(r.left-u)/o+"px",this.element.style.top=(r.top-d)/l+"px",this.element.style.width=(r.right-r.left)/o+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),i=r&&r.type.spec.disableDropCursor,s=typeof i=="function"?i(this.editorView,n,e):i;if(n&&!s){let o=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=bte(this.editorView.state.doc,o,this.editorView.dragging.slice);l!=null&&(o=l)}this.setCursor(o),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}}class bi extends Fn{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return bi.valid(r)?new bi(r):Fn.near(r)}content(){return $t.empty}eq(e){return e instanceof bi&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new bi(e.resolve(n.pos))}getBookmark(){return new xF(this.anchor)}static valid(e){let n=e.parent;if(n.isTextblock||!B7e(e)||!H7e(e))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let i=n.contentMatchAt(e.index()).defaultType;return i&&i.isTextblock}static findGapCursorFrom(e,n,r=!1){e:for(;;){if(!r&&bi.valid(e))return e;let i=e.pos,s=null;for(let o=e.depth;;o--){let l=e.node(o);if(n>0?e.indexAfter(o)0){s=l.child(n>0?e.indexAfter(o):e.index(o)-1);break}else if(o==0)return null;i+=n;let c=e.doc.resolve(i);if(bi.valid(c))return c}for(;;){let o=n>0?s.firstChild:s.lastChild;if(!o){if(s.isAtom&&!s.isText&&!rn.isSelectable(s)){e=e.doc.resolve(i+s.nodeSize*n),r=!1;continue e}break}s=o,i+=n;let l=e.doc.resolve(i);if(bi.valid(l))return l}return null}}}bi.prototype.visible=!1;bi.findFrom=bi.findGapCursorFrom;Fn.jsonID("gapcursor",bi);class xF{constructor(e){this.pos=e}map(e){return new xF(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return bi.valid(n)?new bi(n):Fn.near(n)}}function xre(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function B7e(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(n-1);;i=i.lastChild){if(i.childCount==0&&!i.inlineContent||xre(i.type))return!0;if(i.inlineContent)return!1}}return!0}function H7e(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(n);;i=i.firstChild){if(i.childCount==0&&!i.inlineContent||xre(i.type))return!0;if(i.inlineContent)return!1}}return!0}function $7e(){return new di({props:{decorations:W7e,createSelectionBetween(t,e,n){return e.pos==n.pos&&bi.valid(n)?new bi(n):null},handleClick:G7e,handleKeyDown:V7e,handleDOMEvents:{beforeinput:q7e}}})}const V7e=bne({ArrowLeft:p1("horiz",-1),ArrowRight:p1("horiz",1),ArrowUp:p1("vert",-1),ArrowDown:p1("vert",1)});function p1(t,e){const n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,i,s){let o=r.selection,l=e>0?o.$to:o.$from,c=o.empty;if(o instanceof yn){if(!s.endOfTextblock(n)||l.depth==0)return!1;c=!1,l=r.doc.resolve(e>0?l.after():l.before())}let u=bi.findGapCursorFrom(l,e,c);return u?(i&&i(r.tr.setSelection(new bi(u))),!0):!1}}function G7e(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!bi.valid(r))return!1;let i=t.posAtCoords({left:n.clientX,top:n.clientY});return i&&i.inside>-1&&rn.isSelectable(t.state.doc.nodeAt(i.inside))?!1:(t.dispatch(t.state.tr.setSelection(new bi(r))),!0)}function q7e(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof bi))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let i=At.empty;for(let o=r.length-1;o>=0;o--)i=At.from(r[o].createAndFill(null,i));let s=t.state.tr.replace(n.pos,n.pos,new $t(i,0,0));return s.setSelection(yn.near(s.doc.resolve(n.pos+1))),t.dispatch(s),!1}function W7e(t){if(!(t.selection instanceof bi))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",oi.create(t.doc,[_s.widget(t.selection.head,e,{key:"gapcursor"})])}var nk=200,Sa=function(){};Sa.prototype.append=function(e){return e.length?(e=Sa.from(e),!this.length&&e||e.length=n?Sa.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))};Sa.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};Sa.prototype.forEach=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(e,n,r,0):this.forEachInvertedInner(e,n,r,0)};Sa.prototype.map=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},n,r),i};Sa.from=function(e){return e instanceof Sa?e:e&&e.length?new yre(e):Sa.empty};var yre=(function(t){function e(r){t.call(this),this.values=r}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var c=s;c=o;c--)if(i(this.values[c],l+c)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=nk)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=nk)return new e(i.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(e.prototype,n),e})(Sa);Sa.empty=new yre([]);var K7e=(function(t){function e(n,r){t.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.depth)+1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(Sa);const X7e=500;class Rl{constructor(e,n){this.items=e,this.eventCount=n}popEvent(e,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;n&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,c,u=[],d=[];return this.items.forEach((h,p)=>{if(!h.step){i||(i=this.remapping(r,p+1),s=i.maps.length),s--,d.push(h);return}if(i){d.push(new tc(h.map));let m=h.step.map(i.slice(s)),b;m&&o.maybeStep(m).doc&&(b=o.mapping.maps[o.mapping.maps.length-1],u.push(new tc(b,void 0,void 0,u.length+d.length))),s--,b&&i.appendMap(b,s)}else o.maybeStep(h.step);if(h.selection)return l=i?h.selection.map(i.slice(s)):h.selection,c=new Rl(this.items.slice(0,r).append(d.reverse().concat(u)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:o,selection:l}}addTransform(e,n,r,i){let s=[],o=this.eventCount,l=this.items,c=!i&&l.length?l.get(l.length-1):null;for(let d=0;dQ7e&&(l=Y7e(l,u),o-=u),new Rl(l.append(s),o)}remapping(e,n){let r=new Ty;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,n),r}addMaps(e){return this.eventCount==0?this:new Rl(this.items.append(e.map(n=>new tc(n))),this.eventCount)}rebased(e,n){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-n),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(p=>{p.selection&&l--},i);let c=n;this.items.forEach(p=>{let m=s.getMirror(--c);if(m==null)return;o=Math.min(o,m);let b=s.maps[m];if(p.step){let y=e.steps[m].invert(e.docs[m]),x=p.selection&&p.selection.map(s.slice(c+1,m));x&&l++,r.push(new tc(b,y,x))}else r.push(new tc(b))},i);let u=[];for(let p=n;pX7e&&(h=h.compress(this.items.length-r.length)),h}emptyItemCount(){let e=0;return this.items.forEach(n=>{n.step||e++}),e}compress(e=this.items.length){let n=this.remapping(0,e),r=n.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let c=o.step.map(n.slice(r)),u=c&&c.getMap();if(r--,u&&n.appendMap(u,r),c){let d=o.selection&&o.selection.map(n.slice(r));d&&s++;let h=new tc(u.invert(),c,d),p,m=i.length-1;(p=i.length&&i[m].merge(h))?i[m]=p:i.push(h)}}else o.map&&r--},this.items.length,0),new Rl(Sa.from(i.reverse()),s)}}Rl.empty=new Rl(Sa.empty,0);function Y7e(t,e){let n;return t.forEach((r,i)=>{if(r.selection&&e--==0)return n=i,!1}),t.slice(n)}class tc{constructor(e,n,r,i){this.map=e,this.step=n,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let n=e.step.merge(this.step);if(n)return new tc(n.getMap().invert(),n,this.selection)}}}class th{constructor(e,n,r,i,s){this.done=e,this.undone=n,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const Q7e=20;function Z7e(t,e,n,r){let i=n.getMeta(om),s;if(i)return i.historyState;n.getMeta(t9e)&&(t=new th(t.done,t.undone,null,0,-1));let o=n.getMeta("appendedTransaction");if(n.steps.length==0)return t;if(o&&o.getMeta(om))return o.getMeta(om).redo?new th(t.done.addTransform(n,void 0,r,G1(e)),t.undone,p9(n.mapping.maps),t.prevTime,t.prevComposition):new th(t.done,t.undone.addTransform(n,void 0,r,G1(e)),null,t.prevTime,t.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=n.getMeta("composition"),c=t.prevTime==0||!o&&t.prevComposition!=l&&(t.prevTime<(n.time||0)-r.newGroupDelay||!J7e(n,t.prevRanges)),u=o?WP(t.prevRanges,n.mapping):p9(n.mapping.maps);return new th(t.done.addTransform(n,c?e.selection.getBookmark():void 0,r,G1(e)),Rl.empty,u,n.time,l??t.prevComposition)}else return(s=n.getMeta("rebased"))?new th(t.done.rebased(n,s),t.undone.rebased(n,s),WP(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new th(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),WP(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function J7e(t,e){if(!e)return!1;if(!t.docChanged)return!0;let n=!1;return t.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(n=!0)}),n}function p9(t){let e=[];for(let n=t.length-1;n>=0&&e.length==0;n--)t[n].forEach((r,i,s,o)=>e.push(s,o));return e}function WP(t,e){if(!t)return null;let n=[];for(let r=0;r{let i=om.getState(n);if(!i||(t?i.undone:i.done).eventCount==0)return!1;if(r){let s=e9e(i,n,t);s&&r(e?s.scrollIntoView():s)}return!0}}const wre=vre(!1,!0),_re=vre(!0,!0);Dr.create({name:"characterCount",addOptions(){return{limit:null,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=t=>{const e=t?.node||this.editor.state.doc;if((t?.mode||this.options.mode)==="textSize"){const r=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(r)}return e.nodeSize},this.storage.words=t=>{const e=t?.node||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new di({key:new ca("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;const i=this.options.limit;if(i==null||i===0){t=!0;return}const s=this.storage.characters({node:r.doc});if(s>i){const o=s-i,l=0,c=o;console.warn(`[CharacterCount] Initial content exceeded limit of ${i} characters. Content was automatically trimmed.`);const u=r.tr.deleteRange(l,c);return t=!0,u}t=!0},filterTransaction:(e,n)=>{const r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;const i=this.storage.characters({node:n.doc}),s=this.storage.characters({node:e.doc});if(s<=r||i>r&&s>r&&s<=i)return!0;if(i>r&&s>r&&s>i||!e.getMeta("paste"))return!1;const l=e.selection.$head.pos,c=s-r,u=l-c,d=l;return e.deleteRange(u,d),!(this.storage.characters({node:e.doc})>r)}})]}});var r9e=Dr.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[z7e(this.options)]}});Dr.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new di({key:new ca("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:i}=e,s=[];if(!n||!r)return oi.create(t,[]);let o=0;this.options.mode==="deepest"&&t.descendants((c,u)=>{if(c.isText)return;if(!(i>=u&&i<=u+c.nodeSize-1))return!1;o+=1});let l=0;return t.descendants((c,u)=>{if(c.isText||!(i>=u&&i<=u+c.nodeSize-1))return!1;if(l+=1,this.options.mode==="deepest"&&o-l>0||this.options.mode==="shallowest"&&l>1)return this.options.mode==="deepest";s.push(_s.node(u,u+c.nodeSize,{class:this.options.className}))}),oi.create(t,s)}}})]}});var i9e=Dr.create({name:"gapCursor",addProseMirrorPlugins(){return[$7e()]},extendNodeSchema(t){var e;const n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=xr(tn(t,"allowGapCursor",n)))!=null?e:null}}});Dr.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[new di({key:new ca("placeholder"),props:{decorations:({doc:t,selection:e})=>{const n=this.editor.isEditable||!this.options.showOnlyWhenEditable,{anchor:r}=e,i=[];if(!n)return null;const s=this.editor.isEmpty;return t.descendants((o,l)=>{const c=r>=l&&r<=l+o.nodeSize,u=!o.isLeaf&&VM(o);if((c||!this.options.showOnlyCurrent)&&u){const d=[this.options.emptyNodeClass];s&&d.push(this.options.emptyEditorClass);const h=_s.node(l,l+o.nodeSize,{class:d.join(" "),"data-placeholder":typeof this.options.placeholder=="function"?this.options.placeholder({editor:this.editor,node:o,pos:l,hasAnchor:c}):this.options.placeholder});i.push(h)}return this.options.includeChildren}),oi.create(t,i)}}})]}});Dr.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:t,options:e}=this;return[new di({key:new ca("selection"),props:{decorations(n){return n.selection.empty||t.isFocused||!t.isEditable||Dne(n.selection)||t.view.dragging?null:oi.create(n.doc,[_s.inline(n.selection.from,n.selection.to,{class:e.className})])}}})]}});function b9({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||e?.type===t}var a9e=Dr.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;const e=new ca(this.name),n=this.options.node||((t=this.editor.schema.topNodeType.contentMatch.defaultType)==null?void 0:t.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,i])=>i).filter(i=>(this.options.notAfter||[]).concat(n).includes(i.name));return[new di({key:e,appendTransaction:(i,s,o)=>{const{doc:l,tr:c,schema:u}=o,d=e.getState(o),h=l.content.size,p=u.nodes[n];if(d)return c.insert(h,p.create())},state:{init:(i,s)=>{const o=s.tr.doc.lastChild;return!b9({node:o,types:r})},apply:(i,s)=>{if(!i.docChanged||i.getMeta("__uniqueIDTransaction"))return s;const o=i.doc.lastChild;return!b9({node:o,types:r})}}})]}}),s9e=Dr.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>wre(t,e),redo:()=>({state:t,dispatch:e})=>_re(t,e)}},addProseMirrorPlugins(){return[n9e(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}}),o9e=Dr.create({name:"starterKit",addExtensions(){var t,e,n,r;const i=[];return this.options.bold!==!1&&i.push(Rqe.configure(this.options.bold)),this.options.blockquote!==!1&&i.push(Aqe.configure(this.options.blockquote)),this.options.bulletList!==!1&&i.push(ore.configure(this.options.bulletList)),this.options.code!==!1&&i.push(Fqe.configure(this.options.code)),this.options.codeBlock!==!1&&i.push(Uqe.configure(this.options.codeBlock)),this.options.document!==!1&&i.push(Bqe.configure(this.options.document)),this.options.dropcursor!==!1&&i.push(r9e.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&i.push(i9e.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&i.push(Hqe.configure(this.options.hardBreak)),this.options.heading!==!1&&i.push($qe.configure(this.options.heading)),this.options.undoRedo!==!1&&i.push(s9e.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&i.push(Vqe.configure(this.options.horizontalRule)),this.options.italic!==!1&&i.push(Xqe.configure(this.options.italic)),this.options.listItem!==!1&&i.push(lre.configure(this.options.listItem)),this.options.listKeymap!==!1&&i.push(mre.configure((t=this.options)==null?void 0:t.listKeymap)),this.options.link!==!1&&i.push(sre.configure((e=this.options)==null?void 0:e.link)),this.options.orderedList!==!1&&i.push(gre.configure(this.options.orderedList)),this.options.paragraph!==!1&&i.push(D7e.configure(this.options.paragraph)),this.options.strike!==!1&&i.push(L7e.configure(this.options.strike)),this.options.text!==!1&&i.push(F7e.configure(this.options.text)),this.options.underline!==!1&&i.push(bre.configure((n=this.options)==null?void 0:n.underline)),this.options.trailingNode!==!1&&i.push(a9e.configure((r=this.options)==null?void 0:r.trailingNode)),i}}),l9e=o9e,c9e=Dr.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:t=>{const e=t.style.textAlign;return this.options.alignments.includes(e)?e:this.options.defaultAlignment},renderHTML:t=>t.textAlign?{style:`text-align: ${t.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:t=>({commands:e})=>this.options.alignments.includes(t)?this.options.types.map(n=>e.updateAttributes(n,{textAlign:t})).some(n=>n):!1,unsetTextAlign:()=>({commands:t})=>this.options.types.map(e=>t.resetAttributes(e,"textAlign")).some(e=>e),toggleTextAlign:t=>({editor:e,commands:n})=>this.options.alignments.includes(t)?e.isActive({textAlign:t})?n.unsetTextAlign():n.setTextAlign(t):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),u9e=c9e,d9e=20,Sre=(t,e=0)=>{const n=[];return!t.children.length||e>d9e||Array.from(t.children).forEach(r=>{r.tagName==="SPAN"?n.push(r):r.children.length&&n.push(...Sre(r,e+1))}),n},h9e=t=>{if(!t.children.length)return;const e=Sre(t);e&&e.forEach(n=>{var r,i;const s=n.getAttribute("style"),o=(i=(r=n.parentElement)==null?void 0:r.closest("span"))==null?void 0:i.getAttribute("style");n.setAttribute("style",`${o};${s}`)})},Nre=Kh.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!0}},parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&h9e(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",_i(this.options.HTMLAttributes,t),0]},addCommands(){return{toggleTextStyle:t=>({commands:e})=>e.toggleMark(this.name,t),removeEmptyTextStyle:()=>({tr:t})=>{const{selection:e}=t;return t.doc.nodesBetween(e.from,e.to,(n,r)=>{if(n.isTextblock)return!0;n.marks.filter(i=>i.type===this.type).some(i=>Object.values(i.attrs).some(s=>!!s))||t.removeMark(r,r+n.nodeSize,this.type)}),!0}}}}),f9e=Dr.create({name:"backgroundColor",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{backgroundColor:{default:null,parseHTML:t=>{var e;const n=t.getAttribute("style");if(n){const r=n.split(";").map(i=>i.trim()).filter(Boolean);for(let i=r.length-1;i>=0;i-=1){const s=r[i].split(":");if(s.length>=2){const o=s[0].trim().toLowerCase(),l=s.slice(1).join(":").trim();if(o==="background-color")return l.replace(/['"]+/g,"")}}}return(e=t.style.backgroundColor)==null?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.backgroundColor?{style:`background-color: ${t.backgroundColor}`}:{}}}}]},addCommands(){return{setBackgroundColor:t=>({chain:e})=>e().setMark("textStyle",{backgroundColor:t}).run(),unsetBackgroundColor:()=>({chain:t})=>t().setMark("textStyle",{backgroundColor:null}).removeEmptyTextStyle().run()}}}),kre=Dr.create({name:"color",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:t=>{var e;const n=t.getAttribute("style");if(n){const r=n.split(";").map(i=>i.trim()).filter(Boolean);for(let i=r.length-1;i>=0;i-=1){const s=r[i].split(":");if(s.length>=2){const o=s[0].trim().toLowerCase(),l=s.slice(1).join(":").trim();if(o==="color")return l.replace(/['"]+/g,"")}}}return(e=t.style.color)==null?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.color?{style:`color: ${t.color}`}:{}}}}]},addCommands(){return{setColor:t=>({chain:e})=>e().setMark("textStyle",{color:t}).run(),unsetColor:()=>({chain:t})=>t().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()}}}),m9e=Dr.create({name:"fontFamily",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontFamily:{default:null,parseHTML:t=>t.style.fontFamily,renderHTML:t=>t.fontFamily?{style:`font-family: ${t.fontFamily}`}:{}}}}]},addCommands(){return{setFontFamily:t=>({chain:e})=>e().setMark("textStyle",{fontFamily:t}).run(),unsetFontFamily:()=>({chain:t})=>t().setMark("textStyle",{fontFamily:null}).removeEmptyTextStyle().run()}}}),p9e=Dr.create({name:"fontSize",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:t=>t.style.fontSize,renderHTML:t=>t.fontSize?{style:`font-size: ${t.fontSize}`}:{}}}}]},addCommands(){return{setFontSize:t=>({chain:e})=>e().setMark("textStyle",{fontSize:t}).run(),unsetFontSize:()=>({chain:t})=>t().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()}}}),g9e=Dr.create({name:"lineHeight",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{lineHeight:{default:null,parseHTML:t=>t.style.lineHeight,renderHTML:t=>t.lineHeight?{style:`line-height: ${t.lineHeight}`}:{}}}}]},addCommands(){return{setLineHeight:t=>({chain:e})=>e().setMark("textStyle",{lineHeight:t}).run(),unsetLineHeight:()=>({chain:t})=>t().setMark("textStyle",{lineHeight:null}).removeEmptyTextStyle().run()}}});Dr.create({name:"textStyleKit",addExtensions(){const t=[];return this.options.backgroundColor!==!1&&t.push(f9e.configure(this.options.backgroundColor)),this.options.color!==!1&&t.push(kre.configure(this.options.color)),this.options.fontFamily!==!1&&t.push(m9e.configure(this.options.fontFamily)),this.options.fontSize!==!1&&t.push(p9e.configure(this.options.fontSize)),this.options.lineHeight!==!1&&t.push(g9e.configure(this.options.lineHeight)),this.options.textStyle!==!1&&t.push(Nre.configure(this.options.textStyle)),t}});var b9e=kre,x9e=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,y9e=Zs.create({name:"image",addOptions(){return{inline:!1,allowBase64:!1,HTMLAttributes:{},resize:!1}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},alt:{default:null},title:{default:null},width:{default:null},height:{default:null}}},parseHTML(){return[{tag:this.options.allowBase64?"img[src]":'img[src]:not([src^="data:"])'}]},renderHTML({HTMLAttributes:t}){return["img",_i(this.options.HTMLAttributes,t)]},parseMarkdown:(t,e)=>e.createNode("image",{src:t.href,title:t.title,alt:t.text}),renderMarkdown:t=>{var e,n,r,i,s,o;const l=(n=(e=t.attrs)==null?void 0:e.src)!=null?n:"",c=(i=(r=t.attrs)==null?void 0:r.alt)!=null?i:"",u=(o=(s=t.attrs)==null?void 0:s.title)!=null?o:"";return u?`![${c}](${l} "${u}")`:`![${c}](${l})`},addNodeView(){if(!this.options.resize||!this.options.resize.enabled||typeof document>"u"||!this.editor.isEditable)return null;const{directions:t,minWidth:e,minHeight:n,alwaysPreserveAspectRatio:r}=this.options.resize;return({node:i,getPos:s,HTMLAttributes:o})=>{const l=document.createElement("img");Object.entries(o).forEach(([d,h])=>{if(h!=null)switch(d){case"width":case"height":break;default:l.setAttribute(d,h);break}}),l.src=o.src;const c=new eqe({element:l,node:i,getPos:s,onResize:(d,h)=>{l.style.width=`${d}px`,l.style.height=`${h}px`},onCommit:(d,h)=>{const p=s();p!==void 0&&this.editor.chain().setNodeSelection(p).updateAttributes(this.name,{width:d,height:h}).run()},onUpdate:(d,h,p)=>d.type===i.type,options:{directions:t,min:{width:e,height:n},preserveAspectRatio:r===!0}}),u=c.dom;return u.style.visibility="hidden",u.style.pointerEvents="none",l.onload=()=>{u.style.visibility="",u.style.pointerEvents=""},c}},addCommands(){return{setImage:t=>({commands:e})=>e.insertContent({type:this.name,attrs:t})}},addInputRules(){return[Kne({find:x9e,type:this.type,getAttributes:t=>{const[,,e,n,r]=t;return{src:n,alt:e,title:r}}})]}}),v9e=y9e;function bR({content:t,onChange:e,placeholder:n}){const{t:r}=Yt(),i=Nqe({extensions:[l9e.configure({heading:!1,codeBlock:!1,code:!1}),I7e,v7e.configure({openOnClick:!1,HTMLAttributes:{target:"_blank",rel:"noopener noreferrer"}}),u9e.configure({types:["paragraph"]}),Nre,b9e,v9e.configure({HTMLAttributes:{style:"max-width: 100%; height: auto;"}})],content:t,onUpdate:({editor:l})=>{e(l.getHTML())},editorProps:{attributes:{class:"prose prose-invert prose-sm max-w-none focus:outline-none min-h-[120px] px-3 py-2",placeholder:n||""}}});if(!i)return null;const s=({onClick:l,isActive:c=!1,children:u,title:d})=>a.jsx("button",{type:"button",onClick:l,title:d,className:`p-1.5 rounded hover:bg-bambu-dark-tertiary transition-colors ${c?"bg-bambu-dark-tertiary text-bambu-green":"text-bambu-gray"}`,children:u}),o=()=>{const l=window.prompt("Enter URL:");l&&i.chain().focus().setLink({href:l}).run()};return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden bg-bambu-dark",children:[a.jsxs("div",{className:"flex items-center gap-0.5 p-1.5 border-b border-bambu-dark-tertiary bg-bambu-dark-secondary",children:[a.jsx(s,{onClick:()=>i.chain().focus().toggleBold().run(),isActive:i.isActive("bold"),title:r("richTextEditor.bold"),children:a.jsx(Bce,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().toggleItalic().run(),isActive:i.isActive("italic"),title:r("richTextEditor.italic"),children:a.jsx(jde,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().toggleUnderline().run(),isActive:i.isActive("underline"),title:r("richTextEditor.underline"),children:a.jsx(wfe,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),a.jsx(s,{onClick:()=>i.chain().focus().toggleBulletList().run(),isActive:i.isActive("bulletList"),title:r("richTextEditor.bulletList"),children:a.jsx(_k,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().toggleOrderedList().run(),isActive:i.isActive("orderedList"),title:r("richTextEditor.numberedList"),children:a.jsx(FW,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),a.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("left").run(),isActive:i.isActive({textAlign:"left"}),title:r("richTextEditor.alignLeft"),children:a.jsx(ffe,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("center").run(),isActive:i.isActive({textAlign:"center"}),title:r("richTextEditor.alignCenter"),children:a.jsx(cfe,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("right").run(),isActive:i.isActive({textAlign:"right"}),title:r("richTextEditor.alignRight"),children:a.jsx(dfe,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),a.jsx(s,{onClick:o,isActive:i.isActive("link"),title:r("richTextEditor.addLink"),children:a.jsx($y,{className:"w-4 h-4"})}),i.isActive("link")&&a.jsx(s,{onClick:()=>i.chain().focus().unsetLink().run(),title:r("richTextEditor.removeLink"),children:a.jsx(WR,{className:"w-4 h-4"})})]}),a.jsx(bqe,{editor:i})]})}function Mre({archiveId:t,archiveName:e,onClose:n}){const r=an(),[i,s]=_.useState(!1),[o,l]=_.useState(null),[c,u]=_.useState({}),{data:d,isLoading:h,error:p}=it({queryKey:["archive-project-page",t],queryFn:()=>ae.getArchiveProjectPage(t)}),m=dt({mutationFn:M=>ae.updateArchiveProjectPage(t,M),onSuccess:()=>{r.invalidateQueries({queryKey:["archive-project-page",t]}),s(!1),u({})}});_.useEffect(()=>{const M=A=>{A.key==="Escape"&&(o!==null?l(null):i?v():n())};return document.addEventListener("keydown",M),()=>document.removeEventListener("keydown",M)},[o,i,n]);const b=[...d?.model_pictures||[],...d?.profile_pictures||[]],y=()=>{u({title:d?.title||"",description:d?.description||"",designer:d?.designer||"",license:d?.license||"",profile_title:d?.profile_title||"",profile_description:d?.profile_description||""}),s(!0)},x=()=>{m.mutate(c)},v=()=>{s(!1),u({})},S=M=>{const A=["p","br","b","strong","i","em","u","a","ul","ol","li","figure","img"],k=new DOMParser().parseFromString(M,"text/html"),R=C=>{if(C.nodeType===Node.TEXT_NODE)return C.textContent||"";if(C.nodeType===Node.ELEMENT_NODE){const P=C,U=P.tagName.toLowerCase();if(!A.includes(U))return Array.from(P.childNodes).map(R).join("");let F="";if(U==="a"&&P.getAttribute("href")){const D=P.getAttribute("href");D?.toLowerCase().startsWith("http")&&(F=` href="${D}" target="_blank" rel="noopener noreferrer"`)}if(U==="img"){const D=P.getAttribute("src");if(!D?.toLowerCase().startsWith("http"))return"";F=` src="${D}" style="max-width: 100%; height: auto;"`}const H=Array.from(P.childNodes).map(R).join("");return["br","img"].includes(U)?`<${U}${F} />`:`<${U}${F}>${H}`}return""};return Array.from(k.body.childNodes).map(R).join("")},N=d&&(d.title||d.description||d.designer||d.profile_title||b.length>0),T=M=>{M.target===M.currentTarget&&n()};return a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:T,children:[a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(ys,{className:"w-5 h-5 text-bambu-green"}),a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Project Page",e&&a.jsxs("span",{className:"text-bambu-gray ml-2",children:["- ",e]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[!i&&N&&a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:y,children:[a.jsx(dm,{className:"w-4 h-4 mr-1"}),"Edit"]}),i&&a.jsxs(a.Fragment,{children:[a.jsx(Ne,{variant:"ghost",size:"sm",onClick:v,children:"Cancel"}),a.jsxs(Ne,{variant:"primary",size:"sm",onClick:x,disabled:m.isPending,children:[a.jsx(vs,{className:"w-4 h-4 mr-1"}),"Save"]})]}),a.jsx("button",{onClick:n,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-6",children:[h&&a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-bambu-green border-t-transparent"})}),p&&a.jsx("div",{className:"text-red-400 text-center py-12",children:"Failed to load project page data"}),d&&!N&&a.jsxs("div",{className:"text-bambu-gray text-center py-12",children:[a.jsx(ys,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),a.jsx("p",{children:"No project page data found in this 3MF file."}),a.jsx("p",{className:"text-sm mt-2",children:"Project pages are typically included in files downloaded from MakerWorld."})]}),d&&N&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"space-y-4",children:[i?a.jsx("input",{type:"text",value:c.title||"",onChange:M=>u({...c,title:M.target.value}),placeholder:"Title",className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-4 py-2 text-white text-xl font-semibold"}):d.title&&a.jsx("h3",{className:"text-xl font-semibold text-white",children:d.title}),a.jsxs("div",{className:"flex flex-wrap gap-4 text-sm",children:[i?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx($u,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c.designer||"",onChange:M=>u({...c,designer:M.target.value}),placeholder:"Designer",className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"})]}):d.designer&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx($u,{className:"w-4 h-4"}),a.jsx("span",{children:d.designer}),d.designer_user_id&&a.jsx("a",{href:`https://makerworld.com/en/@${d.designer_user_id}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline",children:a.jsx(Xr,{className:"w-3 h-3"})})]}),d.creation_date&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx(ti,{className:"w-4 h-4"}),a.jsx("span",{children:d.creation_date})]}),i?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ys,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c.license||"",onChange:M=>u({...c,license:M.target.value}),placeholder:"License",className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"})]}):d.license&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx(ys,{className:"w-4 h-4"}),a.jsx("span",{children:d.license})]}),d.origin&&a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark rounded text-bambu-gray",children:d.origin})]})]}),(d.description||i)&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide",children:"Description"}),i?a.jsx(bR,{content:c.description||"",onChange:M=>u({...c,description:M}),placeholder:"Enter description..."}):a.jsx("div",{className:"prose prose-invert prose-sm max-w-none text-bambu-gray-light",dangerouslySetInnerHTML:{__html:S(d.description||"")}})]}),(d.profile_title||d.profile_description||i)&&a.jsxs("div",{className:"space-y-2 p-4 bg-bambu-dark rounded-lg",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide",children:"Print Profile"}),i?a.jsxs("div",{className:"space-y-2",children:[a.jsx("input",{type:"text",value:c.profile_title||"",onChange:M=>u({...c,profile_title:M.target.value}),placeholder:"Profile Title",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-white"}),a.jsx(bR,{content:c.profile_description||"",onChange:M=>u({...c,profile_description:M}),placeholder:"Profile description..."})]}):a.jsxs(a.Fragment,{children:[d.profile_title&&a.jsx("p",{className:"text-white font-medium",children:d.profile_title}),d.profile_description&&a.jsx("div",{className:"prose prose-invert prose-sm max-w-none text-bambu-gray-light",dangerouslySetInnerHTML:{__html:S(d.profile_description)}}),d.profile_user_name&&a.jsxs("p",{className:"text-sm text-bambu-gray",children:["by ",d.profile_user_name]})]})]}),b.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide flex items-center gap-2",children:[a.jsx(Uu,{className:"w-4 h-4"}),"Images (",b.length,")"]}),a.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2",children:b.map((M,A)=>a.jsx("button",{onClick:()=>l(A),className:"aspect-square rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",children:a.jsx("img",{src:M.url,alt:M.name,className:"w-full h-full object-cover"})},M.path))})]}),d.design_model_id&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("a",{href:`https://makerworld.com/en/models/${d.design_model_id}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-bambu-green hover:underline",children:[a.jsx(Xr,{className:"w-4 h-4"}),"View on MakerWorld"]})})]})]})]}),o!==null&&b[o]&&a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-60",onClick:()=>l(null),children:[a.jsx("button",{onClick:M=>{M.stopPropagation(),l(Math.max(0,o-1))},disabled:o===0,className:"absolute left-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary disabled:opacity-30",children:a.jsx(Eh,{className:"w-6 h-6 text-white"})}),a.jsx("img",{src:b[o].url,alt:b[o].name,className:"max-w-[90vw] max-h-[90vh] object-contain",onClick:M=>M.stopPropagation()}),a.jsx("button",{onClick:M=>{M.stopPropagation(),l(Math.min(b.length-1,o+1))},disabled:o===b.length-1,className:"absolute right-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary disabled:opacity-30",children:a.jsx(ks,{className:"w-6 h-6 text-white"})}),a.jsx("button",{onClick:()=>l(null),className:"absolute top-4 right-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary",children:a.jsx(Lt,{className:"w-6 h-6 text-white"})}),a.jsxs("div",{className:"absolute bottom-4 text-white text-sm",children:[o+1," / ",b.length]})]})]})}const w9e=[.25,.5,.75,1,1.5,2,3,4];function sg(t){const e=Math.floor(t/60),n=Math.floor(t%60);return`${e}:${n.toString().padStart(2,"0")}`}function _9e({archiveId:t,timelapseSrc:e,onClose:n,onSave:r}){const{showToast:i}=Tn(),s=_.useRef(null),o=_.useRef(null),[l,c]=_.useState(!1),[u,d]=_.useState(0),[h,p]=_.useState(0),[m,b]=_.useState(0),[y,x]=_.useState(0),[v,S]=_.useState(1),[N,T]=_.useState(null),[M,A]=_.useState(null),[k,R]=_.useState(.8),[C,P]=_.useState(!1),{data:U,isLoading:F}=it({queryKey:["timelapse-info",t],queryFn:()=>ae.getTimelapseInfo(t)}),{data:H}=it({queryKey:["timelapse-thumbnails",t],queryFn:()=>ae.getTimelapseThumbnails(t,15)}),D=dt({mutationFn:()=>ae.processTimelapse(t,{trimStart:m,trimEnd:y,speed:v,saveMode:"replace"},N||void 0),onSuccess:B=>{i(B.message,"success"),r?.(),n()},onError:B=>{i(B.message||"Processing failed","error")}});_.useEffect(()=>{U?.duration&&y===0&&x(U.duration)},[U?.duration,y]),_.useEffect(()=>{const B=W=>{W.key==="Escape"&&n()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[n]),_.useEffect(()=>{const B=s.current;if(!B)return;const W=()=>{const fe=B.currentTime;d(fe),fe>=y&&(B.currentTime=m)},J=()=>{p(B.duration),y===0&&x(B.duration)},ne=()=>c(!0),me=()=>c(!1);return B.addEventListener("timeupdate",W),B.addEventListener("durationchange",J),B.addEventListener("play",ne),B.addEventListener("pause",me),()=>{B.removeEventListener("timeupdate",W),B.removeEventListener("durationchange",J),B.removeEventListener("play",ne),B.removeEventListener("pause",me)}},[m,y]),_.useEffect(()=>{const B=o.current,W=s.current;!B||!W||!M||(B.currentTime=W.currentTime,B.playbackRate=W.playbackRate,l&&!C?B.play().catch(()=>{}):B.pause())},[l,M,C]),_.useEffect(()=>{o.current&&(o.current.volume=C?0:k)},[k,C]),_.useEffect(()=>{s.current&&(s.current.playbackRate=v),o.current&&(o.current.playbackRate=v)},[v]);const $=_.useCallback(()=>{const B=s.current;B&&(l?B.pause():(B.currentTime{const W=s.current;W&&(W.currentTime=Math.max(m,Math.min(y,B)))},I=B=>{const W=B.target.files?.[0];W&&(M&&URL.revokeObjectURL(M),T(W),A(URL.createObjectURL(W)))},K=()=>{M&&URL.revokeObjectURL(M),T(null),A(null)};_.useEffect(()=>()=>{M&&URL.revokeObjectURL(M)},[M]);const Q=y-m,oe=Q/v;return F?a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:a.jsxs("div",{className:"flex items-center gap-3 text-white",children:[a.jsx(ct,{className:"w-6 h-6 animate-spin"}),"Loading video info..."]})}):a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:a.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl max-w-5xl w-full mx-4 max-h-[90vh] overflow-hidden flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ph,{className:"w-5 h-5 text-bambu-green"}),"Edit Timelapse"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ne,{variant:"primary",size:"sm",onClick:()=>D.mutate(),disabled:D.isPending,children:D.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(vs,{className:"w-4 h-4"}),"Save"]})}),a.jsx("button",{onClick:n,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[a.jsxs("div",{className:"relative",children:[a.jsx("video",{ref:s,src:e,className:"w-full rounded-lg bg-black",onClick:$,muted:!!M}),!l&&a.jsx("button",{onClick:$,className:"absolute inset-0 flex items-center justify-center bg-black/30 hover:bg-black/40 transition-colors",children:a.jsx("div",{className:"p-4 bg-bambu-green rounded-full",children:a.jsx(Eo,{className:"w-8 h-8 text-white"})})}),M&&a.jsx("audio",{ref:o,src:M,loop:!0})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(Fhe,{className:"w-4 h-4"}),a.jsx("span",{children:"Trim"}),a.jsxs("span",{className:"ml-auto",children:[sg(m)," - ",sg(y)," (",sg(Q),")"]})]}),a.jsxs("div",{className:"relative h-16 bg-bambu-dark rounded-lg overflow-hidden",children:[a.jsx("div",{className:"absolute inset-0 flex",children:H?.thumbnails.map((B,W)=>a.jsx("div",{className:"flex-1 bg-cover bg-center",style:{backgroundImage:`url(data:image/jpeg;base64,${B})`}},W))}),a.jsx("div",{className:"absolute inset-y-0 left-0 bg-black/60",style:{width:`${m/h*100}%`}}),a.jsx("div",{className:"absolute inset-y-0 right-0 bg-black/60",style:{width:`${(h-y)/h*100}%`}}),a.jsx("div",{className:"absolute inset-y-0 border-2 border-bambu-green",style:{left:`${m/h*100}%`,right:`${(h-y)/h*100}%`}}),a.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-white shadow-lg",style:{left:`${u/h*100}%`}}),a.jsx("input",{type:"range",min:0,max:h,step:.1,value:m,onChange:B=>{const W=parseFloat(B.target.value);W{const W=parseFloat(B.target.value);W>m+1&&x(W)},className:"absolute inset-0 w-full opacity-0 cursor-ew-resize",style:{clipPath:"inset(0 0 0 50%)"}})]}),a.jsx("input",{type:"range",min:0,max:h,step:.1,value:u,onChange:B=>G(parseFloat(B.target.value)),className:`w-full h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full - [&::-webkit-slider-thumb]:cursor-pointer`}),a.jsx("div",{className:"flex items-center justify-center gap-2",children:a.jsx("button",{onClick:$,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?a.jsx(Sk,{className:"w-5 h-5 text-white"}):a.jsx(Eo,{className:"w-5 h-5 text-white"})})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(vk,{className:"w-4 h-4"}),a.jsx("span",{children:"Speed"}),a.jsxs("span",{className:"ml-auto",children:[v,"x (output: ",sg(oe),")"]})]}),a.jsx("div",{className:"flex gap-1",children:v9e.map(B=>a.jsxs("button",{onClick:()=>S(B),className:`flex-1 px-2 py-2 text-sm rounded transition-colors ${v===B?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[B,"x"]},B))})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(Cj,{className:"w-4 h-4"}),a.jsx("span",{children:"Music Overlay"})]}),N?a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(Cj,{className:"w-5 h-5 text-bambu-green"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:N.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[(N.size/1024/1024).toFixed(1)," MB"]})]}),a.jsx("button",{onClick:()=>P(!C),className:"p-2 hover:bg-bambu-dark-tertiary rounded transition-colors",children:C?a.jsx(Cfe,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Tfe,{className:"w-4 h-4 text-bambu-green"})}),a.jsx("input",{type:"range",min:0,max:1,step:.1,value:k,onChange:B=>R(parseFloat(B.target.value)),className:`w-20 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer + [&::-webkit-slider-thumb]:cursor-pointer`}),a.jsx("div",{className:"flex items-center justify-center gap-2",children:a.jsx("button",{onClick:$,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?a.jsx(Sk,{className:"w-5 h-5 text-white"}):a.jsx(Eo,{className:"w-5 h-5 text-white"})})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(vk,{className:"w-4 h-4"}),a.jsx("span",{children:"Speed"}),a.jsxs("span",{className:"ml-auto",children:[v,"x (output: ",sg(oe),")"]})]}),a.jsx("div",{className:"flex gap-1",children:w9e.map(B=>a.jsxs("button",{onClick:()=>S(B),className:`flex-1 px-2 py-2 text-sm rounded transition-colors ${v===B?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[B,"x"]},B))})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(Cj,{className:"w-4 h-4"}),a.jsx("span",{children:"Music Overlay"})]}),N?a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(Cj,{className:"w-5 h-5 text-bambu-green"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:N.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[(N.size/1024/1024).toFixed(1)," MB"]})]}),a.jsx("button",{onClick:()=>P(!C),className:"p-2 hover:bg-bambu-dark-tertiary rounded transition-colors",children:C?a.jsx(Cfe,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Tfe,{className:"w-4 h-4 text-bambu-green"})}),a.jsx("input",{type:"range",min:0,max:1,step:.1,value:k,onChange:B=>R(parseFloat(B.target.value)),className:`w-20 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 - [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full`}),a.jsx("button",{onClick:K,className:"p-2 hover:bg-red-500/20 rounded transition-colors",children:a.jsx(ln,{className:"w-4 h-4 text-red-400"})})]}):a.jsxs("label",{className:"flex flex-col items-center justify-center gap-2 p-6 border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green/50 transition-colors",children:[a.jsx(Na,{className:"w-8 h-8 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"Drop audio file or click to upload"}),a.jsx("span",{className:"text-xs text-bambu-gray/60",children:"MP3, WAV, M4A, AAC, OGG"}),a.jsx("input",{type:"file",accept:".mp3,.wav,.m4a,.aac,.ogg,audio/*",onChange:I,className:"hidden"})]})]}),a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg text-sm space-y-1",children:[a.jsxs("p",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white",children:"Original:"})," ",sg(h)," @ ",U?.width,"x",U?.height]}),a.jsxs("p",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white",children:"Output:"})," ",sg(oe)," @ ",v,"x speed",N&&" + music overlay"]})]})]}),D.isPending&&a.jsxs("div",{className:"absolute inset-0 bg-black/80 flex flex-col items-center justify-center gap-4",children:[a.jsx(ct,{className:"w-12 h-12 text-bambu-green animate-spin"}),a.jsx("p",{className:"text-white text-lg",children:"Processing timelapse..."}),a.jsx("p",{className:"text-bambu-gray text-sm",children:"This may take a few moments"})]})]})})}const _9e=[.25,.5,.75,1,1.5,2,3,4];function Ere({src:t,title:e,downloadFilename:n,archiveId:r,onClose:i,onEdit:s}){const o=_.useRef(null),[l,c]=_.useState(!0),[u,d]=_.useState(1),[h,p]=_.useState(0),[m,b]=_.useState(0),[y,x]=_.useState(!1);_.useEffect(()=>{const k=o.current;k&&(k.playbackRate=u)},[u]),_.useEffect(()=>{const k=R=>{R.key==="Escape"&&i()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[i]),_.useEffect(()=>{const k=o.current;if(!k)return;const R=()=>p(k.currentTime),C=()=>b(k.duration),P=()=>c(!0),U=()=>c(!1);return k.addEventListener("timeupdate",R),k.addEventListener("durationchange",C),k.addEventListener("play",P),k.addEventListener("pause",U),()=>{k.removeEventListener("timeupdate",R),k.removeEventListener("durationchange",C),k.removeEventListener("play",P),k.removeEventListener("pause",U)}},[]);const v=()=>{const k=o.current;k&&(l?k.pause():k.play())},S=k=>{const R=o.current;R&&(R.currentTime=parseFloat(k.target.value))},N=()=>{const k=o.current;k&&(k.currentTime=Math.max(0,k.currentTime-5))},T=()=>{const k=o.current;k&&(k.currentTime=Math.min(m,k.currentTime+5))},M=k=>{const R=Math.floor(k/60),C=Math.floor(k%60);return`${R}:${C.toString().padStart(2,"0")}`},A=()=>{const k=document.createElement("a");k.href=t,k.download=n,k.click()};return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:[a.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl max-w-4xl w-full mx-4 overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ph,{className:"w-5 h-5 text-bambu-green"}),e]}),a.jsxs("div",{className:"flex items-center gap-2",children:[r&&a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>x(!0),children:[a.jsx(Ji,{className:"w-4 h-4"}),"Edit"]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:A,children:[a.jsx(wi,{className:"w-4 h-4"}),"Download"]}),a.jsx("button",{onClick:i,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),a.jsxs("div",{className:"p-4",children:[a.jsx("video",{ref:o,src:t,autoPlay:!0,className:"w-full rounded-lg",onClick:v}),a.jsxs("div",{className:"mt-4 space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("span",{className:"text-xs text-bambu-gray w-12 text-right",children:M(h)}),a.jsx("input",{type:"range",min:0,max:m||100,value:h,onChange:S,className:`flex-1 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer + [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full`}),a.jsx("button",{onClick:K,className:"p-2 hover:bg-red-500/20 rounded transition-colors",children:a.jsx(ln,{className:"w-4 h-4 text-red-400"})})]}):a.jsxs("label",{className:"flex flex-col items-center justify-center gap-2 p-6 border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green/50 transition-colors",children:[a.jsx(Na,{className:"w-8 h-8 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"Drop audio file or click to upload"}),a.jsx("span",{className:"text-xs text-bambu-gray/60",children:"MP3, WAV, M4A, AAC, OGG"}),a.jsx("input",{type:"file",accept:".mp3,.wav,.m4a,.aac,.ogg,audio/*",onChange:I,className:"hidden"})]})]}),a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg text-sm space-y-1",children:[a.jsxs("p",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white",children:"Original:"})," ",sg(h)," @ ",U?.width,"x",U?.height]}),a.jsxs("p",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white",children:"Output:"})," ",sg(oe)," @ ",v,"x speed",N&&" + music overlay"]})]})]}),D.isPending&&a.jsxs("div",{className:"absolute inset-0 bg-black/80 flex flex-col items-center justify-center gap-4",children:[a.jsx(ct,{className:"w-12 h-12 text-bambu-green animate-spin"}),a.jsx("p",{className:"text-white text-lg",children:"Processing timelapse..."}),a.jsx("p",{className:"text-bambu-gray text-sm",children:"This may take a few moments"})]})]})})}const S9e=[.25,.5,.75,1,1.5,2,3,4];function Ere({src:t,title:e,downloadFilename:n,archiveId:r,onClose:i,onEdit:s}){const o=_.useRef(null),[l,c]=_.useState(!0),[u,d]=_.useState(1),[h,p]=_.useState(0),[m,b]=_.useState(0),[y,x]=_.useState(!1);_.useEffect(()=>{const k=o.current;k&&(k.playbackRate=u)},[u]),_.useEffect(()=>{const k=R=>{R.key==="Escape"&&i()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[i]),_.useEffect(()=>{const k=o.current;if(!k)return;const R=()=>p(k.currentTime),C=()=>b(k.duration),P=()=>c(!0),U=()=>c(!1);return k.addEventListener("timeupdate",R),k.addEventListener("durationchange",C),k.addEventListener("play",P),k.addEventListener("pause",U),()=>{k.removeEventListener("timeupdate",R),k.removeEventListener("durationchange",C),k.removeEventListener("play",P),k.removeEventListener("pause",U)}},[]);const v=()=>{const k=o.current;k&&(l?k.pause():k.play())},S=k=>{const R=o.current;R&&(R.currentTime=parseFloat(k.target.value))},N=()=>{const k=o.current;k&&(k.currentTime=Math.max(0,k.currentTime-5))},T=()=>{const k=o.current;k&&(k.currentTime=Math.min(m,k.currentTime+5))},M=k=>{const R=Math.floor(k/60),C=Math.floor(k%60);return`${R}:${C.toString().padStart(2,"0")}`},A=()=>{const k=document.createElement("a");k.href=t,k.download=n,k.click()};return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:[a.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl max-w-4xl w-full mx-4 overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ph,{className:"w-5 h-5 text-bambu-green"}),e]}),a.jsxs("div",{className:"flex items-center gap-2",children:[r&&a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>x(!0),children:[a.jsx(Ji,{className:"w-4 h-4"}),"Edit"]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:A,children:[a.jsx(wi,{className:"w-4 h-4"}),"Download"]}),a.jsx("button",{onClick:i,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),a.jsxs("div",{className:"p-4",children:[a.jsx("video",{ref:o,src:t,autoPlay:!0,className:"w-full rounded-lg",onClick:v}),a.jsxs("div",{className:"mt-4 space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("span",{className:"text-xs text-bambu-gray w-12 text-right",children:M(h)}),a.jsx("input",{type:"range",min:0,max:m||100,value:h,onChange:S,className:`flex-1 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full - [&::-webkit-slider-thumb]:cursor-pointer`}),a.jsx("span",{className:"text-xs text-bambu-gray w-12",children:M(m)})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{onClick:N,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip back 5s",children:a.jsx(Khe,{className:"w-5 h-5 text-bambu-gray"})}),a.jsx("button",{onClick:v,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?a.jsx(Sk,{className:"w-5 h-5 text-white"}):a.jsx(Eo,{className:"w-5 h-5 text-white"})}),a.jsx("button",{onClick:T,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip forward 5s",children:a.jsx(qR,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:"Speed:"}),a.jsx("div",{className:"flex gap-1",children:_9e.map(k=>a.jsxs("button",{onClick:()=>d(k),className:`px-2 py-1 text-xs rounded transition-colors ${u===k?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary/80"}`,children:[k,"x"]},k))})]})]})]})]})]}),y&&r&&a.jsx(w9e,{archiveId:r,timelapseSrc:t,onClose:()=>x(!1),onSave:s})]})}function S9e({archiveIds:t,onClose:e}){_.useEffect(()=>{const s=o=>{o.key==="Escape"&&e()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e]);const{data:n,isLoading:r,error:i}=it({queryKey:["archive-comparison",t],queryFn:()=>ae.compareArchives(t)});return a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg max-w-4xl w-full max-h-[90vh] flex flex-col border border-bambu-dark-tertiary",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white",children:["Compare Archives (",t.length,")"]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white p-1",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 overflow-auto p-4 bg-bambu-dark-secondary",children:r?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i?a.jsxs("div",{className:"text-center py-12 text-red-400",children:[a.jsx(En,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),a.jsx("p",{children:"Failed to load comparison"}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:i instanceof Error?i.message:"Unknown error"})]}):n?a.jsx(N9e,{comparison:n}):null}),a.jsx("div",{className:"p-4 border-t border-bambu-dark-tertiary",children:a.jsx(Ne,{variant:"secondary",onClick:e,className:"w-full",children:"Close"})})]})})}function N9e({comparison:t}){return a.jsxs("div",{className:"space-y-6",children:[a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{className:"text-left text-sm text-bambu-gray font-medium pb-2 pr-4 min-w-[150px]",children:"Setting"}),t.archives.map(e=>a.jsxs("th",{className:"text-left text-sm font-medium pb-2 px-2 min-w-[120px]",children:[a.jsx("div",{className:"text-white truncate max-w-[150px]",title:e.print_name,children:e.print_name}),a.jsx("div",{className:`text-xs ${e.status==="completed"?"text-status-ok":e.status==="failed"?"text-status-error":"text-bambu-gray"}`,children:e.status})]},e.id))]})}),a.jsx("tbody",{className:"divide-y divide-bambu-gray/20",children:t.comparison.map(e=>a.jsxs("tr",{className:e.has_difference?"bg-yellow-500/5":"",children:[a.jsx("td",{className:"py-2 pr-4 text-sm",children:a.jsxs("div",{className:"flex items-center gap-2",children:[e.has_difference&&a.jsx(En,{className:"w-3 h-3 text-yellow-400 flex-shrink-0"}),a.jsx("span",{className:e.has_difference?"text-yellow-400":"text-bambu-gray",children:e.label})]})}),e.values.map((n,r)=>a.jsxs("td",{className:"py-2 px-2 text-sm text-white",children:[n??a.jsx("span",{className:"text-bambu-gray/50",children:"-"}),e.unit&&n!==null&&a.jsx("span",{className:"text-bambu-gray ml-1",children:e.unit})]},r))]},e.field))})]})}),t.differences.length>0&&a.jsxs("div",{className:"p-4 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[a.jsxs("h4",{className:"text-sm font-medium text-yellow-400 mb-2 flex items-center gap-2",children:[a.jsx(En,{className:"w-4 h-4"}),t.differences.length," Difference",t.differences.length>1?"s":""," Found"]}),a.jsxs("ul",{className:"text-sm text-white/80 space-y-1",children:[t.differences.slice(0,5).map(e=>a.jsxs("li",{children:[a.jsx("span",{className:"text-yellow-400",children:e.label}),": ",e.values.join(" vs ")," ",e.unit||""]},e.field)),t.differences.length>5&&a.jsxs("li",{className:"text-bambu-gray",children:["...and ",t.differences.length-5," more"]})]})]}),t.success_correlation.has_both_outcomes?a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("h4",{className:"text-sm font-medium text-white mb-3 flex items-center gap-2",children:[a.jsx($i,{className:"w-4 h-4 text-bambu-green"}),"Success/Failure Analysis"]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm mb-3",children:[a.jsxs("span",{className:"text-bambu-green",children:[t.success_correlation.successful_count," successful"]}),a.jsxs("span",{className:"text-red-400",children:[t.success_correlation.failed_count," failed"]})]}),t.success_correlation.insights&&t.success_correlation.insights.length>0?a.jsx("div",{className:"space-y-2",children:t.success_correlation.insights.map(e=>a.jsxs("div",{className:"text-sm p-2 bg-bambu-dark-secondary rounded",children:[a.jsxs("span",{className:"text-white font-medium",children:[e.label,":"]})," ",a.jsx("span",{className:"text-white/80",children:e.insight})]},e.field))}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No clear correlations found between settings and outcomes."})]}):a.jsx("div",{className:"p-4 bg-bambu-dark rounded-lg text-sm text-bambu-gray",children:a.jsx("p",{children:t.success_correlation.message||"Need both successful and failed prints for correlation analysis."})})]})}function k9e(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function M9e(t){const e=new Date(t),r=new Date().getTime()-e.getTime(),i=Math.floor(r/6e4);if(i<1)return"Just now";if(i<60)return`${i}m ago`;const s=Math.floor(i/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}function E9e({upload:t,projects:e,onArchive:n,onDiscard:r,isArchiving:i,isDiscarding:s}){const[o,l]=_.useState(!1),[c,u]=_.useState(t.tags||""),[d,h]=_.useState(t.notes||""),[p,m]=_.useState(t.project_id),[b,y]=_.useState(!1);return a.jsx(St,{children:a.jsxs(Et,{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Kf,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[a.jsx("span",{children:k9e(t.file_size)}),a.jsx("span",{children:"·"}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(tr,{className:"w-3 h-3"}),M9e(t.uploaded_at)]}),t.source_ip&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"·"}),a.jsxs("span",{children:["from ",t.source_ip]})]})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{onClick:()=>l(!o),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:o?a.jsx(zu,{className:"w-5 h-5"}):a.jsx(fr,{className:"w-5 h-5"})}),a.jsx(Ne,{variant:"primary",size:"sm",onClick:()=>n(t.id,{tags:c,notes:d,project_id:p||void 0}),disabled:i,children:i?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(vo,{className:"w-4 h-4"}),"Archive"]})}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>y(!0),disabled:s,children:s?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4 text-red-400"})})]})]}),b&&a.jsx(er,{title:"Discard Upload",message:`Are you sure you want to discard "${t.filename}"? This cannot be undone.`,confirmText:"Discard",variant:"danger",onConfirm:()=>{r(t.id),y(!1)},onCancel:()=>y(!1)}),o&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Tags"}),a.jsx("input",{type:"text",value:c,onChange:x=>u(x.target.value),placeholder:"e.g., functional, prototype, gift",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white placeholder-bambu-gray text-sm"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes"}),a.jsx("textarea",{value:d,onChange:x=>h(x.target.value),placeholder:"Add notes about this print...",rows:2,className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white placeholder-bambu-gray text-sm resize-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Project"}),a.jsxs("select",{value:p||"",onChange:x=>m(x.target.value?Number(x.target.value):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white text-sm",children:[a.jsx("option",{value:"",children:"No project"}),e.map(x=>a.jsx("option",{value:x.id,children:x.name},x.id))]})]})]})]})})}function T9e(){const t=an(),{showToast:e}=Tn(),[n,r]=_.useState(!1),[i,s]=_.useState(!1),[o,l]=_.useState(new Set),[c,u]=_.useState(new Set),{data:d,isLoading:h}=it({queryKey:["pending-uploads"],queryFn:cg.list,refetchInterval:1e4}),{data:p}=it({queryKey:["projects"],queryFn:()=>ae.getProjects()}),m=dt({mutationFn:({id:v,data:S})=>cg.archive(v,S),onMutate:({id:v})=>{l(S=>new Set(S).add(v))},onSettled:(v,S,{id:N})=>{l(T=>{const M=new Set(T);return M.delete(N),M})},onSuccess:v=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived: ${v.print_name}`)},onError:v=>{e(v.message||"Failed to archive","error")}}),b=dt({mutationFn:v=>cg.discard(v),onMutate:v=>{u(S=>new Set(S).add(v))},onSettled:(v,S,N)=>{u(T=>{const M=new Set(T);return M.delete(N),M})},onSuccess:()=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e("Upload discarded")},onError:v=>{e(v.message||"Failed to discard","error")}}),y=dt({mutationFn:cg.archiveAll,onSuccess:v=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived ${v.archived} files${v.failed>0?`, ${v.failed} failed`:""}`)},onError:v=>{e(v.message||"Failed to archive all","error")}}),x=dt({mutationFn:cg.discardAll,onSuccess:v=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e(`Discarded ${v.discarded} files`)},onError:v=>{e(v.message||"Failed to discard all","error")}});return h?a.jsx(St,{children:a.jsx(Et,{className:"py-8 flex justify-center",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})})}):!d||d.length===0?null:a.jsxs("div",{className:"mb-6",children:[a.jsxs(St,{className:"border-l-4 border-l-yellow-500",children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Na,{className:"w-5 h-5 text-yellow-500"}),a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Pending Uploads (",d.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ne,{variant:"primary",size:"sm",onClick:()=>r(!0),disabled:y.isPending,children:y.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(vo,{className:"w-4 h-4"}),"Archive All"]})}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>s(!0),disabled:x.isPending,children:x.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(ln,{className:"w-4 h-4"}),"Discard All"]})})]})]})}),a.jsxs(Et,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"These files were uploaded via the virtual printer. Review and archive them to add to your collection."}),a.jsx("div",{className:"space-y-3",children:d.map(v=>a.jsx(E9e,{upload:v,projects:p||[],onArchive:(S,N)=>m.mutate({id:S,data:N}),onDiscard:S=>b.mutate(S),isArchiving:o.has(v.id),isDiscarding:c.has(v.id)},v.id))})]})]}),n&&a.jsx(er,{title:"Archive All Uploads",message:`Are you sure you want to archive all ${d.length} pending uploads?`,confirmText:"Archive All",onConfirm:()=>{y.mutate(),r(!1)},onCancel:()=>r(!1)}),i&&a.jsx(er,{title:"Discard All Uploads",message:`Are you sure you want to discard all ${d.length} pending uploads? This cannot be undone.`,confirmText:"Discard All",variant:"danger",onConfirm:()=>{x.mutate(),s(!1)},onCancel:()=>s(!1)})]})}function A9e({onClose:t}){const e=an(),{showToast:n}=Tn(),[r,i]=_.useState(""),[s,o]=_.useState(null),[l,c]=_.useState(""),[u,d]=_.useState(null),[h,p]=_.useState("count");_.useEffect(()=>{const C=P=>{P.key==="Escape"&&(s?o(null):u?d(null):t())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[t,s,u]);const{data:m,isLoading:b}=it({queryKey:["tags"],queryFn:ae.getTags}),y=dt({mutationFn:({oldName:C,newName:P})=>ae.renameTag(C,P),onSuccess:(C,{oldName:P,newName:U})=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Renamed "${P}" to "${U}" in ${C.affected} archive${C.affected!==1?"s":""}`),o(null)},onError:C=>{n(C.message||"Failed to rename tag","error")}}),x=dt({mutationFn:C=>ae.deleteTag(C),onSuccess:(C,P)=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Deleted "${P}" from ${C.affected} archive${C.affected!==1?"s":""}`),d(null)},onError:C=>{n(C.message||"Failed to delete tag","error")}}),v=C=>{o(C.name),c(C.name),d(null)},S=()=>{o(null),c("")},N=()=>{if(!s||!l.trim())return;const C=l.trim();if(C===s){S();return}y.mutate({oldName:s,newName:C})},T=C=>{C.key==="Enter"?(C.preventDefault(),N()):C.key==="Escape"&&(C.preventDefault(),S())},M=C=>{d(C),o(null)},A=()=>{u&&x.mutate(u)},k=m?.filter(C=>C.name.toLowerCase().includes(r.toLowerCase())).sort((C,P)=>h==="count"&&P.count-C.count||C.name.localeCompare(P.name)),R=m?.reduce((C,P)=>C+P.count,0)||0;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-lg max-h-[80vh] flex flex-col",children:a.jsxs(Et,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Th,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Manage Tags"})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:"Search tags...",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:r,onChange:C=>i(C.target.value)})]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:h,onChange:C=>p(C.target.value),children:[a.jsx("option",{value:"count",children:"Sort by Count"}),a.jsx("option",{value:"name",children:"Sort by Name"})]})]}),m&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[m.length," tag",m.length!==1?"s":""," across ",R," usage",R!==1?"s":""]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 p-4",children:b?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):k?.length?a.jsx("div",{className:"space-y-2",children:k.map(C=>a.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary transition-colors group",children:s===C.name?a.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[a.jsx("input",{type:"text",className:"flex-1 px-2 py-1 bg-bambu-dark-tertiary border border-bambu-green rounded text-white text-sm focus:outline-none",value:l,onChange:P=>c(P.target.value),onKeyDown:T,autoFocus:!0}),a.jsx(Ne,{size:"sm",variant:"primary",onClick:N,disabled:!l.trim()||y.isPending,className:"p-1.5",children:y.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx($i,{className:"w-4 h-4"})}),a.jsx(Ne,{size:"sm",variant:"ghost",onClick:S,className:"p-1.5",children:a.jsx(Lt,{className:"w-4 h-4"})})]}):u===C.name?a.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[a.jsx(En,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-bambu-gray-light flex-1",children:['Delete "',C.name,'" from ',C.count," archive",C.count!==1?"s":"","?"]}),a.jsx(Ne,{size:"sm",variant:"danger",onClick:A,disabled:x.isPending,className:"p-1.5",children:x.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4"})}),a.jsx(Ne,{size:"sm",variant:"ghost",onClick:()=>d(null),className:"p-1.5",children:a.jsx(Lt,{className:"w-4 h-4"})})]}):a.jsxs(a.Fragment,{children:[a.jsx(Th,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-white flex-1 truncate",children:C.name}),a.jsx("span",{className:"px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-xs",children:C.count}),a.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[a.jsx("button",{onClick:()=>v(C),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors",title:"Rename tag",children:a.jsx(Ji,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>M(C.name),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors",title:"Delete tag",children:a.jsx(ln,{className:"w-4 h-4"})})]})]})},C.name))}):a.jsx("div",{className:"text-center py-8 text-bambu-gray",children:r?"No tags match your search":"No tags found"})}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:a.jsx(Ne,{variant:"secondary",onClick:t,className:"flex-1",children:"Close"})})]})})})}function rk(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function s0(t){const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function Ff(t){if(!t)return!1;const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function Tre(t){if(!t)return;const e=t.toLowerCase();return e.endsWith(".3mf")?"3mf":e.endsWith(".stl")?"stl":e.endsWith(".gcode")||e.includes(".gcode.")?"gcode":e.split(".").pop()}function C9e({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:i,projects:s,isHighlighted:o,timeFormat:l="system",preferredSlicer:c="bambu_studio",t:u}){o&&console.log("ArchiveCard isHighlighted=true for archive:",t.id);const d=an(),{showToast:h}=Tn(),{hasPermission:p,canModify:m}=Ir(),b=QR(),[y,x]=_.useState(!1),[v,S]=_.useState(!1),[N,T]=_.useState(!1),[M,A]=_.useState(!1),[k,R]=_.useState(!1),[C,P]=_.useState(!1),[U,F]=_.useState([]),[H,D]=_.useState(!1),[$,G]=_.useState(!1),[I,K]=_.useState(!1),[Q,oe]=_.useState(!1),[B,W]=_.useState(!1),[J,ne]=_.useState(!1),[me,fe]=_.useState(null),[de,Re]=_.useState(null),[se,ke]=_.useState(!1),Fe=_.useRef(null),ce=_.useRef(null),{data:Ve}=it({queryKey:["archive-plates",t.id],queryFn:()=>ae.getArchivePlates(t.id),enabled:se,staleTime:300*1e3}),V=Ve?.plates??[],Y=Ve?.is_multi_plate??!1,ue=de??0,q=dt({mutationFn:we=>ae.uploadSource3mf(t.id,we),onSuccess:we=>{d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.source3mfAttached",{filename:we.filename}))},onError:we=>{h(we.message||u("archives.toast.failedUploadSource3mf"),"error")}}),re=dt({mutationFn:()=>ae.deleteSource3mf(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.source3mfRemoved"))},onError:we=>{h(we.message||u("archives.toast.failedRemoveSource3mf"),"error")}}),X=dt({mutationFn:we=>ae.uploadF3d(t.id,we),onSuccess:we=>{d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.f3dAttached",{filename:we.filename}))},onError:we=>{h(we.message||u("archives.toast.failedUploadF3d"),"error")}}),le=dt({mutationFn:()=>ae.deleteF3d(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.f3dRemoved"))},onError:we=>{h(we.message||u("archives.toast.failedRemoveF3d"),"error")}}),pe=dt({mutationFn:()=>ae.scanArchiveTimelapse(t.id),onSuccess:we=>{we.status==="attached"?(d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.timelapseAttached",{filename:we.filename}))):we.status==="exists"?h(u("archives.toast.timelapseAlreadyAttached")):we.status==="not_found"&&we.available_files&&we.available_files.length>0?(F(we.available_files),P(!0)):h(we.message||u("archives.toast.noMatchingTimelapse"),"warning")},onError:we=>{h(we.message||u("archives.toast.failedScanTimelapse"),"error")}}),ee=dt({mutationFn:we=>ae.selectArchiveTimelapse(t.id,we),onSuccess:we=>{d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.timelapseAttached",{filename:we.filename})),P(!1),F([])},onError:we=>{h(we.message||u("archives.toast.failedAttachTimelapse"),"error")}}),z=dt({mutationFn:()=>ae.deleteArchive(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.archiveDeleted"))},onError:()=>{h(u("archives.toast.failedDeleteArchive"),"error")}}),O=dt({mutationFn:()=>ae.toggleFavorite(t.id),onSuccess:we=>{d.invalidateQueries({queryKey:["archives"]}),h(we.is_favorite?u("archives.toast.addedToFavorites"):u("archives.toast.removedFromFavorites"))}}),{data:Z}=it({queryKey:["archive-folders",t.id],queryFn:()=>ae.getLibraryFoldersByArchive(t.id)}),ge=dt({mutationFn:we=>ae.updateArchive(t.id,{project_id:we}),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),d.invalidateQueries({queryKey:["projects"]}),h(u("archives.toast.projectUpdated"))},onError:()=>{h(u("archives.toast.failedUpdateProject"),"error")}}),Ce=we=>{we.preventDefault(),fe({x:we.clientX,y:we.clientY})},Te=[...Ff(t.filename)?[{label:u("archives.menu.print"),icon:a.jsx(jr,{className:"w-4 h-4"}),onClick:()=>S(!0),disabled:!m("archives","reprint",t.created_by_id),title:m("archives","reprint",t.created_by_id)?void 0:u("archives.permission.noReprint")},{label:u("archives.menu.schedule"),icon:a.jsx(ti,{className:"w-4 h-4"}),onClick:()=>oe(!0),disabled:!p("queue:create"),title:p("queue:create")?void 0:u("archives.permission.noAddToQueue")},{label:u("archives.menu.openInBambuStudio"),icon:a.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>{const we=t.print_name||t.filename||"model",$e=`${window.location.origin}${ae.getArchiveForSlicer(t.id,we)}`;sc($e,c)}}]:[{label:u("archives.menu.slice"),icon:a.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>{const we=t.print_name||t.filename||"model",$e=`${window.location.origin}${ae.getArchiveForSlicer(t.id,we)}`;sc($e,c)}}],{label:t.external_url?u("archives.menu.externalLink"):u("archives.menu.viewOnMakerWorld"),icon:a.jsx(gh,{className:"w-4 h-4"}),onClick:()=>{const we=t.external_url||t.makerworld_url;we&&window.open(we,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:u("archives.menu.preview3d"),icon:a.jsx(Ii,{className:"w-4 h-4"}),onClick:()=>x(!0)},{label:u("archives.menu.viewTimelapse"),icon:a.jsx(ph,{className:"w-4 h-4"}),onClick:()=>R(!0),disabled:!t.timelapse_path},{label:u("archives.menu.scanForTimelapse"),icon:a.jsx(nS,{className:"w-4 h-4"}),onClick:()=>pe.mutate(),disabled:!t.printer_id||!!t.timelapse_path||pe.isPending||!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},{label:"",divider:!0,onClick:()=>{}},{label:t.source_3mf_path?u("archives.menu.downloadSource3mf"):u("archives.menu.uploadSource3mf"),icon:a.jsx(J1,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?ae.downloadSource3mf(t.id).catch(we=>{console.error("Source 3MF download failed:",we)}):Fe.current?.click()},disabled:!t.source_3mf_path&&!m("archives","update",t.created_by_id),title:!t.source_3mf_path&&!m("archives","update",t.created_by_id)?u("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:u("archives.menu.replaceSource3mf"),icon:a.jsx(Na,{className:"w-4 h-4"}),onClick:()=>Fe.current?.click(),disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},{label:u("archives.menu.removeSource3mf"),icon:a.jsx(ln,{className:"w-4 h-4"}),onClick:()=>W(!0),danger:!0,disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")}]:[],{label:t.f3d_path?u("archives.menu.replaceF3d"):u("archives.menu.uploadF3d"),icon:a.jsx(Ii,{className:"w-4 h-4"}),onClick:()=>ce.current?.click(),disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:u("archives.menu.downloadF3d"),icon:a.jsx(wi,{className:"w-4 h-4"}),onClick:()=>{ae.downloadF3d(t.id).catch(we=>{console.error("F3D download failed:",we)})}},{label:u("archives.menu.removeF3d"),icon:a.jsx(ln,{className:"w-4 h-4"}),onClick:()=>ne(!0),danger:!0,disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:u("archives.menu.download"),icon:a.jsx(wi,{className:"w-4 h-4"}),onClick:()=>{ae.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(we=>{console.error("Archive download failed:",we)})},disabled:!p("archives:read"),title:p("archives:read")?void 0:u("archives.permission.noDownload")},{label:u("archives.menu.copyDownloadLink"),icon:a.jsx(zl,{className:"w-4 h-4"}),onClick:()=>{const we=`${window.location.origin}${ae.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(we).then(()=>{h(u("archives.toast.linkCopied"))}).catch(()=>{h(u("archives.toast.failedCopyLink"),"error")})},disabled:!p("archives:read"),title:p("archives:read")?void 0:u("archives.permission.noCopyLink")},{label:u("archives.menu.qrCode"),icon:a.jsx(UW,{className:"w-4 h-4"}),onClick:()=>D(!0)},{label:t.photos?.length?u("archives.menu.viewPhotosCount",{count:t.photos.length}):u("archives.menu.viewPhotos"),icon:a.jsx($g,{className:"w-4 h-4"}),onClick:()=>G(!0),disabled:!t.photos?.length},{label:u("archives.menu.projectPage"),icon:a.jsx(ys,{className:"w-4 h-4"}),onClick:()=>K(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?u("archives.menu.removeFromFavorites"):u("archives.menu.addToFavorites"),icon:a.jsx(hm,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>O.mutate(),disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},{label:u("archives.menu.edit"),icon:a.jsx(Ji,{className:"w-4 h-4"}),onClick:()=>A(!0),disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},...t.project_id&&t.project_name?[{label:u("archives.menu.goToProject",{name:t.project_name}),icon:a.jsx(rs,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:u("archives.menu.addToProject"),icon:a.jsx(rs,{className:"w-4 h-4"}),onClick:()=>{},disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives"),submenu:(()=>{const we=[];if(t.project_id&&we.push({label:u("archives.menu.removeFromProject"),icon:a.jsx(Lt,{className:"w-4 h-4"}),onClick:()=>ge.mutate(null),disabled:!m("archives","update",t.created_by_id)}),!s)we.push({label:u("archives.menu.loading"),icon:a.jsx(ct,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const $e=s.filter(Ge=>Ge.status==="active");$e.length===0?we.push({label:u("archives.menu.noProjectsAvailable"),icon:a.jsx(rs,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):$e.forEach(Ge=>{we.push({label:Ge.name,icon:a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:Ge.color||"#888"}}),onClick:()=>ge.mutate(Ge.id),disabled:t.project_id===Ge.id||!m("archives","update",t.created_by_id)})})}return we})()},{label:u(n?"archives.menu.deselect":"archives.menu.select"),icon:n?a.jsx(Xs,{className:"w-4 h-4"}):a.jsx(ul,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:u("archives.menu.delete"),icon:a.jsx(ln,{className:"w-4 h-4"}),onClick:()=>T(!0),danger:!0,disabled:!m("archives","delete",t.created_by_id),title:m("archives","delete",t.created_by_id)?void 0:u("archives.permission.noDelete")}];return a.jsxs(St,{"data-archive-id":t.id,className:`relative flex flex-col group ${n?"ring-2 ring-bambu-green":""} ${i?"cursor-pointer":""}`,style:o?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,onContextMenu:Ce,onClick:i?()=>r(t.id):void 0,children:[i&&a.jsx("button",{className:"absolute top-2 left-2 z-10 p-1 rounded bg-black/50 hover:bg-black/70 transition-colors",onClick:we=>{we.stopPropagation(),r(t.id)},children:n?a.jsx(Xs,{className:"w-5 h-5 text-bambu-green"}):a.jsx(ul,{className:"w-5 h-5 text-white"})}),a.jsxs("div",{className:"aspect-video bg-bambu-dark relative flex-shrink-0 overflow-hidden rounded-t-xl",onMouseEnter:()=>ke(!0),onMouseLeave:()=>ke(!1),children:[t.thumbnail_path?a.jsx("img",{src:de!==null&&V.length>0?ae.getArchivePlateThumbnail(t.id,V[ue]?.index??0):ae.getArchiveThumbnail(t.id),alt:t.print_name||t.filename,className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(Uu,{className:"w-12 h-12 text-bambu-dark-tertiary"})}),Y&&V.length>1&&a.jsxs(a.Fragment,{children:[a.jsx("button",{className:`absolute left-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${b?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:we=>{we.stopPropagation(),Re($e=>{const Ge=$e??0;return Ge>0?Ge-1:V.length-1})},title:u("archives.card.previousPlate"),children:a.jsx(Eh,{className:"w-4 h-4 text-white"})}),a.jsx("button",{className:`absolute right-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${b?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:we=>{we.stopPropagation(),Re($e=>{const Ge=$e??0;return Gea.jsx("button",{className:`w-2 h-2 rounded-full transition-colors ${$e===ue?"bg-bambu-green":"bg-white/50 hover:bg-white/80"}`,onClick:Ge=>{Ge.stopPropagation(),Re($e)},title:we.name||u("archives.card.plateNumber",{index:we.index})},we.index))})]}),a.jsx("button",{className:`absolute top-2 left-2 p-1.5 rounded bg-black/50 hover:bg-black/70 transition-all ${b?"opacity-100":"opacity-0 group-hover:opacity-100"} ${i?"left-10":""}`,onClick:we=>{we.stopPropagation();const $e=we.currentTarget.getBoundingClientRect();fe({x:$e.left,y:$e.bottom+4})},title:u("archives.card.moreOptions"),children:a.jsx(mh,{className:"w-5 h-5 text-white"})}),a.jsx("button",{className:`absolute top-2 right-2 p-1 rounded transition-colors ${m("archives","update",t.created_by_id)?"bg-black/50 hover:bg-black/70":"bg-black/30 cursor-not-allowed"}`,onClick:we=>{we.stopPropagation(),m("archives","update",t.created_by_id)&&O.mutate()},disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?t.is_favorite?u("archives.card.removeFromFavorites"):u("archives.card.addToFavorites"):u("archives.permission.noUpdateArchives"),children:a.jsx(hm,{className:`w-5 h-5 ${t.is_favorite?"text-yellow-400 fill-yellow-400":"text-white"} ${m("archives","update",t.created_by_id)?"":"opacity-50"}`})}),(t.status==="failed"||t.status==="aborted")&&a.jsx("div",{className:"absolute top-2 left-12 px-2 py-1 rounded text-xs bg-status-error/80 text-white",children:t.status==="aborted"?u("archives.card.cancelled"):u("archives.card.failed")}),t.duplicate_count>0&&a.jsxs("div",{className:"absolute top-2 right-2 px-2 py-1 rounded text-xs bg-purple-500/80 text-white flex items-center gap-1",title:u("archives.card.duplicateTitle"),children:[a.jsx(zl,{className:"w-3 h-3"}),u("archives.card.duplicate")]}),t.source_3mf_path&&a.jsx("button",{className:"absolute bottom-2 left-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:we=>{we.stopPropagation();const $e=(t.print_name||t.filename||"source").replace(/\.gcode\.3mf$/i,"")+"_source",Ge=`${window.location.origin}${ae.getSource3mfForSlicer(t.id,$e)}`;sc(Ge,c)},title:u("archives.card.openSource3mf"),children:a.jsx(J1,{className:"w-4 h-4 text-orange-400"})}),t.f3d_path&&a.jsx("button",{className:`absolute bottom-2 ${t.source_3mf_path?"left-12":"left-2"} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`,onClick:we=>{we.stopPropagation(),ae.downloadF3d(t.id).catch($e=>{console.error("F3D download failed:",$e)})},title:u("archives.card.downloadF3d"),children:a.jsx(Ii,{className:"w-4 h-4 text-cyan-400"})}),t.timelapse_path&&a.jsx("button",{className:"absolute bottom-2 right-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:we=>{we.stopPropagation(),R(!0)},title:u("archives.card.viewTimelapse"),children:a.jsx(ph,{className:"w-4 h-4 text-bambu-green"})}),t.photos&&t.photos.length>0&&a.jsxs("button",{className:`absolute bottom-2 ${t.timelapse_path?"right-12":"right-2"} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`,onClick:we=>{we.stopPropagation(),G(!0)},title:t.photos.length===1?u("archives.card.viewPhoto"):u("archives.card.viewPhotos",{count:t.photos.length}),children:[a.jsx($g,{className:"w-4 h-4 text-blue-400"}),t.photos.length>1&&a.jsx("span",{className:"absolute -top-1 -right-1 w-4 h-4 bg-blue-500 rounded-full text-[10px] text-white flex items-center justify-center",children:t.photos.length})]}),Z&&Z.length>0&&a.jsx(Bs,{to:`/files?folder=${Z[0].id}`,className:"absolute bottom-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:we=>we.stopPropagation(),title:u("archives.card.openFolder",{name:Z[0].name}),style:{left:t.source_3mf_path?t.f3d_path?"5.5rem":"3rem":t.f3d_path?"3rem":"0.5rem"},children:a.jsx(Ul,{className:"w-4 h-4 text-yellow-400"})})]}),a.jsxs(Et,{className:"p-4 flex-1 flex flex-col",children:[a.jsx("h3",{className:"font-medium text-white mb-1 truncate",children:t.print_name||t.filename}),a.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-wrap",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:e}),a.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium ${Ff(t.filename)?"bg-bambu-green/20 text-bambu-green":"bg-orange-500/20 text-orange-400"}`,title:Ff(t.filename)?u("archives.card.slicedFile"):u("archives.card.sourceFile"),children:Ff(t.filename)?u("archives.card.gcode"):u("archives.card.source")}),t.project_name&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full truncate max-w-[120px]",style:{backgroundColor:`${s?.find(we=>we.id===t.project_id)?.color||"#6b7280"}20`,color:s?.find(we=>we.id===t.project_id)?.color||"#6b7280"},title:u("archives.card.project",{name:t.project_name}),children:t.project_name})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs mb-4 min-h-[48px]",children:[(t.print_time_seconds||t.actual_time_seconds)&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.time_accuracy?`Estimated: ${s0(t.print_time_seconds||0)} + [&::-webkit-slider-thumb]:cursor-pointer`}),a.jsx("span",{className:"text-xs text-bambu-gray w-12",children:M(m)})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{onClick:N,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip back 5s",children:a.jsx(Khe,{className:"w-5 h-5 text-bambu-gray"})}),a.jsx("button",{onClick:v,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?a.jsx(Sk,{className:"w-5 h-5 text-white"}):a.jsx(Eo,{className:"w-5 h-5 text-white"})}),a.jsx("button",{onClick:T,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip forward 5s",children:a.jsx(qR,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:"Speed:"}),a.jsx("div",{className:"flex gap-1",children:S9e.map(k=>a.jsxs("button",{onClick:()=>d(k),className:`px-2 py-1 text-xs rounded transition-colors ${u===k?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary/80"}`,children:[k,"x"]},k))})]})]})]})]})]}),y&&r&&a.jsx(_9e,{archiveId:r,timelapseSrc:t,onClose:()=>x(!1),onSave:s})]})}function N9e({archiveIds:t,onClose:e}){_.useEffect(()=>{const s=o=>{o.key==="Escape"&&e()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e]);const{data:n,isLoading:r,error:i}=it({queryKey:["archive-comparison",t],queryFn:()=>ae.compareArchives(t)});return a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg max-w-4xl w-full max-h-[90vh] flex flex-col border border-bambu-dark-tertiary",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white",children:["Compare Archives (",t.length,")"]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white p-1",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 overflow-auto p-4 bg-bambu-dark-secondary",children:r?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i?a.jsxs("div",{className:"text-center py-12 text-red-400",children:[a.jsx(En,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),a.jsx("p",{children:"Failed to load comparison"}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:i instanceof Error?i.message:"Unknown error"})]}):n?a.jsx(k9e,{comparison:n}):null}),a.jsx("div",{className:"p-4 border-t border-bambu-dark-tertiary",children:a.jsx(Ne,{variant:"secondary",onClick:e,className:"w-full",children:"Close"})})]})})}function k9e({comparison:t}){return a.jsxs("div",{className:"space-y-6",children:[a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{className:"text-left text-sm text-bambu-gray font-medium pb-2 pr-4 min-w-[150px]",children:"Setting"}),t.archives.map(e=>a.jsxs("th",{className:"text-left text-sm font-medium pb-2 px-2 min-w-[120px]",children:[a.jsx("div",{className:"text-white truncate max-w-[150px]",title:e.print_name,children:e.print_name}),a.jsx("div",{className:`text-xs ${e.status==="completed"?"text-status-ok":e.status==="failed"?"text-status-error":"text-bambu-gray"}`,children:e.status})]},e.id))]})}),a.jsx("tbody",{className:"divide-y divide-bambu-gray/20",children:t.comparison.map(e=>a.jsxs("tr",{className:e.has_difference?"bg-yellow-500/5":"",children:[a.jsx("td",{className:"py-2 pr-4 text-sm",children:a.jsxs("div",{className:"flex items-center gap-2",children:[e.has_difference&&a.jsx(En,{className:"w-3 h-3 text-yellow-400 flex-shrink-0"}),a.jsx("span",{className:e.has_difference?"text-yellow-400":"text-bambu-gray",children:e.label})]})}),e.values.map((n,r)=>a.jsxs("td",{className:"py-2 px-2 text-sm text-white",children:[n??a.jsx("span",{className:"text-bambu-gray/50",children:"-"}),e.unit&&n!==null&&a.jsx("span",{className:"text-bambu-gray ml-1",children:e.unit})]},r))]},e.field))})]})}),t.differences.length>0&&a.jsxs("div",{className:"p-4 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[a.jsxs("h4",{className:"text-sm font-medium text-yellow-400 mb-2 flex items-center gap-2",children:[a.jsx(En,{className:"w-4 h-4"}),t.differences.length," Difference",t.differences.length>1?"s":""," Found"]}),a.jsxs("ul",{className:"text-sm text-white/80 space-y-1",children:[t.differences.slice(0,5).map(e=>a.jsxs("li",{children:[a.jsx("span",{className:"text-yellow-400",children:e.label}),": ",e.values.join(" vs ")," ",e.unit||""]},e.field)),t.differences.length>5&&a.jsxs("li",{className:"text-bambu-gray",children:["...and ",t.differences.length-5," more"]})]})]}),t.success_correlation.has_both_outcomes?a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("h4",{className:"text-sm font-medium text-white mb-3 flex items-center gap-2",children:[a.jsx($i,{className:"w-4 h-4 text-bambu-green"}),"Success/Failure Analysis"]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm mb-3",children:[a.jsxs("span",{className:"text-bambu-green",children:[t.success_correlation.successful_count," successful"]}),a.jsxs("span",{className:"text-red-400",children:[t.success_correlation.failed_count," failed"]})]}),t.success_correlation.insights&&t.success_correlation.insights.length>0?a.jsx("div",{className:"space-y-2",children:t.success_correlation.insights.map(e=>a.jsxs("div",{className:"text-sm p-2 bg-bambu-dark-secondary rounded",children:[a.jsxs("span",{className:"text-white font-medium",children:[e.label,":"]})," ",a.jsx("span",{className:"text-white/80",children:e.insight})]},e.field))}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No clear correlations found between settings and outcomes."})]}):a.jsx("div",{className:"p-4 bg-bambu-dark rounded-lg text-sm text-bambu-gray",children:a.jsx("p",{children:t.success_correlation.message||"Need both successful and failed prints for correlation analysis."})})]})}function M9e(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function E9e(t){const e=new Date(t),r=new Date().getTime()-e.getTime(),i=Math.floor(r/6e4);if(i<1)return"Just now";if(i<60)return`${i}m ago`;const s=Math.floor(i/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}function T9e({upload:t,projects:e,onArchive:n,onDiscard:r,isArchiving:i,isDiscarding:s}){const[o,l]=_.useState(!1),[c,u]=_.useState(t.tags||""),[d,h]=_.useState(t.notes||""),[p,m]=_.useState(t.project_id),[b,y]=_.useState(!1);return a.jsx(St,{children:a.jsxs(Et,{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Kf,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[a.jsx("span",{children:M9e(t.file_size)}),a.jsx("span",{children:"·"}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(tr,{className:"w-3 h-3"}),E9e(t.uploaded_at)]}),t.source_ip&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"·"}),a.jsxs("span",{children:["from ",t.source_ip]})]})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{onClick:()=>l(!o),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:o?a.jsx(zu,{className:"w-5 h-5"}):a.jsx(fr,{className:"w-5 h-5"})}),a.jsx(Ne,{variant:"primary",size:"sm",onClick:()=>n(t.id,{tags:c,notes:d,project_id:p||void 0}),disabled:i,children:i?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(vo,{className:"w-4 h-4"}),"Archive"]})}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>y(!0),disabled:s,children:s?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4 text-red-400"})})]})]}),b&&a.jsx(er,{title:"Discard Upload",message:`Are you sure you want to discard "${t.filename}"? This cannot be undone.`,confirmText:"Discard",variant:"danger",onConfirm:()=>{r(t.id),y(!1)},onCancel:()=>y(!1)}),o&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Tags"}),a.jsx("input",{type:"text",value:c,onChange:x=>u(x.target.value),placeholder:"e.g., functional, prototype, gift",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white placeholder-bambu-gray text-sm"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes"}),a.jsx("textarea",{value:d,onChange:x=>h(x.target.value),placeholder:"Add notes about this print...",rows:2,className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white placeholder-bambu-gray text-sm resize-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Project"}),a.jsxs("select",{value:p||"",onChange:x=>m(x.target.value?Number(x.target.value):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white text-sm",children:[a.jsx("option",{value:"",children:"No project"}),e.map(x=>a.jsx("option",{value:x.id,children:x.name},x.id))]})]})]})]})})}function A9e(){const t=an(),{showToast:e}=Tn(),[n,r]=_.useState(!1),[i,s]=_.useState(!1),[o,l]=_.useState(new Set),[c,u]=_.useState(new Set),{data:d,isLoading:h}=it({queryKey:["pending-uploads"],queryFn:cg.list,refetchInterval:1e4}),{data:p}=it({queryKey:["projects"],queryFn:()=>ae.getProjects()}),m=dt({mutationFn:({id:v,data:S})=>cg.archive(v,S),onMutate:({id:v})=>{l(S=>new Set(S).add(v))},onSettled:(v,S,{id:N})=>{l(T=>{const M=new Set(T);return M.delete(N),M})},onSuccess:v=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived: ${v.print_name}`)},onError:v=>{e(v.message||"Failed to archive","error")}}),b=dt({mutationFn:v=>cg.discard(v),onMutate:v=>{u(S=>new Set(S).add(v))},onSettled:(v,S,N)=>{u(T=>{const M=new Set(T);return M.delete(N),M})},onSuccess:()=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e("Upload discarded")},onError:v=>{e(v.message||"Failed to discard","error")}}),y=dt({mutationFn:cg.archiveAll,onSuccess:v=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived ${v.archived} files${v.failed>0?`, ${v.failed} failed`:""}`)},onError:v=>{e(v.message||"Failed to archive all","error")}}),x=dt({mutationFn:cg.discardAll,onSuccess:v=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e(`Discarded ${v.discarded} files`)},onError:v=>{e(v.message||"Failed to discard all","error")}});return h?a.jsx(St,{children:a.jsx(Et,{className:"py-8 flex justify-center",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})})}):!d||d.length===0?null:a.jsxs("div",{className:"mb-6",children:[a.jsxs(St,{className:"border-l-4 border-l-yellow-500",children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Na,{className:"w-5 h-5 text-yellow-500"}),a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Pending Uploads (",d.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ne,{variant:"primary",size:"sm",onClick:()=>r(!0),disabled:y.isPending,children:y.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(vo,{className:"w-4 h-4"}),"Archive All"]})}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>s(!0),disabled:x.isPending,children:x.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(ln,{className:"w-4 h-4"}),"Discard All"]})})]})]})}),a.jsxs(Et,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"These files were uploaded via the virtual printer. Review and archive them to add to your collection."}),a.jsx("div",{className:"space-y-3",children:d.map(v=>a.jsx(T9e,{upload:v,projects:p||[],onArchive:(S,N)=>m.mutate({id:S,data:N}),onDiscard:S=>b.mutate(S),isArchiving:o.has(v.id),isDiscarding:c.has(v.id)},v.id))})]})]}),n&&a.jsx(er,{title:"Archive All Uploads",message:`Are you sure you want to archive all ${d.length} pending uploads?`,confirmText:"Archive All",onConfirm:()=>{y.mutate(),r(!1)},onCancel:()=>r(!1)}),i&&a.jsx(er,{title:"Discard All Uploads",message:`Are you sure you want to discard all ${d.length} pending uploads? This cannot be undone.`,confirmText:"Discard All",variant:"danger",onConfirm:()=>{x.mutate(),s(!1)},onCancel:()=>s(!1)})]})}function C9e({onClose:t}){const e=an(),{showToast:n}=Tn(),[r,i]=_.useState(""),[s,o]=_.useState(null),[l,c]=_.useState(""),[u,d]=_.useState(null),[h,p]=_.useState("count");_.useEffect(()=>{const C=P=>{P.key==="Escape"&&(s?o(null):u?d(null):t())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[t,s,u]);const{data:m,isLoading:b}=it({queryKey:["tags"],queryFn:ae.getTags}),y=dt({mutationFn:({oldName:C,newName:P})=>ae.renameTag(C,P),onSuccess:(C,{oldName:P,newName:U})=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Renamed "${P}" to "${U}" in ${C.affected} archive${C.affected!==1?"s":""}`),o(null)},onError:C=>{n(C.message||"Failed to rename tag","error")}}),x=dt({mutationFn:C=>ae.deleteTag(C),onSuccess:(C,P)=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Deleted "${P}" from ${C.affected} archive${C.affected!==1?"s":""}`),d(null)},onError:C=>{n(C.message||"Failed to delete tag","error")}}),v=C=>{o(C.name),c(C.name),d(null)},S=()=>{o(null),c("")},N=()=>{if(!s||!l.trim())return;const C=l.trim();if(C===s){S();return}y.mutate({oldName:s,newName:C})},T=C=>{C.key==="Enter"?(C.preventDefault(),N()):C.key==="Escape"&&(C.preventDefault(),S())},M=C=>{d(C),o(null)},A=()=>{u&&x.mutate(u)},k=m?.filter(C=>C.name.toLowerCase().includes(r.toLowerCase())).sort((C,P)=>h==="count"&&P.count-C.count||C.name.localeCompare(P.name)),R=m?.reduce((C,P)=>C+P.count,0)||0;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-lg max-h-[80vh] flex flex-col",children:a.jsxs(Et,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Th,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Manage Tags"})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:"Search tags...",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:r,onChange:C=>i(C.target.value)})]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:h,onChange:C=>p(C.target.value),children:[a.jsx("option",{value:"count",children:"Sort by Count"}),a.jsx("option",{value:"name",children:"Sort by Name"})]})]}),m&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[m.length," tag",m.length!==1?"s":""," across ",R," usage",R!==1?"s":""]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 p-4",children:b?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):k?.length?a.jsx("div",{className:"space-y-2",children:k.map(C=>a.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary transition-colors group",children:s===C.name?a.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[a.jsx("input",{type:"text",className:"flex-1 px-2 py-1 bg-bambu-dark-tertiary border border-bambu-green rounded text-white text-sm focus:outline-none",value:l,onChange:P=>c(P.target.value),onKeyDown:T,autoFocus:!0}),a.jsx(Ne,{size:"sm",variant:"primary",onClick:N,disabled:!l.trim()||y.isPending,className:"p-1.5",children:y.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx($i,{className:"w-4 h-4"})}),a.jsx(Ne,{size:"sm",variant:"ghost",onClick:S,className:"p-1.5",children:a.jsx(Lt,{className:"w-4 h-4"})})]}):u===C.name?a.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[a.jsx(En,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-bambu-gray-light flex-1",children:['Delete "',C.name,'" from ',C.count," archive",C.count!==1?"s":"","?"]}),a.jsx(Ne,{size:"sm",variant:"danger",onClick:A,disabled:x.isPending,className:"p-1.5",children:x.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4"})}),a.jsx(Ne,{size:"sm",variant:"ghost",onClick:()=>d(null),className:"p-1.5",children:a.jsx(Lt,{className:"w-4 h-4"})})]}):a.jsxs(a.Fragment,{children:[a.jsx(Th,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-white flex-1 truncate",children:C.name}),a.jsx("span",{className:"px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-xs",children:C.count}),a.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[a.jsx("button",{onClick:()=>v(C),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors",title:"Rename tag",children:a.jsx(Ji,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>M(C.name),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors",title:"Delete tag",children:a.jsx(ln,{className:"w-4 h-4"})})]})]})},C.name))}):a.jsx("div",{className:"text-center py-8 text-bambu-gray",children:r?"No tags match your search":"No tags found"})}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:a.jsx(Ne,{variant:"secondary",onClick:t,className:"flex-1",children:"Close"})})]})})})}function rk(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function s0(t){const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function Ff(t){if(!t)return!1;const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function Tre(t){if(!t)return;const e=t.toLowerCase();return e.endsWith(".3mf")?"3mf":e.endsWith(".stl")?"stl":e.endsWith(".gcode")||e.includes(".gcode.")?"gcode":e.split(".").pop()}function P9e({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:i,projects:s,isHighlighted:o,timeFormat:l="system",preferredSlicer:c="bambu_studio",t:u}){o&&console.log("ArchiveCard isHighlighted=true for archive:",t.id);const d=an(),{showToast:h}=Tn(),{hasPermission:p,canModify:m}=Ir(),b=QR(),[y,x]=_.useState(!1),[v,S]=_.useState(!1),[N,T]=_.useState(!1),[M,A]=_.useState(!1),[k,R]=_.useState(!1),[C,P]=_.useState(!1),[U,F]=_.useState([]),[H,D]=_.useState(!1),[$,G]=_.useState(!1),[I,K]=_.useState(!1),[Q,oe]=_.useState(!1),[B,W]=_.useState(!1),[J,ne]=_.useState(!1),[me,fe]=_.useState(null),[de,Re]=_.useState(null),[se,ke]=_.useState(!1),Fe=_.useRef(null),ce=_.useRef(null),{data:Ve}=it({queryKey:["archive-plates",t.id],queryFn:()=>ae.getArchivePlates(t.id),enabled:se,staleTime:300*1e3}),V=Ve?.plates??[],Y=Ve?.is_multi_plate??!1,ue=de??0,q=dt({mutationFn:we=>ae.uploadSource3mf(t.id,we),onSuccess:we=>{d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.source3mfAttached",{filename:we.filename}))},onError:we=>{h(we.message||u("archives.toast.failedUploadSource3mf"),"error")}}),re=dt({mutationFn:()=>ae.deleteSource3mf(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.source3mfRemoved"))},onError:we=>{h(we.message||u("archives.toast.failedRemoveSource3mf"),"error")}}),X=dt({mutationFn:we=>ae.uploadF3d(t.id,we),onSuccess:we=>{d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.f3dAttached",{filename:we.filename}))},onError:we=>{h(we.message||u("archives.toast.failedUploadF3d"),"error")}}),le=dt({mutationFn:()=>ae.deleteF3d(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.f3dRemoved"))},onError:we=>{h(we.message||u("archives.toast.failedRemoveF3d"),"error")}}),pe=dt({mutationFn:()=>ae.scanArchiveTimelapse(t.id),onSuccess:we=>{we.status==="attached"?(d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.timelapseAttached",{filename:we.filename}))):we.status==="exists"?h(u("archives.toast.timelapseAlreadyAttached")):we.status==="not_found"&&we.available_files&&we.available_files.length>0?(F(we.available_files),P(!0)):h(we.message||u("archives.toast.noMatchingTimelapse"),"warning")},onError:we=>{h(we.message||u("archives.toast.failedScanTimelapse"),"error")}}),ee=dt({mutationFn:we=>ae.selectArchiveTimelapse(t.id,we),onSuccess:we=>{d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.timelapseAttached",{filename:we.filename})),P(!1),F([])},onError:we=>{h(we.message||u("archives.toast.failedAttachTimelapse"),"error")}}),z=dt({mutationFn:()=>ae.deleteArchive(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.archiveDeleted"))},onError:()=>{h(u("archives.toast.failedDeleteArchive"),"error")}}),O=dt({mutationFn:()=>ae.toggleFavorite(t.id),onSuccess:we=>{d.invalidateQueries({queryKey:["archives"]}),h(we.is_favorite?u("archives.toast.addedToFavorites"):u("archives.toast.removedFromFavorites"))}}),{data:Z}=it({queryKey:["archive-folders",t.id],queryFn:()=>ae.getLibraryFoldersByArchive(t.id)}),ge=dt({mutationFn:we=>ae.updateArchive(t.id,{project_id:we}),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),d.invalidateQueries({queryKey:["projects"]}),h(u("archives.toast.projectUpdated"))},onError:()=>{h(u("archives.toast.failedUpdateProject"),"error")}}),Ce=we=>{we.preventDefault(),fe({x:we.clientX,y:we.clientY})},Te=[...Ff(t.filename)?[{label:u("archives.menu.print"),icon:a.jsx(jr,{className:"w-4 h-4"}),onClick:()=>S(!0),disabled:!m("archives","reprint",t.created_by_id),title:m("archives","reprint",t.created_by_id)?void 0:u("archives.permission.noReprint")},{label:u("archives.menu.schedule"),icon:a.jsx(ti,{className:"w-4 h-4"}),onClick:()=>oe(!0),disabled:!p("queue:create"),title:p("queue:create")?void 0:u("archives.permission.noAddToQueue")},{label:u("archives.menu.openInBambuStudio"),icon:a.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>{const we=t.print_name||t.filename||"model",$e=`${window.location.origin}${ae.getArchiveForSlicer(t.id,we)}`;sc($e,c)}}]:[{label:u("archives.menu.slice"),icon:a.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>{const we=t.print_name||t.filename||"model",$e=`${window.location.origin}${ae.getArchiveForSlicer(t.id,we)}`;sc($e,c)}}],{label:t.external_url?u("archives.menu.externalLink"):u("archives.menu.viewOnMakerWorld"),icon:a.jsx(gh,{className:"w-4 h-4"}),onClick:()=>{const we=t.external_url||t.makerworld_url;we&&window.open(we,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:u("archives.menu.preview3d"),icon:a.jsx(Ii,{className:"w-4 h-4"}),onClick:()=>x(!0)},{label:u("archives.menu.viewTimelapse"),icon:a.jsx(ph,{className:"w-4 h-4"}),onClick:()=>R(!0),disabled:!t.timelapse_path},{label:u("archives.menu.scanForTimelapse"),icon:a.jsx(nS,{className:"w-4 h-4"}),onClick:()=>pe.mutate(),disabled:!t.printer_id||!!t.timelapse_path||pe.isPending||!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},{label:"",divider:!0,onClick:()=>{}},{label:t.source_3mf_path?u("archives.menu.downloadSource3mf"):u("archives.menu.uploadSource3mf"),icon:a.jsx(J1,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?ae.downloadSource3mf(t.id).catch(we=>{console.error("Source 3MF download failed:",we)}):Fe.current?.click()},disabled:!t.source_3mf_path&&!m("archives","update",t.created_by_id),title:!t.source_3mf_path&&!m("archives","update",t.created_by_id)?u("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:u("archives.menu.replaceSource3mf"),icon:a.jsx(Na,{className:"w-4 h-4"}),onClick:()=>Fe.current?.click(),disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},{label:u("archives.menu.removeSource3mf"),icon:a.jsx(ln,{className:"w-4 h-4"}),onClick:()=>W(!0),danger:!0,disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")}]:[],{label:t.f3d_path?u("archives.menu.replaceF3d"):u("archives.menu.uploadF3d"),icon:a.jsx(Ii,{className:"w-4 h-4"}),onClick:()=>ce.current?.click(),disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:u("archives.menu.downloadF3d"),icon:a.jsx(wi,{className:"w-4 h-4"}),onClick:()=>{ae.downloadF3d(t.id).catch(we=>{console.error("F3D download failed:",we)})}},{label:u("archives.menu.removeF3d"),icon:a.jsx(ln,{className:"w-4 h-4"}),onClick:()=>ne(!0),danger:!0,disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:u("archives.menu.download"),icon:a.jsx(wi,{className:"w-4 h-4"}),onClick:()=>{ae.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(we=>{console.error("Archive download failed:",we)})},disabled:!p("archives:read"),title:p("archives:read")?void 0:u("archives.permission.noDownload")},{label:u("archives.menu.copyDownloadLink"),icon:a.jsx(zl,{className:"w-4 h-4"}),onClick:()=>{const we=`${window.location.origin}${ae.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(we).then(()=>{h(u("archives.toast.linkCopied"))}).catch(()=>{h(u("archives.toast.failedCopyLink"),"error")})},disabled:!p("archives:read"),title:p("archives:read")?void 0:u("archives.permission.noCopyLink")},{label:u("archives.menu.qrCode"),icon:a.jsx(UW,{className:"w-4 h-4"}),onClick:()=>D(!0)},{label:t.photos?.length?u("archives.menu.viewPhotosCount",{count:t.photos.length}):u("archives.menu.viewPhotos"),icon:a.jsx($g,{className:"w-4 h-4"}),onClick:()=>G(!0),disabled:!t.photos?.length},{label:u("archives.menu.projectPage"),icon:a.jsx(ys,{className:"w-4 h-4"}),onClick:()=>K(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?u("archives.menu.removeFromFavorites"):u("archives.menu.addToFavorites"),icon:a.jsx(hm,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>O.mutate(),disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},{label:u("archives.menu.edit"),icon:a.jsx(Ji,{className:"w-4 h-4"}),onClick:()=>A(!0),disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},...t.project_id&&t.project_name?[{label:u("archives.menu.goToProject",{name:t.project_name}),icon:a.jsx(rs,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:u("archives.menu.addToProject"),icon:a.jsx(rs,{className:"w-4 h-4"}),onClick:()=>{},disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives"),submenu:(()=>{const we=[];if(t.project_id&&we.push({label:u("archives.menu.removeFromProject"),icon:a.jsx(Lt,{className:"w-4 h-4"}),onClick:()=>ge.mutate(null),disabled:!m("archives","update",t.created_by_id)}),!s)we.push({label:u("archives.menu.loading"),icon:a.jsx(ct,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const $e=s.filter(Ge=>Ge.status==="active");$e.length===0?we.push({label:u("archives.menu.noProjectsAvailable"),icon:a.jsx(rs,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):$e.forEach(Ge=>{we.push({label:Ge.name,icon:a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:Ge.color||"#888"}}),onClick:()=>ge.mutate(Ge.id),disabled:t.project_id===Ge.id||!m("archives","update",t.created_by_id)})})}return we})()},{label:u(n?"archives.menu.deselect":"archives.menu.select"),icon:n?a.jsx(Xs,{className:"w-4 h-4"}):a.jsx(ul,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:u("archives.menu.delete"),icon:a.jsx(ln,{className:"w-4 h-4"}),onClick:()=>T(!0),danger:!0,disabled:!m("archives","delete",t.created_by_id),title:m("archives","delete",t.created_by_id)?void 0:u("archives.permission.noDelete")}];return a.jsxs(St,{"data-archive-id":t.id,className:`relative flex flex-col group ${n?"ring-2 ring-bambu-green":""} ${i?"cursor-pointer":""}`,style:o?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,onContextMenu:Ce,onClick:i?()=>r(t.id):void 0,children:[i&&a.jsx("button",{className:"absolute top-2 left-2 z-10 p-1 rounded bg-black/50 hover:bg-black/70 transition-colors",onClick:we=>{we.stopPropagation(),r(t.id)},children:n?a.jsx(Xs,{className:"w-5 h-5 text-bambu-green"}):a.jsx(ul,{className:"w-5 h-5 text-white"})}),a.jsxs("div",{className:"aspect-video bg-bambu-dark relative flex-shrink-0 overflow-hidden rounded-t-xl",onMouseEnter:()=>ke(!0),onMouseLeave:()=>ke(!1),children:[t.thumbnail_path?a.jsx("img",{src:de!==null&&V.length>0?ae.getArchivePlateThumbnail(t.id,V[ue]?.index??0):ae.getArchiveThumbnail(t.id),alt:t.print_name||t.filename,className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(Uu,{className:"w-12 h-12 text-bambu-dark-tertiary"})}),Y&&V.length>1&&a.jsxs(a.Fragment,{children:[a.jsx("button",{className:`absolute left-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${b?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:we=>{we.stopPropagation(),Re($e=>{const Ge=$e??0;return Ge>0?Ge-1:V.length-1})},title:u("archives.card.previousPlate"),children:a.jsx(Eh,{className:"w-4 h-4 text-white"})}),a.jsx("button",{className:`absolute right-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${b?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:we=>{we.stopPropagation(),Re($e=>{const Ge=$e??0;return Gea.jsx("button",{className:`w-2 h-2 rounded-full transition-colors ${$e===ue?"bg-bambu-green":"bg-white/50 hover:bg-white/80"}`,onClick:Ge=>{Ge.stopPropagation(),Re($e)},title:we.name||u("archives.card.plateNumber",{index:we.index})},we.index))})]}),a.jsx("button",{className:`absolute top-2 left-2 p-1.5 rounded bg-black/50 hover:bg-black/70 transition-all ${b?"opacity-100":"opacity-0 group-hover:opacity-100"} ${i?"left-10":""}`,onClick:we=>{we.stopPropagation();const $e=we.currentTarget.getBoundingClientRect();fe({x:$e.left,y:$e.bottom+4})},title:u("archives.card.moreOptions"),children:a.jsx(mh,{className:"w-5 h-5 text-white"})}),a.jsx("button",{className:`absolute top-2 right-2 p-1 rounded transition-colors ${m("archives","update",t.created_by_id)?"bg-black/50 hover:bg-black/70":"bg-black/30 cursor-not-allowed"}`,onClick:we=>{we.stopPropagation(),m("archives","update",t.created_by_id)&&O.mutate()},disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?t.is_favorite?u("archives.card.removeFromFavorites"):u("archives.card.addToFavorites"):u("archives.permission.noUpdateArchives"),children:a.jsx(hm,{className:`w-5 h-5 ${t.is_favorite?"text-yellow-400 fill-yellow-400":"text-white"} ${m("archives","update",t.created_by_id)?"":"opacity-50"}`})}),(t.status==="failed"||t.status==="aborted")&&a.jsx("div",{className:"absolute top-2 left-12 px-2 py-1 rounded text-xs bg-status-error/80 text-white",children:t.status==="aborted"?u("archives.card.cancelled"):u("archives.card.failed")}),t.duplicate_count>0&&a.jsxs("div",{className:"absolute top-2 right-2 px-2 py-1 rounded text-xs bg-purple-500/80 text-white flex items-center gap-1",title:u("archives.card.duplicateTitle"),children:[a.jsx(zl,{className:"w-3 h-3"}),u("archives.card.duplicate")]}),t.source_3mf_path&&a.jsx("button",{className:"absolute bottom-2 left-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:we=>{we.stopPropagation();const $e=(t.print_name||t.filename||"source").replace(/\.gcode\.3mf$/i,"")+"_source",Ge=`${window.location.origin}${ae.getSource3mfForSlicer(t.id,$e)}`;sc(Ge,c)},title:u("archives.card.openSource3mf"),children:a.jsx(J1,{className:"w-4 h-4 text-orange-400"})}),t.f3d_path&&a.jsx("button",{className:`absolute bottom-2 ${t.source_3mf_path?"left-12":"left-2"} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`,onClick:we=>{we.stopPropagation(),ae.downloadF3d(t.id).catch($e=>{console.error("F3D download failed:",$e)})},title:u("archives.card.downloadF3d"),children:a.jsx(Ii,{className:"w-4 h-4 text-cyan-400"})}),t.timelapse_path&&a.jsx("button",{className:"absolute bottom-2 right-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:we=>{we.stopPropagation(),R(!0)},title:u("archives.card.viewTimelapse"),children:a.jsx(ph,{className:"w-4 h-4 text-bambu-green"})}),t.photos&&t.photos.length>0&&a.jsxs("button",{className:`absolute bottom-2 ${t.timelapse_path?"right-12":"right-2"} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`,onClick:we=>{we.stopPropagation(),G(!0)},title:t.photos.length===1?u("archives.card.viewPhoto"):u("archives.card.viewPhotos",{count:t.photos.length}),children:[a.jsx($g,{className:"w-4 h-4 text-blue-400"}),t.photos.length>1&&a.jsx("span",{className:"absolute -top-1 -right-1 w-4 h-4 bg-blue-500 rounded-full text-[10px] text-white flex items-center justify-center",children:t.photos.length})]}),Z&&Z.length>0&&a.jsx(Bs,{to:`/files?folder=${Z[0].id}`,className:"absolute bottom-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:we=>we.stopPropagation(),title:u("archives.card.openFolder",{name:Z[0].name}),style:{left:t.source_3mf_path?t.f3d_path?"5.5rem":"3rem":t.f3d_path?"3rem":"0.5rem"},children:a.jsx(Ul,{className:"w-4 h-4 text-yellow-400"})})]}),a.jsxs(Et,{className:"p-4 flex-1 flex flex-col",children:[a.jsx("h3",{className:"font-medium text-white mb-1 truncate",children:t.print_name||t.filename}),a.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-wrap",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:e}),a.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium ${Ff(t.filename)?"bg-bambu-green/20 text-bambu-green":"bg-orange-500/20 text-orange-400"}`,title:Ff(t.filename)?u("archives.card.slicedFile"):u("archives.card.sourceFile"),children:Ff(t.filename)?u("archives.card.gcode"):u("archives.card.source")}),t.project_name&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full truncate max-w-[120px]",style:{backgroundColor:`${s?.find(we=>we.id===t.project_id)?.color||"#6b7280"}20`,color:s?.find(we=>we.id===t.project_id)?.color||"#6b7280"},title:u("archives.card.project",{name:t.project_name}),children:t.project_name})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs mb-4 min-h-[48px]",children:[(t.print_time_seconds||t.actual_time_seconds)&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.time_accuracy?`Estimated: ${s0(t.print_time_seconds||0)} Actual: ${s0(t.actual_time_seconds||0)} -Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${s0(t.actual_time_seconds)}`:`Estimated: ${s0(t.print_time_seconds||0)}`,children:[a.jsx(tr,{className:"w-3 h-3"}),s0(t.actual_time_seconds||t.print_time_seconds||0),t.time_accuracy&&a.jsxs("span",{className:`text-[10px] px-1 rounded ${t.time_accuracy>=95&&t.time_accuracy<=105?"bg-bambu-green/20 text-bambu-green":t.time_accuracy>105?"bg-blue-500/20 text-blue-400":"bg-orange-500/20 text-orange-400"}`,children:[t.time_accuracy>100?"+":"",(t.time_accuracy-100).toFixed(0),"%"]})]}),t.filament_used_grams&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(bc,{className:"w-3 h-3"}),t.filament_used_grams.toFixed(1),"g"]}),(t.layer_height||t.total_layers)&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(is,{className:"w-3 h-3"}),t.total_layers&&a.jsx("span",{children:t.total_layers===1?u("archives.card.layer",{count:t.total_layers}):u("archives.card.layers",{count:t.total_layers})}),t.total_layers&&t.layer_height&&a.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.layer_height&&a.jsxs("span",{children:[t.layer_height,"mm"]})]}),t.object_count!=null&&t.object_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.object_count===1?u("archives.card.object",{count:t.object_count}):u("archives.card.objects",{count:t.object_count}),children:[a.jsx(Ii,{className:"w-3 h-3"}),t.object_count===1?u("archives.card.object",{count:t.object_count}):u("archives.card.objects",{count:t.object_count})]}),t.sliced_for_model&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:u("archives.card.slicedFor",{model:t.sliced_for_model}),children:[a.jsx(jr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.filament_type&&a.jsxs("div",{className:"flex items-center gap-1.5 col-span-2",children:[a.jsx("span",{className:"text-bambu-gray text-xs",children:t.filament_type}),t.filament_color&&a.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((we,$e)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:we},title:we},$e))})]})]}),(t.tags||t.notes)&&a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[t.notes&&a.jsx("div",{className:"flex items-center gap-1 px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded text-xs",title:t.notes,children:a.jsx(HW,{className:"w-3 h-3"})}),t.tags?.split(",").map((we,$e)=>a.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-dark-tertiary text-bambu-gray-light rounded text-xs",children:we.trim()},$e))]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray border-t border-bambu-dark-tertiary pt-3",children:[a.jsx("span",{children:qg(t.created_at,l)}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.created_by_username&&a.jsxs("span",{className:"flex items-center gap-1",title:u("archives.card.uploadedBy",{name:t.created_by_username}),children:[a.jsx($u,{className:"w-3 h-3"}),t.created_by_username]}),a.jsx("span",{children:rk(t.file_size)})]})]}),a.jsxs("div",{className:"flex gap-1 mt-3",children:[Ff(t.filename)?a.jsxs(a.Fragment,{children:[a.jsxs(Ne,{variant:"primary",size:"sm",className:"flex-1 min-w-0",onClick:()=>S(!0),disabled:!m("archives","reprint",t.created_by_id),title:m("archives","reprint",t.created_by_id)?void 0:u("archives.card.noPermissionReprint"),children:[a.jsx(jr,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"hidden sm:inline",children:u("archives.card.reprint")})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",className:"flex-1 min-w-0",onClick:()=>oe(!0),disabled:!p("queue:create"),title:p("queue:create")?u("archives.card.schedulePrint"):u("archives.permission.noAddToQueue"),children:[a.jsx(ti,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"hidden sm:inline",children:u("archives.card.schedule")})]}),a.jsx(Ne,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const we=t.print_name||t.filename||"model",$e=`${window.location.origin}${ae.getArchiveForSlicer(t.id,we)}`;sc($e,c)},title:u("archives.card.openInBambuStudio"),children:a.jsx(Xr,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}):a.jsxs(Ne,{variant:"primary",size:"sm",className:"flex-1 min-w-0",onClick:()=>{const we=t.print_name||t.filename||"model",$e=`${window.location.origin}${ae.getArchiveForSlicer(t.id,we)}`;sc($e,c)},title:u("archives.card.openInBambuStudioToSlice"),children:[a.jsx(Xr,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"hidden sm:inline",children:u("archives.card.slice")})]}),a.jsx(Ne,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const we=t.external_url||t.makerworld_url;we&&window.open(we,"_blank")},disabled:!t.external_url&&!t.makerworld_url,title:t.external_url?u("archives.card.externalLink"):t.makerworld_url?u("archives.card.makerWorld",{designer:t.designer||u("archives.card.viewProject")}):u("archives.card.noExternalLink"),children:a.jsx(gh,{className:`w-3 h-3 sm:w-4 sm:h-4 ${!t.external_url&&!t.makerworld_url?"opacity-20":""}`})}),a.jsx(Ne,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>x(!0),title:u("archives.card.preview3d"),children:a.jsx(Ii,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),a.jsx(Ne,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{ae.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(we=>{console.error("Archive download failed:",we)})},title:u("archives.card.download"),children:a.jsx(wi,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>A(!0),disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?u("archives.card.edit"):u("archives.card.noPermissionEdit"),children:a.jsx(Ji,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>T(!0),disabled:!m("archives","delete",t.created_by_id),title:m("archives","delete",t.created_by_id)?u("archives.card.delete"):u("archives.card.noPermissionDelete"),children:a.jsx(ln,{className:"w-3 h-3 sm:w-4 sm:h-4 text-red-400"})})]})]}),M&&a.jsx(Bee,{archive:t,onClose:()=>A(!1)}),y&&a.jsx(C4,{archiveId:t.id,title:t.print_name||t.filename,fileType:Tre(t.filename),onClose:()=>x(!1)}),v&&a.jsx(Ou,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>S(!1)}),N&&a.jsx(er,{title:u("archives.modal.deleteArchive"),message:u("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{z.mutate(),T(!1)},onCancel:()=>T(!1)}),B&&a.jsx(er,{title:u("archives.modal.removeSource3mf"),message:u("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{re.mutate(),W(!1)},onCancel:()=>W(!1)}),J&&a.jsx(er,{title:u("archives.modal.removeF3d"),message:u("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{le.mutate(),ne(!1)},onCancel:()=>ne(!1)}),me&&a.jsx(Hee,{x:me.x,y:me.y,items:Te,onClose:()=>fe(null)}),k&&t.timelapse_path&&a.jsx(Ere,{src:ae.getArchiveTimelapse(t.id),title:u("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>R(!1),onEdit:()=>{d.invalidateQueries({queryKey:["archives"]}),R(!1)}}),C&&U.length>0&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:"Select Timelapse"}),a.jsx("p",{className:"text-sm text-gray-400 mt-1",children:"No auto-match found. Select the timelapse for this print:"})]}),a.jsx("button",{onClick:()=>{P(!1),F([])},className:"text-gray-400 hover:text-white p-1",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:U.map(we=>a.jsxs("button",{onClick:()=>ee.mutate(we.name),disabled:ee.isPending,className:"w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors flex items-center gap-3 disabled:opacity-50",children:[a.jsx(ph,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-white font-medium truncate",children:we.name}),a.jsxs("p",{className:"text-sm text-gray-400",children:[rk(we.size),we.mtime&&` • ${qg(we.mtime,l)}`]})]})]},we.name))}),a.jsx("div",{className:"p-4 border-t border-gray-700",children:a.jsx(Ne,{variant:"secondary",onClick:()=>{P(!1),F([])},className:"w-full",children:"Cancel"})})]})}),H&&a.jsx($ee,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>D(!1)}),$&&t.photos&&t.photos.length>0&&a.jsx(Vee,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>G(!1),onDelete:async we=>{try{await ae.deleteArchivePhoto(t.id,we),d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.photoDeleted"))}catch{h(u("archives.toast.failedDeletePhoto"),"error")}}}),I&&a.jsx(Mre,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>K(!1)}),Q&&a.jsx(Ou,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>oe(!1)}),a.jsx("input",{ref:Fe,type:"file",accept:".3mf",className:"hidden",onChange:we=>{const $e=we.target.files?.[0];$e&&q.mutate($e),we.target.value=""}}),a.jsx("input",{ref:ce,type:"file",accept:".f3d",className:"hidden",onChange:we=>{const $e=we.target.files?.[0];$e&&X.mutate($e),we.target.value=""}})]})}function P9e({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:i,projects:s,isHighlighted:o,preferredSlicer:l="bambu_studio",t:c}){const u=an(),{showToast:d}=Tn(),{hasPermission:h,canModify:p}=Ir(),[m,b]=_.useState(!1),[y,x]=_.useState(!1),[v,S]=_.useState(!1),[N,T]=_.useState(!1),[M,A]=_.useState(!1),[k,R]=_.useState(!1),[C,P]=_.useState(!1),[U,F]=_.useState([]),[H,D]=_.useState(!1),[$,G]=_.useState(!1),[I,K]=_.useState(!1),[Q,oe]=_.useState(!1),[B,W]=_.useState(!1),[J,ne]=_.useState(null),me=_.useRef(null),fe=_.useRef(null),de=dt({mutationFn:le=>ae.uploadSource3mf(t.id,le),onSuccess:le=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.source3mfAttached",{filename:le.filename}))},onError:le=>{d(le.message||c("archives.toast.failedUploadSource3mf"),"error")}}),Re=dt({mutationFn:()=>ae.deleteSource3mf(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.source3mfRemoved"))},onError:le=>{d(le.message||c("archives.toast.failedRemoveSource3mf"),"error")}}),se=dt({mutationFn:le=>ae.uploadF3d(t.id,le),onSuccess:le=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.f3dAttached",{filename:le.filename}))},onError:le=>{d(le.message||c("archives.toast.failedUploadF3d"),"error")}}),ke=dt({mutationFn:()=>ae.deleteF3d(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.f3dRemoved"))},onError:le=>{d(le.message||c("archives.toast.failedRemoveF3d"),"error")}}),Fe=dt({mutationFn:()=>ae.scanArchiveTimelapse(t.id),onSuccess:le=>{le.status==="attached"?(u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.timelapseAttached",{filename:le.filename}))):le.status==="exists"?d(c("archives.toast.timelapseAlreadyAttached")):le.status==="not_found"&&le.available_files&&le.available_files.length>0?(F(le.available_files),P(!0)):d(le.message||c("archives.toast.noMatchingTimelapse"),"warning")},onError:le=>{d(le.message||c("archives.toast.failedScanTimelapse"),"error")}}),ce=dt({mutationFn:le=>ae.selectArchiveTimelapse(t.id,le),onSuccess:le=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.timelapseAttached",{filename:le.filename})),P(!1),F([])},onError:le=>{d(le.message||c("archives.toast.failedAttachTimelapse"),"error")}}),Ve=dt({mutationFn:()=>ae.deleteArchive(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.archiveDeleted"))},onError:()=>{d(c("archives.toast.failedDeleteArchive"),"error")}}),V=dt({mutationFn:()=>ae.toggleFavorite(t.id),onSuccess:le=>{u.invalidateQueries({queryKey:["archives"]}),d(le.is_favorite?c("archives.toast.addedToFavorites"):c("archives.toast.removedFromFavorites"))}}),{data:Y}=it({queryKey:["archive-folders",t.id],queryFn:()=>ae.getLibraryFoldersByArchive(t.id)}),ue=dt({mutationFn:le=>ae.updateArchive(t.id,{project_id:le}),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),u.invalidateQueries({queryKey:["projects"]}),d(c("archives.toast.projectUpdated"))},onError:()=>{d(c("archives.toast.failedUpdateProject"),"error")}}),q=le=>{le.preventDefault(),ne({x:le.clientX,y:le.clientY})},X=[...Ff(t.filename)?[{label:c("archives.menu.print"),icon:a.jsx(jr,{className:"w-4 h-4"}),onClick:()=>S(!0),disabled:!p("archives","reprint",t.created_by_id),title:p("archives","reprint",t.created_by_id)?void 0:c("archives.permission.noReprint")},{label:c("archives.menu.schedule"),icon:a.jsx(ti,{className:"w-4 h-4"}),onClick:()=>T(!0),disabled:!h("queue:create"),title:h("queue:create")?void 0:c("archives.permission.noAddToQueue")},{label:c("archives.menu.openInBambuStudio"),icon:a.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>{const le=t.print_name||t.filename||"model",pe=`${window.location.origin}${ae.getArchiveForSlicer(t.id,le)}`;sc(pe,l)}}]:[{label:c("archives.menu.slice"),icon:a.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>{const le=t.print_name||t.filename||"model",pe=`${window.location.origin}${ae.getArchiveForSlicer(t.id,le)}`;sc(pe,l)}}],{label:t.external_url?c("archives.menu.externalLink"):c("archives.menu.viewOnMakerWorld"),icon:a.jsx(gh,{className:"w-4 h-4"}),onClick:()=>{const le=t.external_url||t.makerworld_url;le&&window.open(le,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.preview3d"),icon:a.jsx(Ii,{className:"w-4 h-4"}),onClick:()=>A(!0)},{label:c("archives.menu.viewTimelapse"),icon:a.jsx(ph,{className:"w-4 h-4"}),onClick:()=>R(!0),disabled:!t.timelapse_path},{label:c("archives.menu.scanForTimelapse"),icon:a.jsx(nS,{className:"w-4 h-4"}),onClick:()=>Fe.mutate(),disabled:!t.printer_id||!!t.timelapse_path||Fe.isPending||!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:"",divider:!0,onClick:()=>{}},{label:t.source_3mf_path?c("archives.menu.downloadSource3mf"):c("archives.menu.uploadSource3mf"),icon:a.jsx(J1,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?ae.downloadSource3mf(t.id).catch(le=>{console.error("Source 3MF download failed:",le)}):me.current?.click()},disabled:!t.source_3mf_path&&!p("archives","update",t.created_by_id),title:!t.source_3mf_path&&!p("archives","update",t.created_by_id)?c("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:c("archives.menu.replaceSource3mf"),icon:a.jsx(Na,{className:"w-4 h-4"}),onClick:()=>me.current?.click(),disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.removeSource3mf"),icon:a.jsx(ln,{className:"w-4 h-4"}),onClick:()=>oe(!0),danger:!0,disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")}]:[],{label:t.f3d_path?c("archives.menu.replaceF3d"):c("archives.menu.uploadF3d"),icon:a.jsx(Ii,{className:"w-4 h-4"}),onClick:()=>fe.current?.click(),disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:c("archives.menu.downloadF3d"),icon:a.jsx(wi,{className:"w-4 h-4"}),onClick:()=>{ae.downloadF3d(t.id).catch(le=>{console.error("F3D download failed:",le)})}},{label:c("archives.menu.removeF3d"),icon:a.jsx(ln,{className:"w-4 h-4"}),onClick:()=>W(!0),danger:!0,disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.download"),icon:a.jsx(wi,{className:"w-4 h-4"}),onClick:()=>{ae.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(le=>{console.error("Archive download failed:",le)})},disabled:!h("archives:read"),title:h("archives:read")?void 0:c("archives.permission.noDownload")},{label:c("archives.menu.copyDownloadLink"),icon:a.jsx(zl,{className:"w-4 h-4"}),onClick:()=>{const le=`${window.location.origin}${ae.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(le).then(()=>{d(c("archives.toast.linkCopied"))}).catch(()=>{d(c("archives.toast.failedCopyLink"),"error")})},disabled:!h("archives:read"),title:h("archives:read")?void 0:c("archives.permission.noCopyLink")},{label:c("archives.menu.qrCode"),icon:a.jsx(UW,{className:"w-4 h-4"}),onClick:()=>D(!0)},{label:t.photos?.length?c("archives.menu.viewPhotosCount",{count:t.photos.length}):c("archives.menu.viewPhotos"),icon:a.jsx($g,{className:"w-4 h-4"}),onClick:()=>G(!0),disabled:!t.photos?.length},{label:c("archives.menu.projectPage"),icon:a.jsx(ys,{className:"w-4 h-4"}),onClick:()=>K(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?c("archives.menu.removeFromFavorites"):c("archives.menu.addToFavorites"),icon:a.jsx(hm,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>V.mutate(),disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.edit"),icon:a.jsx(Ji,{className:"w-4 h-4"}),onClick:()=>b(!0),disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.project_id&&t.project_name?[{label:c("archives.menu.goToProject",{name:t.project_name}),icon:a.jsx(rs,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:c("archives.menu.addToProject"),icon:a.jsx(rs,{className:"w-4 h-4"}),onClick:()=>{},submenu:(()=>{const le=[];if(t.project_id&&le.push({label:c("archives.menu.removeFromProject"),icon:a.jsx(Lt,{className:"w-4 h-4"}),onClick:()=>ue.mutate(null)}),!s)le.push({label:c("archives.menu.loading"),icon:a.jsx(ct,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const pe=s.filter(ee=>ee.status==="active");pe.length===0?le.push({label:c("archives.menu.noProjectsAvailable"),icon:a.jsx(rs,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):pe.forEach(ee=>{le.push({label:ee.name,icon:a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:ee.color||"#888"}}),onClick:()=>ue.mutate(ee.id),disabled:t.project_id===ee.id})})}return le})()},{label:c(n?"archives.menu.deselect":"archives.menu.select"),icon:n?a.jsx(Xs,{className:"w-4 h-4"}):a.jsx(ul,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.delete"),icon:a.jsx(ln,{className:"w-4 h-4"}),onClick:()=>x(!0),danger:!0,disabled:!p("archives","delete",t.created_by_id),title:p("archives","delete",t.created_by_id)?void 0:c("archives.permission.noDelete")}];return a.jsxs(a.Fragment,{children:[a.jsxs("div",{"data-archive-id":t.id,className:`grid grid-cols-12 gap-4 px-4 py-3 items-center hover:bg-bambu-dark-tertiary/30 ${n?"bg-bambu-green/10":""}`,style:o?{outline:"4px solid #facc15",outlineOffset:"-4px"}:void 0,onContextMenu:q,children:[a.jsxs("div",{className:"col-span-1 flex items-center gap-2",children:[i&&a.jsx("button",{onClick:()=>r(t.id),children:n?a.jsx(Xs,{className:"w-4 h-4 text-bambu-green"}):a.jsx(ul,{className:"w-4 h-4 text-bambu-gray"})}),t.thumbnail_path?a.jsx("img",{src:ae.getArchiveThumbnail(t.id),alt:"",className:"w-10 h-10 object-cover rounded"}):a.jsx("div",{className:"w-10 h-10 bg-bambu-dark rounded flex items-center justify-center",children:a.jsx(Uu,{className:"w-5 h-5 text-bambu-dark-tertiary"})})]}),a.jsxs("div",{className:"col-span-4",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-white text-sm truncate",children:t.print_name||t.filename}),t.timelapse_path&&a.jsx("span",{title:c("archives.list.hasTimelapse"),children:a.jsx(ph,{className:"w-3.5 h-3.5 text-bambu-green flex-shrink-0"})}),Y&&Y.length>0&&a.jsx(Bs,{to:`/files?folder=${Y[0].id}`,className:"flex-shrink-0",title:c("archives.card.openFolder",{name:Y[0].name}),onClick:le=>le.stopPropagation(),children:a.jsx(Ul,{className:"w-3.5 h-3.5 text-yellow-400"})})]}),(t.filament_type||t.sliced_for_model)&&a.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[t.sliced_for_model&&a.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",title:c("archives.card.slicedFor",{model:t.sliced_for_model}),children:[a.jsx(jr,{className:"w-2.5 h-2.5"}),t.sliced_for_model]}),t.sliced_for_model&&t.filament_type&&a.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.filament_type&&a.jsx("span",{className:"text-xs text-bambu-gray",children:t.filament_type}),t.filament_color&&a.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((le,pe)=>a.jsx("div",{className:"w-2.5 h-2.5 rounded-full border border-white/20",style:{backgroundColor:le},title:le},pe))})]})]}),a.jsx("div",{className:"col-span-2 text-sm text-bambu-gray truncate",children:e}),a.jsxs("div",{className:"col-span-2 text-sm text-bambu-gray",children:[a.jsx("div",{children:Gg(t.created_at)}),t.created_by_username&&a.jsxs("div",{className:"flex items-center gap-1 text-xs opacity-75",title:c("archives.card.uploadedBy",{name:t.created_by_username}),children:[a.jsx($u,{className:"w-3 h-3"}),t.created_by_username]})]}),a.jsx("div",{className:"col-span-1 text-sm text-bambu-gray",children:rk(t.file_size)}),a.jsxs("div",{className:"col-span-2 flex justify-end gap-1",children:[a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{const le=t.print_name||t.filename||"model",pe=`${window.location.origin}${ae.getArchiveForSlicer(t.id,le)}`;sc(pe,l)},title:c("archives.card.openInBambuStudio"),children:a.jsx(Xr,{className:"w-4 h-4"})}),(t.external_url||t.makerworld_url)&&a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>window.open(t.external_url||t.makerworld_url,"_blank"),title:t.external_url?c("archives.card.externalLink"):"MakerWorld",children:a.jsx(gh,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{ae.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(le=>{console.error("Archive download failed:",le)})},title:c("archives.card.download"),children:a.jsx(wi,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>b(!0),disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?c("archives.card.edit"):c("archives.card.noPermissionEdit"),children:a.jsx(Ji,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>x(!0),disabled:!p("archives","delete",t.created_by_id),title:p("archives","delete",t.created_by_id)?c("archives.card.delete"):c("archives.card.noPermissionDelete"),children:a.jsx(ln,{className:"w-4 h-4 text-red-400"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:le=>{const pe=le.currentTarget.getBoundingClientRect();ne({x:pe.left,y:pe.bottom+4})},title:c("archives.card.moreOptions"),children:a.jsx(mh,{className:"w-4 h-4"})})]})]}),m&&a.jsx(Bee,{archive:t,onClose:()=>b(!1)}),M&&a.jsx(C4,{archiveId:t.id,title:t.print_name||t.filename,fileType:Tre(t.filename),onClose:()=>A(!1)}),v&&a.jsx(Ou,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>S(!1)}),y&&a.jsx(er,{title:c("archives.modal.deleteArchive"),message:c("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{Ve.mutate(),x(!1)},onCancel:()=>x(!1)}),Q&&a.jsx(er,{title:c("archives.modal.removeSource3mf"),message:c("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{Re.mutate(),oe(!1)},onCancel:()=>oe(!1)}),B&&a.jsx(er,{title:c("archives.modal.removeF3d"),message:c("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{ke.mutate(),W(!1)},onCancel:()=>W(!1)}),J&&a.jsx(Hee,{x:J.x,y:J.y,items:X,onClose:()=>ne(null)}),k&&t.timelapse_path&&a.jsx(Ere,{src:ae.getArchiveTimelapse(t.id),title:c("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>R(!1),onEdit:()=>{u.invalidateQueries({queryKey:["archives"]}),R(!1)}}),C&&U.length>0&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:"Select Timelapse"}),a.jsx("p",{className:"text-sm text-gray-400 mt-1",children:"No auto-match found. Select the timelapse for this print:"})]}),a.jsx("button",{onClick:()=>{P(!1),F([])},className:"text-gray-400 hover:text-white p-1",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:U.map(le=>a.jsxs("button",{onClick:()=>ce.mutate(le.name),disabled:ce.isPending,className:"w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors mb-1",children:[a.jsx("div",{className:"font-medium text-white",children:le.name}),a.jsxs("div",{className:"text-sm text-gray-400 flex gap-3",children:[a.jsx("span",{children:rk(le.size)}),le.mtime&&a.jsx("span",{children:Gg(le.mtime)})]})]},le.name))})]})}),H&&a.jsx($ee,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>D(!1)}),$&&t.photos&&a.jsx(Vee,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>G(!1),onDelete:async le=>{try{await ae.deleteArchivePhoto(t.id,le),u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.photoDeleted"))}catch{d(c("archives.toast.failedDeletePhoto"),"error")}}}),I&&a.jsx(Mre,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>K(!1)}),N&&a.jsx(Ou,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>T(!1)}),a.jsx("input",{ref:me,type:"file",accept:".3mf",className:"hidden",onChange:le=>{const pe=le.target.files?.[0];pe&&de.mutate(pe),le.target.value=""}}),a.jsx("input",{ref:fe,type:"file",accept:".f3d",className:"hidden",onChange:le=>{const pe=le.target.files?.[0];pe&&se.mutate(pe),le.target.value=""}})]})}const j9e=[{id:"all",label:"All Archives",icon:a.jsx(Ul,{className:"w-4 h-4"})},{id:"recent",label:"Last 24 Hours",icon:a.jsx(tr,{className:"w-4 h-4"})},{id:"this-week",label:"This Week",icon:a.jsx(ti,{className:"w-4 h-4"})},{id:"this-month",label:"This Month",icon:a.jsx(ti,{className:"w-4 h-4"})},{id:"favorites",label:"Favorites",icon:a.jsx(hm,{className:"w-4 h-4"})},{id:"failed",label:"Failed Prints",icon:a.jsx(Ti,{className:"w-4 h-4"})},{id:"duplicates",label:"Duplicates",icon:a.jsx(zl,{className:"w-4 h-4"})}];function D9e(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),{hasPermission:r,hasAnyPermission:i}=Ir(),s=_.useRef(null),[o,l]=_.useState(""),[c,u]=_.useState(()=>{const ye=localStorage.getItem("archiveFilterPrinter");return ye?Number(ye):null}),[d,h]=_.useState(()=>localStorage.getItem("archiveFilterMaterial")),[p,m]=_.useState(()=>{const ye=localStorage.getItem("archiveFilterColors");return ye?new Set(JSON.parse(ye)):new Set}),[b,y]=_.useState(()=>localStorage.getItem("archiveColorFilterMode")||"or"),[x,v]=_.useState(()=>localStorage.getItem("archiveFilterFavorites")==="true"),[S,N]=_.useState(()=>localStorage.getItem("archiveHideFailed")==="true"),[T,M]=_.useState(()=>localStorage.getItem("archiveFilterTag")),[A,k]=_.useState(()=>localStorage.getItem("archiveFilterFileType")||"all"),[R,C]=_.useState(!1),[P,U]=_.useState([]),[F,H]=_.useState(!1),[D,$]=_.useState(new Set),[G,I]=_.useState(!1),[K,Q]=_.useState(!1),[oe,B]=_.useState(!1),[W,J]=_.useState(!1),[ne,me]=_.useState(()=>localStorage.getItem("archiveViewMode")||"grid"),[fe,de]=_.useState(()=>localStorage.getItem("archiveSortBy")||"date-desc"),[Re,se]=_.useState(()=>localStorage.getItem("archiveCollection")||"all"),[ke,Fe]=_.useState(!1),[ce,Ve]=_.useState(!1),[V,Y]=_.useState(!1),[ue,q]=_.useState(!1),[re,X]=_.useState(null);_.useEffect(()=>{if(re){const ye=setTimeout(()=>{const yt=document.querySelector(`[data-archive-id="${re}"]`);yt&&yt.scrollIntoView({behavior:"smooth",block:"center"})},100),Qe=setTimeout(()=>X(null),5e3);return()=>{clearTimeout(ye),clearTimeout(Qe)}}},[re]);const{data:le,isLoading:pe}=it({queryKey:["archives",c],queryFn:()=>ae.getArchives(c||void 0)}),{data:ee}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:z}=it({queryKey:["projects"],queryFn:()=>ae.getProjects()}),{data:O}=it({queryKey:["settings"],queryFn:ae.getSettings}),Z=O?.time_format||"system",ge=O?.preferred_slicer||"bambu_studio",Ce=dt({mutationFn:async ye=>(await Promise.all(ye.map(Qe=>ae.deleteArchive(Qe))),ye.length),onSuccess:ye=>{e.invalidateQueries({queryKey:["archives"]}),$(new Set),n(`${ye} archive${ye!==1?"s":""} deleted`)},onError:()=>{n(t("archives.toast.failedDeleteArchives"),"error")}});_.useEffect(()=>{c!==null?localStorage.setItem("archiveFilterPrinter",c.toString()):localStorage.removeItem("archiveFilterPrinter")},[c]),_.useEffect(()=>{d?localStorage.setItem("archiveFilterMaterial",d):localStorage.removeItem("archiveFilterMaterial")},[d]),_.useEffect(()=>{localStorage.setItem("archiveFilterColors",JSON.stringify([...p]))},[p]),_.useEffect(()=>{localStorage.setItem("archiveColorFilterMode",b)},[b]),_.useEffect(()=>{localStorage.setItem("archiveFilterFavorites",x.toString())},[x]),_.useEffect(()=>{localStorage.setItem("archiveHideFailed",S.toString())},[S]),_.useEffect(()=>{T?localStorage.setItem("archiveFilterTag",T):localStorage.removeItem("archiveFilterTag")},[T]),_.useEffect(()=>{localStorage.setItem("archiveFilterFileType",A)},[A]),_.useEffect(()=>{localStorage.setItem("archiveViewMode",ne)},[ne]),_.useEffect(()=>{localStorage.setItem("archiveSortBy",fe)},[fe]),_.useEffect(()=>{localStorage.setItem("archiveCollection",Re)},[Re]);const _e=new Map(ee?.map(ye=>[ye.id,ye.name])||[]),Te=[...new Set(le?.flatMap(ye=>ye.filament_type?.split(", ")||[]).filter(Boolean)||[])].sort(),we=[...new Set(le?.flatMap(ye=>ye.filament_color?.split(",")||[]).filter(Boolean)||[])],$e=[...new Set(le?.flatMap(ye=>ye.tags?.split(",").map(Qe=>Qe.trim())||[]).filter(Boolean)||[])].sort(),Ge=le?.filter(ye=>{const Qe=new Date,yt=zi(ye.created_at)||new Date(0);let at=!0;switch(Re){case"recent":at=Qe.getTime()-yt.getTime()<1440*60*1e3;break;case"this-week":at=Qe.getTime()-yt.getTime()<10080*60*1e3;break;case"this-month":at=yt.getMonth()===Qe.getMonth()&&yt.getFullYear()===Qe.getFullYear();break;case"favorites":at=ye.is_favorite===!0;break;case"failed":at=ye.status==="failed"||ye.status==="aborted";break;case"duplicates":at=ye.duplicate_count>0;break}const Ut=(ye.print_name||ye.filename).toLowerCase().includes(o.toLowerCase()),zt=!d||ye.filament_type?.split(", ").includes(d),Ie=ye.filament_color?.split(",")||[],vt=p.size===0||(b==="or"?Ie.some(kn=>p.has(kn)):[...p].every(kn=>Ie.includes(kn))),Gt=Re==="favorites"||!x||ye.is_favorite,dn=Re==="failed"||!S||ye.status!=="failed"&&ye.status!=="aborted",fn=ye.tags?.split(",").map(kn=>kn.trim())||[],vn=!T||fn.includes(T),dr=Ff(ye.filename);return at&&Ut&&zt&&vt&&Gt&&dn&&vn&&(A==="all"||A==="gcode"&&dr||A==="source"&&!dr)}).sort((ye,Qe)=>{switch(fe){case"date-desc":return(zi(Qe.created_at)?.getTime()||0)-(zi(ye.created_at)?.getTime()||0);case"date-asc":return(zi(ye.created_at)?.getTime()||0)-(zi(Qe.created_at)?.getTime()||0);case"name-asc":return(ye.print_name||ye.filename).localeCompare(Qe.print_name||Qe.filename);case"name-desc":return(Qe.print_name||Qe.filename).localeCompare(ye.print_name||ye.filename);case"size-desc":return Qe.file_size-ye.file_size;case"size-asc":return ye.file_size-Qe.file_size;default:return 0}}),ze=G||D.size>0,be=ye=>{$(Qe=>{const yt=new Set(Qe);return yt.has(ye)?yt.delete(ye):yt.add(ye),yt})},Me=()=>{Ge&&$(new Set(Ge.map(ye=>ye.id)))},Be=()=>{$(new Set),I(!1)},Ae=ye=>{m(Qe=>{const yt=new Set(Qe);return yt.has(ye)?yt.delete(ye):yt.add(ye),yt})},qe=()=>{m(new Set)},ve=()=>{l(""),u(null),h(null),v(!1),N(!1),M(null),k("all")},et=o||c||d||x||S||T||A!=="all",Ee=_.useCallback(ye=>{ye.preventDefault(),ye.dataTransfer.types.includes("Files")&&H(!0)},[]),Ye=_.useCallback(ye=>{ye.preventDefault(),ye.currentTarget===ye.target&&H(!1)},[]),je=_.useCallback(ye=>{ye.preventDefault(),H(!1);const Qe=Array.from(ye.dataTransfer.files).filter(yt=>yt.name.endsWith(".3mf"));Qe.length>0?(U(Qe),C(!0)):ye.dataTransfer.files.length>0&&n(t("archives.page.only3mfSupported"),"warning")},[n,t]),Pe=_.useCallback(ye=>{const Qe=ye.target;if(Qe.tagName==="INPUT"||Qe.tagName==="TEXTAREA"||Qe.isContentEditable){ye.key==="Escape"&&Qe.blur();return}switch(ye.key){case"/":ye.preventDefault(),s.current?.focus();break;case"u":case"U":!ye.metaKey&&!ye.ctrlKey&&(ye.preventDefault(),C(!0));break;case"Escape":ze&&Be();break}},[ze]);return _.useEffect(()=>(document.addEventListener("keydown",Pe),()=>document.removeEventListener("keydown",Pe)),[Pe]),a.jsxs("div",{className:"p-4 md:p-8 relative min-h-full",onDragOver:Ee,onDragLeave:Ye,onDrop:je,children:[F&&a.jsx("div",{className:"fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none",children:a.jsxs("div",{className:"border-4 border-dashed border-bambu-green rounded-xl p-12 text-center",children:[a.jsx(Na,{className:"w-16 h-16 mx-auto mb-4 text-bambu-green"}),a.jsx("p",{className:"text-2xl font-semibold text-white mb-2",children:"Drop .3mf files here"}),a.jsx("p",{className:"text-bambu-gray",children:t("archives.releaseToUpload")})]})}),ze&&a.jsxs("div",{className:"fixed bottom-6 left-1/2 -translate-x-1/2 z-40 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl px-4 py-3 flex items-center gap-4",children:[a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:Be,children:[a.jsx(Lt,{className:"w-4 h-4"}),"Close"]}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("span",{className:"text-white font-medium",children:[D.size," selected"]}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:Me,children:"Select All"}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>B(!0),disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[a.jsx(Th,{className:"w-4 h-4"}),"Tags"]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>J(!0),disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[a.jsx(rs,{className:"w-4 h-4"}),"Project"]}),a.jsxs(Ne,{variant:"secondary",size:"sm",disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),onClick:()=>{const ye=Array.from(D);Promise.all(ye.map(Qe=>ae.toggleFavorite(Qe))).then(()=>{e.invalidateQueries({queryKey:["archives"]}),n(`Toggled favorites for ${ye.length} archive${ye.length!==1?"s":""}`)}).catch(()=>{n(t("archives.toast.failedUpdateFavorites"),"error")})},children:[a.jsx(hm,{className:"w-4 h-4"}),"Favorite"]}),a.jsxs(Ne,{size:"sm",className:"bg-red-500 hover:bg-red-600",onClick:()=>Q(!0),disabled:!i("archives:delete_own","archives:delete_all"),title:i("archives:delete_own","archives:delete_all")?void 0:t("archives.permission.noDelete"),children:[a.jsx(ln,{className:"w-4 h-4"}),"Delete"]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:"Archives"}),a.jsx("select",{className:"px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray-light text-sm focus:border-bambu-green focus:outline-none",value:Re,onChange:ye=>se(ye.target.value),children:j9e.map(ye=>a.jsx("option",{value:ye.id,children:ye.label},ye.id))})]}),a.jsxs("p",{className:"text-bambu-gray",children:[Ge?.length||0," of ",le?.length||0," prints"]})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"relative",children:[a.jsxs(Ne,{variant:"secondary",onClick:()=>Fe(!ke),disabled:ce,children:[ce?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(eS,{className:"w-4 h-4"}),"Export"]}),ke&&a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20",children:[a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg",onClick:async()=>{Fe(!1),Ve(!0);try{const{blob:ye,filename:Qe}=await ae.exportArchives({format:"csv",printerId:c||void 0,status:Re==="failed"?"failed":void 0,search:o||void 0}),yt=URL.createObjectURL(ye),at=document.createElement("a");at.href=yt,at.download=Qe,at.click(),URL.revokeObjectURL(yt),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{Ve(!1)}},children:[a.jsx(ys,{className:"w-4 h-4"}),"Export as CSV"]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg",onClick:async()=>{Fe(!1),Ve(!0);try{const{blob:ye,filename:Qe}=await ae.exportArchives({format:"xlsx",printerId:c||void 0,status:Re==="failed"?"failed":void 0,search:o||void 0}),yt=URL.createObjectURL(ye),at=document.createElement("a");at.href=yt,at.download=Qe,at.click(),URL.revokeObjectURL(yt),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{Ve(!1)}},children:[a.jsx(eS,{className:"w-4 h-4"}),"Export as Excel"]})]})]}),D.size>=2&&D.size<=5&&a.jsxs(Ne,{variant:"secondary",onClick:()=>Y(!0),children:[a.jsx(Mg,{className:"w-4 h-4"}),"Compare (",D.size,")"]}),!ze&&a.jsxs(Ne,{variant:"secondary",onClick:()=>I(!0),children:[a.jsx(Xs,{className:"w-4 h-4"}),"Select"]}),a.jsxs(Ne,{onClick:()=>C(!0),disabled:!r("archives:create"),title:r("archives:create")?void 0:t("archives.permission.noCreate"),children:[a.jsx(Na,{className:"w-4 h-4"}),"Upload 3MF"]})]})]}),a.jsx(St,{className:"mb-6",children:a.jsxs(Et,{className:"py-4",children:[a.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:gap-4 md:items-center md:flex-wrap",children:[a.jsxs("div",{className:"w-full md:flex-1 relative md:min-w-[200px]",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{ref:s,type:"text",placeholder:t("archives.searchPlaceholder"),className:"w-full pl-10 pr-4 py-3 md:py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:o,onChange:ye=>l(ye.target.value)})]}),a.jsxs("div",{className:"flex gap-2 md:gap-4 overflow-x-auto pb-1 md:pb-0 -mx-4 px-4 md:mx-0 md:px-0 md:flex-wrap scrollbar-hide",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(yk,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c||"",onChange:ye=>u(ye.target.value?Number(ye.target.value):null),children:[a.jsx("option",{value:"",children:"All Printers"}),ee?.map(ye=>a.jsx("option",{value:ye.id,children:ye.name},ye.id))]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(bc,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:d||"",onChange:ye=>h(ye.target.value||null),children:[a.jsx("option",{value:"",children:"All Materials"}),Te.map(ye=>a.jsx("option",{value:ye,children:ye},ye))]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(J1,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:A,onChange:ye=>k(ye.target.value),children:[a.jsx("option",{value:"all",children:"All Files"}),a.jsx("option",{value:"gcode",children:"Sliced (GCODE)"}),a.jsx("option",{value:"source",children:"Source Only"})]})]}),a.jsxs("button",{onClick:()=>v(!x),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${x?"bg-yellow-500/20 border-yellow-500 text-yellow-400":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t(x?"archives.showAll":"archives.showFavoritesOnly"),children:[a.jsx(hm,{className:`w-4 h-4 ${x?"fill-yellow-400":""}`}),a.jsx("span",{className:"text-sm hidden md:inline",children:"Favorites"})]}),a.jsxs("button",{onClick:()=>N(!S),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${S?"bg-red-500/20 border-red-500 text-red-400":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t(S?"archives.showFailedPrints":"archives.hideFailedPrints"),children:[a.jsx(Ti,{className:"w-4 h-4 "}),a.jsx("span",{className:"text-sm hidden md:inline",children:"Hide Failed"})]}),$e.length>0&&a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(Th,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:T||"",onChange:ye=>M(ye.target.value||null),children:[a.jsx("option",{value:"",children:"All Tags"}),$e.map(ye=>a.jsx("option",{value:ye,children:ye},ye))]}),a.jsx("button",{onClick:()=>q(!0),className:"p-2 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",title:t("archives.manageTags"),children:a.jsx(Mk,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(PW,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:fe,onChange:ye=>de(ye.target.value),children:[a.jsx("option",{value:"date-desc",children:t("archives.sortNewest")}),a.jsx("option",{value:"date-asc",children:t("archives.sortOldest")}),a.jsxs("option",{value:"name-asc",children:[t("archives.sortName")," A-Z"]}),a.jsxs("option",{value:"name-desc",children:[t("archives.sortName")," Z-A"]}),a.jsx("option",{value:"size-desc",children:t("archives.sortLargest")}),a.jsx("option",{value:"size-asc",children:t("archives.sortSmallest")})]})]}),a.jsxs("div",{className:"flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden flex-shrink-0",children:[a.jsx("button",{className:`p-2 ${ne==="grid"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>me("grid"),title:t("archives.gridView"),children:a.jsx(wk,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 ${ne==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>me("list"),title:t("archives.listView"),children:a.jsx(_k,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 ${ne==="calendar"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>me("calendar"),title:t("archives.calendarView"),children:a.jsx(eue,{className:"w-4 h-4"})})]})]}),et&&a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:ve,className:"text-bambu-gray hover:text-white",children:[a.jsx(Lt,{className:"w-4 h-4"}),"Reset"]})]}),we.length>0&&a.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Colors:"}),p.size>1&&a.jsx("button",{onClick:()=>y(ye=>ye==="or"?"and":"or"),className:`px-2 py-0.5 text-xs rounded transition-colors ${b==="and"?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:b==="or"?"Match ANY selected color":"Match ALL selected colors",children:b.toUpperCase()}),a.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:we.map(ye=>a.jsx("button",{onClick:()=>Ae(ye),className:`w-6 h-6 rounded-full border-2 transition-all ${p.has(ye)?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:ye},title:ye},ye))}),p.size>0&&a.jsxs("button",{onClick:qe,className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1",children:[a.jsx(Lt,{className:"w-3 h-3"}),"Clear"]})]})]})}),a.jsx(T9e,{}),pe?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.loadingArchives")}):Ge?.length===0?a.jsx(St,{children:a.jsxs(Et,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray",children:t(o?"archives.noArchivesSearch":"archives.noArchivesYet")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:"Archives are created automatically when prints complete"})]})}):ne==="calendar"?a.jsx(St,{className:"p-6",children:a.jsx(a6e,{archives:Ge||[],onArchiveClick:ye=>{l(""),me("grid"),X(ye.id)},highlightedArchiveId:re})}):ne==="grid"?a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:Ge?.map(ye=>a.jsx(C9e,{archive:ye,printerName:ye.printer_id?_e.get(ye.printer_id)||"Unknown":ye.sliced_for_model?`Sliced for ${ye.sliced_for_model}`:"No Printer",isSelected:D.has(ye.id),onSelect:be,selectionMode:ze,projects:z,isHighlighted:ye.id===re,timeFormat:Z,preferredSlicer:ge,t},ye.id))}):ne==="list"?a.jsx(St,{children:a.jsxs("div",{className:"divide-y divide-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-12 gap-4 px-4 py-3 text-xs text-bambu-gray font-medium",children:[a.jsx("div",{className:"col-span-1"}),a.jsx("div",{className:"col-span-4",children:"Name"}),a.jsx("div",{className:"col-span-2",children:"Printer"}),a.jsx("div",{className:"col-span-2",children:"Date"}),a.jsx("div",{className:"col-span-1",children:"Size"}),a.jsx("div",{className:"col-span-2 text-right",children:"Actions"})]}),Ge?.map(ye=>a.jsx(P9e,{archive:ye,printerName:ye.printer_id?_e.get(ye.printer_id)||"Unknown":ye.sliced_for_model?`Sliced for ${ye.sliced_for_model}`:"No Printer",isSelected:D.has(ye.id),onSelect:be,selectionMode:ze,projects:z,isHighlighted:ye.id===re,preferredSlicer:ge,t},ye.id))]})}):null,R&&a.jsx(Y8e,{onClose:()=>{C(!1),U([])},initialFiles:P}),K&&a.jsx(er,{title:t("archives.modal.deleteArchives"),message:t("archives.modal.deleteArchivesConfirm",{count:D.size}),confirmText:t("archives.modal.deleteCount",{count:D.size}),variant:"danger",onConfirm:()=>{Ce.mutate(Array.from(D)),Q(!1)},onCancel:()=>Q(!1)}),oe&&a.jsx(J8e,{selectedIds:Array.from(D),existingTags:$e,onClose:()=>B(!1)}),W&&a.jsx(e6e,{selectedIds:Array.from(D),onClose:()=>J(!1)}),V&&D.size>=2&&D.size<=5&&a.jsx(S9e,{archiveIds:Array.from(D),onClose:()=>{Y(!1),$(new Set),I(!1)}}),ue&&a.jsx(A9e,{onClose:()=>q(!1)})]})}function R9e(){for(var t=arguments.length,e=new Array(t),n=0;nr=>{e.forEach(i=>i(r))},e)}const KM=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Bb(t){const e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function yF(t){return"nodeType"in t}function Js(t){var e,n;return t?Bb(t)?t:yF(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function vF(t){const{Document:e}=Js(t);return t instanceof e}function Mv(t){return Bb(t)?!1:t instanceof Js(t).HTMLElement}function Are(t){return t instanceof Js(t).SVGElement}function Hb(t){return t?Bb(t)?t.document:yF(t)?vF(t)?t:Mv(t)||Are(t)?t.ownerDocument:document:document:document}const kc=KM?_.useLayoutEffect:_.useEffect;function wF(t){const e=_.useRef(t);return kc(()=>{e.current=t}),_.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i{t.current=setInterval(r,i)},[]),n=_.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function Ly(t,e){e===void 0&&(e=[t]);const n=_.useRef(t);return kc(()=>{n.current!==t&&(n.current=t)},e),n}function Ev(t,e){const n=_.useRef();return _.useMemo(()=>{const r=t(n.current);return n.current=r,r},[...e])}function ik(t){const e=wF(t),n=_.useRef(null),r=_.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,r]}function xR(t){const e=_.useRef();return _.useEffect(()=>{e.current=t},[t]),e.current}let XP={};function Tv(t,e){return _.useMemo(()=>{if(e)return e;const n=XP[t]==null?0:XP[t]+1;return XP[t]=n,t+"-"+n},[t,e])}function Cre(t){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i{const l=Object.entries(o);for(const[c,u]of l){const d=s[c];d!=null&&(s[c]=d+t*u)}return s},{...e})}}const Ug=Cre(1),Fy=Cre(-1);function L9e(t){return"clientX"in t&&"clientY"in t}function _F(t){if(!t)return!1;const{KeyboardEvent:e}=Js(t.target);return e&&t instanceof e}function F9e(t){if(!t)return!1;const{TouchEvent:e}=Js(t.target);return e&&t instanceof e}function yR(t){if(F9e(t)){if(t.touches&&t.touches.length){const{clientX:e,clientY:n}=t.touches[0];return{x:e,y:n}}else if(t.changedTouches&&t.changedTouches.length){const{clientX:e,clientY:n}=t.changedTouches[0];return{x:e,y:n}}}return L9e(t)?{x:t.clientX,y:t.clientY}:null}const xb=Object.freeze({Translate:{toString(t){if(!t)return;const{x:e,y:n}=t;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(t){if(!t)return;const{scaleX:e,scaleY:n}=t;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(t){if(t)return[xb.Translate.toString(t),xb.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:r}=t;return e+" "+n+"ms "+r}}}),x9="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function I9e(t){return t.matches(x9)?t:t.querySelector(x9)}const z9e={display:"none"};function U9e(t){let{id:e,value:n}=t;return ei.createElement("div",{id:e,style:z9e},n)}function B9e(t){let{id:e,announcement:n,ariaLiveType:r="assertive"}=t;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return ei.createElement("div",{id:e,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function H9e(){const[t,e]=_.useState("");return{announce:_.useCallback(r=>{r!=null&&e(r)},[]),announcement:t}}const Pre=_.createContext(null);function $9e(t){const e=_.useContext(Pre);_.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(t)},[t,e])}function V9e(){const[t]=_.useState(()=>new Set),e=_.useCallback(r=>(t.add(r),()=>t.delete(r)),[t]);return[_.useCallback(r=>{let{type:i,event:s}=r;t.forEach(o=>{var l;return(l=o[i])==null?void 0:l.call(o,s)})},[t]),e]}const G9e={draggable:` +Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${s0(t.actual_time_seconds)}`:`Estimated: ${s0(t.print_time_seconds||0)}`,children:[a.jsx(tr,{className:"w-3 h-3"}),s0(t.actual_time_seconds||t.print_time_seconds||0),t.time_accuracy&&a.jsxs("span",{className:`text-[10px] px-1 rounded ${t.time_accuracy>=95&&t.time_accuracy<=105?"bg-bambu-green/20 text-bambu-green":t.time_accuracy>105?"bg-blue-500/20 text-blue-400":"bg-orange-500/20 text-orange-400"}`,children:[t.time_accuracy>100?"+":"",(t.time_accuracy-100).toFixed(0),"%"]})]}),t.filament_used_grams&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(bc,{className:"w-3 h-3"}),t.filament_used_grams.toFixed(1),"g"]}),(t.layer_height||t.total_layers)&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(is,{className:"w-3 h-3"}),t.total_layers&&a.jsx("span",{children:t.total_layers===1?u("archives.card.layer",{count:t.total_layers}):u("archives.card.layers",{count:t.total_layers})}),t.total_layers&&t.layer_height&&a.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.layer_height&&a.jsxs("span",{children:[t.layer_height,"mm"]})]}),t.object_count!=null&&t.object_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.object_count===1?u("archives.card.object",{count:t.object_count}):u("archives.card.objects",{count:t.object_count}),children:[a.jsx(Ii,{className:"w-3 h-3"}),t.object_count===1?u("archives.card.object",{count:t.object_count}):u("archives.card.objects",{count:t.object_count})]}),t.sliced_for_model&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:u("archives.card.slicedFor",{model:t.sliced_for_model}),children:[a.jsx(jr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.filament_type&&a.jsxs("div",{className:"flex items-center gap-1.5 col-span-2",children:[a.jsx("span",{className:"text-bambu-gray text-xs",children:t.filament_type}),t.filament_color&&a.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((we,$e)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:we},title:we},$e))})]})]}),(t.tags||t.notes)&&a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[t.notes&&a.jsx("div",{className:"flex items-center gap-1 px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded text-xs",title:t.notes,children:a.jsx(HW,{className:"w-3 h-3"})}),t.tags?.split(",").map((we,$e)=>a.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-dark-tertiary text-bambu-gray-light rounded text-xs",children:we.trim()},$e))]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray border-t border-bambu-dark-tertiary pt-3",children:[a.jsx("span",{children:qg(t.created_at,l)}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.created_by_username&&a.jsxs("span",{className:"flex items-center gap-1",title:u("archives.card.uploadedBy",{name:t.created_by_username}),children:[a.jsx($u,{className:"w-3 h-3"}),t.created_by_username]}),a.jsx("span",{children:rk(t.file_size)})]})]}),a.jsxs("div",{className:"flex gap-1 mt-3",children:[Ff(t.filename)?a.jsxs(a.Fragment,{children:[a.jsxs(Ne,{variant:"primary",size:"sm",className:"flex-1 min-w-0",onClick:()=>S(!0),disabled:!m("archives","reprint",t.created_by_id),title:m("archives","reprint",t.created_by_id)?void 0:u("archives.card.noPermissionReprint"),children:[a.jsx(jr,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"hidden sm:inline",children:u("archives.card.reprint")})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",className:"flex-1 min-w-0",onClick:()=>oe(!0),disabled:!p("queue:create"),title:p("queue:create")?u("archives.card.schedulePrint"):u("archives.permission.noAddToQueue"),children:[a.jsx(ti,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"hidden sm:inline",children:u("archives.card.schedule")})]}),a.jsx(Ne,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const we=t.print_name||t.filename||"model",$e=`${window.location.origin}${ae.getArchiveForSlicer(t.id,we)}`;sc($e,c)},title:u("archives.card.openInBambuStudio"),children:a.jsx(Xr,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}):a.jsxs(Ne,{variant:"primary",size:"sm",className:"flex-1 min-w-0",onClick:()=>{const we=t.print_name||t.filename||"model",$e=`${window.location.origin}${ae.getArchiveForSlicer(t.id,we)}`;sc($e,c)},title:u("archives.card.openInBambuStudioToSlice"),children:[a.jsx(Xr,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"hidden sm:inline",children:u("archives.card.slice")})]}),a.jsx(Ne,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const we=t.external_url||t.makerworld_url;we&&window.open(we,"_blank")},disabled:!t.external_url&&!t.makerworld_url,title:t.external_url?u("archives.card.externalLink"):t.makerworld_url?u("archives.card.makerWorld",{designer:t.designer||u("archives.card.viewProject")}):u("archives.card.noExternalLink"),children:a.jsx(gh,{className:`w-3 h-3 sm:w-4 sm:h-4 ${!t.external_url&&!t.makerworld_url?"opacity-20":""}`})}),a.jsx(Ne,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>x(!0),title:u("archives.card.preview3d"),children:a.jsx(Ii,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),a.jsx(Ne,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{ae.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(we=>{console.error("Archive download failed:",we)})},title:u("archives.card.download"),children:a.jsx(wi,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>A(!0),disabled:!m("archives","update",t.created_by_id),title:m("archives","update",t.created_by_id)?u("archives.card.edit"):u("archives.card.noPermissionEdit"),children:a.jsx(Ji,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>T(!0),disabled:!m("archives","delete",t.created_by_id),title:m("archives","delete",t.created_by_id)?u("archives.card.delete"):u("archives.card.noPermissionDelete"),children:a.jsx(ln,{className:"w-3 h-3 sm:w-4 sm:h-4 text-red-400"})})]})]}),M&&a.jsx(Bee,{archive:t,onClose:()=>A(!1)}),y&&a.jsx(C4,{archiveId:t.id,title:t.print_name||t.filename,fileType:Tre(t.filename),onClose:()=>x(!1)}),v&&a.jsx(Ou,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>S(!1)}),N&&a.jsx(er,{title:u("archives.modal.deleteArchive"),message:u("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{z.mutate(),T(!1)},onCancel:()=>T(!1)}),B&&a.jsx(er,{title:u("archives.modal.removeSource3mf"),message:u("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{re.mutate(),W(!1)},onCancel:()=>W(!1)}),J&&a.jsx(er,{title:u("archives.modal.removeF3d"),message:u("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{le.mutate(),ne(!1)},onCancel:()=>ne(!1)}),me&&a.jsx(Hee,{x:me.x,y:me.y,items:Te,onClose:()=>fe(null)}),k&&t.timelapse_path&&a.jsx(Ere,{src:ae.getArchiveTimelapse(t.id),title:u("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>R(!1),onEdit:()=>{d.invalidateQueries({queryKey:["archives"]}),R(!1)}}),C&&U.length>0&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:"Select Timelapse"}),a.jsx("p",{className:"text-sm text-gray-400 mt-1",children:"No auto-match found. Select the timelapse for this print:"})]}),a.jsx("button",{onClick:()=>{P(!1),F([])},className:"text-gray-400 hover:text-white p-1",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:U.map(we=>a.jsxs("button",{onClick:()=>ee.mutate(we.name),disabled:ee.isPending,className:"w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors flex items-center gap-3 disabled:opacity-50",children:[a.jsx(ph,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-white font-medium truncate",children:we.name}),a.jsxs("p",{className:"text-sm text-gray-400",children:[rk(we.size),we.mtime&&` • ${qg(we.mtime,l)}`]})]})]},we.name))}),a.jsx("div",{className:"p-4 border-t border-gray-700",children:a.jsx(Ne,{variant:"secondary",onClick:()=>{P(!1),F([])},className:"w-full",children:"Cancel"})})]})}),H&&a.jsx($ee,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>D(!1)}),$&&t.photos&&t.photos.length>0&&a.jsx(Vee,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>G(!1),onDelete:async we=>{try{await ae.deleteArchivePhoto(t.id,we),d.invalidateQueries({queryKey:["archives"]}),h(u("archives.toast.photoDeleted"))}catch{h(u("archives.toast.failedDeletePhoto"),"error")}}}),I&&a.jsx(Mre,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>K(!1)}),Q&&a.jsx(Ou,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>oe(!1)}),a.jsx("input",{ref:Fe,type:"file",accept:".3mf",className:"hidden",onChange:we=>{const $e=we.target.files?.[0];$e&&q.mutate($e),we.target.value=""}}),a.jsx("input",{ref:ce,type:"file",accept:".f3d",className:"hidden",onChange:we=>{const $e=we.target.files?.[0];$e&&X.mutate($e),we.target.value=""}})]})}function j9e({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:i,projects:s,isHighlighted:o,preferredSlicer:l="bambu_studio",t:c}){const u=an(),{showToast:d}=Tn(),{hasPermission:h,canModify:p}=Ir(),[m,b]=_.useState(!1),[y,x]=_.useState(!1),[v,S]=_.useState(!1),[N,T]=_.useState(!1),[M,A]=_.useState(!1),[k,R]=_.useState(!1),[C,P]=_.useState(!1),[U,F]=_.useState([]),[H,D]=_.useState(!1),[$,G]=_.useState(!1),[I,K]=_.useState(!1),[Q,oe]=_.useState(!1),[B,W]=_.useState(!1),[J,ne]=_.useState(null),me=_.useRef(null),fe=_.useRef(null),de=dt({mutationFn:le=>ae.uploadSource3mf(t.id,le),onSuccess:le=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.source3mfAttached",{filename:le.filename}))},onError:le=>{d(le.message||c("archives.toast.failedUploadSource3mf"),"error")}}),Re=dt({mutationFn:()=>ae.deleteSource3mf(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.source3mfRemoved"))},onError:le=>{d(le.message||c("archives.toast.failedRemoveSource3mf"),"error")}}),se=dt({mutationFn:le=>ae.uploadF3d(t.id,le),onSuccess:le=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.f3dAttached",{filename:le.filename}))},onError:le=>{d(le.message||c("archives.toast.failedUploadF3d"),"error")}}),ke=dt({mutationFn:()=>ae.deleteF3d(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.f3dRemoved"))},onError:le=>{d(le.message||c("archives.toast.failedRemoveF3d"),"error")}}),Fe=dt({mutationFn:()=>ae.scanArchiveTimelapse(t.id),onSuccess:le=>{le.status==="attached"?(u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.timelapseAttached",{filename:le.filename}))):le.status==="exists"?d(c("archives.toast.timelapseAlreadyAttached")):le.status==="not_found"&&le.available_files&&le.available_files.length>0?(F(le.available_files),P(!0)):d(le.message||c("archives.toast.noMatchingTimelapse"),"warning")},onError:le=>{d(le.message||c("archives.toast.failedScanTimelapse"),"error")}}),ce=dt({mutationFn:le=>ae.selectArchiveTimelapse(t.id,le),onSuccess:le=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.timelapseAttached",{filename:le.filename})),P(!1),F([])},onError:le=>{d(le.message||c("archives.toast.failedAttachTimelapse"),"error")}}),Ve=dt({mutationFn:()=>ae.deleteArchive(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.archiveDeleted"))},onError:()=>{d(c("archives.toast.failedDeleteArchive"),"error")}}),V=dt({mutationFn:()=>ae.toggleFavorite(t.id),onSuccess:le=>{u.invalidateQueries({queryKey:["archives"]}),d(le.is_favorite?c("archives.toast.addedToFavorites"):c("archives.toast.removedFromFavorites"))}}),{data:Y}=it({queryKey:["archive-folders",t.id],queryFn:()=>ae.getLibraryFoldersByArchive(t.id)}),ue=dt({mutationFn:le=>ae.updateArchive(t.id,{project_id:le}),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),u.invalidateQueries({queryKey:["projects"]}),d(c("archives.toast.projectUpdated"))},onError:()=>{d(c("archives.toast.failedUpdateProject"),"error")}}),q=le=>{le.preventDefault(),ne({x:le.clientX,y:le.clientY})},X=[...Ff(t.filename)?[{label:c("archives.menu.print"),icon:a.jsx(jr,{className:"w-4 h-4"}),onClick:()=>S(!0),disabled:!p("archives","reprint",t.created_by_id),title:p("archives","reprint",t.created_by_id)?void 0:c("archives.permission.noReprint")},{label:c("archives.menu.schedule"),icon:a.jsx(ti,{className:"w-4 h-4"}),onClick:()=>T(!0),disabled:!h("queue:create"),title:h("queue:create")?void 0:c("archives.permission.noAddToQueue")},{label:c("archives.menu.openInBambuStudio"),icon:a.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>{const le=t.print_name||t.filename||"model",pe=`${window.location.origin}${ae.getArchiveForSlicer(t.id,le)}`;sc(pe,l)}}]:[{label:c("archives.menu.slice"),icon:a.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>{const le=t.print_name||t.filename||"model",pe=`${window.location.origin}${ae.getArchiveForSlicer(t.id,le)}`;sc(pe,l)}}],{label:t.external_url?c("archives.menu.externalLink"):c("archives.menu.viewOnMakerWorld"),icon:a.jsx(gh,{className:"w-4 h-4"}),onClick:()=>{const le=t.external_url||t.makerworld_url;le&&window.open(le,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.preview3d"),icon:a.jsx(Ii,{className:"w-4 h-4"}),onClick:()=>A(!0)},{label:c("archives.menu.viewTimelapse"),icon:a.jsx(ph,{className:"w-4 h-4"}),onClick:()=>R(!0),disabled:!t.timelapse_path},{label:c("archives.menu.scanForTimelapse"),icon:a.jsx(nS,{className:"w-4 h-4"}),onClick:()=>Fe.mutate(),disabled:!t.printer_id||!!t.timelapse_path||Fe.isPending||!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:"",divider:!0,onClick:()=>{}},{label:t.source_3mf_path?c("archives.menu.downloadSource3mf"):c("archives.menu.uploadSource3mf"),icon:a.jsx(J1,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?ae.downloadSource3mf(t.id).catch(le=>{console.error("Source 3MF download failed:",le)}):me.current?.click()},disabled:!t.source_3mf_path&&!p("archives","update",t.created_by_id),title:!t.source_3mf_path&&!p("archives","update",t.created_by_id)?c("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:c("archives.menu.replaceSource3mf"),icon:a.jsx(Na,{className:"w-4 h-4"}),onClick:()=>me.current?.click(),disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.removeSource3mf"),icon:a.jsx(ln,{className:"w-4 h-4"}),onClick:()=>oe(!0),danger:!0,disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")}]:[],{label:t.f3d_path?c("archives.menu.replaceF3d"):c("archives.menu.uploadF3d"),icon:a.jsx(Ii,{className:"w-4 h-4"}),onClick:()=>fe.current?.click(),disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:c("archives.menu.downloadF3d"),icon:a.jsx(wi,{className:"w-4 h-4"}),onClick:()=>{ae.downloadF3d(t.id).catch(le=>{console.error("F3D download failed:",le)})}},{label:c("archives.menu.removeF3d"),icon:a.jsx(ln,{className:"w-4 h-4"}),onClick:()=>W(!0),danger:!0,disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.download"),icon:a.jsx(wi,{className:"w-4 h-4"}),onClick:()=>{ae.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(le=>{console.error("Archive download failed:",le)})},disabled:!h("archives:read"),title:h("archives:read")?void 0:c("archives.permission.noDownload")},{label:c("archives.menu.copyDownloadLink"),icon:a.jsx(zl,{className:"w-4 h-4"}),onClick:()=>{const le=`${window.location.origin}${ae.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(le).then(()=>{d(c("archives.toast.linkCopied"))}).catch(()=>{d(c("archives.toast.failedCopyLink"),"error")})},disabled:!h("archives:read"),title:h("archives:read")?void 0:c("archives.permission.noCopyLink")},{label:c("archives.menu.qrCode"),icon:a.jsx(UW,{className:"w-4 h-4"}),onClick:()=>D(!0)},{label:t.photos?.length?c("archives.menu.viewPhotosCount",{count:t.photos.length}):c("archives.menu.viewPhotos"),icon:a.jsx($g,{className:"w-4 h-4"}),onClick:()=>G(!0),disabled:!t.photos?.length},{label:c("archives.menu.projectPage"),icon:a.jsx(ys,{className:"w-4 h-4"}),onClick:()=>K(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?c("archives.menu.removeFromFavorites"):c("archives.menu.addToFavorites"),icon:a.jsx(hm,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>V.mutate(),disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.edit"),icon:a.jsx(Ji,{className:"w-4 h-4"}),onClick:()=>b(!0),disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.project_id&&t.project_name?[{label:c("archives.menu.goToProject",{name:t.project_name}),icon:a.jsx(rs,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:c("archives.menu.addToProject"),icon:a.jsx(rs,{className:"w-4 h-4"}),onClick:()=>{},submenu:(()=>{const le=[];if(t.project_id&&le.push({label:c("archives.menu.removeFromProject"),icon:a.jsx(Lt,{className:"w-4 h-4"}),onClick:()=>ue.mutate(null)}),!s)le.push({label:c("archives.menu.loading"),icon:a.jsx(ct,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const pe=s.filter(ee=>ee.status==="active");pe.length===0?le.push({label:c("archives.menu.noProjectsAvailable"),icon:a.jsx(rs,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):pe.forEach(ee=>{le.push({label:ee.name,icon:a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:ee.color||"#888"}}),onClick:()=>ue.mutate(ee.id),disabled:t.project_id===ee.id})})}return le})()},{label:c(n?"archives.menu.deselect":"archives.menu.select"),icon:n?a.jsx(Xs,{className:"w-4 h-4"}):a.jsx(ul,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.delete"),icon:a.jsx(ln,{className:"w-4 h-4"}),onClick:()=>x(!0),danger:!0,disabled:!p("archives","delete",t.created_by_id),title:p("archives","delete",t.created_by_id)?void 0:c("archives.permission.noDelete")}];return a.jsxs(a.Fragment,{children:[a.jsxs("div",{"data-archive-id":t.id,className:`grid grid-cols-12 gap-4 px-4 py-3 items-center hover:bg-bambu-dark-tertiary/30 ${n?"bg-bambu-green/10":""}`,style:o?{outline:"4px solid #facc15",outlineOffset:"-4px"}:void 0,onContextMenu:q,children:[a.jsxs("div",{className:"col-span-1 flex items-center gap-2",children:[i&&a.jsx("button",{onClick:()=>r(t.id),children:n?a.jsx(Xs,{className:"w-4 h-4 text-bambu-green"}):a.jsx(ul,{className:"w-4 h-4 text-bambu-gray"})}),t.thumbnail_path?a.jsx("img",{src:ae.getArchiveThumbnail(t.id),alt:"",className:"w-10 h-10 object-cover rounded"}):a.jsx("div",{className:"w-10 h-10 bg-bambu-dark rounded flex items-center justify-center",children:a.jsx(Uu,{className:"w-5 h-5 text-bambu-dark-tertiary"})})]}),a.jsxs("div",{className:"col-span-4",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-white text-sm truncate",children:t.print_name||t.filename}),t.timelapse_path&&a.jsx("span",{title:c("archives.list.hasTimelapse"),children:a.jsx(ph,{className:"w-3.5 h-3.5 text-bambu-green flex-shrink-0"})}),Y&&Y.length>0&&a.jsx(Bs,{to:`/files?folder=${Y[0].id}`,className:"flex-shrink-0",title:c("archives.card.openFolder",{name:Y[0].name}),onClick:le=>le.stopPropagation(),children:a.jsx(Ul,{className:"w-3.5 h-3.5 text-yellow-400"})})]}),(t.filament_type||t.sliced_for_model)&&a.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[t.sliced_for_model&&a.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",title:c("archives.card.slicedFor",{model:t.sliced_for_model}),children:[a.jsx(jr,{className:"w-2.5 h-2.5"}),t.sliced_for_model]}),t.sliced_for_model&&t.filament_type&&a.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.filament_type&&a.jsx("span",{className:"text-xs text-bambu-gray",children:t.filament_type}),t.filament_color&&a.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((le,pe)=>a.jsx("div",{className:"w-2.5 h-2.5 rounded-full border border-white/20",style:{backgroundColor:le},title:le},pe))})]})]}),a.jsx("div",{className:"col-span-2 text-sm text-bambu-gray truncate",children:e}),a.jsxs("div",{className:"col-span-2 text-sm text-bambu-gray",children:[a.jsx("div",{children:Gg(t.created_at)}),t.created_by_username&&a.jsxs("div",{className:"flex items-center gap-1 text-xs opacity-75",title:c("archives.card.uploadedBy",{name:t.created_by_username}),children:[a.jsx($u,{className:"w-3 h-3"}),t.created_by_username]})]}),a.jsx("div",{className:"col-span-1 text-sm text-bambu-gray",children:rk(t.file_size)}),a.jsxs("div",{className:"col-span-2 flex justify-end gap-1",children:[a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{const le=t.print_name||t.filename||"model",pe=`${window.location.origin}${ae.getArchiveForSlicer(t.id,le)}`;sc(pe,l)},title:c("archives.card.openInBambuStudio"),children:a.jsx(Xr,{className:"w-4 h-4"})}),(t.external_url||t.makerworld_url)&&a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>window.open(t.external_url||t.makerworld_url,"_blank"),title:t.external_url?c("archives.card.externalLink"):"MakerWorld",children:a.jsx(gh,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{ae.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(le=>{console.error("Archive download failed:",le)})},title:c("archives.card.download"),children:a.jsx(wi,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>b(!0),disabled:!p("archives","update",t.created_by_id),title:p("archives","update",t.created_by_id)?c("archives.card.edit"):c("archives.card.noPermissionEdit"),children:a.jsx(Ji,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>x(!0),disabled:!p("archives","delete",t.created_by_id),title:p("archives","delete",t.created_by_id)?c("archives.card.delete"):c("archives.card.noPermissionDelete"),children:a.jsx(ln,{className:"w-4 h-4 text-red-400"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:le=>{const pe=le.currentTarget.getBoundingClientRect();ne({x:pe.left,y:pe.bottom+4})},title:c("archives.card.moreOptions"),children:a.jsx(mh,{className:"w-4 h-4"})})]})]}),m&&a.jsx(Bee,{archive:t,onClose:()=>b(!1)}),M&&a.jsx(C4,{archiveId:t.id,title:t.print_name||t.filename,fileType:Tre(t.filename),onClose:()=>A(!1)}),v&&a.jsx(Ou,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>S(!1)}),y&&a.jsx(er,{title:c("archives.modal.deleteArchive"),message:c("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{Ve.mutate(),x(!1)},onCancel:()=>x(!1)}),Q&&a.jsx(er,{title:c("archives.modal.removeSource3mf"),message:c("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{Re.mutate(),oe(!1)},onCancel:()=>oe(!1)}),B&&a.jsx(er,{title:c("archives.modal.removeF3d"),message:c("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{ke.mutate(),W(!1)},onCancel:()=>W(!1)}),J&&a.jsx(Hee,{x:J.x,y:J.y,items:X,onClose:()=>ne(null)}),k&&t.timelapse_path&&a.jsx(Ere,{src:ae.getArchiveTimelapse(t.id),title:c("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>R(!1),onEdit:()=>{u.invalidateQueries({queryKey:["archives"]}),R(!1)}}),C&&U.length>0&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:"Select Timelapse"}),a.jsx("p",{className:"text-sm text-gray-400 mt-1",children:"No auto-match found. Select the timelapse for this print:"})]}),a.jsx("button",{onClick:()=>{P(!1),F([])},className:"text-gray-400 hover:text-white p-1",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:U.map(le=>a.jsxs("button",{onClick:()=>ce.mutate(le.name),disabled:ce.isPending,className:"w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors mb-1",children:[a.jsx("div",{className:"font-medium text-white",children:le.name}),a.jsxs("div",{className:"text-sm text-gray-400 flex gap-3",children:[a.jsx("span",{children:rk(le.size)}),le.mtime&&a.jsx("span",{children:Gg(le.mtime)})]})]},le.name))})]})}),H&&a.jsx($ee,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>D(!1)}),$&&t.photos&&a.jsx(Vee,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>G(!1),onDelete:async le=>{try{await ae.deleteArchivePhoto(t.id,le),u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.photoDeleted"))}catch{d(c("archives.toast.failedDeletePhoto"),"error")}}}),I&&a.jsx(Mre,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>K(!1)}),N&&a.jsx(Ou,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>T(!1)}),a.jsx("input",{ref:me,type:"file",accept:".3mf",className:"hidden",onChange:le=>{const pe=le.target.files?.[0];pe&&de.mutate(pe),le.target.value=""}}),a.jsx("input",{ref:fe,type:"file",accept:".f3d",className:"hidden",onChange:le=>{const pe=le.target.files?.[0];pe&&se.mutate(pe),le.target.value=""}})]})}const D9e=[{id:"all",label:"All Archives",icon:a.jsx(Ul,{className:"w-4 h-4"})},{id:"recent",label:"Last 24 Hours",icon:a.jsx(tr,{className:"w-4 h-4"})},{id:"this-week",label:"This Week",icon:a.jsx(ti,{className:"w-4 h-4"})},{id:"this-month",label:"This Month",icon:a.jsx(ti,{className:"w-4 h-4"})},{id:"favorites",label:"Favorites",icon:a.jsx(hm,{className:"w-4 h-4"})},{id:"failed",label:"Failed Prints",icon:a.jsx(Ti,{className:"w-4 h-4"})},{id:"duplicates",label:"Duplicates",icon:a.jsx(zl,{className:"w-4 h-4"})}];function R9e(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),{hasPermission:r,hasAnyPermission:i}=Ir(),s=_.useRef(null),[o,l]=_.useState(""),[c,u]=_.useState(()=>{const ye=localStorage.getItem("archiveFilterPrinter");return ye?Number(ye):null}),[d,h]=_.useState(()=>localStorage.getItem("archiveFilterMaterial")),[p,m]=_.useState(()=>{const ye=localStorage.getItem("archiveFilterColors");return ye?new Set(JSON.parse(ye)):new Set}),[b,y]=_.useState(()=>localStorage.getItem("archiveColorFilterMode")||"or"),[x,v]=_.useState(()=>localStorage.getItem("archiveFilterFavorites")==="true"),[S,N]=_.useState(()=>localStorage.getItem("archiveHideFailed")==="true"),[T,M]=_.useState(()=>localStorage.getItem("archiveFilterTag")),[A,k]=_.useState(()=>localStorage.getItem("archiveFilterFileType")||"all"),[R,C]=_.useState(!1),[P,U]=_.useState([]),[F,H]=_.useState(!1),[D,$]=_.useState(new Set),[G,I]=_.useState(!1),[K,Q]=_.useState(!1),[oe,B]=_.useState(!1),[W,J]=_.useState(!1),[ne,me]=_.useState(()=>localStorage.getItem("archiveViewMode")||"grid"),[fe,de]=_.useState(()=>localStorage.getItem("archiveSortBy")||"date-desc"),[Re,se]=_.useState(()=>localStorage.getItem("archiveCollection")||"all"),[ke,Fe]=_.useState(!1),[ce,Ve]=_.useState(!1),[V,Y]=_.useState(!1),[ue,q]=_.useState(!1),[re,X]=_.useState(null);_.useEffect(()=>{if(re){const ye=setTimeout(()=>{const yt=document.querySelector(`[data-archive-id="${re}"]`);yt&&yt.scrollIntoView({behavior:"smooth",block:"center"})},100),Qe=setTimeout(()=>X(null),5e3);return()=>{clearTimeout(ye),clearTimeout(Qe)}}},[re]);const{data:le,isLoading:pe}=it({queryKey:["archives",c],queryFn:()=>ae.getArchives(c||void 0)}),{data:ee}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:z}=it({queryKey:["projects"],queryFn:()=>ae.getProjects()}),{data:O}=it({queryKey:["settings"],queryFn:ae.getSettings}),Z=O?.time_format||"system",ge=O?.preferred_slicer||"bambu_studio",Ce=dt({mutationFn:async ye=>(await Promise.all(ye.map(Qe=>ae.deleteArchive(Qe))),ye.length),onSuccess:ye=>{e.invalidateQueries({queryKey:["archives"]}),$(new Set),n(`${ye} archive${ye!==1?"s":""} deleted`)},onError:()=>{n(t("archives.toast.failedDeleteArchives"),"error")}});_.useEffect(()=>{c!==null?localStorage.setItem("archiveFilterPrinter",c.toString()):localStorage.removeItem("archiveFilterPrinter")},[c]),_.useEffect(()=>{d?localStorage.setItem("archiveFilterMaterial",d):localStorage.removeItem("archiveFilterMaterial")},[d]),_.useEffect(()=>{localStorage.setItem("archiveFilterColors",JSON.stringify([...p]))},[p]),_.useEffect(()=>{localStorage.setItem("archiveColorFilterMode",b)},[b]),_.useEffect(()=>{localStorage.setItem("archiveFilterFavorites",x.toString())},[x]),_.useEffect(()=>{localStorage.setItem("archiveHideFailed",S.toString())},[S]),_.useEffect(()=>{T?localStorage.setItem("archiveFilterTag",T):localStorage.removeItem("archiveFilterTag")},[T]),_.useEffect(()=>{localStorage.setItem("archiveFilterFileType",A)},[A]),_.useEffect(()=>{localStorage.setItem("archiveViewMode",ne)},[ne]),_.useEffect(()=>{localStorage.setItem("archiveSortBy",fe)},[fe]),_.useEffect(()=>{localStorage.setItem("archiveCollection",Re)},[Re]);const _e=new Map(ee?.map(ye=>[ye.id,ye.name])||[]),Te=[...new Set(le?.flatMap(ye=>ye.filament_type?.split(", ")||[]).filter(Boolean)||[])].sort(),we=[...new Set(le?.flatMap(ye=>ye.filament_color?.split(",")||[]).filter(Boolean)||[])],$e=[...new Set(le?.flatMap(ye=>ye.tags?.split(",").map(Qe=>Qe.trim())||[]).filter(Boolean)||[])].sort(),Ge=le?.filter(ye=>{const Qe=new Date,yt=zi(ye.created_at)||new Date(0);let at=!0;switch(Re){case"recent":at=Qe.getTime()-yt.getTime()<1440*60*1e3;break;case"this-week":at=Qe.getTime()-yt.getTime()<10080*60*1e3;break;case"this-month":at=yt.getMonth()===Qe.getMonth()&&yt.getFullYear()===Qe.getFullYear();break;case"favorites":at=ye.is_favorite===!0;break;case"failed":at=ye.status==="failed"||ye.status==="aborted";break;case"duplicates":at=ye.duplicate_count>0;break}const Ut=(ye.print_name||ye.filename).toLowerCase().includes(o.toLowerCase()),zt=!d||ye.filament_type?.split(", ").includes(d),Ie=ye.filament_color?.split(",")||[],vt=p.size===0||(b==="or"?Ie.some(kn=>p.has(kn)):[...p].every(kn=>Ie.includes(kn))),Gt=Re==="favorites"||!x||ye.is_favorite,dn=Re==="failed"||!S||ye.status!=="failed"&&ye.status!=="aborted",fn=ye.tags?.split(",").map(kn=>kn.trim())||[],vn=!T||fn.includes(T),dr=Ff(ye.filename);return at&&Ut&&zt&&vt&&Gt&&dn&&vn&&(A==="all"||A==="gcode"&&dr||A==="source"&&!dr)}).sort((ye,Qe)=>{switch(fe){case"date-desc":return(zi(Qe.created_at)?.getTime()||0)-(zi(ye.created_at)?.getTime()||0);case"date-asc":return(zi(ye.created_at)?.getTime()||0)-(zi(Qe.created_at)?.getTime()||0);case"name-asc":return(ye.print_name||ye.filename).localeCompare(Qe.print_name||Qe.filename);case"name-desc":return(Qe.print_name||Qe.filename).localeCompare(ye.print_name||ye.filename);case"size-desc":return Qe.file_size-ye.file_size;case"size-asc":return ye.file_size-Qe.file_size;default:return 0}}),ze=G||D.size>0,be=ye=>{$(Qe=>{const yt=new Set(Qe);return yt.has(ye)?yt.delete(ye):yt.add(ye),yt})},Me=()=>{Ge&&$(new Set(Ge.map(ye=>ye.id)))},Be=()=>{$(new Set),I(!1)},Ae=ye=>{m(Qe=>{const yt=new Set(Qe);return yt.has(ye)?yt.delete(ye):yt.add(ye),yt})},qe=()=>{m(new Set)},ve=()=>{l(""),u(null),h(null),v(!1),N(!1),M(null),k("all")},et=o||c||d||x||S||T||A!=="all",Ee=_.useCallback(ye=>{ye.preventDefault(),ye.dataTransfer.types.includes("Files")&&H(!0)},[]),Ye=_.useCallback(ye=>{ye.preventDefault(),ye.currentTarget===ye.target&&H(!1)},[]),je=_.useCallback(ye=>{ye.preventDefault(),H(!1);const Qe=Array.from(ye.dataTransfer.files).filter(yt=>yt.name.endsWith(".3mf"));Qe.length>0?(U(Qe),C(!0)):ye.dataTransfer.files.length>0&&n(t("archives.page.only3mfSupported"),"warning")},[n,t]),Pe=_.useCallback(ye=>{const Qe=ye.target;if(Qe.tagName==="INPUT"||Qe.tagName==="TEXTAREA"||Qe.isContentEditable){ye.key==="Escape"&&Qe.blur();return}switch(ye.key){case"/":ye.preventDefault(),s.current?.focus();break;case"u":case"U":!ye.metaKey&&!ye.ctrlKey&&(ye.preventDefault(),C(!0));break;case"Escape":ze&&Be();break}},[ze]);return _.useEffect(()=>(document.addEventListener("keydown",Pe),()=>document.removeEventListener("keydown",Pe)),[Pe]),a.jsxs("div",{className:"p-4 md:p-8 relative min-h-full",onDragOver:Ee,onDragLeave:Ye,onDrop:je,children:[F&&a.jsx("div",{className:"fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none",children:a.jsxs("div",{className:"border-4 border-dashed border-bambu-green rounded-xl p-12 text-center",children:[a.jsx(Na,{className:"w-16 h-16 mx-auto mb-4 text-bambu-green"}),a.jsx("p",{className:"text-2xl font-semibold text-white mb-2",children:"Drop .3mf files here"}),a.jsx("p",{className:"text-bambu-gray",children:t("archives.releaseToUpload")})]})}),ze&&a.jsxs("div",{className:"fixed bottom-6 left-1/2 -translate-x-1/2 z-40 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl px-4 py-3 flex items-center gap-4",children:[a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:Be,children:[a.jsx(Lt,{className:"w-4 h-4"}),"Close"]}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("span",{className:"text-white font-medium",children:[D.size," selected"]}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:Me,children:"Select All"}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>B(!0),disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[a.jsx(Th,{className:"w-4 h-4"}),"Tags"]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>J(!0),disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[a.jsx(rs,{className:"w-4 h-4"}),"Project"]}),a.jsxs(Ne,{variant:"secondary",size:"sm",disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),onClick:()=>{const ye=Array.from(D);Promise.all(ye.map(Qe=>ae.toggleFavorite(Qe))).then(()=>{e.invalidateQueries({queryKey:["archives"]}),n(`Toggled favorites for ${ye.length} archive${ye.length!==1?"s":""}`)}).catch(()=>{n(t("archives.toast.failedUpdateFavorites"),"error")})},children:[a.jsx(hm,{className:"w-4 h-4"}),"Favorite"]}),a.jsxs(Ne,{size:"sm",className:"bg-red-500 hover:bg-red-600",onClick:()=>Q(!0),disabled:!i("archives:delete_own","archives:delete_all"),title:i("archives:delete_own","archives:delete_all")?void 0:t("archives.permission.noDelete"),children:[a.jsx(ln,{className:"w-4 h-4"}),"Delete"]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:"Archives"}),a.jsx("select",{className:"px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray-light text-sm focus:border-bambu-green focus:outline-none",value:Re,onChange:ye=>se(ye.target.value),children:D9e.map(ye=>a.jsx("option",{value:ye.id,children:ye.label},ye.id))})]}),a.jsxs("p",{className:"text-bambu-gray",children:[Ge?.length||0," of ",le?.length||0," prints"]})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"relative",children:[a.jsxs(Ne,{variant:"secondary",onClick:()=>Fe(!ke),disabled:ce,children:[ce?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(eS,{className:"w-4 h-4"}),"Export"]}),ke&&a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20",children:[a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg",onClick:async()=>{Fe(!1),Ve(!0);try{const{blob:ye,filename:Qe}=await ae.exportArchives({format:"csv",printerId:c||void 0,status:Re==="failed"?"failed":void 0,search:o||void 0}),yt=URL.createObjectURL(ye),at=document.createElement("a");at.href=yt,at.download=Qe,at.click(),URL.revokeObjectURL(yt),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{Ve(!1)}},children:[a.jsx(ys,{className:"w-4 h-4"}),"Export as CSV"]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg",onClick:async()=>{Fe(!1),Ve(!0);try{const{blob:ye,filename:Qe}=await ae.exportArchives({format:"xlsx",printerId:c||void 0,status:Re==="failed"?"failed":void 0,search:o||void 0}),yt=URL.createObjectURL(ye),at=document.createElement("a");at.href=yt,at.download=Qe,at.click(),URL.revokeObjectURL(yt),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{Ve(!1)}},children:[a.jsx(eS,{className:"w-4 h-4"}),"Export as Excel"]})]})]}),D.size>=2&&D.size<=5&&a.jsxs(Ne,{variant:"secondary",onClick:()=>Y(!0),children:[a.jsx(Mg,{className:"w-4 h-4"}),"Compare (",D.size,")"]}),!ze&&a.jsxs(Ne,{variant:"secondary",onClick:()=>I(!0),children:[a.jsx(Xs,{className:"w-4 h-4"}),"Select"]}),a.jsxs(Ne,{onClick:()=>C(!0),disabled:!r("archives:create"),title:r("archives:create")?void 0:t("archives.permission.noCreate"),children:[a.jsx(Na,{className:"w-4 h-4"}),"Upload 3MF"]})]})]}),a.jsx(St,{className:"mb-6",children:a.jsxs(Et,{className:"py-4",children:[a.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:gap-4 md:items-center md:flex-wrap",children:[a.jsxs("div",{className:"w-full md:flex-1 relative md:min-w-[200px]",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{ref:s,type:"text",placeholder:t("archives.searchPlaceholder"),className:"w-full pl-10 pr-4 py-3 md:py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:o,onChange:ye=>l(ye.target.value)})]}),a.jsxs("div",{className:"flex gap-2 md:gap-4 overflow-x-auto pb-1 md:pb-0 -mx-4 px-4 md:mx-0 md:px-0 md:flex-wrap scrollbar-hide",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(yk,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c||"",onChange:ye=>u(ye.target.value?Number(ye.target.value):null),children:[a.jsx("option",{value:"",children:"All Printers"}),ee?.map(ye=>a.jsx("option",{value:ye.id,children:ye.name},ye.id))]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(bc,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:d||"",onChange:ye=>h(ye.target.value||null),children:[a.jsx("option",{value:"",children:"All Materials"}),Te.map(ye=>a.jsx("option",{value:ye,children:ye},ye))]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(J1,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:A,onChange:ye=>k(ye.target.value),children:[a.jsx("option",{value:"all",children:"All Files"}),a.jsx("option",{value:"gcode",children:"Sliced (GCODE)"}),a.jsx("option",{value:"source",children:"Source Only"})]})]}),a.jsxs("button",{onClick:()=>v(!x),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${x?"bg-yellow-500/20 border-yellow-500 text-yellow-400":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t(x?"archives.showAll":"archives.showFavoritesOnly"),children:[a.jsx(hm,{className:`w-4 h-4 ${x?"fill-yellow-400":""}`}),a.jsx("span",{className:"text-sm hidden md:inline",children:"Favorites"})]}),a.jsxs("button",{onClick:()=>N(!S),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${S?"bg-red-500/20 border-red-500 text-red-400":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t(S?"archives.showFailedPrints":"archives.hideFailedPrints"),children:[a.jsx(Ti,{className:"w-4 h-4 "}),a.jsx("span",{className:"text-sm hidden md:inline",children:"Hide Failed"})]}),$e.length>0&&a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(Th,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:T||"",onChange:ye=>M(ye.target.value||null),children:[a.jsx("option",{value:"",children:"All Tags"}),$e.map(ye=>a.jsx("option",{value:ye,children:ye},ye))]}),a.jsx("button",{onClick:()=>q(!0),className:"p-2 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",title:t("archives.manageTags"),children:a.jsx(Mk,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(PW,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:fe,onChange:ye=>de(ye.target.value),children:[a.jsx("option",{value:"date-desc",children:t("archives.sortNewest")}),a.jsx("option",{value:"date-asc",children:t("archives.sortOldest")}),a.jsxs("option",{value:"name-asc",children:[t("archives.sortName")," A-Z"]}),a.jsxs("option",{value:"name-desc",children:[t("archives.sortName")," Z-A"]}),a.jsx("option",{value:"size-desc",children:t("archives.sortLargest")}),a.jsx("option",{value:"size-asc",children:t("archives.sortSmallest")})]})]}),a.jsxs("div",{className:"flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden flex-shrink-0",children:[a.jsx("button",{className:`p-2 ${ne==="grid"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>me("grid"),title:t("archives.gridView"),children:a.jsx(wk,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 ${ne==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>me("list"),title:t("archives.listView"),children:a.jsx(_k,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 ${ne==="calendar"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>me("calendar"),title:t("archives.calendarView"),children:a.jsx(eue,{className:"w-4 h-4"})})]})]}),et&&a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:ve,className:"text-bambu-gray hover:text-white",children:[a.jsx(Lt,{className:"w-4 h-4"}),"Reset"]})]}),we.length>0&&a.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Colors:"}),p.size>1&&a.jsx("button",{onClick:()=>y(ye=>ye==="or"?"and":"or"),className:`px-2 py-0.5 text-xs rounded transition-colors ${b==="and"?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:b==="or"?"Match ANY selected color":"Match ALL selected colors",children:b.toUpperCase()}),a.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:we.map(ye=>a.jsx("button",{onClick:()=>Ae(ye),className:`w-6 h-6 rounded-full border-2 transition-all ${p.has(ye)?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:ye},title:ye},ye))}),p.size>0&&a.jsxs("button",{onClick:qe,className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1",children:[a.jsx(Lt,{className:"w-3 h-3"}),"Clear"]})]})]})}),a.jsx(A9e,{}),pe?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.loadingArchives")}):Ge?.length===0?a.jsx(St,{children:a.jsxs(Et,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray",children:t(o?"archives.noArchivesSearch":"archives.noArchivesYet")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:"Archives are created automatically when prints complete"})]})}):ne==="calendar"?a.jsx(St,{className:"p-6",children:a.jsx(s6e,{archives:Ge||[],onArchiveClick:ye=>{l(""),me("grid"),X(ye.id)},highlightedArchiveId:re})}):ne==="grid"?a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:Ge?.map(ye=>a.jsx(P9e,{archive:ye,printerName:ye.printer_id?_e.get(ye.printer_id)||"Unknown":ye.sliced_for_model?`Sliced for ${ye.sliced_for_model}`:"No Printer",isSelected:D.has(ye.id),onSelect:be,selectionMode:ze,projects:z,isHighlighted:ye.id===re,timeFormat:Z,preferredSlicer:ge,t},ye.id))}):ne==="list"?a.jsx(St,{children:a.jsxs("div",{className:"divide-y divide-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-12 gap-4 px-4 py-3 text-xs text-bambu-gray font-medium",children:[a.jsx("div",{className:"col-span-1"}),a.jsx("div",{className:"col-span-4",children:"Name"}),a.jsx("div",{className:"col-span-2",children:"Printer"}),a.jsx("div",{className:"col-span-2",children:"Date"}),a.jsx("div",{className:"col-span-1",children:"Size"}),a.jsx("div",{className:"col-span-2 text-right",children:"Actions"})]}),Ge?.map(ye=>a.jsx(j9e,{archive:ye,printerName:ye.printer_id?_e.get(ye.printer_id)||"Unknown":ye.sliced_for_model?`Sliced for ${ye.sliced_for_model}`:"No Printer",isSelected:D.has(ye.id),onSelect:be,selectionMode:ze,projects:z,isHighlighted:ye.id===re,preferredSlicer:ge,t},ye.id))]})}):null,R&&a.jsx(Q8e,{onClose:()=>{C(!1),U([])},initialFiles:P}),K&&a.jsx(er,{title:t("archives.modal.deleteArchives"),message:t("archives.modal.deleteArchivesConfirm",{count:D.size}),confirmText:t("archives.modal.deleteCount",{count:D.size}),variant:"danger",onConfirm:()=>{Ce.mutate(Array.from(D)),Q(!1)},onCancel:()=>Q(!1)}),oe&&a.jsx(e6e,{selectedIds:Array.from(D),existingTags:$e,onClose:()=>B(!1)}),W&&a.jsx(t6e,{selectedIds:Array.from(D),onClose:()=>J(!1)}),V&&D.size>=2&&D.size<=5&&a.jsx(N9e,{archiveIds:Array.from(D),onClose:()=>{Y(!1),$(new Set),I(!1)}}),ue&&a.jsx(C9e,{onClose:()=>q(!1)})]})}function O9e(){for(var t=arguments.length,e=new Array(t),n=0;nr=>{e.forEach(i=>i(r))},e)}const KM=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Bb(t){const e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function yF(t){return"nodeType"in t}function Js(t){var e,n;return t?Bb(t)?t:yF(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function vF(t){const{Document:e}=Js(t);return t instanceof e}function Mv(t){return Bb(t)?!1:t instanceof Js(t).HTMLElement}function Are(t){return t instanceof Js(t).SVGElement}function Hb(t){return t?Bb(t)?t.document:yF(t)?vF(t)?t:Mv(t)||Are(t)?t.ownerDocument:document:document:document}const kc=KM?_.useLayoutEffect:_.useEffect;function wF(t){const e=_.useRef(t);return kc(()=>{e.current=t}),_.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i{t.current=setInterval(r,i)},[]),n=_.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function Ly(t,e){e===void 0&&(e=[t]);const n=_.useRef(t);return kc(()=>{n.current!==t&&(n.current=t)},e),n}function Ev(t,e){const n=_.useRef();return _.useMemo(()=>{const r=t(n.current);return n.current=r,r},[...e])}function ik(t){const e=wF(t),n=_.useRef(null),r=_.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,r]}function xR(t){const e=_.useRef();return _.useEffect(()=>{e.current=t},[t]),e.current}let XP={};function Tv(t,e){return _.useMemo(()=>{if(e)return e;const n=XP[t]==null?0:XP[t]+1;return XP[t]=n,t+"-"+n},[t,e])}function Cre(t){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i{const l=Object.entries(o);for(const[c,u]of l){const d=s[c];d!=null&&(s[c]=d+t*u)}return s},{...e})}}const Ug=Cre(1),Fy=Cre(-1);function F9e(t){return"clientX"in t&&"clientY"in t}function _F(t){if(!t)return!1;const{KeyboardEvent:e}=Js(t.target);return e&&t instanceof e}function I9e(t){if(!t)return!1;const{TouchEvent:e}=Js(t.target);return e&&t instanceof e}function yR(t){if(I9e(t)){if(t.touches&&t.touches.length){const{clientX:e,clientY:n}=t.touches[0];return{x:e,y:n}}else if(t.changedTouches&&t.changedTouches.length){const{clientX:e,clientY:n}=t.changedTouches[0];return{x:e,y:n}}}return F9e(t)?{x:t.clientX,y:t.clientY}:null}const xb=Object.freeze({Translate:{toString(t){if(!t)return;const{x:e,y:n}=t;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(t){if(!t)return;const{scaleX:e,scaleY:n}=t;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(t){if(t)return[xb.Translate.toString(t),xb.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:r}=t;return e+" "+n+"ms "+r}}}),x9="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function z9e(t){return t.matches(x9)?t:t.querySelector(x9)}const U9e={display:"none"};function B9e(t){let{id:e,value:n}=t;return ei.createElement("div",{id:e,style:U9e},n)}function H9e(t){let{id:e,announcement:n,ariaLiveType:r="assertive"}=t;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return ei.createElement("div",{id:e,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function $9e(){const[t,e]=_.useState("");return{announce:_.useCallback(r=>{r!=null&&e(r)},[]),announcement:t}}const Pre=_.createContext(null);function V9e(t){const e=_.useContext(Pre);_.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(t)},[t,e])}function G9e(){const[t]=_.useState(()=>new Set),e=_.useCallback(r=>(t.add(r),()=>t.delete(r)),[t]);return[_.useCallback(r=>{let{type:i,event:s}=r;t.forEach(o=>{var l;return(l=o[i])==null?void 0:l.call(o,s)})},[t]),e]}const q9e={draggable:` To pick up a draggable item, press the space bar. While dragging, use the arrow keys to move the item. Press space again to drop the item in its new position, or press escape to cancel. - `},q9e={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function W9e(t){let{announcements:e=q9e,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=G9e}=t;const{announce:s,announcement:o}=H9e(),l=Tv("DndLiveRegion"),[c,u]=_.useState(!1);if(_.useEffect(()=>{u(!0)},[]),$9e(_.useMemo(()=>({onDragStart(h){let{active:p}=h;s(e.onDragStart({active:p}))},onDragMove(h){let{active:p,over:m}=h;e.onDragMove&&s(e.onDragMove({active:p,over:m}))},onDragOver(h){let{active:p,over:m}=h;s(e.onDragOver({active:p,over:m}))},onDragEnd(h){let{active:p,over:m}=h;s(e.onDragEnd({active:p,over:m}))},onDragCancel(h){let{active:p,over:m}=h;s(e.onDragCancel({active:p,over:m}))}}),[s,e])),!c)return null;const d=ei.createElement(ei.Fragment,null,ei.createElement(U9e,{id:r,value:i.draggable}),ei.createElement(B9e,{id:l,announcement:o}));return n?vu.createPortal(d,n):d}var Yi;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Yi||(Yi={}));function ak(){}function sk(t,e){return _.useMemo(()=>({sensor:t,options:e??{}}),[t,e])}function jre(){for(var t=arguments.length,e=new Array(t),n=0;n[...e].filter(r=>r!=null),[...e])}const Hl=Object.freeze({x:0,y:0});function Dre(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function Rre(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return n-r}function K9e(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return r-n}function y9(t){let{left:e,top:n,height:r,width:i}=t;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+r},{x:e+i,y:n+r}]}function Ore(t,e){if(!t||t.length===0)return null;const[n]=t;return n[e]}function v9(t,e,n){return e===void 0&&(e=t.left),n===void 0&&(n=t.top),{x:e+t.width*.5,y:n+t.height*.5}}const Lre=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=v9(e,e.left,e.top),s=[];for(const o of r){const{id:l}=o,c=n.get(l);if(c){const u=Dre(v9(c),i);s.push({id:l,data:{droppableContainer:o,value:u}})}}return s.sort(Rre)},X9e=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=y9(e),s=[];for(const o of r){const{id:l}=o,c=n.get(l);if(c){const u=y9(c),d=i.reduce((p,m,b)=>p+Dre(u[b],m),0),h=Number((d/4).toFixed(4));s.push({id:l,data:{droppableContainer:o,value:h}})}}return s.sort(Rre)};function Y9e(t,e){const n=Math.max(e.top,t.top),r=Math.max(e.left,t.left),i=Math.min(e.left+e.width,t.left+t.width),s=Math.min(e.top+e.height,t.top+t.height),o=i-r,l=s-n;if(r{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=[];for(const s of r){const{id:o}=s,l=n.get(o);if(l){const c=Y9e(l,e);c>0&&i.push({id:o,data:{droppableContainer:s,value:c}})}}return i.sort(K9e)};function Z9e(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function Fre(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:Hl}function J9e(t){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),s=1;s({...o,top:o.top+t*l.y,bottom:o.bottom+t*l.y,left:o.left+t*l.x,right:o.right+t*l.x}),{...n})}}const eWe=J9e(1);function tWe(t){if(t.startsWith("matrix3d(")){const e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){const e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function nWe(t,e,n){const r=tWe(e);if(!r)return t;const{scaleX:i,scaleY:s,x:o,y:l}=r,c=t.left-o-(1-i)*parseFloat(n),u=t.top-l-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),d=i?t.width/i:t.width,h=s?t.height/s:t.height;return{width:d,height:h,top:u,right:c+d,bottom:u+h,left:c}}const rWe={ignoreTransform:!1};function $b(t,e){e===void 0&&(e=rWe);let n=t.getBoundingClientRect();if(e.ignoreTransform){const{transform:u,transformOrigin:d}=Js(t).getComputedStyle(t);u&&(n=nWe(n,u,d))}const{top:r,left:i,width:s,height:o,bottom:l,right:c}=n;return{top:r,left:i,width:s,height:o,bottom:l,right:c}}function w9(t){return $b(t,{ignoreTransform:!0})}function iWe(t){const e=t.innerWidth,n=t.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function aWe(t,e){return e===void 0&&(e=Js(t).getComputedStyle(t)),e.position==="fixed"}function sWe(t,e){e===void 0&&(e=Js(t).getComputedStyle(t));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const s=e[i];return typeof s=="string"?n.test(s):!1})}function XM(t,e){const n=[];function r(i){if(e!=null&&n.length>=e||!i)return n;if(vF(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!Mv(i)||Are(i)||n.includes(i))return n;const s=Js(t).getComputedStyle(i);return i!==t&&sWe(i,s)&&n.push(i),aWe(i,s)?n:r(i.parentNode)}return t?r(t):n}function Ire(t){const[e]=XM(t,1);return e??null}function YP(t){return!KM||!t?null:Bb(t)?t:yF(t)?vF(t)||t===Hb(t).scrollingElement?window:Mv(t)?t:null:null}function zre(t){return Bb(t)?t.scrollX:t.scrollLeft}function Ure(t){return Bb(t)?t.scrollY:t.scrollTop}function vR(t){return{x:zre(t),y:Ure(t)}}var ya;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(ya||(ya={}));function Bre(t){return!KM||!t?!1:t===document.scrollingElement}function Hre(t){const e={x:0,y:0},n=Bre(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},r={x:t.scrollWidth-n.width,y:t.scrollHeight-n.height},i=t.scrollTop<=e.y,s=t.scrollLeft<=e.x,o=t.scrollTop>=r.y,l=t.scrollLeft>=r.x;return{isTop:i,isLeft:s,isBottom:o,isRight:l,maxScroll:r,minScroll:e}}const oWe={x:.2,y:.2};function lWe(t,e,n,r,i){let{top:s,left:o,right:l,bottom:c}=n;r===void 0&&(r=10),i===void 0&&(i=oWe);const{isTop:u,isBottom:d,isLeft:h,isRight:p}=Hre(t),m={x:0,y:0},b={x:0,y:0},y={height:e.height*i.y,width:e.width*i.x};return!u&&s<=e.top+y.height?(m.y=ya.Backward,b.y=r*Math.abs((e.top+y.height-s)/y.height)):!d&&c>=e.bottom-y.height&&(m.y=ya.Forward,b.y=r*Math.abs((e.bottom-y.height-c)/y.height)),!p&&l>=e.right-y.width?(m.x=ya.Forward,b.x=r*Math.abs((e.right-y.width-l)/y.width)):!h&&o<=e.left+y.width&&(m.x=ya.Backward,b.x=r*Math.abs((e.left+y.width-o)/y.width)),{direction:m,speed:b}}function cWe(t){if(t===document.scrollingElement){const{innerWidth:s,innerHeight:o}=window;return{top:0,left:0,right:s,bottom:o,width:s,height:o}}const{top:e,left:n,right:r,bottom:i}=t.getBoundingClientRect();return{top:e,left:n,right:r,bottom:i,width:t.clientWidth,height:t.clientHeight}}function $re(t){return t.reduce((e,n)=>Ug(e,vR(n)),Hl)}function uWe(t){return t.reduce((e,n)=>e+zre(n),0)}function dWe(t){return t.reduce((e,n)=>e+Ure(n),0)}function hWe(t,e){if(e===void 0&&(e=$b),!t)return;const{top:n,left:r,bottom:i,right:s}=e(t);Ire(t)&&(i<=0||s<=0||n>=window.innerHeight||r>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}const fWe=[["x",["left","right"],uWe],["y",["top","bottom"],dWe]];class SF{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=XM(n),i=$re(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[s,o,l]of fWe)for(const c of o)Object.defineProperty(this,c,{get:()=>{const u=l(r),d=i[s]-u;return this.rect[c]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class B0{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var i;(i=this.target)==null||i.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function mWe(t){const{EventTarget:e}=Js(t);return t instanceof e?t:Hb(t)}function QP(t,e){const n=Math.abs(t.x),r=Math.abs(t.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var Zo;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(Zo||(Zo={}));function _9(t){t.preventDefault()}function pWe(t){t.stopPropagation()}var Jn;(function(t){t.Space="Space",t.Down="ArrowDown",t.Right="ArrowRight",t.Left="ArrowLeft",t.Up="ArrowUp",t.Esc="Escape",t.Enter="Enter",t.Tab="Tab"})(Jn||(Jn={}));const Vre={start:[Jn.Space,Jn.Enter],cancel:[Jn.Esc],end:[Jn.Space,Jn.Enter,Jn.Tab]},gWe=(t,e)=>{let{currentCoordinates:n}=e;switch(t.code){case Jn.Right:return{...n,x:n.x+25};case Jn.Left:return{...n,x:n.x-25};case Jn.Down:return{...n,y:n.y+25};case Jn.Up:return{...n,y:n.y-25}}};class YM{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:n}}=e;this.props=e,this.listeners=new B0(Hb(n)),this.windowListeners=new B0(Js(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Zo.Resize,this.handleCancel),this.windowListeners.add(Zo.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Zo.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&hWe(r),n(Hl)}handleKeyDown(e){if(_F(e)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:s=Vre,coordinateGetter:o=gWe,scrollBehavior:l="smooth"}=i,{code:c}=e;if(s.end.includes(c)){this.handleEnd(e);return}if(s.cancel.includes(c)){this.handleCancel(e);return}const{collisionRect:u}=r.current,d=u?{x:u.left,y:u.top}:Hl;this.referenceCoordinates||(this.referenceCoordinates=d);const h=o(e,{active:n,context:r.current,currentCoordinates:d});if(h){const p=Fy(h,d),m={x:0,y:0},{scrollableAncestors:b}=r.current;for(const y of b){const x=e.code,{isTop:v,isRight:S,isLeft:N,isBottom:T,maxScroll:M,minScroll:A}=Hre(y),k=cWe(y),R={x:Math.min(x===Jn.Right?k.right-k.width/2:k.right,Math.max(x===Jn.Right?k.left:k.left+k.width/2,h.x)),y:Math.min(x===Jn.Down?k.bottom-k.height/2:k.bottom,Math.max(x===Jn.Down?k.top:k.top+k.height/2,h.y))},C=x===Jn.Right&&!S||x===Jn.Left&&!N,P=x===Jn.Down&&!T||x===Jn.Up&&!v;if(C&&R.x!==h.x){const U=y.scrollLeft+p.x,F=x===Jn.Right&&U<=M.x||x===Jn.Left&&U>=A.x;if(F&&!p.y){y.scrollTo({left:U,behavior:l});return}F?m.x=y.scrollLeft-U:m.x=x===Jn.Right?y.scrollLeft-M.x:y.scrollLeft-A.x,m.x&&y.scrollBy({left:-m.x,behavior:l});break}else if(P&&R.y!==h.y){const U=y.scrollTop+p.y,F=x===Jn.Down&&U<=M.y||x===Jn.Up&&U>=A.y;if(F&&!p.x){y.scrollTo({top:U,behavior:l});return}F?m.y=y.scrollTop-U:m.y=x===Jn.Down?y.scrollTop-M.y:y.scrollTop-A.y,m.y&&y.scrollBy({top:-m.y,behavior:l});break}}this.handleMove(e,Ug(Fy(h,this.referenceCoordinates),m))}}}handleMove(e,n){const{onMove:r}=this.props;e.preventDefault(),r(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}YM.activators=[{eventName:"onKeyDown",handler:(t,e,n)=>{let{keyboardCodes:r=Vre,onActivation:i}=e,{active:s}=n;const{code:o}=t.nativeEvent;if(r.start.includes(o)){const l=s.activatorNode.current;return l&&t.target!==l?!1:(t.preventDefault(),i?.({event:t.nativeEvent}),!0)}return!1}}];function S9(t){return!!(t&&"distance"in t)}function N9(t){return!!(t&&"delay"in t)}class NF{constructor(e,n,r){var i;r===void 0&&(r=mWe(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;const{event:s}=e,{target:o}=s;this.props=e,this.events=n,this.document=Hb(o),this.documentListeners=new B0(this.document),this.listeners=new B0(r),this.windowListeners=new B0(Js(o)),this.initialCoordinates=(i=yR(s))!=null?i:Hl,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(Zo.Resize,this.handleCancel),this.windowListeners.add(Zo.DragStart,_9),this.windowListeners.add(Zo.VisibilityChange,this.handleCancel),this.windowListeners.add(Zo.ContextMenu,_9),this.documentListeners.add(Zo.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(N9(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(S9(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){const{active:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(Zo.Click,pWe,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Zo.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:i,props:s}=this,{onMove:o,options:{activationConstraint:l}}=s;if(!i)return;const c=(n=yR(e))!=null?n:Hl,u=Fy(i,c);if(!r&&l){if(S9(l)){if(l.tolerance!=null&&QP(u,l.tolerance))return this.handleCancel();if(QP(u,l.distance))return this.handleStart()}if(N9(l)&&QP(u,l.tolerance))return this.handleCancel();this.handlePending(l,u);return}e.cancelable&&e.preventDefault(),o(c)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===Jn.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const bWe={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class QM extends NF{constructor(e){const{event:n}=e,r=Hb(n.target);super(e,bWe,r)}}QM.activators=[{eventName:"onPointerDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];const xWe={move:{name:"mousemove"},end:{name:"mouseup"}};var wR;(function(t){t[t.RightClick=2]="RightClick"})(wR||(wR={}));class yWe extends NF{constructor(e){super(e,xWe,Hb(e.event.target))}}yWe.activators=[{eventName:"onMouseDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return n.button===wR.RightClick?!1:(r?.({event:n}),!0)}}];const ZP={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class vWe extends NF{constructor(e){super(e,ZP)}static setup(){return window.addEventListener(ZP.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(ZP.move.name,e)};function e(){}}}vWe.activators=[{eventName:"onTouchStart",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;const{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var H0;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(H0||(H0={}));var ok;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(ok||(ok={}));function wWe(t){let{acceleration:e,activator:n=H0.Pointer,canScroll:r,draggingRect:i,enabled:s,interval:o=5,order:l=ok.TreeOrder,pointerCoordinates:c,scrollableAncestors:u,scrollableAncestorRects:d,delta:h,threshold:p}=t;const m=SWe({delta:h,disabled:!s}),[b,y]=O9e(),x=_.useRef({x:0,y:0}),v=_.useRef({x:0,y:0}),S=_.useMemo(()=>{switch(n){case H0.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case H0.DraggableRect:return i}},[n,i,c]),N=_.useRef(null),T=_.useCallback(()=>{const A=N.current;if(!A)return;const k=x.current.x*v.current.x,R=x.current.y*v.current.y;A.scrollBy(k,R)},[]),M=_.useMemo(()=>l===ok.TreeOrder?[...u].reverse():u,[l,u]);_.useEffect(()=>{if(!s||!u.length||!S){y();return}for(const A of M){if(r?.(A)===!1)continue;const k=u.indexOf(A),R=d[k];if(!R)continue;const{direction:C,speed:P}=lWe(A,R,S,e,p);for(const U of["x","y"])m[U][C[U]]||(P[U]=0,C[U]=0);if(P.x>0||P.y>0){y(),N.current=A,b(T,o),x.current=P,v.current=C;return}}x.current={x:0,y:0},v.current={x:0,y:0},y()},[e,T,r,y,s,o,JSON.stringify(S),JSON.stringify(m),b,u,M,d,JSON.stringify(p)])}const _We={x:{[ya.Backward]:!1,[ya.Forward]:!1},y:{[ya.Backward]:!1,[ya.Forward]:!1}};function SWe(t){let{delta:e,disabled:n}=t;const r=xR(e);return Ev(i=>{if(n||!r||!i)return _We;const s={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[ya.Backward]:i.x[ya.Backward]||s.x===-1,[ya.Forward]:i.x[ya.Forward]||s.x===1},y:{[ya.Backward]:i.y[ya.Backward]||s.y===-1,[ya.Forward]:i.y[ya.Forward]||s.y===1}}},[n,e,r])}function NWe(t,e){const n=e!=null?t.get(e):void 0,r=n?n.node.current:null;return Ev(i=>{var s;return e==null?null:(s=r??i)!=null?s:null},[r,e])}function kWe(t,e){return _.useMemo(()=>t.reduce((n,r)=>{const{sensor:i}=r,s=i.activators.map(o=>({eventName:o.eventName,handler:e(o.handler,r)}));return[...n,...s]},[]),[t,e])}var Iy;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(Iy||(Iy={}));var _R;(function(t){t.Optimized="optimized"})(_R||(_R={}));const k9=new Map;function MWe(t,e){let{dragging:n,dependencies:r,config:i}=e;const[s,o]=_.useState(null),{frequency:l,measure:c,strategy:u}=i,d=_.useRef(t),h=x(),p=Ly(h),m=_.useCallback(function(v){v===void 0&&(v=[]),!p.current&&o(S=>S===null?v:S.concat(v.filter(N=>!S.includes(N))))},[p]),b=_.useRef(null),y=Ev(v=>{if(h&&!n)return k9;if(!v||v===k9||d.current!==t||s!=null){const S=new Map;for(let N of t){if(!N)continue;if(s&&s.length>0&&!s.includes(N.id)&&N.rect.current){S.set(N.id,N.rect.current);continue}const T=N.node.current,M=T?new SF(c(T),T):null;N.rect.current=M,M&&S.set(N.id,M)}return S}return v},[t,s,n,h,c]);return _.useEffect(()=>{d.current=t},[t]),_.useEffect(()=>{h||m()},[n,h]),_.useEffect(()=>{s&&s.length>0&&o(null)},[JSON.stringify(s)]),_.useEffect(()=>{h||typeof l!="number"||b.current!==null||(b.current=setTimeout(()=>{m(),b.current=null},l))},[l,h,m,...r]),{droppableRects:y,measureDroppableContainers:m,measuringScheduled:s!=null};function x(){switch(u){case Iy.Always:return!1;case Iy.BeforeDragging:return n;default:return!n}}}function Gre(t,e){return Ev(n=>t?n||(typeof e=="function"?e(t):t):null,[e,t])}function EWe(t,e){return Gre(t,e)}function TWe(t){let{callback:e,disabled:n}=t;const r=wF(e),i=_.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(r)},[r,n]);return _.useEffect(()=>()=>i?.disconnect(),[i]),i}function ZM(t){let{callback:e,disabled:n}=t;const r=wF(e),i=_.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(r)},[n]);return _.useEffect(()=>()=>i?.disconnect(),[i]),i}function AWe(t){return new SF($b(t),t)}function M9(t,e,n){e===void 0&&(e=AWe);const[r,i]=_.useState(null);function s(){i(c=>{if(!t)return null;if(t.isConnected===!1){var u;return(u=c??n)!=null?u:null}const d=e(t);return JSON.stringify(c)===JSON.stringify(d)?c:d})}const o=TWe({callback(c){if(t)for(const u of c){const{type:d,target:h}=u;if(d==="childList"&&h instanceof HTMLElement&&h.contains(t)){s();break}}}}),l=ZM({callback:s});return kc(()=>{s(),t?(l?.observe(t),o?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),o?.disconnect())},[t]),r}function CWe(t){const e=Gre(t);return Fre(t,e)}const E9=[];function PWe(t){const e=_.useRef(t),n=Ev(r=>t?r&&r!==E9&&t&&e.current&&t.parentNode===e.current.parentNode?r:XM(t):E9,[t]);return _.useEffect(()=>{e.current=t},[t]),n}function jWe(t){const[e,n]=_.useState(null),r=_.useRef(t),i=_.useCallback(s=>{const o=YP(s.target);o&&n(l=>l?(l.set(o,vR(o)),new Map(l)):null)},[]);return _.useEffect(()=>{const s=r.current;if(t!==s){o(s);const l=t.map(c=>{const u=YP(c);return u?(u.addEventListener("scroll",i,{passive:!0}),[u,vR(u)]):null}).filter(c=>c!=null);n(l.length?new Map(l):null),r.current=t}return()=>{o(t),o(s)};function o(l){l.forEach(c=>{const u=YP(c);u?.removeEventListener("scroll",i)})}},[i,t]),_.useMemo(()=>t.length?e?Array.from(e.values()).reduce((s,o)=>Ug(s,o),Hl):$re(t):Hl,[t,e])}function T9(t,e){e===void 0&&(e=[]);const n=_.useRef(null);return _.useEffect(()=>{n.current=null},e),_.useEffect(()=>{const r=t!==Hl;r&&!n.current&&(n.current=t),!r&&n.current&&(n.current=null)},[t]),n.current?Fy(t,n.current):Hl}function DWe(t){_.useEffect(()=>{if(!KM)return;const e=t.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of e)n?.()}},t.map(e=>{let{sensor:n}=e;return n}))}function RWe(t,e){return _.useMemo(()=>t.reduce((n,r)=>{let{eventName:i,handler:s}=r;return n[i]=o=>{s(o,e)},n},{}),[t,e])}function qre(t){return _.useMemo(()=>t?iWe(t):null,[t])}const A9=[];function OWe(t,e){e===void 0&&(e=$b);const[n]=t,r=qre(n?Js(n):null),[i,s]=_.useState(A9);function o(){s(()=>t.length?t.map(c=>Bre(c)?r:new SF(e(c),c)):A9)}const l=ZM({callback:o});return kc(()=>{l?.disconnect(),o(),t.forEach(c=>l?.observe(c))},[t]),i}function LWe(t){if(!t)return null;if(t.children.length>1)return t;const e=t.children[0];return Mv(e)?e:t}function FWe(t){let{measure:e}=t;const[n,r]=_.useState(null),i=_.useCallback(u=>{for(const{target:d}of u)if(Mv(d)){r(h=>{const p=e(d);return h?{...h,width:p.width,height:p.height}:p});break}},[e]),s=ZM({callback:i}),o=_.useCallback(u=>{const d=LWe(u);s?.disconnect(),d&&s?.observe(d),r(d?e(d):null)},[e,s]),[l,c]=ik(o);return _.useMemo(()=>({nodeRef:l,rect:n,setRef:c}),[n,l,c])}const IWe=[{sensor:QM,options:{}},{sensor:YM,options:{}}],zWe={current:{}},q1={draggable:{measure:w9},droppable:{measure:w9,strategy:Iy.WhileDragging,frequency:_R.Optimized},dragOverlay:{measure:$b}};class $0 extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}}const UWe={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new $0,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:ak},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:q1,measureDroppableContainers:ak,windowRect:null,measuringScheduled:!1},BWe={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:ak,draggableNodes:new Map,over:null,measureDroppableContainers:ak},JM=_.createContext(BWe),Wre=_.createContext(UWe);function HWe(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new $0}}}function $We(t,e){switch(e.type){case Yi.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case Yi.DragMove:return t.draggable.active==null?t:{...t,draggable:{...t.draggable,translate:{x:e.coordinates.x-t.draggable.initialCoordinates.x,y:e.coordinates.y-t.draggable.initialCoordinates.y}}};case Yi.DragEnd:case Yi.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Yi.RegisterDroppable:{const{element:n}=e,{id:r}=n,i=new $0(t.droppable.containers);return i.set(r,n),{...t,droppable:{...t.droppable,containers:i}}}case Yi.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=e,s=t.droppable.containers.get(n);if(!s||r!==s.key)return t;const o=new $0(t.droppable.containers);return o.set(n,{...s,disabled:i}),{...t,droppable:{...t.droppable,containers:o}}}case Yi.UnregisterDroppable:{const{id:n,key:r}=e,i=t.droppable.containers.get(n);if(!i||r!==i.key)return t;const s=new $0(t.droppable.containers);return s.delete(n),{...t,droppable:{...t.droppable,containers:s}}}default:return t}}function VWe(t){let{disabled:e}=t;const{active:n,activatorEvent:r,draggableNodes:i}=_.useContext(JM),s=xR(r),o=xR(n?.id);return _.useEffect(()=>{if(!e&&!r&&s&&o!=null){if(!_F(s)||document.activeElement===s.target)return;const l=i.get(o);if(!l)return;const{activatorNode:c,node:u}=l;if(!c.current&&!u.current)return;requestAnimationFrame(()=>{for(const d of[c.current,u.current]){if(!d)continue;const h=I9e(d);if(h){h.focus();break}}})}},[r,e,i,o,s]),null}function GWe(t,e){let{transform:n,...r}=e;return t!=null&&t.length?t.reduce((i,s)=>s({transform:i,...r}),n):n}function qWe(t){return _.useMemo(()=>({draggable:{...q1.draggable,...t?.draggable},droppable:{...q1.droppable,...t?.droppable},dragOverlay:{...q1.dragOverlay,...t?.dragOverlay}}),[t?.draggable,t?.droppable,t?.dragOverlay])}function WWe(t){let{activeNode:e,measure:n,initialRect:r,config:i=!0}=t;const s=_.useRef(!1),{x:o,y:l}=typeof i=="boolean"?{x:i,y:i}:i;kc(()=>{if(!o&&!l||!e){s.current=!1;return}if(s.current||!r)return;const u=e?.node.current;if(!u||u.isConnected===!1)return;const d=n(u),h=Fre(d,r);if(o||(h.x=0),l||(h.y=0),s.current=!0,Math.abs(h.x)>0||Math.abs(h.y)>0){const p=Ire(u);p&&p.scrollBy({top:h.y,left:h.x})}},[e,o,l,r,n])}const Kre=_.createContext({...Hl,scaleX:1,scaleY:1});var nh;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(nh||(nh={}));const Xre=_.memo(function(e){var n,r,i,s;let{id:o,accessibility:l,autoScroll:c=!0,children:u,sensors:d=IWe,collisionDetection:h=Q9e,measuring:p,modifiers:m,...b}=e;const y=_.useReducer($We,void 0,HWe),[x,v]=y,[S,N]=V9e(),[T,M]=_.useState(nh.Uninitialized),A=T===nh.Initialized,{draggable:{active:k,nodes:R,translate:C},droppable:{containers:P}}=x,U=k!=null?R.get(k):null,F=_.useRef({initial:null,translated:null}),H=_.useMemo(()=>{var Ye;return k!=null?{id:k,data:(Ye=U?.data)!=null?Ye:zWe,rect:F}:null},[k,U]),D=_.useRef(null),[$,G]=_.useState(null),[I,K]=_.useState(null),Q=Ly(b,Object.values(b)),oe=Tv("DndDescribedBy",o),B=_.useMemo(()=>P.getEnabled(),[P]),W=qWe(p),{droppableRects:J,measureDroppableContainers:ne,measuringScheduled:me}=MWe(B,{dragging:A,dependencies:[C.x,C.y],config:W.droppable}),fe=NWe(R,k),de=_.useMemo(()=>I?yR(I):null,[I]),Re=Ee(),se=EWe(fe,W.draggable.measure);WWe({activeNode:k!=null?R.get(k):null,config:Re.layoutShiftCompensation,initialRect:se,measure:W.draggable.measure});const ke=M9(fe,W.draggable.measure,se),Fe=M9(fe?fe.parentElement:null),ce=_.useRef({activatorEvent:null,active:null,activeNode:fe,collisionRect:null,collisions:null,droppableRects:J,draggableNodes:R,draggingNode:null,draggingNodeRect:null,droppableContainers:P,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ve=P.getNodeFor((n=ce.current.over)==null?void 0:n.id),V=FWe({measure:W.dragOverlay.measure}),Y=(r=V.nodeRef.current)!=null?r:fe,ue=A?(i=V.rect)!=null?i:ke:null,q=!!(V.nodeRef.current&&V.rect),re=CWe(q?null:ke),X=qre(Y?Js(Y):null),le=PWe(A?Ve??fe:null),pe=OWe(le),ee=GWe(m,{transform:{x:C.x-re.x,y:C.y-re.y,scaleX:1,scaleY:1},activatorEvent:I,active:H,activeNodeRect:ke,containerNodeRect:Fe,draggingNodeRect:ue,over:ce.current.over,overlayNodeRect:V.rect,scrollableAncestors:le,scrollableAncestorRects:pe,windowRect:X}),z=de?Ug(de,C):null,O=jWe(le),Z=T9(O),ge=T9(O,[ke]),Ce=Ug(ee,Z),_e=ue?eWe(ue,ee):null,Te=H&&_e?h({active:H,collisionRect:_e,droppableRects:J,droppableContainers:B,pointerCoordinates:z}):null,we=Ore(Te,"id"),[$e,Ge]=_.useState(null),ze=q?ee:Ug(ee,ge),be=Z9e(ze,(s=$e?.rect)!=null?s:null,ke),Me=_.useRef(null),Be=_.useCallback((Ye,je)=>{let{sensor:Pe,options:ye}=je;if(D.current==null)return;const Qe=R.get(D.current);if(!Qe)return;const yt=Ye.nativeEvent,at=new Pe({active:D.current,activeNode:Qe,event:yt,options:ye,context:ce,onAbort(zt){if(!R.get(zt))return;const{onDragAbort:vt}=Q.current,Gt={id:zt};vt?.(Gt),S({type:"onDragAbort",event:Gt})},onPending(zt,Ie,vt,Gt){if(!R.get(zt))return;const{onDragPending:fn}=Q.current,vn={id:zt,constraint:Ie,initialCoordinates:vt,offset:Gt};fn?.(vn),S({type:"onDragPending",event:vn})},onStart(zt){const Ie=D.current;if(Ie==null)return;const vt=R.get(Ie);if(!vt)return;const{onDragStart:Gt}=Q.current,dn={activatorEvent:yt,active:{id:Ie,data:vt.data,rect:F}};vu.unstable_batchedUpdates(()=>{Gt?.(dn),M(nh.Initializing),v({type:Yi.DragStart,initialCoordinates:zt,active:Ie}),S({type:"onDragStart",event:dn}),G(Me.current),K(yt)})},onMove(zt){v({type:Yi.DragMove,coordinates:zt})},onEnd:Ut(Yi.DragEnd),onCancel:Ut(Yi.DragCancel)});Me.current=at;function Ut(zt){return async function(){const{active:vt,collisions:Gt,over:dn,scrollAdjustedTranslate:fn}=ce.current;let vn=null;if(vt&&fn){const{cancelDrop:dr}=Q.current;vn={activatorEvent:yt,active:vt,collisions:Gt,delta:fn,over:dn},zt===Yi.DragEnd&&typeof dr=="function"&&await Promise.resolve(dr(vn))&&(zt=Yi.DragCancel)}D.current=null,vu.unstable_batchedUpdates(()=>{v({type:zt}),M(nh.Uninitialized),Ge(null),G(null),K(null),Me.current=null;const dr=zt===Yi.DragEnd?"onDragEnd":"onDragCancel";if(vn){const ar=Q.current[dr];ar?.(vn),S({type:dr,event:vn})}})}}},[R]),Ae=_.useCallback((Ye,je)=>(Pe,ye)=>{const Qe=Pe.nativeEvent,yt=R.get(ye);if(D.current!==null||!yt||Qe.dndKit||Qe.defaultPrevented)return;const at={active:yt};Ye(Pe,je.options,at)===!0&&(Qe.dndKit={capturedBy:je.sensor},D.current=ye,Be(Pe,je))},[R,Be]),qe=kWe(d,Ae);DWe(d),kc(()=>{ke&&T===nh.Initializing&&M(nh.Initialized)},[ke,T]),_.useEffect(()=>{const{onDragMove:Ye}=Q.current,{active:je,activatorEvent:Pe,collisions:ye,over:Qe}=ce.current;if(!je||!Pe)return;const yt={active:je,activatorEvent:Pe,collisions:ye,delta:{x:Ce.x,y:Ce.y},over:Qe};vu.unstable_batchedUpdates(()=>{Ye?.(yt),S({type:"onDragMove",event:yt})})},[Ce.x,Ce.y]),_.useEffect(()=>{const{active:Ye,activatorEvent:je,collisions:Pe,droppableContainers:ye,scrollAdjustedTranslate:Qe}=ce.current;if(!Ye||D.current==null||!je||!Qe)return;const{onDragOver:yt}=Q.current,at=ye.get(we),Ut=at&&at.rect.current?{id:at.id,rect:at.rect.current,data:at.data,disabled:at.disabled}:null,zt={active:Ye,activatorEvent:je,collisions:Pe,delta:{x:Qe.x,y:Qe.y},over:Ut};vu.unstable_batchedUpdates(()=>{Ge(Ut),yt?.(zt),S({type:"onDragOver",event:zt})})},[we]),kc(()=>{ce.current={activatorEvent:I,active:H,activeNode:fe,collisionRect:_e,collisions:Te,droppableRects:J,draggableNodes:R,draggingNode:Y,draggingNodeRect:ue,droppableContainers:P,over:$e,scrollableAncestors:le,scrollAdjustedTranslate:Ce},F.current={initial:ue,translated:_e}},[H,fe,Te,_e,R,Y,ue,J,P,$e,le,Ce]),wWe({...Re,delta:C,draggingRect:_e,pointerCoordinates:z,scrollableAncestors:le,scrollableAncestorRects:pe});const ve=_.useMemo(()=>({active:H,activeNode:fe,activeNodeRect:ke,activatorEvent:I,collisions:Te,containerNodeRect:Fe,dragOverlay:V,draggableNodes:R,droppableContainers:P,droppableRects:J,over:$e,measureDroppableContainers:ne,scrollableAncestors:le,scrollableAncestorRects:pe,measuringConfiguration:W,measuringScheduled:me,windowRect:X}),[H,fe,ke,I,Te,Fe,V,R,P,J,$e,ne,le,pe,W,me,X]),et=_.useMemo(()=>({activatorEvent:I,activators:qe,active:H,activeNodeRect:ke,ariaDescribedById:{draggable:oe},dispatch:v,draggableNodes:R,over:$e,measureDroppableContainers:ne}),[I,qe,H,ke,v,oe,R,$e,ne]);return ei.createElement(Pre.Provider,{value:N},ei.createElement(JM.Provider,{value:et},ei.createElement(Wre.Provider,{value:ve},ei.createElement(Kre.Provider,{value:be},u)),ei.createElement(VWe,{disabled:l?.restoreFocus===!1})),ei.createElement(W9e,{...l,hiddenTextDescribedById:oe}));function Ee(){const Ye=$?.autoScrollEnabled===!1,je=typeof c=="object"?c.enabled===!1:c===!1,Pe=A&&!Ye&&!je;return typeof c=="object"?{...c,enabled:Pe}:{enabled:Pe}}}),KWe=_.createContext(null),C9="button",XWe="Draggable";function YWe(t){let{id:e,data:n,disabled:r=!1,attributes:i}=t;const s=Tv(XWe),{activators:o,activatorEvent:l,active:c,activeNodeRect:u,ariaDescribedById:d,draggableNodes:h,over:p}=_.useContext(JM),{role:m=C9,roleDescription:b="draggable",tabIndex:y=0}=i??{},x=c?.id===e,v=_.useContext(x?Kre:KWe),[S,N]=ik(),[T,M]=ik(),A=RWe(o,e),k=Ly(n);kc(()=>(h.set(e,{id:e,key:s,node:S,activatorNode:T,data:k}),()=>{const C=h.get(e);C&&C.key===s&&h.delete(e)}),[h,e]);const R=_.useMemo(()=>({role:m,tabIndex:y,"aria-disabled":r,"aria-pressed":x&&m===C9?!0:void 0,"aria-roledescription":b,"aria-describedby":d.draggable}),[r,m,y,x,b,d.draggable]);return{active:c,activatorEvent:l,activeNodeRect:u,attributes:R,isDragging:x,listeners:r?void 0:A,node:S,over:p,setNodeRef:N,setActivatorNodeRef:M,transform:v}}function QWe(){return _.useContext(Wre)}const ZWe="Droppable",JWe={timeout:25};function eKe(t){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:i}=t;const s=Tv(ZWe),{active:o,dispatch:l,over:c,measureDroppableContainers:u}=_.useContext(JM),d=_.useRef({disabled:n}),h=_.useRef(!1),p=_.useRef(null),m=_.useRef(null),{disabled:b,updateMeasurementsFor:y,timeout:x}={...JWe,...i},v=Ly(y??r),S=_.useCallback(()=>{if(!h.current){h.current=!0;return}m.current!=null&&clearTimeout(m.current),m.current=setTimeout(()=>{u(Array.isArray(v.current)?v.current:[v.current]),m.current=null},x)},[x]),N=ZM({callback:S,disabled:b||!o}),T=_.useCallback((R,C)=>{N&&(C&&(N.unobserve(C),h.current=!1),R&&N.observe(R))},[N]),[M,A]=ik(T),k=Ly(e);return _.useEffect(()=>{!N||!M.current||(N.disconnect(),h.current=!1,N.observe(M.current))},[M,N]),_.useEffect(()=>(l({type:Yi.RegisterDroppable,element:{id:r,key:s,disabled:n,node:M,rect:p,data:k}}),()=>l({type:Yi.UnregisterDroppable,key:s,id:r})),[r]),_.useEffect(()=>{n!==d.current.disabled&&(l({type:Yi.SetDroppableDisabled,id:r,key:s,disabled:n}),d.current.disabled=n)},[r,s,n,l]),{active:o,rect:p,isOver:c?.id===r,node:M,over:c,setNodeRef:A}}function e2(t,e,n){const r=t.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function tKe(t,e){return t.reduce((n,r,i)=>{const s=e.get(r);return s&&(n[i]=s),n},Array(t.length))}function g1(t){return t!==null&&t>=0}function nKe(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n{let{rects:e,activeIndex:n,overIndex:r,index:i}=t;const s=e2(e,r,n),o=e[i],l=s[i];return!l||!o?null:{x:l.left-o.left,y:l.top-o.top,scaleX:l.width/o.width,scaleY:l.height/o.height}},b1={scaleX:1,scaleY:1},iKe=t=>{var e;let{activeIndex:n,activeNodeRect:r,index:i,rects:s,overIndex:o}=t;const l=(e=s[n])!=null?e:r;if(!l)return null;if(i===n){const u=s[o];return u?{x:0,y:nn&&i<=o?{x:0,y:-l.height-c,...b1}:i=o?{x:0,y:l.height+c,...b1}:{x:0,y:0,...b1}};function aKe(t,e,n){const r=t[e],i=t[e-1],s=t[e+1];return r?nr.map(A=>typeof A=="object"&&"id"in A?A.id:A),[r]),b=o!=null,y=o?m.indexOf(o.id):-1,x=u?m.indexOf(u.id):-1,v=_.useRef(m),S=!nKe(m,v.current),N=x!==-1&&y===-1||S,T=rKe(s);kc(()=>{S&&b&&d(m)},[S,m,b,d]),_.useEffect(()=>{v.current=m},[m]);const M=_.useMemo(()=>({activeIndex:y,containerId:h,disabled:T,disableTransforms:N,items:m,overIndex:x,useDragOverlay:p,sortedRects:tKe(m,c),strategy:i}),[y,h,T.draggable,T.droppable,N,m,x,c,p,i]);return ei.createElement(Qre.Provider,{value:M},e)}const sKe=t=>{let{id:e,items:n,activeIndex:r,overIndex:i}=t;return e2(n,r,i).indexOf(e)},oKe=t=>{let{containerId:e,isSorting:n,wasDragging:r,index:i,items:s,newIndex:o,previousItems:l,previousContainerId:c,transition:u}=t;return!u||!r||l!==s&&i===o?!1:n?!0:o!==i&&e===c},lKe={duration:200,easing:"ease"},Jre="transform",cKe=xb.Transition.toString({property:Jre,duration:0,easing:"linear"}),uKe={roleDescription:"sortable"};function dKe(t){let{disabled:e,index:n,node:r,rect:i}=t;const[s,o]=_.useState(null),l=_.useRef(n);return kc(()=>{if(!e&&n!==l.current&&r.current){const c=i.current;if(c){const u=$b(r.current,{ignoreTransform:!0}),d={x:c.left-u.left,y:c.top-u.top,scaleX:c.width/u.width,scaleY:c.height/u.height};(d.x||d.y)&&o(d)}}n!==l.current&&(l.current=n)},[e,n,r,i]),_.useEffect(()=>{s&&o(null)},[s]),s}function eie(t){let{animateLayoutChanges:e=oKe,attributes:n,disabled:r,data:i,getNewIndex:s=sKe,id:o,strategy:l,resizeObserverConfig:c,transition:u=lKe}=t;const{items:d,containerId:h,activeIndex:p,disabled:m,disableTransforms:b,sortedRects:y,overIndex:x,useDragOverlay:v,strategy:S}=_.useContext(Qre),N=hKe(r,m),T=d.indexOf(o),M=_.useMemo(()=>({sortable:{containerId:h,index:T,items:d},...i}),[h,i,T,d]),A=_.useMemo(()=>d.slice(d.indexOf(o)),[d,o]),{rect:k,node:R,isOver:C,setNodeRef:P}=eKe({id:o,data:M,disabled:N.droppable,resizeObserverConfig:{updateMeasurementsFor:A,...c}}),{active:U,activatorEvent:F,activeNodeRect:H,attributes:D,setNodeRef:$,listeners:G,isDragging:I,over:K,setActivatorNodeRef:Q,transform:oe}=YWe({id:o,data:M,attributes:{...uKe,...n},disabled:N.draggable}),B=R9e(P,$),W=!!U,J=W&&!b&&g1(p)&&g1(x),ne=!v&&I,me=ne&&J?oe:null,de=J?me??(l??S)({rects:y,activeNodeRect:H,activeIndex:p,overIndex:x,index:T}):null,Re=g1(p)&&g1(x)?s({id:o,items:d,activeIndex:p,overIndex:x}):T,se=U?.id,ke=_.useRef({activeId:se,items:d,newIndex:Re,containerId:h}),Fe=d!==ke.current.items,ce=e({active:U,containerId:h,isDragging:I,isSorting:W,id:o,index:T,items:d,newIndex:ke.current.newIndex,previousItems:ke.current.items,previousContainerId:ke.current.containerId,transition:u,wasDragging:ke.current.activeId!=null}),Ve=dKe({disabled:!ce,index:T,node:R,rect:k});return _.useEffect(()=>{W&&ke.current.newIndex!==Re&&(ke.current.newIndex=Re),h!==ke.current.containerId&&(ke.current.containerId=h),d!==ke.current.items&&(ke.current.items=d)},[W,Re,h,d]),_.useEffect(()=>{if(se===ke.current.activeId)return;if(se!=null&&ke.current.activeId==null){ke.current.activeId=se;return}const Y=setTimeout(()=>{ke.current.activeId=se},50);return()=>clearTimeout(Y)},[se]),{active:U,activeIndex:p,attributes:D,data:M,rect:k,index:T,newIndex:Re,items:d,isOver:C,isSorting:W,isDragging:I,listeners:G,node:R,overIndex:x,over:K,setNodeRef:B,setActivatorNodeRef:Q,setDroppableNodeRef:P,setDraggableNodeRef:$,transform:Ve??de,transition:V()};function V(){if(Ve||Fe&&ke.current.newIndex===T)return cKe;if(!(ne&&!_F(F)||!u)&&(W||ce))return xb.Transition.toString({...u,property:Jre})}}function hKe(t,e){var n,r;return typeof t=="boolean"?{draggable:t,droppable:!1}:{draggable:(n=t?.draggable)!=null?n:e.draggable,droppable:(r=t?.droppable)!=null?r:e.droppable}}function lk(t){if(!t)return!1;const e=t.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const fKe=[Jn.Down,Jn.Right,Jn.Up,Jn.Left],tie=(t,e)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:s,over:o,scrollableAncestors:l}}=e;if(fKe.includes(t.code)){if(t.preventDefault(),!n||!r)return;const c=[];s.getEnabled().forEach(h=>{if(!h||h!=null&&h.disabled)return;const p=i.get(h.id);if(p)switch(t.code){case Jn.Down:r.topp.top&&c.push(h);break;case Jn.Left:r.left>p.left&&c.push(h);break;case Jn.Right:r.left1&&(d=u[1].id),d!=null){const h=s.get(n.id),p=s.get(d),m=p?i.get(p.id):null,b=p?.node.current;if(b&&m&&h&&p){const x=XM(b).some((A,k)=>l[k]!==A),v=nie(h,p),S=mKe(h,p),N=x||!v?{x:0,y:0}:{x:S?r.width-m.width:0,y:S?r.height-m.height:0},T={x:m.left,y:m.top};return N.x&&N.y?T:Fy(T,N)}}}};function nie(t,e){return!lk(t)||!lk(e)?!1:t.data.current.sortable.containerId===e.data.current.sortable.containerId}function mKe(t,e){return!lk(t)||!lk(e)||!nie(t,e)?!1:t.data.current.sortable.index0?`${e}h ${n}m`:`${n}m`}function pKe(t,e="system",n){if(!t)return n?.("queue.time.asap")??"ASAP";const r=zi(t);if(!r)return n?.("queue.time.asap")??"ASAP";const i=new Date,s=r.getTime()-i.getTime();return s<-6e4?n?.("queue.time.overdue")??"Overdue":s<0?n?.("queue.time.now")??"Now":s<6e4?n?.("queue.time.lessThanMinute")??"In less than a minute":s<36e5?n?.("queue.time.inMinutes",{count:Math.round(s/6e4)})??`In ${Math.round(s/6e4)} min`:s<864e5?n?.("queue.time.inHours",{count:Math.round(s/36e5)})??`In ${Math.round(s/36e5)} hours`:qg(t,e)}function gKe({status:t,waitingReason:e,printerState:n,t:r}){if(t==="pending"&&e)return a.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-purple-400 bg-purple-400/10 border-purple-400/20",children:[a.jsx(tr,{className:"w-3.5 h-3.5"}),r("queue.status.waiting")]});if(t==="printing"&&(n==="PAUSE"||n==="PAUSED"))return a.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-yellow-400 bg-yellow-400/10 border-yellow-400/20",children:[a.jsx(Sk,{className:"w-3.5 h-3.5"}),r("queue.status.paused")]});const i={pending:{icon:tr,color:"text-status-warning bg-status-warning/10 border-status-warning/20",label:r("queue.status.pending")},printing:{icon:Eo,color:"text-blue-400 bg-blue-400/10 border-blue-400/20",label:r("queue.status.printing")},completed:{icon:mr,color:"text-status-ok bg-status-ok/10 border-status-ok/20",label:r("queue.status.completed")},failed:{icon:Zi,color:"text-status-error bg-status-error/10 border-status-error/20",label:r("queue.status.failed")},skipped:{icon:qR,color:"text-orange-400 bg-orange-400/10 border-orange-400/20",label:r("queue.status.skipped")},cancelled:{icon:Lt,color:"text-gray-400 bg-gray-400/10 border-gray-400/20",label:r("queue.status.cancelled")}},{icon:s,color:o,label:l}=i[t];return a.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${o}`,children:[a.jsx(s,{className:"w-3.5 h-3.5"}),l]})}function bKe({selectedCount:t,printers:e,onSave:n,onClose:r,isSaving:i,t:s}){const[o,l]=_.useState("unchanged"),[c,u]=_.useState("unchanged"),[d,h]=_.useState("unchanged"),[p,m]=_.useState("unchanged"),[b,y]=_.useState("unchanged"),[x,v]=_.useState("unchanged"),[S,N]=_.useState("unchanged"),[T,M]=_.useState("unchanged"),[A,k]=_.useState("unchanged"),[R,C]=_.useState("unchanged"),P=()=>{const F={};o!=="unchanged"&&(F.printer_id=o),c!=="unchanged"&&(F.manual_start=c),d!=="unchanged"&&(F.auto_off_after=d),p!=="unchanged"&&(F.require_previous_success=p),b!=="unchanged"&&(F.bed_levelling=b),x!=="unchanged"&&(F.flow_cali=x),S!=="unchanged"&&(F.vibration_cali=S),T!=="unchanged"&&(F.layer_inspect=T),A!=="unchanged"&&(F.timelapse=A),R!=="unchanged"&&(F.use_ams=R),n(F)},U=o!=="unchanged"||c!=="unchanged"||d!=="unchanged"||p!=="unchanged"||b!=="unchanged"||x!=="unchanged"||S!=="unchanged"||T!=="unchanged"||A!=="unchanged"||R!=="unchanged";return a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg max-h-[90vh] overflow-y-auto",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:s("queue.bulkEdit.title",{count:t})}),a.jsx("button",{onClick:r,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Lt,{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:s("queue.bulkEdit.description")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:s("queue.bulkEdit.printer")}),a.jsxs("select",{value:o===null?"null":o==="unchanged"?"unchanged":String(o),onChange:F=>{const H=F.target.value;l(H==="unchanged"?"unchanged":H==="null"?null:Number(H))},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:"unchanged",children:s("queue.bulkEdit.noChange")}),a.jsx("option",{value:"null",children:s("queue.filter.unassigned")}),e.map(F=>a.jsx("option",{value:F.id,children:F.name},F.id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:s("queue.bulkEdit.queueOptions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(du,{label:s("queue.bulkEdit.staged"),value:c,onChange:u,t:s}),a.jsx(du,{label:s("queue.bulkEdit.autoPowerOff"),value:d,onChange:h,t:s}),a.jsx(du,{label:s("queue.bulkEdit.requirePrevious"),value:p,onChange:m,t:s})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:s("queue.bulkEdit.printOptions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(du,{label:s("queue.bulkEdit.bedLevelling"),value:b,onChange:y,t:s}),a.jsx(du,{label:s("queue.bulkEdit.flowCalibration"),value:x,onChange:v,t:s}),a.jsx(du,{label:s("queue.bulkEdit.vibrationCalibration"),value:S,onChange:N,t:s}),a.jsx(du,{label:s("queue.bulkEdit.layerInspection"),value:T,onChange:M,t:s}),a.jsx(du,{label:s("queue.bulkEdit.timelapse"),value:A,onChange:k,t:s}),a.jsx(du,{label:s("queue.bulkEdit.useAms"),value:R,onChange:C,t:s})]})]})]}),a.jsxs("div",{className:"flex justify-end gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ne,{variant:"secondary",onClick:r,children:s("common.cancel")}),a.jsx(Ne,{onClick:P,disabled:!U||i,children:s(i?"common.saving":"queue.bulkEdit.applyChanges")})]})]})})}function du({label:t,value:e,onChange:n,t:r}){return a.jsxs("div",{className:"flex items-center justify-between py-1",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:t}),a.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5",children:[a.jsx("button",{onClick:()=>n("unchanged"),className:`px-2 py-1 text-xs rounded ${e==="unchanged"?"bg-bambu-dark-tertiary text-white":"text-bambu-gray hover:text-white"}`,children:"—"}),a.jsx("button",{onClick:()=>n(!1),className:`px-2 py-1 text-xs rounded ${e===!1?"bg-red-500/20 text-red-400":"text-bambu-gray hover:text-white"}`,children:r("common.off")}),a.jsx("button",{onClick:()=>n(!0),className:`px-2 py-1 text-xs rounded ${e===!0?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white"}`,children:r("common.on")})]})]})}function JP({item:t,position:e,onEdit:n,onCancel:r,onRemove:i,onStop:s,onRequeue:o,onStart:l,timeFormat:c="system",isSelected:u=!1,onToggleSelect:d,hasPermission:h,canModify:p,printerState:m,t:b}){const y=h("queue:reorder"),{attributes:x,listeners:v,setNodeRef:S,transform:N,transition:T,isDragging:M}=eie({id:t.id,disabled:t.status!=="pending"||!y}),A={transform:xb.Transform.toString(N),transition:T},k=t.status==="printing",R=t.status==="pending",C=["completed","failed","skipped","cancelled"].includes(t.status);return a.jsx("div",{ref:S,style:A,className:` + `},W9e={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function K9e(t){let{announcements:e=W9e,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=q9e}=t;const{announce:s,announcement:o}=$9e(),l=Tv("DndLiveRegion"),[c,u]=_.useState(!1);if(_.useEffect(()=>{u(!0)},[]),V9e(_.useMemo(()=>({onDragStart(h){let{active:p}=h;s(e.onDragStart({active:p}))},onDragMove(h){let{active:p,over:m}=h;e.onDragMove&&s(e.onDragMove({active:p,over:m}))},onDragOver(h){let{active:p,over:m}=h;s(e.onDragOver({active:p,over:m}))},onDragEnd(h){let{active:p,over:m}=h;s(e.onDragEnd({active:p,over:m}))},onDragCancel(h){let{active:p,over:m}=h;s(e.onDragCancel({active:p,over:m}))}}),[s,e])),!c)return null;const d=ei.createElement(ei.Fragment,null,ei.createElement(B9e,{id:r,value:i.draggable}),ei.createElement(H9e,{id:l,announcement:o}));return n?vu.createPortal(d,n):d}var Yi;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Yi||(Yi={}));function ak(){}function sk(t,e){return _.useMemo(()=>({sensor:t,options:e??{}}),[t,e])}function jre(){for(var t=arguments.length,e=new Array(t),n=0;n[...e].filter(r=>r!=null),[...e])}const Hl=Object.freeze({x:0,y:0});function Dre(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function Rre(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return n-r}function X9e(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return r-n}function y9(t){let{left:e,top:n,height:r,width:i}=t;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+r},{x:e+i,y:n+r}]}function Ore(t,e){if(!t||t.length===0)return null;const[n]=t;return n[e]}function v9(t,e,n){return e===void 0&&(e=t.left),n===void 0&&(n=t.top),{x:e+t.width*.5,y:n+t.height*.5}}const Lre=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=v9(e,e.left,e.top),s=[];for(const o of r){const{id:l}=o,c=n.get(l);if(c){const u=Dre(v9(c),i);s.push({id:l,data:{droppableContainer:o,value:u}})}}return s.sort(Rre)},Y9e=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=y9(e),s=[];for(const o of r){const{id:l}=o,c=n.get(l);if(c){const u=y9(c),d=i.reduce((p,m,b)=>p+Dre(u[b],m),0),h=Number((d/4).toFixed(4));s.push({id:l,data:{droppableContainer:o,value:h}})}}return s.sort(Rre)};function Q9e(t,e){const n=Math.max(e.top,t.top),r=Math.max(e.left,t.left),i=Math.min(e.left+e.width,t.left+t.width),s=Math.min(e.top+e.height,t.top+t.height),o=i-r,l=s-n;if(r{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=[];for(const s of r){const{id:o}=s,l=n.get(o);if(l){const c=Q9e(l,e);c>0&&i.push({id:o,data:{droppableContainer:s,value:c}})}}return i.sort(X9e)};function J9e(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function Fre(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:Hl}function eWe(t){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),s=1;s({...o,top:o.top+t*l.y,bottom:o.bottom+t*l.y,left:o.left+t*l.x,right:o.right+t*l.x}),{...n})}}const tWe=eWe(1);function nWe(t){if(t.startsWith("matrix3d(")){const e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){const e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function rWe(t,e,n){const r=nWe(e);if(!r)return t;const{scaleX:i,scaleY:s,x:o,y:l}=r,c=t.left-o-(1-i)*parseFloat(n),u=t.top-l-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),d=i?t.width/i:t.width,h=s?t.height/s:t.height;return{width:d,height:h,top:u,right:c+d,bottom:u+h,left:c}}const iWe={ignoreTransform:!1};function $b(t,e){e===void 0&&(e=iWe);let n=t.getBoundingClientRect();if(e.ignoreTransform){const{transform:u,transformOrigin:d}=Js(t).getComputedStyle(t);u&&(n=rWe(n,u,d))}const{top:r,left:i,width:s,height:o,bottom:l,right:c}=n;return{top:r,left:i,width:s,height:o,bottom:l,right:c}}function w9(t){return $b(t,{ignoreTransform:!0})}function aWe(t){const e=t.innerWidth,n=t.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function sWe(t,e){return e===void 0&&(e=Js(t).getComputedStyle(t)),e.position==="fixed"}function oWe(t,e){e===void 0&&(e=Js(t).getComputedStyle(t));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const s=e[i];return typeof s=="string"?n.test(s):!1})}function XM(t,e){const n=[];function r(i){if(e!=null&&n.length>=e||!i)return n;if(vF(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!Mv(i)||Are(i)||n.includes(i))return n;const s=Js(t).getComputedStyle(i);return i!==t&&oWe(i,s)&&n.push(i),sWe(i,s)?n:r(i.parentNode)}return t?r(t):n}function Ire(t){const[e]=XM(t,1);return e??null}function YP(t){return!KM||!t?null:Bb(t)?t:yF(t)?vF(t)||t===Hb(t).scrollingElement?window:Mv(t)?t:null:null}function zre(t){return Bb(t)?t.scrollX:t.scrollLeft}function Ure(t){return Bb(t)?t.scrollY:t.scrollTop}function vR(t){return{x:zre(t),y:Ure(t)}}var ya;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(ya||(ya={}));function Bre(t){return!KM||!t?!1:t===document.scrollingElement}function Hre(t){const e={x:0,y:0},n=Bre(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},r={x:t.scrollWidth-n.width,y:t.scrollHeight-n.height},i=t.scrollTop<=e.y,s=t.scrollLeft<=e.x,o=t.scrollTop>=r.y,l=t.scrollLeft>=r.x;return{isTop:i,isLeft:s,isBottom:o,isRight:l,maxScroll:r,minScroll:e}}const lWe={x:.2,y:.2};function cWe(t,e,n,r,i){let{top:s,left:o,right:l,bottom:c}=n;r===void 0&&(r=10),i===void 0&&(i=lWe);const{isTop:u,isBottom:d,isLeft:h,isRight:p}=Hre(t),m={x:0,y:0},b={x:0,y:0},y={height:e.height*i.y,width:e.width*i.x};return!u&&s<=e.top+y.height?(m.y=ya.Backward,b.y=r*Math.abs((e.top+y.height-s)/y.height)):!d&&c>=e.bottom-y.height&&(m.y=ya.Forward,b.y=r*Math.abs((e.bottom-y.height-c)/y.height)),!p&&l>=e.right-y.width?(m.x=ya.Forward,b.x=r*Math.abs((e.right-y.width-l)/y.width)):!h&&o<=e.left+y.width&&(m.x=ya.Backward,b.x=r*Math.abs((e.left+y.width-o)/y.width)),{direction:m,speed:b}}function uWe(t){if(t===document.scrollingElement){const{innerWidth:s,innerHeight:o}=window;return{top:0,left:0,right:s,bottom:o,width:s,height:o}}const{top:e,left:n,right:r,bottom:i}=t.getBoundingClientRect();return{top:e,left:n,right:r,bottom:i,width:t.clientWidth,height:t.clientHeight}}function $re(t){return t.reduce((e,n)=>Ug(e,vR(n)),Hl)}function dWe(t){return t.reduce((e,n)=>e+zre(n),0)}function hWe(t){return t.reduce((e,n)=>e+Ure(n),0)}function fWe(t,e){if(e===void 0&&(e=$b),!t)return;const{top:n,left:r,bottom:i,right:s}=e(t);Ire(t)&&(i<=0||s<=0||n>=window.innerHeight||r>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}const mWe=[["x",["left","right"],dWe],["y",["top","bottom"],hWe]];class SF{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=XM(n),i=$re(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[s,o,l]of mWe)for(const c of o)Object.defineProperty(this,c,{get:()=>{const u=l(r),d=i[s]-u;return this.rect[c]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class B0{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var i;(i=this.target)==null||i.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function pWe(t){const{EventTarget:e}=Js(t);return t instanceof e?t:Hb(t)}function QP(t,e){const n=Math.abs(t.x),r=Math.abs(t.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var Zo;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(Zo||(Zo={}));function _9(t){t.preventDefault()}function gWe(t){t.stopPropagation()}var Jn;(function(t){t.Space="Space",t.Down="ArrowDown",t.Right="ArrowRight",t.Left="ArrowLeft",t.Up="ArrowUp",t.Esc="Escape",t.Enter="Enter",t.Tab="Tab"})(Jn||(Jn={}));const Vre={start:[Jn.Space,Jn.Enter],cancel:[Jn.Esc],end:[Jn.Space,Jn.Enter,Jn.Tab]},bWe=(t,e)=>{let{currentCoordinates:n}=e;switch(t.code){case Jn.Right:return{...n,x:n.x+25};case Jn.Left:return{...n,x:n.x-25};case Jn.Down:return{...n,y:n.y+25};case Jn.Up:return{...n,y:n.y-25}}};class YM{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:n}}=e;this.props=e,this.listeners=new B0(Hb(n)),this.windowListeners=new B0(Js(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Zo.Resize,this.handleCancel),this.windowListeners.add(Zo.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Zo.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&fWe(r),n(Hl)}handleKeyDown(e){if(_F(e)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:s=Vre,coordinateGetter:o=bWe,scrollBehavior:l="smooth"}=i,{code:c}=e;if(s.end.includes(c)){this.handleEnd(e);return}if(s.cancel.includes(c)){this.handleCancel(e);return}const{collisionRect:u}=r.current,d=u?{x:u.left,y:u.top}:Hl;this.referenceCoordinates||(this.referenceCoordinates=d);const h=o(e,{active:n,context:r.current,currentCoordinates:d});if(h){const p=Fy(h,d),m={x:0,y:0},{scrollableAncestors:b}=r.current;for(const y of b){const x=e.code,{isTop:v,isRight:S,isLeft:N,isBottom:T,maxScroll:M,minScroll:A}=Hre(y),k=uWe(y),R={x:Math.min(x===Jn.Right?k.right-k.width/2:k.right,Math.max(x===Jn.Right?k.left:k.left+k.width/2,h.x)),y:Math.min(x===Jn.Down?k.bottom-k.height/2:k.bottom,Math.max(x===Jn.Down?k.top:k.top+k.height/2,h.y))},C=x===Jn.Right&&!S||x===Jn.Left&&!N,P=x===Jn.Down&&!T||x===Jn.Up&&!v;if(C&&R.x!==h.x){const U=y.scrollLeft+p.x,F=x===Jn.Right&&U<=M.x||x===Jn.Left&&U>=A.x;if(F&&!p.y){y.scrollTo({left:U,behavior:l});return}F?m.x=y.scrollLeft-U:m.x=x===Jn.Right?y.scrollLeft-M.x:y.scrollLeft-A.x,m.x&&y.scrollBy({left:-m.x,behavior:l});break}else if(P&&R.y!==h.y){const U=y.scrollTop+p.y,F=x===Jn.Down&&U<=M.y||x===Jn.Up&&U>=A.y;if(F&&!p.x){y.scrollTo({top:U,behavior:l});return}F?m.y=y.scrollTop-U:m.y=x===Jn.Down?y.scrollTop-M.y:y.scrollTop-A.y,m.y&&y.scrollBy({top:-m.y,behavior:l});break}}this.handleMove(e,Ug(Fy(h,this.referenceCoordinates),m))}}}handleMove(e,n){const{onMove:r}=this.props;e.preventDefault(),r(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}YM.activators=[{eventName:"onKeyDown",handler:(t,e,n)=>{let{keyboardCodes:r=Vre,onActivation:i}=e,{active:s}=n;const{code:o}=t.nativeEvent;if(r.start.includes(o)){const l=s.activatorNode.current;return l&&t.target!==l?!1:(t.preventDefault(),i?.({event:t.nativeEvent}),!0)}return!1}}];function S9(t){return!!(t&&"distance"in t)}function N9(t){return!!(t&&"delay"in t)}class NF{constructor(e,n,r){var i;r===void 0&&(r=pWe(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;const{event:s}=e,{target:o}=s;this.props=e,this.events=n,this.document=Hb(o),this.documentListeners=new B0(this.document),this.listeners=new B0(r),this.windowListeners=new B0(Js(o)),this.initialCoordinates=(i=yR(s))!=null?i:Hl,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(Zo.Resize,this.handleCancel),this.windowListeners.add(Zo.DragStart,_9),this.windowListeners.add(Zo.VisibilityChange,this.handleCancel),this.windowListeners.add(Zo.ContextMenu,_9),this.documentListeners.add(Zo.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(N9(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(S9(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){const{active:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(Zo.Click,gWe,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Zo.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:i,props:s}=this,{onMove:o,options:{activationConstraint:l}}=s;if(!i)return;const c=(n=yR(e))!=null?n:Hl,u=Fy(i,c);if(!r&&l){if(S9(l)){if(l.tolerance!=null&&QP(u,l.tolerance))return this.handleCancel();if(QP(u,l.distance))return this.handleStart()}if(N9(l)&&QP(u,l.tolerance))return this.handleCancel();this.handlePending(l,u);return}e.cancelable&&e.preventDefault(),o(c)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===Jn.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const xWe={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class QM extends NF{constructor(e){const{event:n}=e,r=Hb(n.target);super(e,xWe,r)}}QM.activators=[{eventName:"onPointerDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];const yWe={move:{name:"mousemove"},end:{name:"mouseup"}};var wR;(function(t){t[t.RightClick=2]="RightClick"})(wR||(wR={}));class vWe extends NF{constructor(e){super(e,yWe,Hb(e.event.target))}}vWe.activators=[{eventName:"onMouseDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return n.button===wR.RightClick?!1:(r?.({event:n}),!0)}}];const ZP={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class wWe extends NF{constructor(e){super(e,ZP)}static setup(){return window.addEventListener(ZP.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(ZP.move.name,e)};function e(){}}}wWe.activators=[{eventName:"onTouchStart",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;const{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var H0;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(H0||(H0={}));var ok;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(ok||(ok={}));function _We(t){let{acceleration:e,activator:n=H0.Pointer,canScroll:r,draggingRect:i,enabled:s,interval:o=5,order:l=ok.TreeOrder,pointerCoordinates:c,scrollableAncestors:u,scrollableAncestorRects:d,delta:h,threshold:p}=t;const m=NWe({delta:h,disabled:!s}),[b,y]=L9e(),x=_.useRef({x:0,y:0}),v=_.useRef({x:0,y:0}),S=_.useMemo(()=>{switch(n){case H0.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case H0.DraggableRect:return i}},[n,i,c]),N=_.useRef(null),T=_.useCallback(()=>{const A=N.current;if(!A)return;const k=x.current.x*v.current.x,R=x.current.y*v.current.y;A.scrollBy(k,R)},[]),M=_.useMemo(()=>l===ok.TreeOrder?[...u].reverse():u,[l,u]);_.useEffect(()=>{if(!s||!u.length||!S){y();return}for(const A of M){if(r?.(A)===!1)continue;const k=u.indexOf(A),R=d[k];if(!R)continue;const{direction:C,speed:P}=cWe(A,R,S,e,p);for(const U of["x","y"])m[U][C[U]]||(P[U]=0,C[U]=0);if(P.x>0||P.y>0){y(),N.current=A,b(T,o),x.current=P,v.current=C;return}}x.current={x:0,y:0},v.current={x:0,y:0},y()},[e,T,r,y,s,o,JSON.stringify(S),JSON.stringify(m),b,u,M,d,JSON.stringify(p)])}const SWe={x:{[ya.Backward]:!1,[ya.Forward]:!1},y:{[ya.Backward]:!1,[ya.Forward]:!1}};function NWe(t){let{delta:e,disabled:n}=t;const r=xR(e);return Ev(i=>{if(n||!r||!i)return SWe;const s={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[ya.Backward]:i.x[ya.Backward]||s.x===-1,[ya.Forward]:i.x[ya.Forward]||s.x===1},y:{[ya.Backward]:i.y[ya.Backward]||s.y===-1,[ya.Forward]:i.y[ya.Forward]||s.y===1}}},[n,e,r])}function kWe(t,e){const n=e!=null?t.get(e):void 0,r=n?n.node.current:null;return Ev(i=>{var s;return e==null?null:(s=r??i)!=null?s:null},[r,e])}function MWe(t,e){return _.useMemo(()=>t.reduce((n,r)=>{const{sensor:i}=r,s=i.activators.map(o=>({eventName:o.eventName,handler:e(o.handler,r)}));return[...n,...s]},[]),[t,e])}var Iy;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(Iy||(Iy={}));var _R;(function(t){t.Optimized="optimized"})(_R||(_R={}));const k9=new Map;function EWe(t,e){let{dragging:n,dependencies:r,config:i}=e;const[s,o]=_.useState(null),{frequency:l,measure:c,strategy:u}=i,d=_.useRef(t),h=x(),p=Ly(h),m=_.useCallback(function(v){v===void 0&&(v=[]),!p.current&&o(S=>S===null?v:S.concat(v.filter(N=>!S.includes(N))))},[p]),b=_.useRef(null),y=Ev(v=>{if(h&&!n)return k9;if(!v||v===k9||d.current!==t||s!=null){const S=new Map;for(let N of t){if(!N)continue;if(s&&s.length>0&&!s.includes(N.id)&&N.rect.current){S.set(N.id,N.rect.current);continue}const T=N.node.current,M=T?new SF(c(T),T):null;N.rect.current=M,M&&S.set(N.id,M)}return S}return v},[t,s,n,h,c]);return _.useEffect(()=>{d.current=t},[t]),_.useEffect(()=>{h||m()},[n,h]),_.useEffect(()=>{s&&s.length>0&&o(null)},[JSON.stringify(s)]),_.useEffect(()=>{h||typeof l!="number"||b.current!==null||(b.current=setTimeout(()=>{m(),b.current=null},l))},[l,h,m,...r]),{droppableRects:y,measureDroppableContainers:m,measuringScheduled:s!=null};function x(){switch(u){case Iy.Always:return!1;case Iy.BeforeDragging:return n;default:return!n}}}function Gre(t,e){return Ev(n=>t?n||(typeof e=="function"?e(t):t):null,[e,t])}function TWe(t,e){return Gre(t,e)}function AWe(t){let{callback:e,disabled:n}=t;const r=wF(e),i=_.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(r)},[r,n]);return _.useEffect(()=>()=>i?.disconnect(),[i]),i}function ZM(t){let{callback:e,disabled:n}=t;const r=wF(e),i=_.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(r)},[n]);return _.useEffect(()=>()=>i?.disconnect(),[i]),i}function CWe(t){return new SF($b(t),t)}function M9(t,e,n){e===void 0&&(e=CWe);const[r,i]=_.useState(null);function s(){i(c=>{if(!t)return null;if(t.isConnected===!1){var u;return(u=c??n)!=null?u:null}const d=e(t);return JSON.stringify(c)===JSON.stringify(d)?c:d})}const o=AWe({callback(c){if(t)for(const u of c){const{type:d,target:h}=u;if(d==="childList"&&h instanceof HTMLElement&&h.contains(t)){s();break}}}}),l=ZM({callback:s});return kc(()=>{s(),t?(l?.observe(t),o?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),o?.disconnect())},[t]),r}function PWe(t){const e=Gre(t);return Fre(t,e)}const E9=[];function jWe(t){const e=_.useRef(t),n=Ev(r=>t?r&&r!==E9&&t&&e.current&&t.parentNode===e.current.parentNode?r:XM(t):E9,[t]);return _.useEffect(()=>{e.current=t},[t]),n}function DWe(t){const[e,n]=_.useState(null),r=_.useRef(t),i=_.useCallback(s=>{const o=YP(s.target);o&&n(l=>l?(l.set(o,vR(o)),new Map(l)):null)},[]);return _.useEffect(()=>{const s=r.current;if(t!==s){o(s);const l=t.map(c=>{const u=YP(c);return u?(u.addEventListener("scroll",i,{passive:!0}),[u,vR(u)]):null}).filter(c=>c!=null);n(l.length?new Map(l):null),r.current=t}return()=>{o(t),o(s)};function o(l){l.forEach(c=>{const u=YP(c);u?.removeEventListener("scroll",i)})}},[i,t]),_.useMemo(()=>t.length?e?Array.from(e.values()).reduce((s,o)=>Ug(s,o),Hl):$re(t):Hl,[t,e])}function T9(t,e){e===void 0&&(e=[]);const n=_.useRef(null);return _.useEffect(()=>{n.current=null},e),_.useEffect(()=>{const r=t!==Hl;r&&!n.current&&(n.current=t),!r&&n.current&&(n.current=null)},[t]),n.current?Fy(t,n.current):Hl}function RWe(t){_.useEffect(()=>{if(!KM)return;const e=t.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of e)n?.()}},t.map(e=>{let{sensor:n}=e;return n}))}function OWe(t,e){return _.useMemo(()=>t.reduce((n,r)=>{let{eventName:i,handler:s}=r;return n[i]=o=>{s(o,e)},n},{}),[t,e])}function qre(t){return _.useMemo(()=>t?aWe(t):null,[t])}const A9=[];function LWe(t,e){e===void 0&&(e=$b);const[n]=t,r=qre(n?Js(n):null),[i,s]=_.useState(A9);function o(){s(()=>t.length?t.map(c=>Bre(c)?r:new SF(e(c),c)):A9)}const l=ZM({callback:o});return kc(()=>{l?.disconnect(),o(),t.forEach(c=>l?.observe(c))},[t]),i}function FWe(t){if(!t)return null;if(t.children.length>1)return t;const e=t.children[0];return Mv(e)?e:t}function IWe(t){let{measure:e}=t;const[n,r]=_.useState(null),i=_.useCallback(u=>{for(const{target:d}of u)if(Mv(d)){r(h=>{const p=e(d);return h?{...h,width:p.width,height:p.height}:p});break}},[e]),s=ZM({callback:i}),o=_.useCallback(u=>{const d=FWe(u);s?.disconnect(),d&&s?.observe(d),r(d?e(d):null)},[e,s]),[l,c]=ik(o);return _.useMemo(()=>({nodeRef:l,rect:n,setRef:c}),[n,l,c])}const zWe=[{sensor:QM,options:{}},{sensor:YM,options:{}}],UWe={current:{}},q1={draggable:{measure:w9},droppable:{measure:w9,strategy:Iy.WhileDragging,frequency:_R.Optimized},dragOverlay:{measure:$b}};class $0 extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}}const BWe={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new $0,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:ak},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:q1,measureDroppableContainers:ak,windowRect:null,measuringScheduled:!1},HWe={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:ak,draggableNodes:new Map,over:null,measureDroppableContainers:ak},JM=_.createContext(HWe),Wre=_.createContext(BWe);function $We(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new $0}}}function VWe(t,e){switch(e.type){case Yi.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case Yi.DragMove:return t.draggable.active==null?t:{...t,draggable:{...t.draggable,translate:{x:e.coordinates.x-t.draggable.initialCoordinates.x,y:e.coordinates.y-t.draggable.initialCoordinates.y}}};case Yi.DragEnd:case Yi.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Yi.RegisterDroppable:{const{element:n}=e,{id:r}=n,i=new $0(t.droppable.containers);return i.set(r,n),{...t,droppable:{...t.droppable,containers:i}}}case Yi.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=e,s=t.droppable.containers.get(n);if(!s||r!==s.key)return t;const o=new $0(t.droppable.containers);return o.set(n,{...s,disabled:i}),{...t,droppable:{...t.droppable,containers:o}}}case Yi.UnregisterDroppable:{const{id:n,key:r}=e,i=t.droppable.containers.get(n);if(!i||r!==i.key)return t;const s=new $0(t.droppable.containers);return s.delete(n),{...t,droppable:{...t.droppable,containers:s}}}default:return t}}function GWe(t){let{disabled:e}=t;const{active:n,activatorEvent:r,draggableNodes:i}=_.useContext(JM),s=xR(r),o=xR(n?.id);return _.useEffect(()=>{if(!e&&!r&&s&&o!=null){if(!_F(s)||document.activeElement===s.target)return;const l=i.get(o);if(!l)return;const{activatorNode:c,node:u}=l;if(!c.current&&!u.current)return;requestAnimationFrame(()=>{for(const d of[c.current,u.current]){if(!d)continue;const h=z9e(d);if(h){h.focus();break}}})}},[r,e,i,o,s]),null}function qWe(t,e){let{transform:n,...r}=e;return t!=null&&t.length?t.reduce((i,s)=>s({transform:i,...r}),n):n}function WWe(t){return _.useMemo(()=>({draggable:{...q1.draggable,...t?.draggable},droppable:{...q1.droppable,...t?.droppable},dragOverlay:{...q1.dragOverlay,...t?.dragOverlay}}),[t?.draggable,t?.droppable,t?.dragOverlay])}function KWe(t){let{activeNode:e,measure:n,initialRect:r,config:i=!0}=t;const s=_.useRef(!1),{x:o,y:l}=typeof i=="boolean"?{x:i,y:i}:i;kc(()=>{if(!o&&!l||!e){s.current=!1;return}if(s.current||!r)return;const u=e?.node.current;if(!u||u.isConnected===!1)return;const d=n(u),h=Fre(d,r);if(o||(h.x=0),l||(h.y=0),s.current=!0,Math.abs(h.x)>0||Math.abs(h.y)>0){const p=Ire(u);p&&p.scrollBy({top:h.y,left:h.x})}},[e,o,l,r,n])}const Kre=_.createContext({...Hl,scaleX:1,scaleY:1});var nh;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(nh||(nh={}));const Xre=_.memo(function(e){var n,r,i,s;let{id:o,accessibility:l,autoScroll:c=!0,children:u,sensors:d=zWe,collisionDetection:h=Z9e,measuring:p,modifiers:m,...b}=e;const y=_.useReducer(VWe,void 0,$We),[x,v]=y,[S,N]=G9e(),[T,M]=_.useState(nh.Uninitialized),A=T===nh.Initialized,{draggable:{active:k,nodes:R,translate:C},droppable:{containers:P}}=x,U=k!=null?R.get(k):null,F=_.useRef({initial:null,translated:null}),H=_.useMemo(()=>{var Ye;return k!=null?{id:k,data:(Ye=U?.data)!=null?Ye:UWe,rect:F}:null},[k,U]),D=_.useRef(null),[$,G]=_.useState(null),[I,K]=_.useState(null),Q=Ly(b,Object.values(b)),oe=Tv("DndDescribedBy",o),B=_.useMemo(()=>P.getEnabled(),[P]),W=WWe(p),{droppableRects:J,measureDroppableContainers:ne,measuringScheduled:me}=EWe(B,{dragging:A,dependencies:[C.x,C.y],config:W.droppable}),fe=kWe(R,k),de=_.useMemo(()=>I?yR(I):null,[I]),Re=Ee(),se=TWe(fe,W.draggable.measure);KWe({activeNode:k!=null?R.get(k):null,config:Re.layoutShiftCompensation,initialRect:se,measure:W.draggable.measure});const ke=M9(fe,W.draggable.measure,se),Fe=M9(fe?fe.parentElement:null),ce=_.useRef({activatorEvent:null,active:null,activeNode:fe,collisionRect:null,collisions:null,droppableRects:J,draggableNodes:R,draggingNode:null,draggingNodeRect:null,droppableContainers:P,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ve=P.getNodeFor((n=ce.current.over)==null?void 0:n.id),V=IWe({measure:W.dragOverlay.measure}),Y=(r=V.nodeRef.current)!=null?r:fe,ue=A?(i=V.rect)!=null?i:ke:null,q=!!(V.nodeRef.current&&V.rect),re=PWe(q?null:ke),X=qre(Y?Js(Y):null),le=jWe(A?Ve??fe:null),pe=LWe(le),ee=qWe(m,{transform:{x:C.x-re.x,y:C.y-re.y,scaleX:1,scaleY:1},activatorEvent:I,active:H,activeNodeRect:ke,containerNodeRect:Fe,draggingNodeRect:ue,over:ce.current.over,overlayNodeRect:V.rect,scrollableAncestors:le,scrollableAncestorRects:pe,windowRect:X}),z=de?Ug(de,C):null,O=DWe(le),Z=T9(O),ge=T9(O,[ke]),Ce=Ug(ee,Z),_e=ue?tWe(ue,ee):null,Te=H&&_e?h({active:H,collisionRect:_e,droppableRects:J,droppableContainers:B,pointerCoordinates:z}):null,we=Ore(Te,"id"),[$e,Ge]=_.useState(null),ze=q?ee:Ug(ee,ge),be=J9e(ze,(s=$e?.rect)!=null?s:null,ke),Me=_.useRef(null),Be=_.useCallback((Ye,je)=>{let{sensor:Pe,options:ye}=je;if(D.current==null)return;const Qe=R.get(D.current);if(!Qe)return;const yt=Ye.nativeEvent,at=new Pe({active:D.current,activeNode:Qe,event:yt,options:ye,context:ce,onAbort(zt){if(!R.get(zt))return;const{onDragAbort:vt}=Q.current,Gt={id:zt};vt?.(Gt),S({type:"onDragAbort",event:Gt})},onPending(zt,Ie,vt,Gt){if(!R.get(zt))return;const{onDragPending:fn}=Q.current,vn={id:zt,constraint:Ie,initialCoordinates:vt,offset:Gt};fn?.(vn),S({type:"onDragPending",event:vn})},onStart(zt){const Ie=D.current;if(Ie==null)return;const vt=R.get(Ie);if(!vt)return;const{onDragStart:Gt}=Q.current,dn={activatorEvent:yt,active:{id:Ie,data:vt.data,rect:F}};vu.unstable_batchedUpdates(()=>{Gt?.(dn),M(nh.Initializing),v({type:Yi.DragStart,initialCoordinates:zt,active:Ie}),S({type:"onDragStart",event:dn}),G(Me.current),K(yt)})},onMove(zt){v({type:Yi.DragMove,coordinates:zt})},onEnd:Ut(Yi.DragEnd),onCancel:Ut(Yi.DragCancel)});Me.current=at;function Ut(zt){return async function(){const{active:vt,collisions:Gt,over:dn,scrollAdjustedTranslate:fn}=ce.current;let vn=null;if(vt&&fn){const{cancelDrop:dr}=Q.current;vn={activatorEvent:yt,active:vt,collisions:Gt,delta:fn,over:dn},zt===Yi.DragEnd&&typeof dr=="function"&&await Promise.resolve(dr(vn))&&(zt=Yi.DragCancel)}D.current=null,vu.unstable_batchedUpdates(()=>{v({type:zt}),M(nh.Uninitialized),Ge(null),G(null),K(null),Me.current=null;const dr=zt===Yi.DragEnd?"onDragEnd":"onDragCancel";if(vn){const ar=Q.current[dr];ar?.(vn),S({type:dr,event:vn})}})}}},[R]),Ae=_.useCallback((Ye,je)=>(Pe,ye)=>{const Qe=Pe.nativeEvent,yt=R.get(ye);if(D.current!==null||!yt||Qe.dndKit||Qe.defaultPrevented)return;const at={active:yt};Ye(Pe,je.options,at)===!0&&(Qe.dndKit={capturedBy:je.sensor},D.current=ye,Be(Pe,je))},[R,Be]),qe=MWe(d,Ae);RWe(d),kc(()=>{ke&&T===nh.Initializing&&M(nh.Initialized)},[ke,T]),_.useEffect(()=>{const{onDragMove:Ye}=Q.current,{active:je,activatorEvent:Pe,collisions:ye,over:Qe}=ce.current;if(!je||!Pe)return;const yt={active:je,activatorEvent:Pe,collisions:ye,delta:{x:Ce.x,y:Ce.y},over:Qe};vu.unstable_batchedUpdates(()=>{Ye?.(yt),S({type:"onDragMove",event:yt})})},[Ce.x,Ce.y]),_.useEffect(()=>{const{active:Ye,activatorEvent:je,collisions:Pe,droppableContainers:ye,scrollAdjustedTranslate:Qe}=ce.current;if(!Ye||D.current==null||!je||!Qe)return;const{onDragOver:yt}=Q.current,at=ye.get(we),Ut=at&&at.rect.current?{id:at.id,rect:at.rect.current,data:at.data,disabled:at.disabled}:null,zt={active:Ye,activatorEvent:je,collisions:Pe,delta:{x:Qe.x,y:Qe.y},over:Ut};vu.unstable_batchedUpdates(()=>{Ge(Ut),yt?.(zt),S({type:"onDragOver",event:zt})})},[we]),kc(()=>{ce.current={activatorEvent:I,active:H,activeNode:fe,collisionRect:_e,collisions:Te,droppableRects:J,draggableNodes:R,draggingNode:Y,draggingNodeRect:ue,droppableContainers:P,over:$e,scrollableAncestors:le,scrollAdjustedTranslate:Ce},F.current={initial:ue,translated:_e}},[H,fe,Te,_e,R,Y,ue,J,P,$e,le,Ce]),_We({...Re,delta:C,draggingRect:_e,pointerCoordinates:z,scrollableAncestors:le,scrollableAncestorRects:pe});const ve=_.useMemo(()=>({active:H,activeNode:fe,activeNodeRect:ke,activatorEvent:I,collisions:Te,containerNodeRect:Fe,dragOverlay:V,draggableNodes:R,droppableContainers:P,droppableRects:J,over:$e,measureDroppableContainers:ne,scrollableAncestors:le,scrollableAncestorRects:pe,measuringConfiguration:W,measuringScheduled:me,windowRect:X}),[H,fe,ke,I,Te,Fe,V,R,P,J,$e,ne,le,pe,W,me,X]),et=_.useMemo(()=>({activatorEvent:I,activators:qe,active:H,activeNodeRect:ke,ariaDescribedById:{draggable:oe},dispatch:v,draggableNodes:R,over:$e,measureDroppableContainers:ne}),[I,qe,H,ke,v,oe,R,$e,ne]);return ei.createElement(Pre.Provider,{value:N},ei.createElement(JM.Provider,{value:et},ei.createElement(Wre.Provider,{value:ve},ei.createElement(Kre.Provider,{value:be},u)),ei.createElement(GWe,{disabled:l?.restoreFocus===!1})),ei.createElement(K9e,{...l,hiddenTextDescribedById:oe}));function Ee(){const Ye=$?.autoScrollEnabled===!1,je=typeof c=="object"?c.enabled===!1:c===!1,Pe=A&&!Ye&&!je;return typeof c=="object"?{...c,enabled:Pe}:{enabled:Pe}}}),XWe=_.createContext(null),C9="button",YWe="Draggable";function QWe(t){let{id:e,data:n,disabled:r=!1,attributes:i}=t;const s=Tv(YWe),{activators:o,activatorEvent:l,active:c,activeNodeRect:u,ariaDescribedById:d,draggableNodes:h,over:p}=_.useContext(JM),{role:m=C9,roleDescription:b="draggable",tabIndex:y=0}=i??{},x=c?.id===e,v=_.useContext(x?Kre:XWe),[S,N]=ik(),[T,M]=ik(),A=OWe(o,e),k=Ly(n);kc(()=>(h.set(e,{id:e,key:s,node:S,activatorNode:T,data:k}),()=>{const C=h.get(e);C&&C.key===s&&h.delete(e)}),[h,e]);const R=_.useMemo(()=>({role:m,tabIndex:y,"aria-disabled":r,"aria-pressed":x&&m===C9?!0:void 0,"aria-roledescription":b,"aria-describedby":d.draggable}),[r,m,y,x,b,d.draggable]);return{active:c,activatorEvent:l,activeNodeRect:u,attributes:R,isDragging:x,listeners:r?void 0:A,node:S,over:p,setNodeRef:N,setActivatorNodeRef:M,transform:v}}function ZWe(){return _.useContext(Wre)}const JWe="Droppable",eKe={timeout:25};function tKe(t){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:i}=t;const s=Tv(JWe),{active:o,dispatch:l,over:c,measureDroppableContainers:u}=_.useContext(JM),d=_.useRef({disabled:n}),h=_.useRef(!1),p=_.useRef(null),m=_.useRef(null),{disabled:b,updateMeasurementsFor:y,timeout:x}={...eKe,...i},v=Ly(y??r),S=_.useCallback(()=>{if(!h.current){h.current=!0;return}m.current!=null&&clearTimeout(m.current),m.current=setTimeout(()=>{u(Array.isArray(v.current)?v.current:[v.current]),m.current=null},x)},[x]),N=ZM({callback:S,disabled:b||!o}),T=_.useCallback((R,C)=>{N&&(C&&(N.unobserve(C),h.current=!1),R&&N.observe(R))},[N]),[M,A]=ik(T),k=Ly(e);return _.useEffect(()=>{!N||!M.current||(N.disconnect(),h.current=!1,N.observe(M.current))},[M,N]),_.useEffect(()=>(l({type:Yi.RegisterDroppable,element:{id:r,key:s,disabled:n,node:M,rect:p,data:k}}),()=>l({type:Yi.UnregisterDroppable,key:s,id:r})),[r]),_.useEffect(()=>{n!==d.current.disabled&&(l({type:Yi.SetDroppableDisabled,id:r,key:s,disabled:n}),d.current.disabled=n)},[r,s,n,l]),{active:o,rect:p,isOver:c?.id===r,node:M,over:c,setNodeRef:A}}function e2(t,e,n){const r=t.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function nKe(t,e){return t.reduce((n,r,i)=>{const s=e.get(r);return s&&(n[i]=s),n},Array(t.length))}function g1(t){return t!==null&&t>=0}function rKe(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n{let{rects:e,activeIndex:n,overIndex:r,index:i}=t;const s=e2(e,r,n),o=e[i],l=s[i];return!l||!o?null:{x:l.left-o.left,y:l.top-o.top,scaleX:l.width/o.width,scaleY:l.height/o.height}},b1={scaleX:1,scaleY:1},aKe=t=>{var e;let{activeIndex:n,activeNodeRect:r,index:i,rects:s,overIndex:o}=t;const l=(e=s[n])!=null?e:r;if(!l)return null;if(i===n){const u=s[o];return u?{x:0,y:nn&&i<=o?{x:0,y:-l.height-c,...b1}:i=o?{x:0,y:l.height+c,...b1}:{x:0,y:0,...b1}};function sKe(t,e,n){const r=t[e],i=t[e-1],s=t[e+1];return r?nr.map(A=>typeof A=="object"&&"id"in A?A.id:A),[r]),b=o!=null,y=o?m.indexOf(o.id):-1,x=u?m.indexOf(u.id):-1,v=_.useRef(m),S=!rKe(m,v.current),N=x!==-1&&y===-1||S,T=iKe(s);kc(()=>{S&&b&&d(m)},[S,m,b,d]),_.useEffect(()=>{v.current=m},[m]);const M=_.useMemo(()=>({activeIndex:y,containerId:h,disabled:T,disableTransforms:N,items:m,overIndex:x,useDragOverlay:p,sortedRects:nKe(m,c),strategy:i}),[y,h,T.draggable,T.droppable,N,m,x,c,p,i]);return ei.createElement(Qre.Provider,{value:M},e)}const oKe=t=>{let{id:e,items:n,activeIndex:r,overIndex:i}=t;return e2(n,r,i).indexOf(e)},lKe=t=>{let{containerId:e,isSorting:n,wasDragging:r,index:i,items:s,newIndex:o,previousItems:l,previousContainerId:c,transition:u}=t;return!u||!r||l!==s&&i===o?!1:n?!0:o!==i&&e===c},cKe={duration:200,easing:"ease"},Jre="transform",uKe=xb.Transition.toString({property:Jre,duration:0,easing:"linear"}),dKe={roleDescription:"sortable"};function hKe(t){let{disabled:e,index:n,node:r,rect:i}=t;const[s,o]=_.useState(null),l=_.useRef(n);return kc(()=>{if(!e&&n!==l.current&&r.current){const c=i.current;if(c){const u=$b(r.current,{ignoreTransform:!0}),d={x:c.left-u.left,y:c.top-u.top,scaleX:c.width/u.width,scaleY:c.height/u.height};(d.x||d.y)&&o(d)}}n!==l.current&&(l.current=n)},[e,n,r,i]),_.useEffect(()=>{s&&o(null)},[s]),s}function eie(t){let{animateLayoutChanges:e=lKe,attributes:n,disabled:r,data:i,getNewIndex:s=oKe,id:o,strategy:l,resizeObserverConfig:c,transition:u=cKe}=t;const{items:d,containerId:h,activeIndex:p,disabled:m,disableTransforms:b,sortedRects:y,overIndex:x,useDragOverlay:v,strategy:S}=_.useContext(Qre),N=fKe(r,m),T=d.indexOf(o),M=_.useMemo(()=>({sortable:{containerId:h,index:T,items:d},...i}),[h,i,T,d]),A=_.useMemo(()=>d.slice(d.indexOf(o)),[d,o]),{rect:k,node:R,isOver:C,setNodeRef:P}=tKe({id:o,data:M,disabled:N.droppable,resizeObserverConfig:{updateMeasurementsFor:A,...c}}),{active:U,activatorEvent:F,activeNodeRect:H,attributes:D,setNodeRef:$,listeners:G,isDragging:I,over:K,setActivatorNodeRef:Q,transform:oe}=QWe({id:o,data:M,attributes:{...dKe,...n},disabled:N.draggable}),B=O9e(P,$),W=!!U,J=W&&!b&&g1(p)&&g1(x),ne=!v&&I,me=ne&&J?oe:null,de=J?me??(l??S)({rects:y,activeNodeRect:H,activeIndex:p,overIndex:x,index:T}):null,Re=g1(p)&&g1(x)?s({id:o,items:d,activeIndex:p,overIndex:x}):T,se=U?.id,ke=_.useRef({activeId:se,items:d,newIndex:Re,containerId:h}),Fe=d!==ke.current.items,ce=e({active:U,containerId:h,isDragging:I,isSorting:W,id:o,index:T,items:d,newIndex:ke.current.newIndex,previousItems:ke.current.items,previousContainerId:ke.current.containerId,transition:u,wasDragging:ke.current.activeId!=null}),Ve=hKe({disabled:!ce,index:T,node:R,rect:k});return _.useEffect(()=>{W&&ke.current.newIndex!==Re&&(ke.current.newIndex=Re),h!==ke.current.containerId&&(ke.current.containerId=h),d!==ke.current.items&&(ke.current.items=d)},[W,Re,h,d]),_.useEffect(()=>{if(se===ke.current.activeId)return;if(se!=null&&ke.current.activeId==null){ke.current.activeId=se;return}const Y=setTimeout(()=>{ke.current.activeId=se},50);return()=>clearTimeout(Y)},[se]),{active:U,activeIndex:p,attributes:D,data:M,rect:k,index:T,newIndex:Re,items:d,isOver:C,isSorting:W,isDragging:I,listeners:G,node:R,overIndex:x,over:K,setNodeRef:B,setActivatorNodeRef:Q,setDroppableNodeRef:P,setDraggableNodeRef:$,transform:Ve??de,transition:V()};function V(){if(Ve||Fe&&ke.current.newIndex===T)return uKe;if(!(ne&&!_F(F)||!u)&&(W||ce))return xb.Transition.toString({...u,property:Jre})}}function fKe(t,e){var n,r;return typeof t=="boolean"?{draggable:t,droppable:!1}:{draggable:(n=t?.draggable)!=null?n:e.draggable,droppable:(r=t?.droppable)!=null?r:e.droppable}}function lk(t){if(!t)return!1;const e=t.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const mKe=[Jn.Down,Jn.Right,Jn.Up,Jn.Left],tie=(t,e)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:s,over:o,scrollableAncestors:l}}=e;if(mKe.includes(t.code)){if(t.preventDefault(),!n||!r)return;const c=[];s.getEnabled().forEach(h=>{if(!h||h!=null&&h.disabled)return;const p=i.get(h.id);if(p)switch(t.code){case Jn.Down:r.topp.top&&c.push(h);break;case Jn.Left:r.left>p.left&&c.push(h);break;case Jn.Right:r.left1&&(d=u[1].id),d!=null){const h=s.get(n.id),p=s.get(d),m=p?i.get(p.id):null,b=p?.node.current;if(b&&m&&h&&p){const x=XM(b).some((A,k)=>l[k]!==A),v=nie(h,p),S=pKe(h,p),N=x||!v?{x:0,y:0}:{x:S?r.width-m.width:0,y:S?r.height-m.height:0},T={x:m.left,y:m.top};return N.x&&N.y?T:Fy(T,N)}}}};function nie(t,e){return!lk(t)||!lk(e)?!1:t.data.current.sortable.containerId===e.data.current.sortable.containerId}function pKe(t,e){return!lk(t)||!lk(e)||!nie(t,e)?!1:t.data.current.sortable.index0?`${e}h ${n}m`:`${n}m`}function gKe(t,e="system",n){if(!t)return n?.("queue.time.asap")??"ASAP";const r=zi(t);if(!r)return n?.("queue.time.asap")??"ASAP";const i=new Date,s=r.getTime()-i.getTime();return s<-6e4?n?.("queue.time.overdue")??"Overdue":s<0?n?.("queue.time.now")??"Now":s<6e4?n?.("queue.time.lessThanMinute")??"In less than a minute":s<36e5?n?.("queue.time.inMinutes",{count:Math.round(s/6e4)})??`In ${Math.round(s/6e4)} min`:s<864e5?n?.("queue.time.inHours",{count:Math.round(s/36e5)})??`In ${Math.round(s/36e5)} hours`:qg(t,e)}function bKe({status:t,waitingReason:e,printerState:n,t:r}){if(t==="pending"&&e)return a.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-purple-400 bg-purple-400/10 border-purple-400/20",children:[a.jsx(tr,{className:"w-3.5 h-3.5"}),r("queue.status.waiting")]});if(t==="printing"&&(n==="PAUSE"||n==="PAUSED"))return a.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-yellow-400 bg-yellow-400/10 border-yellow-400/20",children:[a.jsx(Sk,{className:"w-3.5 h-3.5"}),r("queue.status.paused")]});const i={pending:{icon:tr,color:"text-status-warning bg-status-warning/10 border-status-warning/20",label:r("queue.status.pending")},printing:{icon:Eo,color:"text-blue-400 bg-blue-400/10 border-blue-400/20",label:r("queue.status.printing")},completed:{icon:mr,color:"text-status-ok bg-status-ok/10 border-status-ok/20",label:r("queue.status.completed")},failed:{icon:Zi,color:"text-status-error bg-status-error/10 border-status-error/20",label:r("queue.status.failed")},skipped:{icon:qR,color:"text-orange-400 bg-orange-400/10 border-orange-400/20",label:r("queue.status.skipped")},cancelled:{icon:Lt,color:"text-gray-400 bg-gray-400/10 border-gray-400/20",label:r("queue.status.cancelled")}},{icon:s,color:o,label:l}=i[t];return a.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${o}`,children:[a.jsx(s,{className:"w-3.5 h-3.5"}),l]})}function xKe({selectedCount:t,printers:e,onSave:n,onClose:r,isSaving:i,t:s}){const[o,l]=_.useState("unchanged"),[c,u]=_.useState("unchanged"),[d,h]=_.useState("unchanged"),[p,m]=_.useState("unchanged"),[b,y]=_.useState("unchanged"),[x,v]=_.useState("unchanged"),[S,N]=_.useState("unchanged"),[T,M]=_.useState("unchanged"),[A,k]=_.useState("unchanged"),[R,C]=_.useState("unchanged"),P=()=>{const F={};o!=="unchanged"&&(F.printer_id=o),c!=="unchanged"&&(F.manual_start=c),d!=="unchanged"&&(F.auto_off_after=d),p!=="unchanged"&&(F.require_previous_success=p),b!=="unchanged"&&(F.bed_levelling=b),x!=="unchanged"&&(F.flow_cali=x),S!=="unchanged"&&(F.vibration_cali=S),T!=="unchanged"&&(F.layer_inspect=T),A!=="unchanged"&&(F.timelapse=A),R!=="unchanged"&&(F.use_ams=R),n(F)},U=o!=="unchanged"||c!=="unchanged"||d!=="unchanged"||p!=="unchanged"||b!=="unchanged"||x!=="unchanged"||S!=="unchanged"||T!=="unchanged"||A!=="unchanged"||R!=="unchanged";return a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg max-h-[90vh] overflow-y-auto",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:s("queue.bulkEdit.title",{count:t})}),a.jsx("button",{onClick:r,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Lt,{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:s("queue.bulkEdit.description")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:s("queue.bulkEdit.printer")}),a.jsxs("select",{value:o===null?"null":o==="unchanged"?"unchanged":String(o),onChange:F=>{const H=F.target.value;l(H==="unchanged"?"unchanged":H==="null"?null:Number(H))},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:"unchanged",children:s("queue.bulkEdit.noChange")}),a.jsx("option",{value:"null",children:s("queue.filter.unassigned")}),e.map(F=>a.jsx("option",{value:F.id,children:F.name},F.id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:s("queue.bulkEdit.queueOptions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(du,{label:s("queue.bulkEdit.staged"),value:c,onChange:u,t:s}),a.jsx(du,{label:s("queue.bulkEdit.autoPowerOff"),value:d,onChange:h,t:s}),a.jsx(du,{label:s("queue.bulkEdit.requirePrevious"),value:p,onChange:m,t:s})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:s("queue.bulkEdit.printOptions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(du,{label:s("queue.bulkEdit.bedLevelling"),value:b,onChange:y,t:s}),a.jsx(du,{label:s("queue.bulkEdit.flowCalibration"),value:x,onChange:v,t:s}),a.jsx(du,{label:s("queue.bulkEdit.vibrationCalibration"),value:S,onChange:N,t:s}),a.jsx(du,{label:s("queue.bulkEdit.layerInspection"),value:T,onChange:M,t:s}),a.jsx(du,{label:s("queue.bulkEdit.timelapse"),value:A,onChange:k,t:s}),a.jsx(du,{label:s("queue.bulkEdit.useAms"),value:R,onChange:C,t:s})]})]})]}),a.jsxs("div",{className:"flex justify-end gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Ne,{variant:"secondary",onClick:r,children:s("common.cancel")}),a.jsx(Ne,{onClick:P,disabled:!U||i,children:s(i?"common.saving":"queue.bulkEdit.applyChanges")})]})]})})}function du({label:t,value:e,onChange:n,t:r}){return a.jsxs("div",{className:"flex items-center justify-between py-1",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:t}),a.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5",children:[a.jsx("button",{onClick:()=>n("unchanged"),className:`px-2 py-1 text-xs rounded ${e==="unchanged"?"bg-bambu-dark-tertiary text-white":"text-bambu-gray hover:text-white"}`,children:"—"}),a.jsx("button",{onClick:()=>n(!1),className:`px-2 py-1 text-xs rounded ${e===!1?"bg-red-500/20 text-red-400":"text-bambu-gray hover:text-white"}`,children:r("common.off")}),a.jsx("button",{onClick:()=>n(!0),className:`px-2 py-1 text-xs rounded ${e===!0?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white"}`,children:r("common.on")})]})]})}function JP({item:t,position:e,onEdit:n,onCancel:r,onRemove:i,onStop:s,onRequeue:o,onStart:l,timeFormat:c="system",isSelected:u=!1,onToggleSelect:d,hasPermission:h,canModify:p,printerState:m,t:b}){const y=h("queue:reorder"),{attributes:x,listeners:v,setNodeRef:S,transform:N,transition:T,isDragging:M}=eie({id:t.id,disabled:t.status!=="pending"||!y}),A={transform:xb.Transform.toString(N),transition:T},k=t.status==="printing",R=t.status==="pending",C=["completed","failed","skipped","cancelled"].includes(t.status);return a.jsx("div",{ref:S,style:A,className:` group relative bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary transition-all duration-200 hover:border-bambu-dark-tertiary/80 ${M?"opacity-50 scale-[1.02] shadow-xl z-50":""} ${k?"border-blue-500/30 bg-gradient-to-r from-blue-500/5 to-transparent":""} - `,children:a.jsxs("div",{className:"flex items-center gap-4 p-4",children:[R&&d&&a.jsx("button",{onClick:P=>{P.stopPropagation(),d()},className:`flex items-center justify-center w-6 h-6 rounded border transition-colors ${u?"bg-bambu-green border-bambu-green text-white":"border-white/30 bg-black/30 hover:border-bambu-green/50"}`,children:u&&a.jsx($i,{className:"w-4 h-4"})}),R?a.jsx("div",{...x,...v,className:"flex items-center justify-center w-10 h-10 md:w-8 md:h-8 rounded-lg bg-bambu-dark cursor-grab active:cursor-grabbing hover:bg-bambu-dark-tertiary transition-colors touch-manipulation",children:a.jsx(Vg,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}):e!==void 0?a.jsxs("div",{className:"flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark text-bambu-gray text-sm font-medium",children:["#",e]}):a.jsx("div",{className:"w-8"}),a.jsx("div",{className:"w-14 h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:t.archive_thumbnail?a.jsx("img",{src:t.plate_id!=null?ae.getArchivePlateThumbnail(t.archive_id,t.plate_id):ae.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?a.jsx("img",{src:t.plate_id!=null?ae.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):ae.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",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(is,{className:"w-6 h-6"})})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:t.archive_name||t.library_file_name||`File #${t.archive_id||t.library_file_id}`}),t.archive_id?a.jsx(Bs,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:b("queue.viewArchive"),children:a.jsx(Xr,{className:"w-3.5 h-3.5"})}):t.library_file_id?a.jsx(Bs,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:b("queue.viewInFileManager"),children:a.jsx(Xr,{className:"w-3.5 h-3.5"})}):null]}),a.jsxs("div",{className:"flex items-center gap-3 text-sm text-bambu-gray",children:[a.jsxs("span",{className:`flex items-center gap-1.5 ${t.printer_id===null&&!t.target_model?"text-orange-400":""} ${t.target_model?"text-blue-400":""}`,children:[a.jsx(jr,{className:"w-3.5 h-3.5"}),t.target_model?`${b("queue.filter.any")} ${t.target_model}${t.target_location?` @ ${t.target_location}`:""}${t.required_filament_types?.length?` (${t.required_filament_types.join(", ")})`:""}`:t.printer_id===null?b("queue.filter.unassigned"):t.printer_name||`${b("common.printer")} #${t.printer_id}`]}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(wu,{className:"w-3.5 h-3.5"}),rie(t.print_time_seconds)]}),t.created_by_username&&a.jsxs("span",{className:"flex items-center gap-1.5",title:b("queue.addedBy",{name:t.created_by_username}),children:[a.jsx($u,{className:"w-3.5 h-3.5"}),t.created_by_username]}),R&&!t.manual_start&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(tr,{className:"w-3.5 h-3.5"}),pKe(t.scheduled_time,c,b)]})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[t.manual_start&&a.jsxs("span",{className:"text-xs px-2 py-0.5 bg-purple-500/10 text-purple-400 rounded-full border border-purple-500/20 flex items-center gap-1",children:[a.jsx(LW,{className:"w-3 h-3"}),b("queue.badges.staged")]}),t.require_previous_success&&a.jsx("span",{className:"text-xs px-2 py-0.5 bg-orange-500/10 text-orange-400 rounded-full border border-orange-500/20",children:b("queue.badges.requiresPrevious")}),t.auto_off_after&&a.jsxs("span",{className:"text-xs px-2 py-0.5 bg-blue-500/10 text-blue-400 rounded-full border border-blue-500/20 flex items-center gap-1",children:[a.jsx(Ju,{className:"w-3 h-3"}),b("queue.badges.autoPowerOff")]})]}),k&&a.jsxs("div",{className:"mt-3",children:[a.jsx("div",{className:"h-2 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full bg-gradient-to-r from-blue-500 to-blue-400 animate-pulse w-full opacity-50"})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:b("queue.printingInProgress")})]}),t.waiting_reason&&t.status==="pending"&&a.jsxs("p",{className:"text-xs text-purple-400 mt-2 flex items-start gap-1",children:[a.jsx(Ti,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),a.jsx("span",{children:t.waiting_reason})]}),t.error_message&&a.jsxs("p",{className:"text-xs text-red-400 mt-2 flex items-center gap-1",children:[a.jsx(Ti,{className:"w-3 h-3"}),t.error_message]})]}),a.jsx(gKe,{status:t.status,waitingReason:t.waiting_reason,printerState:m,t:b}),a.jsxs("div",{className:"flex items-center gap-1",children:[k&&a.jsx(Ne,{variant:"ghost",size:"sm",onClick:s,disabled:!h("printers:control"),title:h("printers:control")?b("queue.actions.stopPrint"):b("queue.permissions.noStopPrint"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:a.jsx(bue,{className:"w-4 h-4"})}),R&&a.jsxs(a.Fragment,{children:[t.manual_start&&a.jsx(Ne,{variant:"ghost",size:"sm",onClick:l,disabled:!h("printers:control"),title:h("printers:control")?b("queue.actions.startPrint"):b("queue.permissions.noStartPrint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:a.jsx(Eo,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:n,disabled:!p("queue","update",t.created_by_id),title:p("queue","update",t.created_by_id)?b("common.edit"):b("queue.permissions.noEdit"),children:a.jsx(Ji,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:r,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?b("common.cancel"):b("queue.permissions.noCancel"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:a.jsx(Lt,{className:"w-4 h-4"})})]}),C&&a.jsxs(a.Fragment,{children:[a.jsx(Ne,{variant:"ghost",size:"sm",onClick:o,disabled:!h("queue:create"),title:h("queue:create")?b("queue.actions.requeue"):b("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10",children:a.jsx(Or,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:i,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?b("common.remove"):b("queue.permissions.noRemove"),children:a.jsx(ln,{className:"w-4 h-4"})})]})]})]})})}function xKe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),{hasPermission:r,hasAnyPermission:i,canModify:s}=Ir(),[o,l]=_.useState(null),[c,u]=_.useState(""),[d,h]=_.useState(""),[p,m]=_.useState(!1),[b,y]=_.useState(null),[x,v]=_.useState(null),[S,N]=_.useState(null),[T,M]=_.useState([]),[A,k]=_.useState(!1),[R,C]=_.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[P,U]=_.useState(()=>{const ee=localStorage.getItem("queue.historySortAsc");return ee!==null?ee==="true":!1}),[F,H]=_.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[D,$]=_.useState(()=>{const ee=localStorage.getItem("queue.pendingSortAsc");return ee!==null?ee==="true":!0});_.useEffect(()=>{localStorage.setItem("queue.historySortBy",R)},[R]),_.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(P))},[P]),_.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",F)},[F]),_.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(D))},[D]);const G=jre(sk(QM,{activationConstraint:{distance:8}}),sk(YM,{coordinateGetter:tie})),{data:I}=it({queryKey:["settings"],queryFn:ae.getSettings}),K=I?.time_format||"system",{data:Q,isLoading:oe}=it({queryKey:["queue",o,c],queryFn:()=>ae.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:B}=it({queryKey:["printers"],queryFn:()=>ae.getPrinters()}),W=dt({mutationFn:ee=>ae.cancelQueueItem(ee),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),J=dt({mutationFn:ee=>ae.removeFromQueue(ee),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),ne=dt({mutationFn:ee=>ae.stopQueueItem(ee),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),me=dt({mutationFn:ee=>ae.startQueueItem(ee),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),fe=dt({mutationFn:ee=>ae.reorderQueue(ee),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),de=dt({mutationFn:async()=>{const ee=Q?.filter(z=>["completed","failed","skipped","cancelled"].includes(z.status))||[];for(const z of ee)await ae.removeFromQueue(z.id);return ee.length},onSuccess:ee=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:ee}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),Re=dt({mutationFn:ee=>ae.bulkUpdateQueue(ee),onSuccess:ee=>{e.invalidateQueries({queryKey:["queue"]}),M([]),k(!1),n(ee.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),se=dt({mutationFn:async ee=>{for(const z of ee)await ae.cancelQueueItem(z);return ee.length},onSuccess:ee=>{e.invalidateQueries({queryKey:["queue"]}),M([]),n(t("queue.toast.bulkCancelled",{count:ee}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),ke=ee=>{M(z=>z.includes(ee)?z.filter(O=>O!==ee):[...z,ee])},Fe=_.useMemo(()=>{const ee=new Set;return B?.forEach(z=>{z.location&&ee.add(z.location)}),Q?.forEach(z=>{z.target_location&&ee.add(z.target_location)}),Array.from(ee).sort()},[B,Q]),ce=_.useCallback(ee=>d?ee.target_location?ee.target_location===d:ee.printer_id?B?.find(O=>O.id===ee.printer_id)?.location===d:!1:!0,[d,B]),Ve=_.useMemo(()=>{let ee=Q?.filter(O=>O.status==="pending")||[];d&&(ee=ee.filter(ce));const z=O=>{if(!O.scheduled_time)return 0;const Z=new Date(O.scheduled_time).getTime(),ge=Date.now()+4320*60*60*1e3;return Z>ge?0:Z};return[...ee].sort((O,Z)=>{let ge;if(F==="name"){const Ce=O.archive_name||O.library_file_name||"",_e=Z.archive_name||Z.library_file_name||"";ge=Ce.localeCompare(_e)}else F==="printer"?ge=(O.printer_name||"").localeCompare(Z.printer_name||""):F==="time"?ge=z(O)-z(Z):ge=O.position-Z.position;return D?ge:-ge})},[Q,F,D,ce,d]),V=()=>{const ee=Ve.map(z=>z.id);T.length===ee.length?M([]):M(ee)},Y=_.useMemo(()=>{let ee=Q?.filter(z=>z.status==="printing")||[];return d&&(ee=ee.filter(ce)),ee},[Q,d,ce]),ue=_.useMemo(()=>{const ee=new Set;return Y.forEach(z=>{z.printer_id&&ee.add(z.printer_id)}),Array.from(ee)},[Y]),q=BR({queries:ue.map(ee=>({queryKey:["printerStatus",ee],queryFn:()=>ae.getPrinterStatus(ee),refetchInterval:5e3}))}),re=_.useMemo(()=>{const ee={};return ue.forEach((z,O)=>{const Z=q[O];Z?.data?.state&&(ee[z]=Z.data.state)}),ee},[ue,q]),X=_.useMemo(()=>{let ee=Q?.filter(z=>["completed","failed","skipped","cancelled"].includes(z.status))||[];return d&&(ee=ee.filter(ce)),[...ee].sort((z,O)=>{let Z;if(R==="name"){const ge=z.archive_name||z.library_file_name||"",Ce=O.archive_name||O.library_file_name||"";Z=ge.localeCompare(Ce)}else R==="printer"?Z=(z.printer_name||"").localeCompare(O.printer_name||""):Z=new Date(O.completed_at||O.created_at).getTime()-new Date(z.completed_at||z.created_at).getTime();return P?-Z:Z})},[Q,R,P,ce,d]),le=_.useMemo(()=>Ve.reduce((ee,z)=>ee+(z.print_time_seconds||0),0),[Ve]),pe=ee=>{const{active:z,over:O}=ee;if(!O||z.id===O.id)return;const Z=Ve.findIndex(Ce=>Ce.id===z.id),ge=Ve.findIndex(Ce=>Ce.id===O.id);if(Z!==-1&&ge!==-1){const _e=e2(Ve,Z,ge).map((Te,we)=>({id:Te.id,position:we+1}));fe.mutate(_e)}};return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsx("div",{className:"flex items-center justify-between mb-8",children:a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx(FW,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-8",children:[a.jsx(St,{className:"bg-gradient-to-br from-blue-500/10 to-transparent border-blue-500/20",children:a.jsx(Et,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center",children:a.jsx(Eo,{className:"w-5 h-5 text-blue-400"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:Y.length}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.printing")})]})]})})}),a.jsx(St,{className:"bg-gradient-to-br from-yellow-500/10 to-transparent border-yellow-500/20",children:a.jsx(Et,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-yellow-500/20 flex items-center justify-center",children:a.jsx(tr,{className:"w-5 h-5 text-yellow-400"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:Ve.length}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.queued")})]})]})})}),a.jsx(St,{className:"bg-gradient-to-br from-bambu-green/10 to-transparent border-bambu-green/20",children:a.jsx(Et,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-bambu-green/20 flex items-center justify-center",children:a.jsx(wu,{className:"w-5 h-5 text-bambu-green"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:rie(le)}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.totalTime")})]})]})})}),a.jsx(St,{className:"bg-gradient-to-br from-gray-500/10 to-transparent border-gray-500/20",children:a.jsx(Et,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-gray-500/20 flex items-center justify-center",children:a.jsx(mr,{className:"w-5 h-5 text-gray-400"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:X.length}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.history")})]})]})})})]}),a.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:o===-1?"unassigned":o||"",onChange:ee=>{const z=ee.target.value;l(z==="unassigned"?-1:z===""?null:Number(z))},children:[a.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),a.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),B?.map(ee=>a.jsx("option",{value:ee.id,children:ee.name},ee.id))]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c,onChange:ee=>u(ee.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allStatus")}),a.jsx("option",{value:"pending",children:t("queue.status.pending")}),a.jsx("option",{value:"printing",children:t("queue.status.printing")}),a.jsx("option",{value:"completed",children:t("queue.status.completed")}),a.jsx("option",{value:"failed",children:t("queue.status.failed")}),a.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),a.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),Fe.length>0&&a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:d,onChange:ee=>h(ee.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allLocations")}),Fe.map(ee=>a.jsx("option",{value:ee,children:ee},ee))]}),a.jsx("div",{className:"flex-1"}),X.length>0&&a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>m(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[a.jsx(ln,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),oe?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):Q?.length===0?a.jsxs(St,{className:"p-12 text-center border-dashed",children:[a.jsx(ti,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),a.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),a.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):a.jsxs("div",{className:"space-y-8",children:[Y.length>0&&a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-4 flex items-center gap-2",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),a.jsx("div",{className:"space-y-3",children:Y.map(ee=>a.jsx(JP,{item:ee,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>N({type:"stop",item:ee}),onRequeue:()=>{},onStart:()=>{},timeFormat:K,hasPermission:r,canModify:s,printerState:ee.printer_id?re[ee.printer_id]:null,t},ee.id))})]}),Ve.length>0&&a.jsxs("div",{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(tr,{className:"w-5 h-5 text-yellow-400"}),t("queue.sections.queued"),a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:Ve.length}),")"]}),a.jsx("span",{className:"text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-3 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:F,onChange:ee=>H(ee.target.value),children:[a.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),a.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>$(!D),title:t(D?"common.ascending":"common.descending"),className:"px-2",children:D?a.jsx(Hg,{className:"w-4 h-4"}):a.jsx(X0,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-bambu-dark rounded-lg",children:[a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:V,className:"flex items-center gap-2",children:[T.length===Ve.length&&Ve.length>0?a.jsx(Xs,{className:"w-4 h-4 text-bambu-green"}):a.jsx(ul,{className:"w-4 h-4"}),T.length===Ve.length&&Ve.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),T.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:T.length})}),a.jsx("div",{className:"h-4 w-px bg-bambu-dark-tertiary"}),a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:()=>k(!0),className:"flex items-center gap-2 text-bambu-green hover:text-bambu-green-light",disabled:!i("queue:update_own","queue:update_all"),title:i("queue:update_own","queue:update_all")?void 0:t("queue.permissions.noEditItems"),children:[a.jsx(Ji,{className:"w-4 h-4"}),t("queue.bulkEdit.editSelected")]}),a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:()=>se.mutate(T),className:"flex items-center gap-2 text-red-400 hover:text-red-300",disabled:se.isPending||!i("queue:delete_own","queue:delete_all"),title:i("queue:delete_own","queue:delete_all")?void 0:t("queue.permissions.noCancelItems"),children:[a.jsx(Lt,{className:"w-4 h-4"}),t("queue.bulkEdit.cancelSelected")]})]})]}),a.jsx(Xre,{sensors:G,collisionDetection:Lre,onDragEnd:pe,children:a.jsx(Zre,{items:Ve.map(ee=>ee.id),strategy:iKe,children:a.jsx("div",{className:"space-y-3",children:Ve.map((ee,z)=>a.jsx(JP,{item:ee,position:z+1,onEdit:()=>y(ee),onCancel:()=>N({type:"cancel",item:ee}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>me.mutate(ee.id),timeFormat:K,isSelected:T.includes(ee.id),onToggleSelect:()=>ke(ee.id),hasPermission:r,canModify:s,t},ee.id))})})})]}),X.length>0&&a.jsxs("div",{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(mr,{className:"w-5 h-5 text-bambu-gray"}),t("queue.sections.history"),a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:X.length}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-3 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:R,onChange:ee=>C(ee.target.value),children:[a.jsx("option",{value:"date",children:t("queue.sort.byDate")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>U(!P),title:t(P?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:P?a.jsx(Hg,{className:"w-4 h-4"}):a.jsx(X0,{className:"w-4 h-4"})})]})]}),a.jsx("div",{className:"space-y-3",children:X.slice(0,20).map((ee,z)=>a.jsx(JP,{item:ee,position:z+1,onEdit:()=>{},onCancel:()=>{},onRemove:()=>N({type:"remove",item:ee}),onStop:()=>{},onRequeue:()=>v(ee),onStart:()=>{},timeFormat:K,hasPermission:r,canModify:s,t},ee.id))})]})]}),b&&a.jsx(Ou,{mode:"edit-queue-item",archiveId:b.archive_id??void 0,libraryFileId:b.library_file_id??void 0,archiveName:b.archive_name||b.library_file_name||`File #${b.archive_id||b.library_file_id}`,queueItem:b,onClose:()=>y(null)}),x&&a.jsx(Ou,{mode:"add-to-queue",archiveId:x.archive_id??void 0,libraryFileId:x.library_file_id??void 0,archiveName:x.archive_name||x.library_file_name||`File #${x.archive_id||x.library_file_id}`,onClose:()=>v(null)}),S&&a.jsx(er,{title:S.type==="cancel"?t("queue.confirm.cancelTitle"):S.type==="stop"?t("queue.confirm.stopTitle"):t("queue.confirm.removeTitle"),message:S.type==="cancel"?t("queue.confirm.cancelMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):S.type==="stop"?t("queue.confirm.stopMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):t("queue.confirm.removeMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisItem")}),confirmText:S.type==="cancel"?t("queue.confirm.cancelButton"):S.type==="stop"?t("queue.confirm.stopButton"):t("common.remove"),variant:"danger",onConfirm:()=>{S.type==="cancel"?W.mutate(S.item.id):S.type==="stop"?ne.mutate(S.item.id):J.mutate(S.item.id),N(null)},onCancel:()=>N(null)}),p&&a.jsx(er,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:X.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{de.mutate(),m(!1)},onCancel:()=>m(!1)}),A&&a.jsx(bKe,{selectedCount:T.length,printers:B?.map(ee=>({id:ee.id,name:ee.name}))||[],onSave:ee=>{Object.keys(ee).length>0&&Re.mutate({item_ids:T,...ee})},onClose:()=>k(!1),isSaving:Re.isPending,t})]})}function yKe({printDates:t,months:e=3}){const n=_.useRef(null),[r,i]=_.useState(0);_.useEffect(()=>{const S=n.current;if(!S)return;const N=new ResizeObserver(T=>{const M=T[0]?.contentRect.width||0;i(M)});return N.observe(S),()=>N.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=_.useMemo(()=>{const S={};t.forEach(U=>{const F=U.split("T")[0];S[F]=(S[F]||0)+1});const N=new Date,T=new Date(N);T.setMonth(T.getMonth()-e),T.setDate(T.getDate()-T.getDay());const M=[],A=[];let k=[],R=-1;const C=new Date(T);let P=0;for(;C<=N;)C.getDay()===0&&k.length>0&&(M.push(k),k=[],P++),C.getMonth()!==R&&(A.push({month:C.toLocaleDateString("en-US",{month:"short"}),weekIndex:P}),R=C.getMonth()),k.push(new Date(C)),C.setDate(C.getDate()+1);return k.length>0&&M.push(k),{weeks:M,monthLabels:A,printCounts:S}},[t,e]),c=Math.max(1,...Object.values(l)),u=S=>{if(S===0)return"bg-bambu-dark";const N=S/c;return N<=.25?"bg-bambu-green/30":N<=.5?"bg-bambu-green/50":N<=.75?"bg-bambu-green/75":"bg-bambu-green"},d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=s.length,p=32,m=2,b=r-p-16,y=h>0?Math.floor((b-(h-1)*m)/h):12,x=Math.max(8,Math.min(20,y)),v=x<=10?10:12;return a.jsx("div",{ref:n,className:"w-full flex justify-center",children:r>0&&a.jsxs("div",{children:[a.jsx("div",{className:"flex mb-1",style:{marginLeft:p+4},children:o.map(({month:S,weekIndex:N},T)=>a.jsx("div",{className:"text-bambu-gray",style:{fontSize:v,marginLeft:T===0?0:`${(N-(o[T-1]?.weekIndex||0))*(x+m)-24}px`},children:S},T))}),a.jsxs("div",{className:"flex",style:{gap:m},children:[a.jsx("div",{className:"flex flex-col",style:{gap:m,marginRight:4,width:p},children:d.map((S,N)=>a.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:x,fontSize:v,visibility:N%2===1?"visible":"hidden"},children:S},S))}),s.map((S,N)=>a.jsx("div",{className:"flex flex-col",style:{gap:m},children:[0,1,2,3,4,5,6].map(T=>{const M=S.find(C=>C.getDay()===T);if(!M)return a.jsx("div",{style:{width:x,height:x}},T);const A=M.toISOString().split("T")[0],k=l[A]||0,R=A===new Date().toISOString().split("T")[0];return a.jsx("div",{className:`rounded-sm ${u(k)} ${R?"ring-1 ring-white":""}`,style:{width:x,height:x},title:`${M.toLocaleDateString()}: ${k} print${k!==1?"s":""}`},T)})},N))]}),a.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:v},children:[a.jsx("span",{children:"Less"}),a.jsxs("div",{className:"flex",style:{gap:m},children:[a.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:x,height:x}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:x,height:x}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:x,height:x}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:x,height:x}}),a.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:x,height:x}})]}),a.jsx("span",{children:"More"})]})]})})}const x1=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"];function vKe(t){const e=new Date;switch(t){case"7d":return new Date(e.getTime()-10080*60*1e3);case"30d":return new Date(e.getTime()-720*60*60*1e3);case"90d":return new Date(e.getTime()-2160*60*60*1e3);case"365d":return new Date(e.getTime()-365*24*60*60*1e3);case"all":return new Date(0)}}function wKe({archives:t,currency:e="$"}){const[n,r]=_.useState("30d"),i=_.useMemo(()=>{const m=vKe(n);return t.filter(b=>(zi(b.completed_at||b.created_at)||new Date(0))>=m)},[t,n]),s=_.useMemo(()=>{const m=new Map;return i.forEach(b=>{const y=zi(b.completed_at||b.created_at)||new Date,x=`${y.getFullYear()}-${String(y.getMonth()+1).padStart(2,"0")}-${String(y.getDate()).padStart(2,"0")}`,v=m.get(x)||{date:x,filament:0,cost:0,prints:0};v.filament+=b.filament_used_grams||0,v.cost+=b.cost||0,v.prints+=b.quantity||1,m.set(x,v)}),Array.from(m.values()).sort((b,y)=>b.date.localeCompare(y.date)).map(b=>({...b,dateLabel:new Date(b.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[i]),o=_.useMemo(()=>{if(n==="7d"||n==="30d")return s;const m=new Map;return i.forEach(b=>{const y=zi(b.completed_at||b.created_at)||new Date,x=new Date(y);x.setDate(y.getDate()-y.getDay());const v=`${x.getFullYear()}-${String(x.getMonth()+1).padStart(2,"0")}-${String(x.getDate()).padStart(2,"0")}`,S=m.get(v)||{week:v,filament:0,cost:0,prints:0};S.filament+=b.filament_used_grams||0,S.cost+=b.cost||0,S.prints+=b.quantity||1,m.set(v,S)}),Array.from(m.values()).sort((b,y)=>b.week.localeCompare(y.week)).map(b=>({date:b.week,dateLabel:`Week of ${new Date(b.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...b}))},[i,s,n]),l=_.useMemo(()=>{const m=new Map;return i.forEach(b=>{const x=(b.filament_type||"Unknown").split(", ");x.forEach(v=>{const S=(b.filament_used_grams||0)/x.length;m.set(v,(m.get(v)||0)+S)})}),Array.from(m.entries()).map(([b,y])=>({name:b,value:Math.round(y)})).sort((b,y)=>y.value-b.value)},[i]),c=_.useMemo(()=>{const m=new Date,b=[];for(let y=5;y>=0;y--){const x=new Date(m.getFullYear(),m.getMonth()-y,1),v=new Date(m.getFullYear(),m.getMonth()-y+1,0),S=x.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),N=t.filter(T=>{const M=zi(T.completed_at||T.created_at)||new Date(0);return M>=x&&M<=v});b.push({month:S,filament:Math.round(N.reduce((T,M)=>T+(M.filament_used_grams||0),0)),cost:N.reduce((T,M)=>T+(M.cost||0),0),prints:N.reduce((T,M)=>T+(M.quantity||1),0)})}return b},[t]),u=n==="7d"||n==="30d"?s:o,d=i.reduce((m,b)=>m+(b.filament_used_grams||0),0),h=i.reduce((m,b)=>m+(b.cost||0),0),p=i.reduce((m,b)=>m+(b.quantity||1),0);return a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:"Filament Usage Trends"}),a.jsx("div",{className:"flex gap-1 bg-bambu-dark rounded-lg p-1",children:["7d","30d","90d","365d","all"].map(m=>a.jsx("button",{onClick:()=>r(m),className:`px-3 py-1 text-sm rounded-md transition-colors ${n===m?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:m==="all"?"All":m.replace("d","D")},m))})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Period Filament"}),a.jsxs("p",{className:"text-2xl font-bold text-white",children:[(d/1e3).toFixed(2),"kg"]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[d.toFixed(0),"g total"]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Period Cost"}),a.jsxs("p",{className:"text-2xl font-bold text-white",children:[e,h.toFixed(2)]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[p," prints"]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Avg per Print"}),a.jsxs("p",{className:"text-2xl font-bold text-white",children:[p>0?(d/p).toFixed(0):0,"g"]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,p>0?(h/p).toFixed(2):"0.00"," avg"]})]})]}),u.length>0?a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Usage Over Time"}),a.jsx(F1,{width:"100%",height:250,children:a.jsxs(i8e,{data:u,children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),a.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),a.jsx(lN,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(uN,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),a.jsx(dN,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:m=>`${m}g`}),a.jsx(z1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:m=>[`${Number(m??0).toFixed(0)}g`,"Filament"]}),a.jsx(bee,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):a.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:"No data for selected time range"}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"By Filament Type"}),l.length>0?a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(F1,{width:160,height:160,children:a.jsxs(n8e,{children:[a.jsx(BJ,{data:l,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:l.map((m,b)=>a.jsx(yv,{fill:x1[b%x1.length]},`cell-${b}`))}),a.jsx(z1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:m=>[`${m??0}g`,"Usage"]})]})}),a.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:l.map((m,b)=>{const y=l.reduce((v,S)=>v+S.value,0),x=y>0?(m.value/y*100).toFixed(0):0;return a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:x1[b%x1.length]}}),a.jsx("span",{className:"text-white truncate flex-1",children:m.name}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[x,"%"]})]},m.name)})})]}):a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:"No filament data"})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Monthly Comparison"}),a.jsx(F1,{width:"100%",height:200,children:a.jsxs(VBe,{data:c,children:[a.jsx(lN,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(uN,{dataKey:"month",stroke:"#9ca3af",tick:{fontSize:12}}),a.jsx(dN,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:m=>`${m}g`}),a.jsx(z1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:(m,b)=>[b==="filament"?`${m??0}g`:b==="cost"?`${e}${Number(m??0).toFixed(2)}`:m??0,b==="filament"?"Filament":b==="cost"?"Cost":"Prints"]}),a.jsx(eL,{}),a.jsx(WJ,{dataKey:"filament",name:"Filament (g)",fill:"#00ae42",radius:[4,4,0,0]})]})})]})]})]})}function _Ke({id:t,title:e,component:n,isHidden:r,size:i,onToggleVisibility:s,onToggleSize:o}){const{attributes:l,listeners:c,setNodeRef:u,transform:d,transition:h,isDragging:p}=eie({id:t}),m={transform:xb.Transform.toString(d),transition:h,opacity:p?.5:1};return r?null:a.jsxs("div",{ref:u,style:{...m,gridColumn:`span ${i}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${p?"ring-2 ring-bambu-green shadow-lg":""}`,children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{...l,...c,className:"cursor-grab active:cursor-grabbing p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Drag to reorder",children:a.jsx(Vg,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),a.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:`Size: ${i===1?"1/4":i===2?"1/2":"Full"} - Click to cycle`,children:i===4?a.jsx(VR,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):a.jsx($R,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),a.jsx("button",{onClick:s,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:a.jsx(bk,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),a.jsx("div",{className:"p-4",children:typeof n=="function"?n(i):n})]})}function SKe({widgets:t,storageKey:e,columns:n=4,hideControls:r=!1,onResetLayout:i,renderControls:s}){const o=()=>{const T={};return t.forEach(M=>{T[M.id]=M.defaultSize||4}),T},[l,c]=_.useState(()=>{const T=localStorage.getItem(e);if(T)try{const M=JSON.parse(T);return M.sizes||(M.sizes=o()),M}catch{}return{order:t.map(M=>M.id),hidden:t.filter(M=>M.defaultVisible===!1).map(M=>M.id),sizes:o()}}),[u,d]=_.useState(!1);_.useEffect(()=>{const T=()=>d(M=>!M);return window.addEventListener("toggle-hidden-panel",T),()=>window.removeEventListener("toggle-hidden-panel",T)},[]),_.useEffect(()=>{localStorage.setItem(e,JSON.stringify(l))},[l,e]),_.useEffect(()=>{const M=t.map(A=>A.id).filter(A=>!l.order.includes(A));M.length>0&&c(A=>({...A,order:[...A.order,...M]}))},[t,l.order]);const h=jre(sk(QM,{activationConstraint:{distance:8}}),sk(YM,{coordinateGetter:tie})),p=T=>{const{active:M,over:A}=T;A&&M.id!==A.id&&c(k=>{const R=k.order.indexOf(M.id),C=k.order.indexOf(A.id);return{...k,order:e2(k.order,R,C)}})},m=T=>{c(M=>({...M,hidden:M.hidden.includes(T)?M.hidden.filter(A=>A!==T):[...M.hidden,T]}))},b=T=>{c(M=>{const A=M.sizes[T]||4,k=A===1?2:A===2?4:1;return{...M,sizes:{...M.sizes,[T]:k}}})},y=()=>{const T={order:t.map(M=>M.id),hidden:t.filter(M=>M.defaultVisible===!1).map(M=>M.id),sizes:o()};c(T),i?.()},x=l.order.map(T=>t.find(M=>M.id===T)).filter(Boolean),v=x.filter(T=>!l.hidden.includes(T.id)),S=x.filter(T=>l.hidden.includes(T.id)),N=s?.({hiddenCount:S.length,showHiddenPanel:u,setShowHiddenPanel:d,resetLayout:y});return a.jsxs("div",{className:"space-y-4",children:[N,!r&&!s&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:y,children:[a.jsx(Bu,{className:"w-4 h-4"}),"Reset Layout"]}),S.length>0&&a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>d(!u),children:[a.jsx(gc,{className:"w-4 h-4"}),S.length," Hidden"]})]}),u&&S.length>0&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(T=>a.jsxs("button",{onClick:()=>m(T.id),className:"px-3 py-1.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded-lg text-sm text-white transition-colors flex items-center gap-2",children:[a.jsx(gc,{className:"w-3 h-3"}),T.title]},T.id))})]}),a.jsx(Xre,{sensors:h,collisionDetection:Lre,onDragEnd:p,children:a.jsx(Zre,{items:v.map(T=>T.id),strategy:kF,children:a.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${n}, minmax(0, 1fr))`},children:v.map(T=>a.jsx(_Ke,{id:T.id,title:T.title,component:T.component,isHidden:l.hidden.includes(T.id),size:l.sizes[T.id]||2,onToggleVisibility:()=>m(T.id),onToggleSize:()=>b(T.id)},T.id))})})}),v.length===0&&a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx("p",{children:"All widgets are hidden."}),a.jsx(Ne,{className:"mt-4",onClick:y,children:"Reset Layout"})]})]})}function NKe({stats:t,currency:e,t:n}){return a.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:a.jsx(bc,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.totalPrints")}),a.jsx("p",{className:"text-xl font-bold text-white",children:t?.total_prints||0})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-blue-400",children:a.jsx(tr,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.printTime")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_print_time_hours.toFixed(1)||0,"h"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-orange-400",children:a.jsx(bc,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentUsed")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[((t?.total_filament_grams||0)/1e3).toFixed(2),"kg"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-green-400",children:a.jsx(Nj,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentCost")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_cost.toFixed(2)||"0.00"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-400",children:a.jsx(Ah,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyUsed")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_energy_kwh.toFixed(2)||"0.00"," kWh"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-500",children:a.jsx(Nj,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyCost")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_energy_cost.toFixed(2)||"0.00"]})]})]})]})}function kKe({stats:t,printerMap:e,size:n=1,t:r}){const i=t?.total_prints?Math.round(t.successful_prints/t.total_prints*100):0,s=n===1?112:n===2?128:144,o=s/2-8,l=o*2*Math.PI;return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:s,height:s},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${i/100*l} ${l}`})]}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i,"%"]})})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(mr,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Zi,{className:"w-4 h-4 text-status-error flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.failed_prints||0})]})]}),n>=2&&t?.prints_by_printer&&Object.keys(t.prints_by_printer).length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),a.jsx("div",{className:`grid gap-x-6 gap-y-1 ${n===4?"grid-cols-3":"grid-cols-2"}`,style:{width:"fit-content"},children:Object.entries(t.prints_by_printer).map(([c,u])=>a.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(c)||`${r("common.printer")} ${c}`}),a.jsx("span",{className:"text-white font-medium",children:u})]},c))})]})]})]})}function MKe({stats:t,printerMap:e,size:n=1,t:r}){const i=t?.average_time_accuracy;if(i==null)return a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,i))-50)/100*100,c=(y=>y>=95&&y<=105?"#00ae42":y>105?"#3b82f6":"#f97316")(i),u=i-100,d=n===1?112:n===2?128:144,h=d/2-8,p=h*2*Math.PI,m=n===1?3:n===2?6:999,b=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,m):[];return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:d,height:d},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:d/2,cy:d/2,r:h,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:d/2,cy:d/2,r:h,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*p} ${p}`})]}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),a.jsxs("span",{className:`text-xs ${u>=0?"text-blue-400":"text-orange-400"}`,children:[u>=0?"+":"",u.toFixed(0),"%"]})]})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[a.jsx($W,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{children:r("stats.perfectEstimate")})]}),b.length>0&&a.jsx("div",{className:`mt-2 ${n===4?"grid grid-cols-3 gap-x-6 gap-y-1":n===2?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,style:{width:"fit-content"},children:b.map(([y,x])=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(y)||`${r("common.printer")} ${y}`}),a.jsxs("span",{className:`font-medium ${x>=95&&x<=105?"text-status-ok":x>105?"text-blue-400":"text-status-warning"}`,children:[x.toFixed(0),"%"]})]},y))})]})]})}function EKe({stats:t,size:e=1,t:n}){if(!t?.prints_by_filament_type||Object.keys(t.prints_by_filament_type).length===0)return a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noFilamentData")});const r=Object.entries(t.prints_by_filament_type).sort(([,l],[,c])=>c-l),i=e===1?5:e===2?8:999,s=r.slice(0,i),o=r.length>i;return e===4&&s.length>4?a.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-white truncate max-w-[120px]",children:l}),a.jsx("span",{className:"text-bambu-gray",children:c})]}),a.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:a.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)})}):a.jsxs("div",{className:"space-y-3",children:[s.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-white",children:l}),a.jsxs("span",{className:"text-bambu-gray",children:[c," ",n("common.prints")]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:a.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)}),o&&a.jsx("p",{className:"text-xs text-bambu-gray text-center pt-1",children:n("common.more",{count:r.length-i})})]})}function TKe({printDates:t,size:e=2}){const n=e===1?3:e===2?6:12;return a.jsx(yKe,{printDates:t,months:n})}function AKe({stats:t,printerMap:e,t:n}){return!t?.prints_by_printer||Object.keys(t.prints_by_printer).length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrinterData")}):a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:Object.entries(t.prints_by_printer).map(([r,i])=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("div",{className:"p-2 bg-bambu-dark-tertiary rounded-lg",children:a.jsx(jr,{className:"w-4 h-4 text-bambu-green"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium text-sm",children:e.get(r)||`${n("common.printer")} ${r}`}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[i," ",n("common.prints")]})]})]},r))})}function CKe({archives:t,currency:e,t:n}){return!t||t.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrintData")}):a.jsx(wKe,{archives:t,currency:e})}function PKe({size:t=1,t:e}){const{data:n,isLoading:r}=it({queryKey:["failureAnalysis"],queryFn:()=>ae.getFailureAnalysis({days:30})});if(r)return a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!n||n.total_prints===0)return a.jsx("p",{className:"text-bambu-gray text-center py-4",children:e("stats.noPrintDataLast30Days")});const i=t===1?5:t===2?8:999,s=Object.entries(n.failures_by_reason).sort(([,c],[,u])=>u-c),o=s.slice(0,i),l=s.length>i;return a.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[a.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[a.jsx("div",{className:"flex items-center gap-4",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(En,{className:`w-5 h-5 ${n.failure_rate>20?"text-status-error":n.failure_rate>10?"text-status-warning":"text-status-ok"}`}),a.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[n.failure_rate.toFixed(1),"%"]})]})}),a.jsx("div",{className:"text-sm text-bambu-gray mt-1",children:e("stats.failedPrintsCount",{failed:n.failed_prints,total:n.total_prints})}),n.trend&&n.trend.length>=2&&a.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(GW,{className:`w-4 h-4 ${n.trend[n.trend.length-1].failure_rate0&&a.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?e("stats.failureReasons"):e("stats.topFailureReasons")}),a.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:o.map(([c,u])=>a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:c||e("common.unknown")}),a.jsx("span",{className:"text-bambu-gray ml-2",children:u})]},c))}),l&&a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:e("common.more",{count:s.length-i})})]})]})}function jKe(){const{t}=Yt(),{showToast:e}=Tn(),{hasPermission:n}=Ir(),[r,i]=_.useState(!1),[s,o]=_.useState(!1),[l,c]=_.useState(0),[u,d]=_.useState(0),[h,p]=_.useState(!1);_.useEffect(()=>{const C=()=>{try{const U=localStorage.getItem("bambusy-dashboard-layout");if(U){const F=JSON.parse(U);d(F.hidden?.length||0)}}catch{d(0)}};C(),window.addEventListener("storage",C);const P=setInterval(C,500);return()=>{window.removeEventListener("storage",C),clearInterval(P)}},[l]);const{data:m,isLoading:b,refetch:y}=it({queryKey:["archiveStats"],queryFn:ae.getArchiveStats}),{data:x}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:v}=it({queryKey:["archives"],queryFn:()=>ae.getArchives(void 0,void 0,1e3,0)}),{data:S}=it({queryKey:["settings"],queryFn:ae.getSettings}),N=async C=>{o(!1),i(!0);try{const{blob:P,filename:U}=await ae.exportStats({format:C,days:90}),F=URL.createObjectURL(P),H=document.createElement("a");H.href=F,H.download=U,H.click(),URL.revokeObjectURL(F),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{i(!1)}},T=async()=>{p(!0);try{const C=await ae.recalculateCosts();await y(),e(t("stats.recalculatedCosts",{count:C.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{p(!1)}},M=S?.currency||"$",A=new Map(x?.map(C=>[String(C.id),C.name])||[]),k=v?.map(C=>C.created_at)||[];if(b)return a.jsx("div",{className:"p-4 md:p-8",children:a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const R=[{id:"quick-stats",title:t("stats.quickStats"),component:a.jsx(NKe,{stats:m,currency:M,t}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:C=>a.jsx(kKe,{stats:m,printerMap:A,size:C,t}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:C=>a.jsx(MKe,{stats:m,printerMap:A,size:C,t}),defaultSize:1},{id:"filament-types",title:t("stats.filamentTypes"),component:C=>a.jsx(EKe,{stats:m,size:C,t}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:C=>a.jsx(PKe,{size:C,t}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:C=>a.jsx(TKe,{printDates:k,size:C}),defaultSize:2},{id:"prints-by-printer",title:t("stats.printsByPrinter"),component:a.jsx(AKe,{stats:m,printerMap:A,t}),defaultSize:2},{id:"filament-trends",title:t("stats.filamentTrends"),component:a.jsx(CKe,{archives:v||[],currency:M,t}),defaultSize:4}];return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("stats.title")}),a.jsx("p",{className:"text-bambu-gray",children:t("stats.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&a.jsxs(Ne,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[a.jsx(gc,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),a.jsxs(Ne,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout"),c(C=>C+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[a.jsx(Bu,{className:"w-4 h-4"}),t("stats.resetLayout")]}),a.jsxs(Ne,{variant:"secondary",onClick:T,disabled:h||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[h?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Zce,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),a.jsxs("div",{className:"relative",children:[a.jsxs(Ne,{variant:"secondary",onClick:()=>o(!s),disabled:r,children:[r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(eS,{className:"w-4 h-4"}),t("stats.exportStats")]}),s&&a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20",children:[a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg",onClick:()=>N("csv"),children:[a.jsx(ys,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg",onClick:()=>N("xlsx"),children:[a.jsx(eS,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]})]})]}),a.jsx(SKe,{widgets:R,storageKey:"bambusy-dashboard-layout",hideControls:!0},l)]})}function DKe({plug:t,onEdit:e}){const{t:n}=Yt(),r=an(),{showToast:i}=Tn(),[s,o]=_.useState(!1),[l,c]=_.useState(!1),[u,d]=_.useState(!1),[h,p]=_.useState(!1),{data:m,isLoading:b}=it({queryKey:["smart-plug-status",t.id],queryFn:()=>ae.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:y}=it({queryKey:["printers"],queryFn:ae.getPrinters}),x=y?.find(P=>P.id===t.printer_id),v=dt({mutationFn:P=>ae.controlSmartPlug(t.id,P),onMutate:async P=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const U=r.getQueryData(["smart-plug-status",t.id]),F=P==="on"?"ON":P==="off"||m?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],H=>({...H,state:F})),{previousStatus:U}},onError:(P,U,F)=>{F?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],F.previousStatus),i(`Failed to turn ${U} "${t.name}"`,"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),S=dt({mutationFn:P=>ae.updateSmartPlug(t.id,P),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),N=dt({mutationFn:()=>ae.deleteSmartPlug(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),T=m?.state==="ON",M=t.plug_type==="mqtt"&&m?.energy?.power!==null&&m?.energy?.power!==void 0,A=(m?.reachable??!1)||M,k=v.isPending,C=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const P=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${P}/`:`http://${P}/`})();return a.jsxs(a.Fragment,{children:[a.jsx(St,{className:"relative",children:a.jsxs(Et,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?A?"bg-teal-500/20":"bg-red-500/20":A?T?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?a.jsx(GR,{className:`w-5 h-5 ${A?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?a.jsx(Hy,{className:`w-5 h-5 ${A?T?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):a.jsx(sl,{className:`w-5 h-5 ${A?T?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",title:t.plug_type==="mqtt"?t.mqtt_topic??void 0:t.plug_type==="homeassistant"?t.ha_entity_id??void 0:t.ip_address??void 0,children:t.plug_type==="mqtt"?t.mqtt_topic:t.plug_type==="homeassistant"?t.ha_entity_id:t.ip_address})]})]}),a.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[b?a.jsx(ct,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?a.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[a.jsx("span",{className:"px-1.5 py-0.5 bg-teal-500/20 text-teal-400 text-[10px] font-medium rounded flex-shrink-0",children:"MQTT"}),A&&a.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),a.jsx("span",{className:A?T?"text-status-ok":"text-bambu-gray":"text-status-error",children:A?m?.state||"?":"Offline"})]}):A?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx(Eg,{className:"w-4 h-4 text-status-ok"}),a.jsx("span",{className:T?"text-status-ok":"text-bambu-gray",children:m?.state||"Unknown"})]}):a.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[a.jsx(fm,{className:"w-4 h-4"}),a.jsx("span",{children:n("smartPlugs.offline")})]}),C&&a.jsxs("a",{href:C,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 px-2 py-0.5 bg-bambu-dark hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white text-xs rounded-full transition-colors",title:n("smartPlugs.openPlugAdminPage"),children:[a.jsx(Xr,{className:"w-3 h-3"}),n("smartPlugs.admin")]})]})]}),x&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Linked to: "}),a.jsx("span",{className:"text-sm text-white",children:x.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded-full",children:[a.jsx(gc,{className:"w-3 h-3"}),"Monitor Only"]}),t.power_alert_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded-full",children:[a.jsx(kg,{className:"w-3 h-3"}),"Alerts"]}),t.schedule_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded-full",children:[a.jsx(ti,{className:"w-3 h-3"}),t.schedule_on_time&&t.schedule_off_time?`${t.schedule_on_time} - ${t.schedule_off_time}`:t.schedule_on_time?`On ${t.schedule_on_time}`:`Off ${t.schedule_off_time}`]})]}),t.plug_type!=="mqtt"&&a.jsxs("div",{className:"flex gap-2 mb-3",children:[a.jsxs(Ne,{size:"sm",variant:T?"primary":"secondary",disabled:!A||k,onClick:()=>c(!0),className:"flex-1",children:[k?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Ju,{className:"w-4 h-4"}),"On"]}),a.jsxs(Ne,{size:"sm",variant:T?"secondary":"primary",disabled:!A||k,onClick:()=>d(!0),className:"flex-1",children:[k?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Nk,{className:"w-4 h-4"}),"Off"]})]}),t.plug_type==="mqtt"&&m?.energy&&a.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[m.energy.power!==null&&m.energy.power!==void 0&&a.jsxs("div",{className:"flex-1 text-center",children:[a.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(m.energy.power),"W"]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Power"})]}),m.energy.today!==null&&m.energy.today!==void 0&&a.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-lg font-semibold text-white",children:m.energy.today.toFixed(2)}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"kWh Today"})]})]}),a.jsxs("button",{onClick:()=>p(!h),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Hu,{className:"w-4 h-4"}),t.plug_type==="mqtt"?"Settings":"Automation Settings"]}),a.jsx("span",{children:h?"-":"+"})]}),h&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(wk,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Show in Switchbar"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:P=>S.mutate({show_in_switchbar:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.plug_type!=="mqtt"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Enabled"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Enable automation for this plug"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.enabled,onChange:P=>S.mutate({enabled:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Auto On"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn on when print starts"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:P=>S.mutate({auto_on:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Auto Off"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn off when print completes (one-shot)"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:P=>S.mutate({auto_off:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.auto_off&&a.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white mb-2",children:"Turn Off Delay Mode"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:()=>S.mutate({off_delay_mode:"time"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="time"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(tr,{className:"w-4 h-4"}),"Time"]}),a.jsxs("button",{onClick:()=>S.mutate({off_delay_mode:"temperature"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="temperature"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(Ek,{className:"w-4 h-4"}),"Temp"]})]})]}),t.off_delay_mode==="time"?a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Delay (minutes)"}),a.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:P=>S.mutate({off_delay_minutes:parseInt(P.target.value)||5}),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"})]}):a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Temperature threshold (C)"}),a.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:P=>S.mutate({off_temp_threshold:parseInt(P.target.value)||70}),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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Turns off when nozzle cools below this temperature"})]})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Ne,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(bg,{className:"w-4 h-4"}),"Edit"]}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(ln,{className:"w-4 h-4"})})]})]})]})}),s&&a.jsx(er,{title:n("smartPlugs.deleteSmartPlug"),message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{N.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&a.jsx(er,{title:n("smartPlugs.turnOnSmartPlug"),message:`Are you sure you want to turn on "${t.name}"?`,confirmText:n("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{v.mutate("on"),c(!1)},onCancel:()=>c(!1)}),u&&a.jsx(er,{title:n("smartPlugs.turnOffSmartPlug"),message:`Are you sure you want to turn off "${t.name}"? This will cut power to the connected device.`,confirmText:n("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{v.mutate("off"),d(!1)},onCancel:()=>d(!1)})]})}function RKe({plug:t,onClose:e}){const{t:n}=Yt(),r=an(),i=!!t,[s,o]=_.useState(t?.plug_type||"tasmota"),[l,c]=_.useState(t?.name||""),[u,d]=_.useState(t?.ip_address||""),[h,p]=_.useState(t?.username||""),[m,b]=_.useState(t?.password||""),[y,x]=_.useState(t?.ha_entity_id||""),[v,S]=_.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[N,T]=_.useState(t?.mqtt_power_path||""),[M,A]=_.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[k,R]=_.useState(t?.mqtt_energy_topic||""),[C,P]=_.useState(t?.mqtt_energy_path||""),[U,F]=_.useState((t?.mqtt_energy_multiplier??1).toString()),[H,D]=_.useState(t?.mqtt_state_topic||""),[$,G]=_.useState(t?.mqtt_state_path||""),[I,K]=_.useState(t?.mqtt_state_on_value||""),[Q,oe]=_.useState(t?.ha_power_entity||""),[B,W]=_.useState(t?.ha_energy_today_entity||""),[J,ne]=_.useState(t?.ha_energy_total_entity||""),[me,fe]=_.useState(""),[de,Re]=_.useState(""),[se,ke]=_.useState(!1),Fe=_.useRef(null),[ce,Ve]=_.useState(""),[V,Y]=_.useState(!1),ue=_.useRef(null),[q,re]=_.useState(""),[X,le]=_.useState(!1),pe=_.useRef(null),[ee,z]=_.useState(""),[O,Z]=_.useState(!1),ge=_.useRef(null),[Ce,_e]=_.useState(t?.printer_id||null),[Te,we]=_.useState(null),[$e,Ge]=_.useState(null),[ze,be]=_.useState(t?.power_alert_enabled||!1),[Me,Be]=_.useState(t?.power_alert_high?.toString()||""),[Ae,qe]=_.useState(t?.power_alert_low?.toString()||""),[ve,et]=_.useState(t?.schedule_enabled||!1),[Ee,Ye]=_.useState(t?.schedule_on_time||""),[je,Pe]=_.useState(t?.schedule_off_time||""),[ye,Qe]=_.useState(t?.show_in_switchbar||!1),[yt,at]=_.useState(t?.show_on_printer_card??!0),[Ut,zt]=_.useState(!1),[Ie,vt]=_.useState({scanned:0,total:0}),[Gt,dn]=_.useState([]),fn=_.useRef(null),{data:vn}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:dr}=it({queryKey:["smart-plugs"],queryFn:ae.getSmartPlugs}),{data:ar}=it({queryKey:["settings"],queryFn:ae.getSettings}),kn=!!(ar?.ha_enabled&&ar?.ha_url&&ar?.ha_token);_.useEffect(()=>{const Se=setTimeout(()=>{Re(me)},300);return()=>clearTimeout(Se)},[me]),_.useEffect(()=>{const Se=nt=>{Fe.current&&!Fe.current.contains(nt.target)&&ke(!1),ue.current&&!ue.current.contains(nt.target)&&Y(!1),pe.current&&!pe.current.contains(nt.target)&&le(!1),ge.current&&!ge.current.contains(nt.target)&&Z(!1)};return document.addEventListener("mousedown",Se),()=>document.removeEventListener("mousedown",Se)},[]);const{data:Bn,isLoading:Hr,error:Ma}=it({queryKey:["ha-entities",de],queryFn:()=>ae.getHAEntities(de||void 0),enabled:s==="homeassistant"&&kn,retry:!1,staleTime:0}),{data:De}=it({queryKey:["ha-sensor-entities"],queryFn:ae.getHASensorEntities,enabled:s==="homeassistant"&&kn,retry:!1,staleTime:0});_.useEffect(()=>{const Se=nt=>{nt.key==="Escape"&&e()};return window.addEventListener("keydown",Se),()=>{window.removeEventListener("keydown",Se),fn.current&&clearInterval(fn.current)}},[e]);const tt=async()=>{zt(!0),dn([]),vt({scanned:0,total:0}),Ge(null);try{await ae.startTasmotaScan();const Se=async()=>{try{const nt=await ae.getTasmotaScanStatus();vt({scanned:nt.scanned,total:nt.total});const xt=await ae.getDiscoveredTasmotaDevices();dn(xt),nt.running||(zt(!1),fn.current&&(clearInterval(fn.current),fn.current=null))}catch(nt){console.error("Polling error:",nt)}};await Se(),fn.current=setInterval(Se,500)}catch(Se){zt(!1);const nt=Se instanceof Error?Se.message:typeof Se=="string"?Se:JSON.stringify(Se);Ge(nt||"Failed to start scan")}},ht=async()=>{try{await ae.stopTasmotaScan()}catch{}zt(!1),fn.current&&(clearInterval(fn.current),fn.current=null)},mt=Se=>{d(Se.ip_address),c(Se.name),we(null)},ut=dt({mutationFn:()=>ae.testSmartPlugConnection(u,h||null,m||null),onSuccess:Se=>{we(Se),Ge(null),!l&&Se.device_name&&c(Se.device_name)},onError:Se=>{we(null),Ge(Se.message)}}),Dt=dt({mutationFn:Se=>ae.createSmartPlug(Se),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:Se=>{Ge(Se.message)}}),he=dt({mutationFn:Se=>ae.updateSmartPlug(t.id,Se),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:Se=>{Ge(Se.message)}}),Le=vn?.filter(Se=>s==="tasmota"?!dr?.some(xt=>xt.printer_id===Se.id&&xt.id!==t?.id&&xt.plug_type==="tasmota"):!0),Ke=Se=>{if(Se.preventDefault(),Ge(null),!l.trim()){Ge("Name is required");return}if(s==="tasmota"&&!u.trim()){Ge("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!y){Ge("Entity is required for Home Assistant plugs");return}if(s==="mqtt"){const xt=v.trim(),rt=k.trim(),Ct=H.trim();if(!xt&&!rt&&!Ct){Ge("At least one MQTT topic must be configured for power, energy, or state monitoring");return}}const nt={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?u.trim():null,ha_entity_id:s==="homeassistant"?y:null,ha_power_entity:s==="homeassistant"&&Q||null,ha_energy_today_entity:s==="homeassistant"&&B||null,ha_energy_total_entity:s==="homeassistant"&&J||null,mqtt_power_topic:s==="mqtt"&&v.trim()||null,mqtt_power_path:s==="mqtt"&&N.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(M)||1,mqtt_energy_topic:s==="mqtt"&&k.trim()||null,mqtt_energy_path:s==="mqtt"&&C.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat(U)||1,mqtt_state_topic:s==="mqtt"&&H.trim()||null,mqtt_state_path:s==="mqtt"&&$.trim()||null,mqtt_state_on_value:s==="mqtt"&&I.trim()||null,username:s==="tasmota"&&h.trim()||null,password:s==="tasmota"&&m.trim()||null,printer_id:Ce,power_alert_enabled:ze,power_alert_high:Me?parseFloat(Me):null,power_alert_low:Ae?parseFloat(Ae):null,schedule_enabled:ve,schedule_on_time:Ee||null,schedule_off_time:je||null,show_in_switchbar:ye,show_on_printer_card:yt};i?he.mutate(nt):Dt.mutate(nt)},Ue=Dt.isPending||he.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:Se=>Se.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:i?"Edit Smart Plug":"Add Smart Plug"}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Ke,className:"p-6 space-y-4 overflow-y-auto",children:[$e&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:$e}),!i&&a.jsxs("div",{className:"flex gap-2 mb-2",children:[a.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),we(null),Ge(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="tasmota"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(sl,{className:"w-4 h-4"}),"Tasmota"]}),a.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),we(null),Ge(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="homeassistant"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(Hy,{className:"w-4 h-4"}),"HA"]}),a.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),we(null),Ge(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="mqtt"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(GR,{className:"w-4 h-4"}),"MQTT"]})]}),!i&&s==="tasmota"&&a.jsxs("div",{className:"space-y-3",children:[Ut?a.jsxs(Ne,{type:"button",variant:"secondary",onClick:ht,className:"w-full",children:[a.jsx(Lt,{className:"w-4 h-4"}),"Stop Scanning"]}):a.jsxs(Ne,{type:"button",variant:"primary",onClick:tt,className:"w-full",children:[a.jsx(Qi,{className:"w-4 h-4"}),"Discover Tasmota Devices"]}),Ut&&Ie.total>0&&a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:n("smartPlugs.addSmartPlug.scanningNetwork")}),a.jsxs("span",{children:[Ie.scanned," / ",Ie.total]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Ie.scanned/Ie.total*100}%`}})})]}),Gt.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Found ",Gt.length," device(s) - click to select:"]}),a.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:Gt.map(Se=>a.jsxs("button",{type:"button",onClick:()=>mt(Se),className:"w-full flex items-center justify-between p-2 bg-bambu-dark hover:bg-bambu-dark-tertiary rounded-lg transition-colors text-left border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(sl,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:Se.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:Se.ip_address})]})]}),Se.state&&a.jsxs("span",{className:`flex items-center gap-1 text-xs ${Se.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[a.jsx(Ju,{className:"w-3 h-3"}),Se.state]})]},Se.ip_address))})]}),!Ut&&Gt.length===0&&Ie.total>0&&a.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:"No Tasmota devices found on your network"})]}),s==="homeassistant"&&a.jsxs("div",{className:"space-y-3",children:[!kn&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:["Home Assistant is not configured. Set it up in"," ",a.jsx("span",{className:"font-medium",children:"Settings → Network → Home Assistant"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:"Select Entity *"}),a.jsx("select",{disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed opacity-50",children:a.jsx("option",{children:n("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),kn&&a.jsxs(a.Fragment,{children:[Hr&&a.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[a.jsx(ct,{className:"w-5 h-5 animate-spin mr-2"}),"Loading entities..."]}),Ma&&a.jsxs("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:["Failed to load entities: ",Ma.message]}),(()=>{const Se=dr?.filter(rt=>rt.ha_entity_id&&rt.id!==t?.id).map(rt=>rt.ha_entity_id)||[],nt=(Bn||[]).filter(rt=>!Se.includes(rt.entity_id)),xt=Bn?.find(rt=>rt.entity_id===y);return a.jsxs("div",{ref:Fe,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Select Entity *"}),a.jsxs("div",{className:"relative",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:se?me:xt?`${xt.friendly_name} (${xt.entity_id})`:"",onChange:rt=>{fe(rt.target.value),se||ke(!0)},onFocus:()=>{ke(!0),fe("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEntities"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),y&&!se&&a.jsx("button",{type:"button",onClick:()=>{x(""),fe("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Lt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),Hr&&a.jsx(ct,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),se&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[Hr&&a.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Loading..."]}),!Hr&&nt.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:de?`No entities found matching "${de}"`:"No entities available"}),!Hr&&nt.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{x(rt.entity_id),ke(!1),fe(""),l||c(rt.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${rt.entity_id===y?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[a.jsx("span",{children:rt.entity_id}),a.jsx("span",{className:rt.state==="on"?"text-bambu-green":"",children:rt.state})]})]},rt.entity_id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:de?`Searching all entities (${nt.length} found)`:`Showing switch, light, input_boolean (${nt.length} available)`})]})})(),y&&De&&De.length>0&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium mb-1",children:"Energy Monitoring (Optional)"}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Search and select sensors that provide power/energy data."})]}),(()=>{const Se=De.filter(rt=>rt.unit_of_measurement==="W"||rt.unit_of_measurement==="kW"||rt.unit_of_measurement==="mW"),nt=ce?Se.filter(rt=>rt.entity_id.toLowerCase().includes(ce.toLowerCase())||rt.friendly_name.toLowerCase().includes(ce.toLowerCase())):Se,xt=De.find(rt=>rt.entity_id===Q);return a.jsxs("div",{ref:ue,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Power Sensor (W)"}),a.jsxs("div",{className:"relative",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:V?ce:xt?`${xt.friendly_name} (${xt.state} ${xt.unit_of_measurement})`:"",onChange:rt=>{Ve(rt.target.value),V||Y(!0)},onFocus:()=>{Y(!0),Ve("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchPowerSensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),Q&&!V&&a.jsx("button",{type:"button",onClick:()=>{oe(""),Ve("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Lt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),V&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{oe(""),Y(!1),Ve("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),nt.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{oe(rt.entity_id),Y(!1),Ve("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${rt.entity_id===Q?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[rt.entity_id," • ",rt.state," ",rt.unit_of_measurement]})]},rt.entity_id)),nt.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const Se=De.filter(rt=>rt.unit_of_measurement==="kWh"||rt.unit_of_measurement==="Wh"||rt.unit_of_measurement==="MWh"),nt=q?Se.filter(rt=>rt.entity_id.toLowerCase().includes(q.toLowerCase())||rt.friendly_name.toLowerCase().includes(q.toLowerCase())):Se,xt=De.find(rt=>rt.entity_id===B);return a.jsxs("div",{ref:pe,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy Today (kWh)"}),a.jsxs("div",{className:"relative",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:X?q:xt?`${xt.friendly_name} (${xt.state} ${xt.unit_of_measurement})`:"",onChange:rt=>{re(rt.target.value),X||le(!0)},onFocus:()=>{le(!0),re("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),B&&!X&&a.jsx("button",{type:"button",onClick:()=>{W(""),re("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Lt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),X&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{W(""),le(!1),re("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),nt.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{W(rt.entity_id),le(!1),re("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${rt.entity_id===B?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[rt.entity_id," • ",rt.state," ",rt.unit_of_measurement]})]},rt.entity_id)),nt.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const Se=De.filter(rt=>rt.unit_of_measurement==="kWh"||rt.unit_of_measurement==="Wh"||rt.unit_of_measurement==="MWh"),nt=ee?Se.filter(rt=>rt.entity_id.toLowerCase().includes(ee.toLowerCase())||rt.friendly_name.toLowerCase().includes(ee.toLowerCase())):Se,xt=De.find(rt=>rt.entity_id===J);return a.jsxs("div",{ref:ge,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Total Energy (kWh)"}),a.jsxs("div",{className:"relative",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:O?ee:xt?`${xt.friendly_name} (${xt.state} ${xt.unit_of_measurement})`:"",onChange:rt=>{z(rt.target.value),O||Z(!0)},onFocus:()=>{Z(!0),z("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),J&&!O&&a.jsx("button",{type:"button",onClick:()=>{ne(""),z("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Lt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),O&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{ne(""),Z(!1),z("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),nt.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{ne(rt.entity_id),Z(!1),z("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${rt.entity_id===J?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[rt.entity_id," • ",rt.state," ",rt.unit_of_measurement]})]},rt.entity_id)),nt.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})()]})]})]}),s==="mqtt"&&a.jsxs("div",{className:"space-y-3",children:[!ar?.mqtt_broker&&a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:["MQTT broker not configured. Set broker address in"," ",a.jsx("span",{className:"font-medium",children:"Settings → Network → MQTT Publishing"})," ","(you don't need to enable publishing, just fill in the broker details)."]}),ar?.mqtt_broker&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:"Monitor Only"}),a.jsx("p",{className:"text-xs opacity-80",children:"MQTT plugs receive power/energy data via MQTT subscription. On/off control is not available - use your MQTT broker or home automation system."})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-white font-medium text-sm",children:"Power Monitoring"}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),a.jsx("input",{type:"text",value:v,onChange:Se=>S(Se.target.value),placeholder:"zigbee2mqtt/shelly-working-room",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),a.jsx("input",{type:"text",value:N,onChange:Se=>T(Se.target.value),placeholder:"power_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),a.jsx("input",{type:"text",value:M,onChange:Se=>A(Se.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:['JSON path extracts value from JSON payload (e.g., "power_l1"). Leave empty if topic publishes raw numeric values.',a.jsx("br",{}),"Use multiplier 0.001 for mW→W, 1000 for kW→W."]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:["Energy Monitoring ",a.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),a.jsx("input",{type:"text",value:k,onChange:Se=>R(Se.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),a.jsx("input",{type:"text",value:C,onChange:Se=>P(Se.target.value),placeholder:"energy_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),a.jsx("input",{type:"text",value:U,onChange:Se=>F(Se.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",a.jsx("br",{}),"Use multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh."]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:["State Monitoring ",a.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),a.jsx("input",{type:"text",value:H,onChange:Se=>D(Se.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),a.jsx("input",{type:"text",value:$,onChange:Se=>G(Se.target.value),placeholder:"state_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"ON Value"}),a.jsx("input",{type:"text",value:I,onChange:Se=>K(Se.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.mqttStateOnValue"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",a.jsx("br",{}),'ON value: the exact string that means "ON". Leave empty for auto-detect (ON, true, 1).']})]})]})]}),s==="tasmota"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"IP Address *"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:u,onChange:Se=>{d(Se.target.value),we(null)},placeholder:"192.168.1.100",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsxs(Ne,{type:"button",variant:"secondary",onClick:()=>ut.mutate(),disabled:!u.trim()||ut.isPending,children:[ut.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Eg,{className:"w-4 h-4"}),"Test"]})]})]}),s==="tasmota"&&Te&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${Te.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:Te.success?a.jsxs(a.Fragment,{children:[a.jsx(mr,{className:"w-5 h-5"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium",children:"Connected!"}),a.jsxs("p",{className:"text-sm opacity-80",children:[Te.device_name&&`Device: ${Te.device_name} - `,"State: ",Te.state]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx(fm,{className:"w-5 h-5"}),a.jsx("span",{children:n("smartPlugs.addSmartPlug.connectionFailed")})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:l,onChange:Se=>c(Se.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.plugName"),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"})]}),s==="tasmota"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username"}),a.jsx("input",{type:"text",value:h,onChange:Se=>p(Se.target.value),placeholder:"admin",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password"}),a.jsx("input",{type:"password",value:m,onChange:Se=>b(Se.target.value),placeholder:"********",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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:"Leave empty if your Tasmota device doesn't require authentication"})]}),s!=="mqtt"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Link to Printer"}),a.jsxs("select",{value:Ce??"",onChange:Se=>_e(Se.target.value?Number(Se.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:"No printer (manual control only)"}),Le?.map(Se=>a.jsx("option",{value:Se.id,children:Se.name},Se.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Linking enables automatic on/off when prints start/complete"})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(kg,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:"Power Alerts"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ze,onChange:Se=>be(Se.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),ze&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if above (W)"}),a.jsx("input",{type:"number",value:Me,onChange:Se=>Be(Se.target.value),placeholder:"e.g. 200",min:"0",max:"5000",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if below (W)"}),a.jsx("input",{type:"number",value:Ae,onChange:Se=>qe(Se.target.value),placeholder:"e.g. 10",min:"0",max:"5000",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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Get notified when power consumption crosses these thresholds. Leave empty to disable that direction."})]})]}),s!=="mqtt"&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tr,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:"Daily Schedule"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ve,onChange:Se=>et(Se.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),ve&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn On at"}),a.jsx("input",{type:"time",value:Ee,onChange:Se=>Ye(Se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn Off at"}),a.jsx("input",{type:"time",value:je,onChange:Se=>Pe(Se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Automatically turn the plug on/off at these times daily. Leave empty to skip that action."})]})]}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(wk,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:"Show in Switchbar"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ye,onChange:Se=>Qe(Se.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),s==="homeassistant"&&a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(gc,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:"Show on Printer Card"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Display button on printer card"})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:yt,onChange:Se=>at(Se.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Ne,{type:"submit",disabled:Ue,className:"flex-1",children:[Ue?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function $n({checked:t,onChange:e,disabled:n}){const r=i=>{i.preventDefault(),i.stopPropagation(),n||e(!t)};return a.jsx("button",{type:"button",role:"switch","aria-checked":t,disabled:n,onClick:r,className:`relative inline-flex w-11 h-7 md:w-9 md:h-5 rounded-full transition-colors flex-shrink-0 focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${n?"bg-bambu-dark-tertiary/50 cursor-not-allowed opacity-50":t?"bg-bambu-green cursor-pointer":"bg-bambu-dark-tertiary cursor-pointer hover:bg-bambu-dark-tertiary/80"}`,children:a.jsx("span",{className:`pointer-events-none absolute top-[3px] md:top-[2px] left-[3px] md:left-[2px] w-5 h-5 md:w-4 md:h-4 bg-white rounded-full shadow transition-transform duration-200 ease-in-out ${t?"translate-x-4":"translate-x-0"}`})})}const OKe={callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook"};function LKe({provider:t,onEdit:e}){const n=an(),[r,i]=_.useState(!1),[s,o]=_.useState(!1),[l,c]=_.useState(null),{data:u}=it({queryKey:["printers"],queryFn:ae.getPrinters}),d=u?.find(y=>y.id===t.printer_id),h=dt({mutationFn:y=>ae.updateNotificationProvider(t.id,y),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),p=dt({mutationFn:()=>ae.deleteNotificationProvider(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),m=dt({mutationFn:()=>ae.testNotificationProvider(t.id),onSuccess:y=>{c(y),n.invalidateQueries({queryKey:["notification-providers"]})},onError:y=>{c({success:!1,message:y.message})}}),b=y=>y||"";return a.jsxs(a.Fragment,{children:[a.jsx(St,{className:"relative",children:a.jsxs(Et,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:a.jsx(kg,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("h3",{className:"font-medium text-white",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray",children:OKe[t.provider_type]||t.provider_type})]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&a.jsxs("span",{className:"text-xs text-status-ok hidden sm:inline",children:["Last: ",Gg(t.last_success)]}),t.last_error&&t.last_error_at&&(!t.last_success||(zi(t.last_error_at)?.getTime()||0)>(zi(t.last_success)?.getTime()||0))&&a.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:"Error"}),a.jsx($n,{checked:t.enabled,onChange:y=>h.mutate({enabled:y})})]})]}),d&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Printer: "}),a.jsx("span",{className:"text-sm text-white",children:d.name})]}),!d&&!t.printer_id&&a.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"All printers"})}),a.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded",children:"Start"}),t.on_plate_not_empty&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-600/20 text-rose-300 text-xs rounded",children:"Plate Check"}),t.on_print_complete&&a.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:"Complete"}),t.on_print_failed&&a.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:"Failed"}),t.on_print_stopped&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:"Stopped"}),t.on_print_progress&&a.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:"Progress"}),t.on_printer_offline&&a.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:"Offline"}),t.on_printer_error&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:"Error"}),t.on_filament_low&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-500/20 text-cyan-400 text-xs rounded",children:"Low Filament"}),t.on_maintenance_due&&a.jsx("span",{className:"px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded",children:"Maintenance"}),t.on_ams_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-600/20 text-blue-300 text-xs rounded",children:"AMS Humidity"}),t.on_ams_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-600/20 text-orange-300 text-xs rounded",children:"AMS Temp"}),t.on_ams_ht_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-600/20 text-cyan-300 text-xs rounded",children:"AMS-HT Humidity"}),t.on_ams_ht_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-amber-600/20 text-amber-300 text-xs rounded",children:"AMS-HT Temp"}),t.quiet_hours_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[a.jsx(tS,{className:"w-3 h-3"}),"Quiet"]}),t.daily_digest_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[a.jsx(ti,{className:"w-3 h-3"}),"Digest ",t.daily_digest_time]})]}),a.jsx("div",{className:"mb-3",children:a.jsxs(Ne,{size:"sm",variant:"secondary",disabled:m.isPending,onClick:()=>{c(null),m.mutate()},className:"w-full",children:[m.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(kk,{className:"w-4 h-4"}),"Send Test Notification"]})}),l&&a.jsxs("div",{className:`mb-3 p-2 rounded-lg flex items-center gap-2 text-sm ${l.success?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[l.success?a.jsx(mr,{className:"w-4 h-4"}):a.jsx(Zi,{className:"w-4 h-4"}),a.jsx("span",{children:l.message})]}),a.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors border-t border-bambu-dark-tertiary",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Hu,{className:"w-4 h-4"}),"Event Settings"]}),s?a.jsx(zu,{className:"w-4 h-4"}):a.jsx(fr,{className:"w-4 h-4"})]}),s&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Enabled"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Send notifications from this provider"})]}),a.jsx($n,{checked:t.enabled,onChange:y=>h.mutate({enabled:y})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Events"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Started"}),a.jsx($n,{checked:t.on_print_start,onChange:y=>h.mutate({on_print_start:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Plate Not Empty"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Objects detected before print"})]}),a.jsx($n,{checked:t.on_plate_not_empty??!0,onChange:y=>h.mutate({on_plate_not_empty:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Completed"}),a.jsx($n,{checked:t.on_print_complete,onChange:y=>h.mutate({on_print_complete:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Failed"}),a.jsx($n,{checked:t.on_print_failed,onChange:y=>h.mutate({on_print_failed:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Stopped"}),a.jsx($n,{checked:t.on_print_stopped,onChange:y=>h.mutate({on_print_stopped:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Progress Milestones"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify at 25%, 50%, 75%"})]}),a.jsx($n,{checked:t.on_print_progress,onChange:y=>h.mutate({on_print_progress:y})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Printer Status"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Printer Offline"}),a.jsx($n,{checked:t.on_printer_offline,onChange:y=>h.mutate({on_printer_offline:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Printer Error"}),a.jsx($n,{checked:t.on_printer_error,onChange:y=>h.mutate({on_printer_error:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Low Filament"}),a.jsx($n,{checked:t.on_filament_low,onChange:y=>h.mutate({on_filament_low:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Maintenance Due"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify when maintenance is needed"})]}),a.jsx($n,{checked:t.on_maintenance_due??!1,onChange:y=>h.mutate({on_maintenance_due:y})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS Alarms"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS Humidity High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS humidity exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_humidity_high??!1,onChange:y=>h.mutate({on_ams_humidity_high:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS Temperature High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS temperature exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_temperature_high??!1,onChange:y=>h.mutate({on_ams_temperature_high:y})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS-HT Alarms"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS-HT Humidity High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT humidity exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_ht_humidity_high??!1,onChange:y=>h.mutate({on_ams_ht_humidity_high:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS-HT Temperature High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT temperature exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_ht_temperature_high??!1,onChange:y=>h.mutate({on_ams_ht_temperature_high:y})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Queue"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Added"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job added to queue"})]}),a.jsx($n,{checked:t.on_queue_job_added??!1,onChange:y=>h.mutate({on_queue_job_added:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Assigned"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Model-based job assigned to printer"})]}),a.jsx($n,{checked:t.on_queue_job_assigned??!1,onChange:y=>h.mutate({on_queue_job_assigned:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Started"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Queue job started printing"})]}),a.jsx($n,{checked:t.on_queue_job_started??!1,onChange:y=>h.mutate({on_queue_job_started:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Waiting"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job waiting for filament"})]}),a.jsx($n,{checked:t.on_queue_job_waiting??!0,onChange:y=>h.mutate({on_queue_job_waiting:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Skipped"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job skipped (previous failed)"})]}),a.jsx($n,{checked:t.on_queue_job_skipped??!0,onChange:y=>h.mutate({on_queue_job_skipped:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Failed"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job failed to start"})]}),a.jsx($n,{checked:t.on_queue_job_failed??!0,onChange:y=>h.mutate({on_queue_job_failed:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Queue Complete"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"All queue jobs finished"})]}),a.jsx($n,{checked:t.on_queue_completed??!1,onChange:y=>h.mutate({on_queue_completed:y})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tS,{className:"w-4 h-4 text-purple-400"}),a.jsx("p",{className:"text-sm text-white",children:"Quiet Hours"})]}),a.jsx($n,{checked:t.quiet_hours_enabled,onChange:y=>h.mutate({quiet_hours_enabled:y})})]}),t.quiet_hours_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:"No notifications during these hours"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tr,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-white",children:[b(t.quiet_hours_start)||"22:00"," - ",b(t.quiet_hours_end)||"07:00"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change quiet hours"})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ti,{className:"w-4 h-4 text-emerald-400"}),a.jsx("p",{className:"text-sm text-white",children:"Daily Digest"})]}),a.jsx($n,{checked:t.daily_digest_enabled,onChange:y=>h.mutate({daily_digest_enabled:y})})]}),t.daily_digest_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tr,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-white",children:["Send at ",b(t.daily_digest_time)||"08:00"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change digest time"})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Ne,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(bg,{className:"w-4 h-4"}),"Edit"]}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:()=>i(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(ln,{className:"w-4 h-4"})})]})]})]})}),r&&a.jsx(er,{title:"Delete Notification Provider",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{p.mutate(),i(!1)},onCancel:()=>i(!1)})]})}const P9=[{value:"email",label:"Email",description:"SMTP email notifications"},{value:"telegram",label:"Telegram",description:"Notifications via Telegram bot"},{value:"discord",label:"Discord",description:"Send to Discord channel via webhook"},{value:"ntfy",label:"ntfy",description:"Free, self-hostable push notifications"},{value:"pushover",label:"Pushover",description:"Simple, reliable push notifications"},{value:"callmebot",label:"CallMeBot/WhatsApp",description:"Free WhatsApp notifications via CallMeBot"},{value:"webhook",label:"Webhook",description:"Generic HTTP POST to any URL"}];function FKe({provider:t,onClose:e}){const n=an(),r=!!t,[i,s]=_.useState(t?.name||""),[o,l]=_.useState(t?.provider_type||"email"),[c,u]=_.useState(t?.printer_id||null),[d,h]=_.useState(t?.quiet_hours_enabled||!1),[p,m]=_.useState(t?.quiet_hours_start||"22:00"),[b,y]=_.useState(t?.quiet_hours_end||"07:00"),[x,v]=_.useState(t?.daily_digest_enabled||!1),[S,N]=_.useState(t?.daily_digest_time||"08:00"),[T,M]=_.useState(t?.on_print_start??!1),[A,k]=_.useState(t?.on_print_complete??!0),[R,C]=_.useState(t?.on_print_failed??!0),[P,U]=_.useState(t?.on_print_stopped??!0),[F,H]=_.useState(t?.on_print_progress??!1),[D,$]=_.useState(t?.on_printer_offline??!1),[G,I]=_.useState(t?.on_printer_error??!1),[K,Q]=_.useState(t?.on_filament_low??!1),[oe,B]=_.useState(t?.on_maintenance_due??!1),[W,J]=_.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([q,re])=>[q,String(re)])):{}),[ne,me]=_.useState(null),[fe,de]=_.useState(null),{data:Re}=it({queryKey:["printers"],queryFn:ae.getPrinters});_.useEffect(()=>{const q=re=>{re.key==="Escape"&&e()};return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[e]);const se=dt({mutationFn:()=>ae.testNotificationConfig({provider_type:o,config:W}),onSuccess:q=>{me(q),de(null)},onError:q=>{me({success:!1,message:q.message})}}),ke=dt({mutationFn:q=>ae.createNotificationProvider(q),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:q=>{de(q.message)}}),Fe=dt({mutationFn:q=>ae.updateNotificationProvider(t.id,q),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:q=>{de(q.message)}}),ce=q=>{if(q.preventDefault(),de(null),!i.trim()){de("Name is required");return}const re=Y(o);for(const le of re)if(!W[le.key]?.trim()){de(`${le.label} is required`);return}const X={name:i.trim(),provider_type:o,config:W,printer_id:c,quiet_hours_enabled:d,quiet_hours_start:d?p:null,quiet_hours_end:d?b:null,daily_digest_enabled:x,daily_digest_time:x?S:null,on_print_start:T,on_print_complete:A,on_print_failed:R,on_print_stopped:P,on_print_progress:F,on_printer_offline:D,on_printer_error:G,on_filament_low:K,on_maintenance_due:oe};r?Fe.mutate(X):ke.mutate(X)},Ve=ke.isPending||Fe.isPending,V=q=>{switch(q){case"callmebot":return[{key:"phone",label:"Phone Number",placeholder:"+1234567890",type:"text",required:!0},{key:"apikey",label:"API Key",placeholder:"Your CallMeBot API key",type:"text",required:!0}];case"ntfy":return[{key:"server",label:"Server URL",placeholder:"https://ntfy.sh",type:"text",required:!1},{key:"topic",label:"Topic",placeholder:"my-bambuddy",type:"text",required:!0},{key:"auth_token",label:"Auth Token",placeholder:"Optional authentication",type:"password",required:!1}];case"pushover":return[{key:"user_key",label:"User Key",placeholder:"Your Pushover user key",type:"text",required:!0},{key:"app_token",label:"App Token",placeholder:"Your Pushover app token",type:"text",required:!0},{key:"priority",label:"Priority",placeholder:"0 (normal)",type:"number",required:!1}];case"telegram":return[{key:"bot_token",label:"Bot Token",placeholder:"Bot token from @BotFather",type:"password",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"Your chat or group ID",type:"text",required:!0}];case"email":return[{key:"smtp_server",label:"SMTP Server",placeholder:"smtp.gmail.com",type:"text",required:!0},{key:"smtp_port",label:"SMTP Port",placeholder:"587",type:"number",required:!1},{key:"security",label:"Security",type:"select",required:!1,options:[{value:"starttls",label:"STARTTLS (Port 587)"},{value:"ssl",label:"SSL/TLS (Port 465)"},{value:"none",label:"None (Port 25)"}]},{key:"auth_enabled",label:"Authentication",type:"select",required:!1,options:[{value:"true",label:"Enabled"},{value:"false",label:"Disabled"}]},{key:"username",label:"Username",placeholder:"your@email.com",type:"text",required:!1},{key:"password",label:"Password",placeholder:"App password",type:"password",required:!1},{key:"from_email",label:"From Email",placeholder:"your@email.com",type:"text",required:!0},{key:"to_email",label:"To Email",placeholder:"recipient@email.com",type:"text",required:!0}];case"discord":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://discord.com/api/webhooks/...",type:"text",required:!0}];case"webhook":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://example.com/webhook",type:"text",required:!0},{key:"payload_format",label:"Payload Format",type:"select",required:!1,options:[{value:"generic",label:"Generic JSON"},{value:"slack",label:"Slack / Mattermost"}]},{key:"auth_header",label:"Authorization",placeholder:"Bearer token (optional)",type:"password",required:!1},{key:"field_title",label:"Title Field Name",placeholder:"title",type:"text",required:!1,showIf:re=>re.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:re=>re.payload_format!=="slack"}];default:return[]}},Y=q=>V(q).filter(re=>re.required),ue=V(o);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg my-8 max-h-[90vh] overflow-y-auto",onClick:q=>q.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r?"Edit Notification Provider":"Add Notification Provider"}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:ce,className:"p-6 space-y-4",children:[fe&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:fe}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:i,onChange:q=>s(q.target.value),placeholder:"My Notifications",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Provider Type *"}),a.jsx("select",{value:o,onChange:q=>{l(q.target.value),J({}),me(null)},disabled:r,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 disabled:opacity-50",children:P9.map(q=>a.jsx("option",{value:q.value,children:q.label},q.value))}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:P9.find(q=>q.value===o)?.description})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Configuration"}),ue.filter(q=>!("showIf"in q)||q.showIf?.(W)!==!1).map(q=>a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[q.label," ",q.required&&"*"]}),q.type==="select"&&"options"in q&&q.options?a.jsx("select",{value:W[q.key]||q.options[0]?.value||"",onChange:re=>{J({...W,[q.key]:re.target.value}),me(null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:q.options.map(re=>a.jsx("option",{value:re.value,children:re.label},re.value))}):a.jsx("input",{type:q.type,value:W[q.key]||"",onChange:re=>{J({...W,[q.key]:re.target.value}),me(null)},placeholder:q.placeholder,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"})]},q.key))]}),a.jsx("div",{className:"flex gap-2",children:a.jsxs(Ne,{type:"button",variant:"secondary",onClick:()=>{me(null),se.mutate()},disabled:se.isPending||!W[Y(o)[0]?.key],className:"flex-1",children:[se.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(kk,{className:"w-4 h-4"}),"Test Configuration"]})}),ne&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${ne.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:ne.success?a.jsxs(a.Fragment,{children:[a.jsx(mr,{className:"w-5 h-5"}),a.jsx("span",{children:ne.message})]}):a.jsxs(a.Fragment,{children:[a.jsx(Zi,{className:"w-5 h-5"}),a.jsx("span",{children:ne.message})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Printer Filter"}),a.jsxs("select",{value:c??"",onChange:q=>u(q.target.value?Number(q.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:"All printers"}),Re?.map(q=>a.jsx("option",{value:q.id,children:q.name},q.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Only send notifications for events from this printer"})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("label",{className:"text-sm text-white",children:"Quiet Hours (Do Not Disturb)"}),a.jsx($n,{checked:d,onChange:h})]}),d&&a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Start"}),a.jsx("input",{type:"time",value:p,onChange:q=>m(q.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"End"}),a.jsx("input",{type:"time",value:b,onChange:q=>y(q.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"})]})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white",children:"Daily Digest"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"})]}),a.jsx($n,{checked:x,onChange:v})]}),x&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Send digest at"}),a.jsx("input",{type:"time",value:S,onChange:q=>N(q.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Events will be collected and sent as a single summary at this time"})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Notification Events"}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Print Events"}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Start"}),a.jsx($n,{checked:T,onChange:M})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Complete"}),a.jsx($n,{checked:A,onChange:k})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Failed"}),a.jsx($n,{checked:R,onChange:C})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Stopped"}),a.jsx($n,{checked:P,onChange:U})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:"Progress"}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:"(25%, 50%, 75%)"})]}),a.jsx($n,{checked:F,onChange:H})]})]})]}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Printer Status"}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Offline"}),a.jsx($n,{checked:D,onChange:$})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Error"}),a.jsx($n,{checked:G,onChange:I})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Low Filament"}),a.jsx($n,{checked:K,onChange:Q})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Maintenance"}),a.jsx($n,{checked:oe,onChange:B})]})]})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Ne,{type:"submit",disabled:Ve,className:"flex-1",children:[Ve?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function IKe({template:t,onClose:e}){const n=an(),r=_.useRef(null),[i,s]=_.useState(t.title_template),[o,l]=_.useState(t.body_template),[c,u]=_.useState(null),[d,h]=_.useState(!0),{data:p}=it({queryKey:["template-variables"],queryFn:ae.getTemplateVariables}),m=p?.find(M=>M.event_type===t.event_type),{data:b,isLoading:y}=it({queryKey:["template-preview",t.event_type,i,o],queryFn:()=>ae.previewTemplate({event_type:t.event_type,title_template:i,body_template:o}),enabled:d&&i.length>0&&o.length>0});_.useEffect(()=>{const M=A=>{A.key==="Escape"&&e()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[e]);const x=dt({mutationFn:M=>ae.updateNotificationTemplate(t.id,M),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:M=>{u(M.message)}}),v=dt({mutationFn:()=>ae.resetNotificationTemplate(t.id),onSuccess:M=>{s(M.title_template),l(M.body_template),n.invalidateQueries({queryKey:["notification-templates"]})},onError:M=>{u(M.message)}}),S=M=>{if(M.preventDefault(),u(null),!i.trim()){u("Title is required");return}if(!o.trim()){u("Body is required");return}x.mutate({title_template:i,body_template:o})},N=M=>{const A=r.current;if(!A)return;const k=A.selectionStart,R=A.selectionEnd,C=o,P=C.substring(0,k),U=C.substring(R),F=P+`{${M}}`+U;l(F),setTimeout(()=>{A.focus();const H=k+M.length+2;A.setSelectionRange(H,H)},0)},T=i!==t.title_template||o!==t.body_template;return a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-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 shrink-0",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Edit Template: ",t.name]}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("form",{onSubmit:S,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[c&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:c}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Title"}),a.jsx("input",{type:"text",value:i,onChange:M=>s(M.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green",placeholder:"Notification title..."})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Body"}),a.jsx("textarea",{ref:r,value:o,onChange:M=>l(M.target.value),rows:4,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green font-mono text-sm resize-none",placeholder:"Notification body..."})]}),m&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:"Available Variables"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:m.variables.map(M=>a.jsxs("button",{type:"button",onClick:()=>N(M),className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs text-bambu-gray hover:text-white transition-colors",children:[a.jsx(cr,{className:"w-3 h-3"}),M]},M))}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:"Click to insert at cursor position in body"})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[a.jsx(gc,{className:"w-4 h-4"}),"Live Preview"]}),a.jsx("button",{type:"button",onClick:()=>h(!d),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:d?"Hide":"Show"})]}),d&&a.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:y?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Loading preview..."]}):b?a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Title:"}),a.jsx("div",{className:"text-white font-medium",children:b.title})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Body:"}),a.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:b.body})]})]}):a.jsx("div",{className:"text-bambu-gray text-sm",children:"Enter template content to see preview"})})]})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[a.jsxs(Ne,{type:"button",variant:"ghost",onClick:()=>v.mutate(),disabled:v.isPending,className:"text-orange-400 hover:text-orange-300",children:[v.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(Bu,{className:"w-4 h-4 mr-2"}),"Reset to Default"]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:e,children:"Cancel"}),a.jsxs(Ne,{onClick:S,disabled:x.isPending||!T,children:[x.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(vs,{className:"w-4 h-4 mr-2"}),"Save"]})]})]})]})})}const zKe={print_start:"Print Started",print_complete:"Print Complete",print_failed:"Print Failed",print_stopped:"Print Stopped",print_progress:"Progress",printer_offline:"Printer Offline",printer_error:"Printer Error",filament_low:"Low Filament",maintenance_due:"Maintenance Due",test:"Test"},UKe={print_start:"text-blue-400",print_complete:"text-bambu-green",print_failed:"text-red-400",print_stopped:"text-orange-400",print_progress:"text-yellow-400",printer_offline:"text-gray-400",printer_error:"text-rose-400",filament_low:"text-cyan-400",maintenance_due:"text-purple-400",test:"text-bambu-gray"};function BKe({onClose:t}){const e=an(),{showToast:n}=Tn(),[r,i]=_.useState(7),[s,o]=_.useState(null),[l,c]=_.useState(!1),{data:u}=it({queryKey:["settings"],queryFn:ae.getSettings}),d=u?.time_format||"system",{data:h,isLoading:p,refetch:m,isRefetching:b}=it({queryKey:["notification-logs",r,l],queryFn:()=>ae.getNotificationLogs({days:r,limit:100,success:l?!1:void 0})}),{data:y}=it({queryKey:["notification-log-stats",r],queryFn:()=>ae.getNotificationLogStats(r)}),x=dt({mutationFn:()=>ae.clearNotificationLogs(30),onSuccess:S=>{n(S.message,"success"),e.invalidateQueries({queryKey:["notification-logs"]}),e.invalidateQueries({queryKey:["notification-log-stats"]})},onError:S=>{n(`Failed to clear logs: ${S.message}`,"error")}}),v=S=>{const N=zi(S);if(!N)return"";const M=new Date().getTime()-N.getTime();return M<6e4?"Just now":M<36e5?`${Math.floor(M/6e4)}m ago`:M<864e5?`${Math.floor(M/36e5)}h ago`:N.toLocaleDateString()+" "+ime(N,d)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg w-full max-w-3xl max-h-[85vh] flex flex-col",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Y0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Notification Log"})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),y&&a.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:a.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[a.jsxs("span",{className:"text-bambu-gray",children:["Last ",r," days: ",a.jsx("span",{className:"text-white font-medium",children:y.total})," notifications"]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(mr,{className:"w-4 h-4"}),y.success_count," sent"]}),y.failure_count>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(Zi,{className:"w-4 h-4"}),y.failure_count," failed"]})]})}),a.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[a.jsxs("select",{value:r,onChange:S=>i(Number(S.target.value)),className:"px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green",children:[a.jsx("option",{value:1,children:"Last 24 hours"}),a.jsx("option",{value:7,children:"Last 7 days"}),a.jsx("option",{value:30,children:"Last 30 days"}),a.jsx("option",{value:90,children:"Last 90 days"})]}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:l,onChange:S=>c(S.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),"Show failed only"]}),a.jsx("div",{className:"flex-1"}),a.jsxs(Ne,{size:"sm",variant:"secondary",onClick:()=>m(),disabled:b,children:[b?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Or,{className:"w-4 h-4"}),"Refresh"]}),a.jsxs(Ne,{size:"sm",variant:"secondary",onClick:()=>x.mutate(),disabled:x.isPending,className:"text-red-400 hover:text-red-300",children:[x.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4"}),"Clear Old"]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:p?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):h&&h.length>0?a.jsx("div",{className:"space-y-2",children:h.map(S=>a.jsx(HKe,{log:S,isExpanded:s===S.id,onToggle:()=>o(s===S.id?null:S.id),formatDate:v,formatFullDate:N=>qg(N,d)},S.id))}):a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(Y0,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:l?"No failed notifications":"No notifications logged"})]})})]})})}function HKe({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:i}){return a.jsxs("div",{className:`border rounded-lg overflow-hidden transition-colors ${t.success?"border-bambu-dark-tertiary bg-bambu-dark/30":"border-red-500/30 bg-red-500/5"}`,children:[a.jsxs("button",{className:"w-full px-3 py-2 flex items-center gap-3 text-left hover:bg-bambu-dark/50 transition-colors",onClick:n,children:[t.success?a.jsx(mr,{className:"w-4 h-4 text-bambu-green shrink-0"}):a.jsx(Zi,{className:"w-4 h-4 text-red-400 shrink-0"}),a.jsx("span",{className:`text-xs font-medium ${UKe[t.event_type]||"text-bambu-gray"}`,children:zKe[t.event_type]||t.event_type}),a.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||"Unknown Provider"}),t.printer_name&&a.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),a.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?a.jsx(zu,{className:"w-4 h-4 text-bambu-gray shrink-0"}):a.jsx(fr,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&a.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Title"}),a.jsx("p",{className:"text-sm text-white",children:t.title})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Message"}),a.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-red-400 mb-1",children:"Error"}),a.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),a.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[a.jsxs("span",{children:["Provider: ",t.provider_type]}),a.jsxs("span",{children:["Time: ",i(t.created_at)]})]})]})]})}function $Ke({formData:t,setFormData:e,groups:n,onClose:r,onCreate:i,isCreating:s,isCreateButtonDisabled:o}){const{t:l}=Yt();_.useEffect(()=>{const u=d=>{d.key==="Escape"&&r()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[r]);const c=u=>{e({...t,group_ids:t.group_ids.includes(u)?t.group_ids.filter(d=>d!==u):[...t.group_ids,u]})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:r,children:a.jsxs(St,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(zf,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:l("users.modal.createUser")})]}),a.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:l("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:r,children:a.jsx(Lt,{className:"w-5 h-5"})})]})}),a.jsxs(Et,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.username")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:t.username,onChange:u=>e({...t,username:u.target.value}),className:"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:l("users.form.usernamePlaceholder"),autoComplete:"username",required:!0})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.email")||"Email"," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"email",value:t.email,onChange:u=>e({...t,email:u.target.value}),className:"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:l("users.form.emailPlaceholder")||"user@example.com",required:!0})]}),a.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.form.autoGeneratedPassword")||"A secure password will be automatically generated and emailed to the user."})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:l("users.form.groups")}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[n.map(u=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.group_ids.includes(u.id),onChange:()=>c(u.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:u.name}),u.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",l("users.system"),")"]})]},u.id)),n.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:r,children:l("users.modal.cancel")}),a.jsx(Ne,{onClick:i,disabled:o,children:s?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),l("users.modal.creating")]}):a.jsxs(a.Fragment,{children:[a.jsx(cr,{className:"w-4 h-4"}),l("users.modal.createUser")]})})]})]})]})})}function VKe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),[r,i]=_.useState(!1),[s,o]=_.useState(""),[l,c]=_.useState("auto"),[u,d]=_.useState(!1),[h,p]=_.useState(!0),[m,b]=_.useState("all"),[y,x]=_.useState(!1),[v,S]=_.useState(!1),{data:N,isLoading:T}=it({queryKey:["spoolman-settings"],queryFn:ae.getSpoolmanSettings}),{data:M,isLoading:A,refetch:k}=it({queryKey:["spoolman-status"],queryFn:ae.getSpoolmanStatus,refetchInterval:3e4}),{data:R}=it({queryKey:["printers"],queryFn:ae.getPrinters});_.useEffect(()=>{N&&(i(N.spoolman_enabled==="true"),o(N.spoolman_url||""),c(N.spoolman_sync_mode||"auto"),d(N.spoolman_disable_weight_sync==="true"),p(N.spoolman_report_partial_usage!=="false"),x(!0))},[N]),_.useEffect(()=>{if(!y||!N)return;if(N.spoolman_enabled==="true"!==r||(N.spoolman_url||"")!==s||(N.spoolman_sync_mode||"auto")!==l||N.spoolman_disable_weight_sync==="true"!==u||N.spoolman_report_partial_usage!=="false"!==h){const Q=setTimeout(()=>{C.mutate()},500);return()=>clearTimeout(Q)}},[r,s,l,u,h,y]);const C=dt({mutationFn:()=>ae.updateSpoolmanSettings({spoolman_enabled:r?"true":"false",spoolman_url:s,spoolman_sync_mode:l,spoolman_disable_weight_sync:u?"true":"false",spoolman_report_partial_usage:h?"true":"false"}),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolman-settings"]}),e.invalidateQueries({queryKey:["spoolman-status"]}),n(t("settings.toast.settingsSaved"))}}),P=dt({mutationFn:ae.connectSpoolman,onSuccess:()=>{k()}}),U=dt({mutationFn:ae.disconnectSpoolman,onSuccess:()=>{k()}}),F=dt({mutationFn:ae.syncAllPrintersAms,onSuccess:K=>{K.success}}),H=dt({mutationFn:K=>ae.syncPrinterAms(K),onSuccess:K=>{K.success}}),D=()=>{m==="all"?F.mutate():H.mutate(m)},$=F.isPending||H.isPending,G=m==="all"?F.data:H.data,I=m==="all"?F.isSuccess:H.isSuccess;return T?a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Au,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Spoolman Integration"})]})}),a.jsx(Et,{children:a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Au,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Spoolman Integration"})]}),C.isPending&&a.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Connect to Spoolman for filament inventory tracking. AMS data will sync automatically."}),a.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(xo,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:"How Sync Works"}),a.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[a.jsx("li",{children:"Only official Bambu Lab spools with RFID are synced"}),a.jsx("li",{children:"New spools are auto-created in Spoolman on first sync"}),a.jsx("li",{children:"Non-Bambu Lab spools (third-party, refilled) are skipped"})]}),a.jsx("p",{className:"font-medium mt-2 mb-1",children:"Linking Existing Spools"}),a.jsx("p",{className:"text-blue-300/80",children:'To link existing Spoolman spools to your AMS, hover over an AMS slot and click "Link to Spoolman".'})]})]})}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:"Enable Spoolman"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Sync filament data with Spoolman server"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:K=>i(K.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Spoolman URL"}),a.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:K=>o(K.target.value),disabled:!r,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray/50 focus:border-bambu-green focus:outline-none disabled:opacity-50"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"URL of your Spoolman server (e.g., http://localhost:7912)"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Sync Mode"}),a.jsxs("select",{value:l,onChange:K=>c(K.target.value),disabled:!r,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 disabled:opacity-50",children:[a.jsx("option",{value:"auto",children:"Automatic"}),a.jsx("option",{value:"manual",children:"Manual Only"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:l==="auto"?"AMS data syncs automatically when changes are detected":"Only sync when manually triggered"})]}),l==="auto"&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:u,onChange:K=>d(K.target.checked),disabled:!r,className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),u&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:h,onChange:K=>p(K.target.checked),disabled:!r,className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),r&&a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:"Status:"}),A?a.jsx(ct,{className:"w-4 h-4 text-bambu-gray animate-spin"}):M?.connected?a.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[a.jsx($i,{className:"w-4 h-4"}),"Connected"]}):a.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[a.jsx(Lt,{className:"w-4 h-4"}),"Disconnected"]})]}),a.jsx("div",{className:"flex gap-2",children:M?.connected?a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>U.mutate(),disabled:U.isPending,children:[U.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Ide,{className:"w-4 h-4"}),"Disconnect"]}):a.jsxs(Ne,{size:"sm",onClick:()=>P.mutate(),disabled:P.isPending||!s,children:[P.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(dc,{className:"w-4 h-4"}),"Connect"]})})]}),P.isError&&a.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:P.error.message}),M?.connected&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Sync AMS Data"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Manually sync printer AMS data to Spoolman"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsxs("select",{value:m,onChange:K=>b(K.target.value==="all"?"all":Number(K.target.value)),className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"all",children:"All Printers"}),R?.map(K=>a.jsx("option",{value:K.id,children:K.name},K.id))]}),a.jsx(fr,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:D,disabled:$,children:[$?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Or,{className:"w-4 h-4"}),"Sync"]})]})]}),I&&G&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:`p-2 rounded text-sm ${G.success?"bg-green-500/20 border border-green-500/50 text-green-400":"bg-yellow-500/20 border border-yellow-500/50 text-yellow-400"}`,children:G.success?`Synced ${G.synced_count} spool${G.synced_count!==1?"s":""} successfully`:`Synced ${G.synced_count} spool${G.synced_count!==1?"s":""} with ${G.errors.length} error${G.errors.length!==1?"s":""}`}),G.skipped_count>0&&a.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[a.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(En,{className:"w-3.5 h-3.5"}),a.jsxs("span",{className:"font-medium",children:[G.skipped_count," spool",G.skipped_count!==1?"s":""," skipped"]})]}),G.skipped_count>5&&a.jsx("button",{onClick:()=>S(!v),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:v?"Show less":"Show all"})]}),a.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(v?G.skipped:G.skipped.slice(0,5)).map((K,Q)=>a.jsxs("li",{className:"flex items-center gap-2",children:[K.color&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:`#${K.color}`}}),a.jsx("span",{children:K.location}),a.jsxs("span",{className:"text-amber-300/60",children:["- ",K.reason]})]},Q)),!v&&G.skipped_count>5&&a.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",G.skipped_count-5," more"]})]})]}),G.errors.length>0&&a.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[a.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),a.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:G.errors.map((K,Q)=>a.jsx("li",{children:K},Q))})]})]})]})]})]})}function GKe({link:t,onClose:e}){const n=an(),r=!!t,i=_.useRef(null),[s,o]=_.useState(t?.name||""),[l,c]=_.useState(t?.url||""),[u,d]=_.useState(t?.icon||"link"),[h,p]=_.useState(!!t?.custom_icon),[m,b]=_.useState(t?.custom_icon?ae.getExternalLinkIconUrl(t.id):null),[y,x]=_.useState(null),[v,S]=_.useState(null);_.useEffect(()=>{const P=U=>{U.key==="Escape"&&e()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[e]);const N=dt({mutationFn:async P=>{const U=await ae.createExternalLink(P);return y?await ae.uploadExternalLinkIcon(U.id,y):U},onSuccess:()=>{n.invalidateQueries({queryKey:["external-links"]}),e()},onError:P=>{S(P.message)}}),T=dt({mutationFn:async P=>{let U=await ae.updateExternalLink(t.id,P);return y?U=await ae.uploadExternalLinkIcon(t.id,y):!h&&t?.custom_icon&&(U=await ae.deleteExternalLinkIcon(t.id)),U},onSuccess:()=>{n.invalidateQueries({queryKey:["external-links"]}),e()},onError:P=>{S(P.message)}}),M=P=>{const U=P.target.files?.[0];if(U){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(U.type)){S("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(U.size>1024*1024){S("Image file must be less than 1MB");return}x(U),p(!0);const H=new FileReader;H.onload=D=>{b(D.target?.result)},H.readAsDataURL(U)}},A=()=>{x(null),b(null),p(!1),i.current&&(i.current.value="")},k=P=>{if(P.preventDefault(),S(null),!s.trim()){S("Name is required");return}if(!l.trim()){S("URL is required");return}if(!l.startsWith("http://")&&!l.startsWith("https://")){S("URL must start with http:// or https://");return}const U={name:s.trim(),url:l.trim(),icon:u};r?T.mutate(U):N.mutate(U)},R=N.isPending||T.isPending,C=Tk(u);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:P=>P.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:h&&m?a.jsx("img",{src:m,alt:"",className:"w-5 h-5 rounded"}):a.jsx(C,{className:"w-5 h-5"})}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:r?"Edit Link":"Add External Link"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:k,className:"p-6 space-y-4",children:[v&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:v}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:s,onChange:P=>o(P.target.value),placeholder:"My Link",maxLength:50,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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),a.jsx("input",{type:"text",value:l,onChange:P=>c(P.target.value),placeholder:"https://example.com",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"})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),a.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),a.jsx("input",{ref:i,type:"file",accept:"image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon",className:"hidden",onChange:M}),h&&m?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("img",{src:m,alt:"Custom icon",className:"w-8 h-8 rounded border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:A,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:a.jsx(ln,{className:"w-4 h-4"})})]}):a.jsxs(Ne,{type:"button",variant:"secondary",size:"sm",onClick:()=>i.current?.click(),children:[a.jsx(Na,{className:"w-4 h-4"}),"Upload"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!h&&a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),a.jsx(Gfe,{value:u,onChange:d})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Ne,{type:"submit",disabled:R,className:"flex-1",children:[R?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function qKe(){const{t}=Yt(),e=an(),[n,r]=_.useState(!1),[i,s]=_.useState(null),[o,l]=_.useState(null),[c,u]=_.useState(null),{data:d,isLoading:h}=it({queryKey:["external-links"],queryFn:ae.getExternalLinks}),p=dt({mutationFn:N=>ae.deleteExternalLink(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),m=dt({mutationFn:N=>ae.reorderExternalLinks(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),b=(N,T)=>{u(T),N.dataTransfer.effectAllowed="move"},y=N=>{N.preventDefault(),N.dataTransfer.dropEffect="move"},x=(N,T)=>{if(N.preventDefault(),c===null||c===T||!d)return;const M=d.map(C=>C.id),A=M.indexOf(c),k=M.indexOf(T);if(A===-1||k===-1)return;const R=[...M];R.splice(A,1),R.splice(k,0,c),m.mutate(R),u(null)},v=N=>{l(N)},S=()=>{o&&(p.mutate(o.id),l(null))};return a.jsxs(a.Fragment,{children:[a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(dc,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),a.jsxs(Ne,{size:"sm",onClick:()=>r(!0),children:[a.jsx(cr,{className:"w-4 h-4"}),"Add Link"]})]})}),a.jsxs(Et,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),h?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):d&&d.length>0?a.jsx("div",{className:"space-y-2",children:d.map(N=>{const T=Tk(N.icon);return a.jsxs("div",{draggable:!0,onDragStart:M=>b(M,N.id),onDragOver:y,onDrop:M=>x(M,N.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${c===N.id?"opacity-50":""}`,children:[a.jsx(Vg,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(T,{className:"w-4 h-4"})}),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-white font-medium truncate",children:N.name}),a.jsx(Xr,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),a.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:N.url})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[a.jsx("button",{onClick:()=>s(N),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:t("common.edit"),children:a.jsx(Ji,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>v(N),disabled:p.isPending,className:"p-2 rounded-lg hover:bg-red-500/20 text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50",title:t("externalLinks.deleteLink"),children:a.jsx(ln,{className:"w-4 h-4"})})]})]},N.id)})}):a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(dc,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:t("externalLinks.noLinksConfigured")}),a.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(n||i)&&a.jsx(GKe,{link:i,onClose:()=>{r(!1),s(null)}}),o&&a.jsx(er,{title:"Delete Link",message:`Are you sure you want to delete "${o.name}"? This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger",onConfirm:S,onCancel:()=>l(null)})]})}function WKe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),[r,i]=_.useState(!1),[s,o]=_.useState(""),[l,c]=_.useState("immediate"),[u,d]=_.useState("3DPrinter-X1-Carbon"),[h,p]=_.useState(null),[m,b]=_.useState(""),[y,x]=_.useState(!1),[v,S]=_.useState(null),{data:N,isLoading:T}=it({queryKey:["virtual-printer-settings"],queryFn:S1.getSettings,refetchInterval:1e4}),{data:M}=it({queryKey:["virtual-printer-models"],queryFn:S1.getModels}),{data:A}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:k}=it({queryKey:["network-interfaces"],queryFn:()=>ae.getNetworkInterfaces().then(I=>I.interfaces),enabled:r});_.useEffect(()=>{if(N){i(N.enabled);let I=N.mode==="queue"?"review":N.mode;I!=="immediate"&&I!=="review"&&I!=="print_queue"&&I!=="proxy"&&(I="immediate"),c(I),d(N.model),p(N.target_printer_id),b(N.remote_interface_ip||"")}},[N]);const R=dt({mutationFn:I=>S1.updateSettings(I),onSuccess:()=>{e.invalidateQueries({queryKey:["virtual-printer-settings"]}),n(t("virtualPrinter.toast.updated")),S(null)},onError:I=>{if(n(I.message||t("virtualPrinter.toast.failedToUpdate"),"error"),N){i(N.enabled);const K=N.mode==="queue"?"review":N.mode;c(["immediate","review","print_queue","proxy"].includes(K)?K:"immediate"),d(N.model),p(N.target_printer_id)}S(null)}}),C=()=>{const I=!r;if(I){if(l==="proxy"){if(!h){n(t("virtualPrinter.toast.targetPrinterRequired"),"error");return}}else if(!s&&!N?.access_code_set){n(t("virtualPrinter.toast.accessCodeRequired"),"error");return}}i(I),S("toggle"),R.mutate({enabled:I,access_code:l!=="proxy"&&s||void 0,mode:l,target_printer_id:l==="proxy"?h??void 0:void 0})},P=()=>{if(!s){n(t("virtualPrinter.toast.accessCodeEmpty"),"error");return}if(s.length!==8){n(t("virtualPrinter.toast.accessCodeLength"),"error");return}S("accessCode"),R.mutate({access_code:s}),o("")},U=I=>{c(I),S("mode"),R.mutate({mode:I})},F=I=>{p(I),S("targetPrinter"),R.mutate({target_printer_id:I})},H=I=>{d(I),S("model"),R.mutate({model:I})},D=I=>{b(I),S("remoteInterface"),R.mutate({remote_interface_ip:I})};if(T)return a.jsx(St,{children:a.jsx(Et,{className:"py-8 flex justify-center",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const $=N?.status,G=$?.running||!1;return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[a.jsx("div",{className:"space-y-6 lg:w-[480px] lg:flex-shrink-0",children:a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(jr,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("virtualPrinter.title")})]}),$&&a.jsxs("div",{className:`flex items-center gap-2 text-sm ${G?"text-green-400":"text-bambu-gray"}`,children:[a.jsx("span",{className:`w-2 h-2 rounded-full ${G?"bg-green-400 animate-pulse":"bg-gray-500"}`}),t(G?"virtualPrinter.running":"virtualPrinter.stopped")]})]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t(l==="proxy"?"virtualPrinter.description.proxy":"virtualPrinter.description.default")}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-white font-medium",children:t("virtualPrinter.enable.title")}),a.jsx("div",{className:"text-sm text-bambu-gray",children:G?l==="proxy"?t("virtualPrinter.enable.proxyingTo",{name:A?.find(I=>I.id===h)?.name||"printer"}):t("virtualPrinter.enable.visibleInSlicer"):t("virtualPrinter.enable.notActive")})]}),a.jsx("button",{onClick:C,disabled:v==="toggle",className:`relative w-12 h-6 rounded-full transition-colors ${r?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${v==="toggle"?"opacity-50":""}`,children:a.jsx("span",{className:`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${r?"translate-x-6":""}`})})]}),l!=="proxy"&&a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.model.title")}),a.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:t("virtualPrinter.model.description")}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:u,onChange:I=>H(I.target.value),disabled:v==="model",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed pr-10",children:M?.models&&Object.entries(M.models).sort(([,I],[,K])=>I.localeCompare(K)).map(([I,K])=>a.jsx("option",{value:I,children:K},I))}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),r&&G&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[a.jsx(xo,{className:"w-3 h-3 inline mr-1"}),t("virtualPrinter.model.restartWarning")]})]}),l!=="proxy"&&a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.accessCode.title")}),a.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:N?.access_code_set?a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx($i,{className:"w-4 h-4"}),t("virtualPrinter.accessCode.isSet")]}):a.jsxs("span",{className:"flex items-center gap-1 text-yellow-400",children:[a.jsx(En,{className:"w-4 h-4"}),t("virtualPrinter.accessCode.notSet")]})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:y?"text":"password",value:s,onChange:I=>o(I.target.value),placeholder:N?.access_code_set?t("virtualPrinter.accessCode.placeholderChange"):t("virtualPrinter.accessCode.placeholder"),maxLength:8,className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white placeholder-bambu-gray pr-10 font-mono"}),a.jsx("button",{onClick:()=>x(!y),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:y?a.jsx(bk,{className:"w-4 h-4"}):a.jsx(gc,{className:"w-4 h-4"})})]}),a.jsx(Ne,{onClick:P,disabled:!s||v==="accessCode",variant:"primary",children:v==="accessCode"?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):t("common.save")})]}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[t("virtualPrinter.accessCode.hint"),s&&a.jsxs("span",{className:s.length===8?"text-green-400":"text-yellow-400",children:[" ",t("virtualPrinter.accessCode.charCount",{count:s.length})]})]})]}),l==="proxy"&&a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.targetPrinter.title")}),a.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:h?a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx($i,{className:"w-4 h-4"}),t("virtualPrinter.targetPrinter.configured")]}):a.jsxs("span",{className:"flex items-center gap-1 text-yellow-400",children:[a.jsx(En,{className:"w-4 h-4"}),t("virtualPrinter.targetPrinter.notConfigured")]})}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:h??"",onChange:I=>{const K=parseInt(I.target.value,10);isNaN(K)||F(K)},disabled:v==="targetPrinter",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed pr-10",children:[a.jsx("option",{value:"",children:t("virtualPrinter.targetPrinter.placeholder")}),A?.map(I=>a.jsxs("option",{value:I.id,children:[I.name," (",I.ip_address,")"]},I.id))]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:t("virtualPrinter.targetPrinter.hint")}),!A?.length&&a.jsxs("p",{className:"text-xs text-yellow-400 mt-2",children:[a.jsx(En,{className:"w-3 h-3 inline mr-1"}),t("virtualPrinter.targetPrinter.noPrinters")]})]}),r&&a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.remoteInterface.title")}),a.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:m?a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx($i,{className:"w-4 h-4"}),t("virtualPrinter.remoteInterface.configured")]}):a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(xo,{className:"w-4 h-4"}),t("virtualPrinter.remoteInterface.optional")]})}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:m,onChange:I=>D(I.target.value),disabled:v==="remoteInterface",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed pr-10",children:[a.jsx("option",{value:"",children:t("virtualPrinter.remoteInterface.placeholder")}),k?.map(I=>a.jsxs("option",{value:I.ip,children:[I.name," (",I.ip,") - ",I.subnet]},I.ip))]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:t("virtualPrinter.remoteInterface.hint")})]}),a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.mode.title")}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("button",{onClick:()=>U("immediate"),disabled:v==="mode",className:`p-3 rounded-lg border text-left transition-colors ${l==="immediate"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:"text-white font-medium",children:t("virtualPrinter.mode.archive")}),a.jsx("div",{className:"text-xs text-bambu-gray",children:t("virtualPrinter.mode.archiveDesc")})]}),a.jsxs("button",{onClick:()=>U("review"),disabled:v==="mode",className:`p-3 rounded-lg border text-left transition-colors ${l==="review"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:"text-white font-medium",children:t("virtualPrinter.mode.review")}),a.jsx("div",{className:"text-xs text-bambu-gray",children:t("virtualPrinter.mode.reviewDesc")})]}),a.jsxs("button",{onClick:()=>U("print_queue"),disabled:v==="mode",className:`p-3 rounded-lg border text-left transition-colors ${l==="print_queue"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:"text-white font-medium",children:t("virtualPrinter.mode.queue")}),a.jsx("div",{className:"text-xs text-bambu-gray",children:t("virtualPrinter.mode.queueDesc")})]}),a.jsxs("button",{onClick:()=>U("proxy"),disabled:v==="mode",className:`p-3 rounded-lg border text-left transition-colors ${l==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-white font-medium",children:[a.jsx(YU,{className:"w-4 h-4"}),t("virtualPrinter.mode.proxy")]}),a.jsx("div",{className:"text-xs text-bambu-gray",children:t("virtualPrinter.mode.proxyDesc")})]})]})]})]})]})}),a.jsxs("div",{className:"space-y-6 lg:w-[480px] lg:flex-shrink-0",children:[a.jsx(St,{className:"border-l-4 border-l-yellow-500",children:a.jsx(Et,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(En,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-sm",children:[a.jsx("p",{className:"text-white font-medium mb-2",children:t("virtualPrinter.setupRequired.title")}),a.jsx("p",{className:"text-bambu-gray mb-3",children:t("virtualPrinter.setupRequired.description")}),a.jsxs("a",{href:"https://wiki.bambuddy.cool/features/virtual-printer/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-4 py-2 bg-yellow-500/20 border border-yellow-500/50 rounded-md text-yellow-400 hover:bg-yellow-500/30 transition-colors",children:[a.jsx(Xr,{className:"w-4 h-4"}),t("virtualPrinter.setupRequired.readGuide")]})]})]})})}),a.jsx(St,{children:a.jsx(Et,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(xo,{className:"w-5 h-5 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-sm text-bambu-gray",children:[a.jsx("p",{className:"mb-2",children:a.jsxs("strong",{className:"text-white",children:[t(l==="proxy"?"virtualPrinter.howItWorks.titleProxy":"virtualPrinter.howItWorks.title"),":"]})}),l==="proxy"?a.jsxs("ol",{className:"list-decimal list-inside space-y-1",children:[a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep1")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep2")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep3")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep4")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep5")})]}):a.jsxs("ol",{className:"list-decimal list-inside space-y-1",children:[a.jsx("li",{children:t("virtualPrinter.howItWorks.step1")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step2")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step3")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step4")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step5")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step6")})]})]})]})})}),$&&G&&a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h3",{className:"text-md font-semibold text-white",children:t("virtualPrinter.status.title")})}),a.jsx(Et,{children:$.mode==="proxy"&&$.proxy?a.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.targetPrinter")}),a.jsx("div",{className:"text-white",children:A?.find(I=>I.id===h)?.name||$.proxy.target_host}),a.jsx("div",{className:"text-xs text-bambu-gray font-mono",children:$.proxy.target_host})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.mode")}),a.jsxs("div",{className:"text-white flex items-center gap-1.5",children:[a.jsx(YU,{className:"w-4 h-4"}),t("virtualPrinter.mode.proxy")]})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.ftpPort")}),a.jsx("div",{className:"text-white font-mono",children:$.proxy.ftp_port})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.mqttPort")}),a.jsx("div",{className:"text-white font-mono",children:$.proxy.mqtt_port})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.ftpConnections")}),a.jsx("div",{className:"text-white",children:$.proxy.ftp_connections??0})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.mqttConnections")}),a.jsx("div",{className:"text-white",children:$.proxy.mqtt_connections??0})]})]}):a.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.printerName")}),a.jsx("div",{className:"text-white",children:$.name})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.model")}),a.jsx("div",{className:"text-white",children:$.model_name||$.model})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.serialNumber")}),a.jsx("div",{className:"text-white font-mono",children:$.serial})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.mode")}),a.jsx("div",{className:"text-white capitalize",children:$.mode})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.pendingFiles")}),a.jsx("div",{className:"text-white",children:$.pending_files})]})]})})]})]})]})}function j9({status:t}){if(!t)return null;const e={success:"bg-green-500/20 text-green-400",failed:"bg-red-500/20 text-red-400",skipped:"bg-yellow-500/20 text-yellow-400",running:"bg-blue-500/20 text-blue-400"},n={success:a.jsx(mr,{className:"w-3 h-3"}),failed:a.jsx(Zi,{className:"w-3 h-3"}),skipped:a.jsx(qR,{className:"w-3 h-3"}),running:a.jsx(ct,{className:"w-3 h-3 animate-spin"})};return a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium ${e[t]||"bg-gray-500/20 text-gray-400"}`,children:[n[t],t.charAt(0).toUpperCase()+t.slice(1)]})}function KKe(t){return t?new Date(t).toLocaleString():"-"}function D9(t){if(!t)return"-";const e=new Date(t),n=new Date,r=e.getTime()-n.getTime(),i=Math.round(r/6e4);if(i<0){const s=Math.abs(i);if(s<60)return`${s}m ago`;const o=Math.floor(s/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}else{if(i<60)return`in ${i}m`;const s=Math.floor(i/60);return s<24?`in ${s}h`:`in ${Math.floor(s/24)}d`}}function XKe(){const t=an(),{showToast:e}=Tn(),{t:n}=Yt(),[r,i]=_.useState(""),[s,o]=_.useState(""),[l,c]=_.useState("main"),[u,d]=_.useState(!1),[h,p]=_.useState("daily"),[m,b]=_.useState(!0),[y,x]=_.useState(!0),[v,S]=_.useState(!1),[N,T]=_.useState(!0),[M,A]=_.useState(!1),[k,R]=_.useState(!1),[C,P]=_.useState(""),[U,F]=_.useState(!1),[H,D]=_.useState(null),[$,G]=_.useState(null),I=_.useRef(null);_.useEffect(()=>{if(M||k){const z=O=>(O.preventDefault(),O.returnValue="A backup operation is in progress. Are you sure you want to leave?",O.returnValue);return window.addEventListener("beforeunload",z),()=>window.removeEventListener("beforeunload",z)}},[M,k]);const[K,Q]=_.useState(!1),[oe,B]=_.useState(null),W=_.useRef(null),J=_.useRef(!1),{data:ne,isLoading:me}=it({queryKey:["github-backup-config"],queryFn:ae.getGitHubBackupConfig}),{data:fe}=it({queryKey:["github-backup-status"],queryFn:ae.getGitHubBackupStatus,refetchInterval:ee=>ee.state.data?.is_running?500:1e4}),{data:de}=it({queryKey:["github-backup-logs"],queryFn:()=>ae.getGitHubBackupLogs(20)}),{data:Re}=it({queryKey:["cloud-status"],queryFn:ae.getCloudStatus}),{data:se}=it({queryKey:["printers"],queryFn:ae.getPrinters}),ke=BR({queries:(se??[]).map(ee=>({queryKey:["printerStatus",ee.id],queryFn:()=>ae.getPrinterStatus(ee.id),staleTime:1e4,refetchInterval:3e4}))}),Fe=(se??[]).map((ee,z)=>({printer:ee,connected:ke[z]?.data?.connected??!1})),ce=Fe.length,Ve=Fe.filter(ee=>ee.connected).length,V=ce>0&&Ve===0,Y=Ve>0&&Ve{ne&&(i(ne.repository_url),c(ne.branch),d(ne.schedule_enabled),p(ne.schedule_type),b(ne.backup_kprofiles),x(ne.backup_cloud_profiles),S(ne.backup_settings),T(ne.enabled),o(""),setTimeout(()=>{J.current=!0},100))},[ne]);const ue=_.useCallback(async(ee=!1)=>{if(ne?.has_token)try{ee&&s?(await ae.saveGitHubBackupConfig({repository_url:r,access_token:s,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:m,backup_cloud_profiles:y,backup_settings:v,enabled:N}),o(""),e("Token updated")):(await ae.updateGitHubBackupConfig({repository_url:r,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:m,backup_cloud_profiles:y,backup_settings:v,enabled:N}),e("Settings saved")),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(z){e(`Failed to save: ${z.message}`,"error")}},[ne?.has_token,r,s,l,u,h,m,y,v,N,t,e]);_.useEffect(()=>{if(!(!J.current||!ne?.has_token))return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{ue(!1)},500),()=>{W.current&&clearTimeout(W.current)}},[r,l,u,h,m,y,v,N,ue,ne?.has_token]),_.useEffect(()=>{if(!(!J.current||!ne?.has_token||!s))return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{ue(!0)},1e3),()=>{W.current&&clearTimeout(W.current)}},[s,ue,ne?.has_token]);const q=dt({mutationFn:ee=>ae.saveGitHubBackupConfig(ee),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e("GitHub backup enabled"),o(""),J.current=!0},onError:ee=>{e(`Failed to save: ${ee.message}`,"error")}}),re=dt({mutationFn:ae.triggerGitHubBackup,onSuccess:ee=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),ee.success?ee.files_changed>0?e(`Backup complete - ${ee.files_changed} files updated`):e("Backup skipped - no changes"):e(`Backup failed: ${ee.message}`,"error")},onError:ee=>{e(`Backup failed: ${ee.message}`,"error")}}),X=dt({mutationFn:()=>ae.clearGitHubBackupLogs(0),onSuccess:ee=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(`Cleared ${ee.deleted} logs`)},onError:ee=>{e(`Failed to clear logs: ${ee.message}`,"error")}}),le=async()=>{Q(!0),B(null);try{let ee;if(s){if(!r){e("Enter repository URL","error"),Q(!1);return}ee=await ae.testGitHubConnection(r,s)}else if(ne?.has_token)ee=await ae.testGitHubStoredConnection();else{e("Enter repository URL and access token","error"),Q(!1);return}B({success:ee.success,message:ee.message})}catch(ee){B({success:!1,message:ee.message})}finally{Q(!1)}},pe=()=>{if(!r){e("Repository URL is required","error");return}if(!s){e("Access token is required","error");return}q.mutate({repository_url:r,access_token:s,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:m,backup_cloud_profiles:y,backup_settings:v,enabled:N})};return me?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})}):a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"space-y-6",children:[a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(kj,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"GitHub Backup"})]}),ne&&Re?.is_authenticated&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:"Enabled"}),a.jsx($n,{checked:N,onChange:T})]})]})}),a.jsx(Et,{className:"space-y-4",children:Re?.is_authenticated?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically sync your profiles to a private GitHub repository for backup and version history."}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Repository URL"}),a.jsx("input",{type:"text",value:r,onChange:ee=>{i(ee.target.value),B(null)},placeholder:"https://github.com/username/bambuddy-backup",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"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Personal Access Token ",ne?.has_token&&a.jsx("span",{className:"text-green-400",children:"(saved)"})]}),a.jsx("input",{type:"password",value:s,onChange:ee=>{o(ee.target.value),B(null)},placeholder:ne?.has_token?"Enter new token to update":"ghp_xxxxxxxxxxxx",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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Fine-grained token with Contents read/write permission"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Branch"}),a.jsx("input",{type:"text",value:l,onChange:ee=>c(ee.target.value),placeholder:"main",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Auto-backup"}),a.jsxs("select",{value:u?h:"disabled",onChange:ee=>{ee.target.value==="disabled"?d(!1):(d(!0),p(ee.target.value))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"disabled",children:"Manual only"}),a.jsx("option",{value:"hourly",children:"Hourly"}),a.jsx("option",{value:"daily",children:"Daily"}),a.jsx("option",{value:"weekly",children:"Weekly"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Include in backup"}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:`flex items-start gap-2 ${V?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[a.jsx("input",{type:"checkbox",checked:m,onChange:ee=>b(ee.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green",disabled:V}),a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`text-sm ${V?"text-bambu-gray":"text-white"}`,children:"K-Profiles"}),V&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[a.jsx(En,{className:"w-3 h-3"}),"No printers connected"]}),Y&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[a.jsx(En,{className:"w-3 h-3"}),Ve,"/",ce," connected"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Pressure advance calibration from connected printers"})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:y,onChange:ee=>x(ee.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green",disabled:!Re?.is_authenticated}),a.jsxs("div",{children:[a.jsx("span",{className:`text-sm ${Re?.is_authenticated?"text-white":"text-bambu-gray"}`,children:"Cloud Profiles"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Filament, printer, and process presets from Bambu Cloud"})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:v,onChange:ee=>S(ee.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white text-sm",children:"App Settings"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Bambuddy configuration (complete database)"})]})]})]})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[fe?.configured&&a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:fe.last_backup_at?a.jsxs(a.Fragment,{children:[a.jsxs("span",{children:["Last backup: ",D9(fe.last_backup_at)]}),a.jsx(j9,{status:fe.last_backup_status})]}):a.jsx("span",{children:"No backups yet"})}),fe.next_scheduled_run&&a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx(tr,{className:"w-3 h-3 inline mr-1"}),"Next: ",D9(fe.next_scheduled_run)]})]}),oe&&a.jsxs("div",{className:`text-sm flex items-center gap-1 ${oe.success?"text-green-400":"text-red-400"}`,children:[oe.success?a.jsx(mr,{className:"w-4 h-4"}):a.jsx(Zi,{className:"w-4 h-4"}),oe.message]}),a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:fe?.configured?a.jsx(a.Fragment,{children:re.isPending||fe.is_running?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{className:"text-sm",children:fe.progress||"Starting backup..."})]}):a.jsxs(a.Fragment,{children:[a.jsxs(Ne,{variant:"primary",size:"sm",onClick:()=>re.mutate(),disabled:!ne?.enabled,children:[a.jsx(Eo,{className:"w-4 h-4"}),"Backup Now"]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:le,disabled:K,children:[K?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Or,{className:"w-4 h-4"}),"Test"]})]})}):a.jsxs(a.Fragment,{children:[a.jsxs(Ne,{variant:"primary",size:"sm",onClick:pe,disabled:q.isPending||!r||!s,children:[q.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(mr,{className:"w-4 h-4"}),"Enable Backup"]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:le,disabled:K||!r||!s,children:[K?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Or,{className:"w-4 h-4"}),"Test Connection"]})]})})]})]}):a.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[a.jsx(En,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-sm text-yellow-400",children:"Bambu Cloud login required. Sign in under Profiles → Cloud Profiles to enable GitHub backup."})]})})]}),de&&de.length>0&&a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Y0,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"History"})]}),a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:()=>X.mutate(),disabled:X.isPending,children:[a.jsx(ln,{className:"w-4 h-4"}),"Clear"]})]})}),a.jsx(Et,{children:a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left py-2 px-2",children:"Date"}),a.jsx("th",{className:"text-left py-2 px-2",children:"Status"}),a.jsx("th",{className:"text-left py-2 px-2",children:"Commit"})]})}),a.jsx("tbody",{children:de.slice(0,10).map(ee=>a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[a.jsx("td",{className:"py-2 px-2 text-white",children:KKe(ee.started_at)}),a.jsx("td",{className:"py-2 px-2",children:a.jsx(j9,{status:ee.status})}),a.jsx("td",{className:"py-2 px-2",children:ee.commit_sha?a.jsxs("a",{href:`${ne?.repository_url}/commit/${ee.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[ee.commit_sha.substring(0,7),a.jsx(Xr,{className:"w-3 h-3"})]}):a.jsx("span",{className:"text-bambu-gray",children:"-"})})]},ee.id))})]})})})]})]}),a.jsx("div",{className:"space-y-6",children:a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Au,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Local Backup"})]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Create a complete backup of your Bambuddy data including the database, archives, uploads, and all files."}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:"Download Backup"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Complete backup: database + all files (ZIP)"})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",disabled:M||k,onClick:async()=>{A(!0),P("Preparing backup...");try{P("Creating backup archive... This may take a while for large archives.");const{blob:ee,filename:z}=await ae.exportBackup();P("Downloading backup file...");const O=URL.createObjectURL(ee),Z=document.createElement("a");Z.href=O,Z.download=z,Z.click(),URL.revokeObjectURL(O),e("Backup downloaded successfully")}catch(ee){e(`Failed to create backup: ${ee instanceof Error?ee.message:"Unknown error"}`,"error")}finally{A(!1),P("")}},children:[a.jsx(wi,{className:"w-4 h-4"}),"Download"]})]}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:n("backup.restoreBackup")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.restoreDescription")}),a.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.restoreNote")})]}),a.jsx("input",{ref:I,type:"file",accept:".zip",className:"hidden",onChange:ee=>{const z=ee.target.files?.[0];z&&(D(z),F(!0)),ee.target.value=""}}),a.jsxs(Ne,{variant:"secondary",size:"sm",disabled:k||M,onClick:()=>I.current?.click(),children:[a.jsx(Na,{className:"w-4 h-4"}),"Restore"]})]}),$&&a.jsx("div",{className:`p-3 rounded-lg ${$.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[$.success?a.jsx(mr,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):a.jsx(Zi,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:$.success?"text-green-200":"text-red-200",children:[$.message,$.success&&a.jsx("div",{className:"mt-2",children:a.jsxs(Ne,{size:"sm",onClick:()=>window.location.reload(),children:[a.jsx(Bu,{className:"w-3 h-3"}),"Reload Now"]})})]})]})}),a.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[a.jsx(En,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"text-yellow-200",children:[a.jsx("span",{className:"font-medium",children:"Restore replaces all data."})," ",a.jsx("span",{className:"text-yellow-200/70",children:"Your current database and files will be completely replaced. A restart is required after restore."})]})]})})]})]})}),U&&H&&a.jsx(er,{title:"Restore Backup",message:`Are you sure you want to restore from "${H.name}"? This will completely replace your current database and all files. The application will need to be restarted after restore.`,confirmText:"Restore Backup",variant:"danger",onConfirm:async()=>{F(!1),R(!0),G(null);try{P("Uploading backup file...");const ee=await ae.importBackup(H);G(ee),ee.success?e("Backup restored. Please restart Bambuddy.","success"):e(ee.message,"error")}catch(ee){const z=ee instanceof Error?ee.message:"Failed to restore backup";G({success:!1,message:z}),e(z,"error")}finally{R(!1),P(""),D(null)}},onCancel:()=>{F(!1),D(null)}}),(M||k)&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-8 max-w-md w-full mx-4 text-center",children:[a.jsx("div",{className:"flex justify-center mb-4",children:a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),a.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),a.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:M?"Creating Backup":"Restoring Backup"}),a.jsx("p",{className:"text-bambu-gray mb-4",children:C||(M?"Preparing...":"Processing...")}),a.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[a.jsx(En,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-yellow-200 text-left",children:"Please do not close this page or navigate away. This operation may take several minutes for large backups."})]})})]})})]})}function YKe(){const{t}=Yt(),{showToast:e}=Tn(),n=an(),[r,i]=_.useState({smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",smtp_security:"starttls",smtp_auth_enabled:!0,smtp_from_email:"",smtp_from_name:"BamBuddy"}),[s,o]=_.useState(""),{data:l,isLoading:c}=it({queryKey:["smtpSettings"],queryFn:()=>ae.getSMTPSettings()}),{data:u}=it({queryKey:["advancedAuthStatus"],queryFn:()=>ae.getAdvancedAuthStatus()});_.useEffect(()=>{l&&i({...l,smtp_password:""})},[l]);const d=dt({mutationFn:x=>ae.saveSMTPSettings(x),onSuccess:()=>{n.invalidateQueries({queryKey:["smtpSettings"]}),n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(t("settings.email.success.settingsSaved"),"success")},onError:x=>{e(x.message,"error")}}),h=dt({mutationFn:x=>ae.testSMTP(x),onSuccess:x=>{e(x.message,x.success?"success":"error")},onError:x=>{e(x.message,"error")}}),p=dt({mutationFn:x=>x?ae.enableAdvancedAuth():ae.disableAdvancedAuth(),onSuccess:x=>{n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(x.message,"success")},onError:x=>{e(x.message,"error")}}),m=()=>{if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.requiredFields"),"error");return}if(r.smtp_auth_enabled&&!r.smtp_username){e(t("settings.email.errors.usernameRequired"),"error");return}d.mutate(r)},b=()=>{if(!s){e(t("settings.email.errors.enterTestEmail"),"error");return}if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.smtpServerAndEmail"),"error");return}if(r.smtp_auth_enabled&&(!r.smtp_username||!r.smtp_password)){e(t("settings.email.errors.usernamePasswordRequired"),"error");return}h.mutate({smtp_host:r.smtp_host,smtp_port:r.smtp_port,smtp_username:r.smtp_username,smtp_password:r.smtp_password,smtp_security:r.smtp_security,smtp_auth_enabled:r.smtp_auth_enabled,smtp_from_email:r.smtp_from_email,test_recipient:s})},y=()=>{if(!u?.advanced_auth_enabled&&!u?.smtp_configured){e(t("settings.email.errors.configureSmtpFirst"),"error");return}p.mutate(!u?.advanced_auth_enabled)};return c?a.jsx("div",{className:"flex items-center justify-center p-12",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})}):a.jsxs("div",{className:"space-y-6",children:[u?.smtp_configured&&a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Q0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.advancedAuth")||"Advanced Authentication"})]}),a.jsx(Ne,{onClick:y,disabled:p.isPending,variant:u?.advanced_auth_enabled?"danger":"primary",children:u?.advanced_auth_enabled?a.jsxs(a.Fragment,{children:[a.jsx(_1,{className:"w-4 h-4"}),t("settings.email.disable")||"Disable"]}):a.jsxs(a.Fragment,{children:[a.jsx(kf,{className:"w-4 h-4"}),t("settings.email.enable")||"Enable"]})})]})}),a.jsx(Et,{children:a.jsx("div",{className:"space-y-4",children:u?.advanced_auth_enabled?a.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(mr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthEnabled")||"Advanced Authentication is enabled"}),a.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[a.jsx("li",{children:t("settings.email.feature1")||"Passwords are auto-generated and emailed to new users"}),a.jsx("li",{children:t("settings.email.feature2")||"Users can login with username or email"}),a.jsx("li",{children:t("settings.email.feature3")||"Forgot password feature is available"}),a.jsx("li",{children:t("settings.email.feature4")||"Admins can reset user passwords via email"})]})]})]})}):a.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(En,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthDisabled")||"Advanced Authentication is disabled"}),a.jsx("p",{className:"text-sm text-yellow-300",children:t("settings.email.advancedAuthDisabledDesc")||"Enable advanced authentication to activate email-based features for user management."})]})]})})})})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.smtpSettings")||"SMTP Configuration"})}),a.jsx(Et,{children:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[t("settings.email.smtpHost")||"SMTP Server"," *"]}),a.jsx("input",{type:"text",value:r.smtp_host,onChange:x=>i({...r,smtp_host:x.target.value}),placeholder:"smtp.gmail.com",className:"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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.smtpPort")||"SMTP Port"}),a.jsx("input",{type:"number",value:r.smtp_port,onChange:x=>i({...r,smtp_port:parseInt(x.target.value)||587}),placeholder:"587",className:"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"})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.security")||"Security"}),a.jsxs("select",{value:r.smtp_security,onChange:x=>i({...r,smtp_security:x.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",children:[a.jsx("option",{value:"starttls",children:t("settings.email.securityOptions.starttls")}),a.jsx("option",{value:"ssl",children:t("settings.email.securityOptions.ssl")}),a.jsx("option",{value:"none",children:t("settings.email.securityOptions.none")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.authentication")||"Authentication"}),a.jsxs("select",{value:r.smtp_auth_enabled?"true":"false",onChange:x=>i({...r,smtp_auth_enabled:x.target.value==="true"}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",children:[a.jsx("option",{value:"true",children:t("settings.email.authOptions.enabled")}),a.jsx("option",{value:"false",children:t("settings.email.authOptions.disabled")})]})]})]}),r.smtp_auth_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.username")||"Username"}),a.jsx("input",{type:"text",value:r.smtp_username||"",onChange:x=>i({...r,smtp_username:x.target.value}),placeholder:"your.email@gmail.com",className:"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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.password")||"Password"}),a.jsx("input",{type:"password",value:r.smtp_password||"",onChange:x=>i({...r,smtp_password:x.target.value}),placeholder:l?"••••••••":"App password",className:"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"})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[t("settings.email.fromEmail")||"From Email"," *"]}),a.jsx("input",{type:"email",value:r.smtp_from_email,onChange:x=>i({...r,smtp_from_email:x.target.value}),placeholder:"your@email.com",className:"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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.fromName")||"From Name"}),a.jsx("input",{type:"text",value:r.smtp_from_name,onChange:x=>i({...r,smtp_from_name:x.target.value}),placeholder:"BamBuddy",className:"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"})]})]}),a.jsx("div",{className:"flex gap-2",children:a.jsx(Ne,{onClick:m,disabled:d.isPending,className:"flex-1",children:d.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),t("settings.email.saving")||"Saving..."]}):t("settings.email.save")||"Save Settings"})})]})})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.testConnection")||"Test SMTP Connection"})}),a.jsx(Et,{children:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.testRecipient")||"Test Recipient Email"}),a.jsx("input",{type:"email",value:s,onChange:x=>o(x.target.value),placeholder:"test@example.com",className:"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"})]}),a.jsx(Ne,{onClick:b,disabled:h.isPending,variant:"secondary",children:h.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),t("settings.email.sending")||"Sending..."]}):a.jsxs(a.Fragment,{children:[a.jsx(kk,{className:"w-4 h-4"}),t("settings.email.sendTest")||"Send Test Email"]})})]})})]})]})}const QKe={get:"bg-blue-500/20 text-blue-400 border-blue-500/30",post:"bg-green-500/20 text-green-400 border-green-500/30",put:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",patch:"bg-orange-500/20 text-orange-400 border-orange-500/30",delete:"bg-red-500/20 text-red-400 border-red-500/30"};function ZKe(t,e){const n=e.replace("#/","").split("/");let r=t;for(const i of n)r=r[i];return r}function y0(t,e,n=0){if(n>5)return"...";if(e.$ref)return y0(t,ZKe(t,e.$ref),n+1);if(e.allOf){const r={};for(const i of e.allOf){const s=y0(t,i,n+1);typeof s=="object"&&s!==null&&Object.assign(r,s)}return r}if(e.example!==void 0)return e.example;if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:"string";case"integer":case"number":return 0;case"boolean":return!1;case"array":return e.items?[y0(t,e.items,n+1)]:[];case"object":if(e.properties){const r={};for(const[i,s]of Object.entries(e.properties))r[i]=y0(t,s,n+1);return r}return{};default:return null}}function JKe({path:t,method:e,spec:n,schema:r,apiKey:i}){const[s,o]=_.useState(!1),[l,c]=_.useState({}),[u,d]=_.useState(""),[h,p]=_.useState(null),[m,b]=_.useState(!1),[y,x]=_.useState(!1);_.useEffect(()=>{if(s&&n.parameters){const R={};for(const C of n.parameters)C.schema?.default!==void 0&&(R[C.name]=String(C.schema.default));c(C=>({...R,...C}))}},[s,n.parameters]),_.useEffect(()=>{if(s&&n.requestBody?.content?.["application/json"]?.schema&&!u){const R=n.requestBody.content["application/json"].schema,C=y0(r,R);d(JSON.stringify(C,null,2))}},[s,n.requestBody,r,u]);const S=(()=>{const R=[];for(const C of n.parameters||[])if(C.in==="path"||C.required){const P=l[C.name];(P===void 0||P==="")&&R.push(C.name)}return R})(),N=async()=>{if(S.length>0){p({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${S.join(", ")}`,duration:0});return}b(!0),p(null);try{let R=t;const C=new URLSearchParams;for(const oe of n.parameters||[]){const B=l[oe.name];B!==void 0&&B!==""&&(oe.in==="path"?R=R.replace(`{${oe.name}}`,encodeURIComponent(B)):oe.in==="query"&&C.append(oe.name,B))}const P=C.toString(),U=`${R}${P?`?${P}`:""}`,F={"Content-Type":"application/json"};i&&(F["X-API-Key"]=i);const H={method:e.toUpperCase(),headers:F};["post","put","patch"].includes(e)&&u&&(H.body=u);const D=performance.now(),$=await fetch(U,H),G=Math.round(performance.now()-D),I={};$.headers.forEach((oe,B)=>{I[B]=oe});let K;$.headers.get("content-type")?.includes("application/json")?K=await $.json():K=await $.text(),p({status:$.status,statusText:$.statusText,headers:I,body:K,duration:G})}catch(R){p({status:0,statusText:"Network Error",headers:{},body:R instanceof Error?R.message:"Unknown error",duration:0})}finally{b(!1)}},T=async()=>{if(h){const R=typeof h.body=="string"?h.body:JSON.stringify(h.body,null,2);try{await navigator.clipboard.writeText(R),x(!0),setTimeout(()=>x(!1),2e3)}catch{const C=document.createElement("textarea");C.value=R,C.style.position="fixed",C.style.left="-999999px",document.body.appendChild(C),C.select(),document.execCommand("copy"),document.body.removeChild(C),x(!0),setTimeout(()=>x(!1),2e3)}}},M=(n.parameters||[]).filter(R=>R.in==="path"),A=(n.parameters||[]).filter(R=>R.in==="query"),k=["post","put","patch"].includes(e)&&n.requestBody;return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center gap-3 p-3 hover:bg-bambu-dark-tertiary/50 transition-colors text-left",children:[s?a.jsx(fr,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):a.jsx(ks,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:`px-2 py-0.5 text-xs font-mono font-semibold uppercase rounded border ${QKe[e]||"bg-gray-500/20 text-gray-400"}`,children:e}),a.jsx("code",{className:"text-sm text-white font-mono flex-1 truncate",children:t}),n.summary&&a.jsx("span",{className:"text-sm text-bambu-gray truncate max-w-[40%]",children:n.summary})]}),s&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary p-4 space-y-4 bg-bambu-dark/50",children:[n.description&&a.jsx("p",{className:"text-sm text-bambu-gray",children:n.description}),M.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Path Parameters"}),a.jsx("div",{className:"space-y-2",children:M.map(R=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[R.name,R.required&&a.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),a.jsx("input",{type:"text",value:l[R.name]||"",onChange:C=>c(P=>({...P,[R.name]:C.target.value})),placeholder:R.description||R.schema?.type||"value",className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none"})]},R.name))})]}),A.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Query Parameters"}),a.jsx("div",{className:"space-y-2",children:A.map(R=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[R.name,R.required&&a.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),R.schema?.enum?a.jsxs("select",{value:l[R.name]||"",onChange:C=>c(P=>({...P,[R.name]:C.target.value})),className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:"-- Select --"}),R.schema.enum.map(C=>a.jsx("option",{value:C,children:C},C))]}):a.jsx("input",{type:"text",value:l[R.name]||"",onChange:C=>c(P=>({...P,[R.name]:C.target.value})),placeholder:R.description||R.schema?.type||"value",className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none"})]},R.name))})]}),k&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Request Body"}),a.jsx("textarea",{value:u,onChange:R=>d(R.target.value),rows:8,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono focus:border-bambu-green focus:outline-none resize-y",placeholder:"JSON request body..."})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ne,{onClick:N,disabled:m,children:[m?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Eo,{className:"w-4 h-4"}),"Execute"]}),S.length>0&&a.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[a.jsx(Ti,{className:"w-3 h-3"}),"Fill in: ",S.join(", ")]})]}),h&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h4",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Response",a.jsxs("span",{className:`px-2 py-0.5 text-xs rounded ${h.status>=200&&h.status<300?"bg-green-500/20 text-green-400":h.status>=400?"bg-red-500/20 text-red-400":"bg-yellow-500/20 text-yellow-400"}`,children:[h.status," ",h.statusText]}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[h.duration,"ms"]})]}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:T,children:y?a.jsx(mr,{className:"w-3 h-3 text-green-400"}):a.jsx(zl,{className:"w-3 h-3"})})]}),a.jsx("pre",{className:"p-3 bg-bambu-dark rounded-lg text-sm font-mono text-white overflow-auto max-h-96 border border-bambu-dark-tertiary",children:typeof h.body=="string"?h.body:JSON.stringify(h.body,null,2)})]})]})]})}function eXe({apiKey:t=""}){const[e,n]=_.useState(null),[r,i]=_.useState(!0),[s,o]=_.useState(null),[l,c]=_.useState(new Set),[u,d]=_.useState("");if(_.useEffect(()=>{async function x(){try{const v=await fetch("/openapi.json");if(!v.ok)throw new Error("Failed to fetch OpenAPI schema");const S=await v.json();n(S)}catch(v){o(v instanceof Error?v.message:"Unknown error")}finally{i(!1)}}x()},[]),r)return a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(s||!e)return a.jsx(St,{children:a.jsx(Et,{className:"py-8",children:a.jsxs("div",{className:"text-center text-red-400",children:[a.jsx(Ti,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),a.jsx("p",{children:"Failed to load API schema"}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:s})]})})});const h={};for(const[x,v]of Object.entries(e.paths))for(const[S,N]of Object.entries(v)){if(S==="parameters")continue;const T=N.tags||["Other"];for(const M of T)h[M]||(h[M]=[]),h[M].push({path:x,method:S,spec:N})}const p=Object.entries(h).map(([x,v])=>{if(!u)return{tag:x,endpoints:v};const S=v.filter(({path:N,method:T,spec:M})=>{const A=u.toLowerCase();return N.toLowerCase().includes(A)||T.toLowerCase().includes(A)||(M.summary?.toLowerCase()||"").includes(A)||(M.description?.toLowerCase()||"").includes(A)});return{tag:x,endpoints:S}}).filter(({endpoints:x})=>x.length>0).sort((x,v)=>x.tag.localeCompare(v.tag)),m=x=>{c(v=>{const S=new Set(v);return S.has(x)?S.delete(x):S.add(x),S})},b=()=>{c(new Set(p.map(x=>x.tag)))},y=()=>{c(new Set)};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-4",children:[a.jsx("div",{className:"flex-1",children:a.jsx("input",{type:"text",value:u,onChange:x=>d(x.target.value),placeholder:"Search endpoints...",className:"w-full max-w-md px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ne,{variant:"secondary",size:"sm",onClick:b,children:"Expand All"}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:y,children:"Collapse All"}),a.jsxs("a",{href:"/docs",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-bambu-green hover:underline",children:[a.jsx(Xr,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[p.reduce((x,v)=>x+v.endpoints.length,0)," endpoints in ",p.length," categories"]}),a.jsx("div",{className:"space-y-3",children:p.map(({tag:x,endpoints:v})=>a.jsxs(St,{children:[a.jsx("button",{onClick:()=>m(x),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/30 transition-colors text-left",children:a.jsxs("div",{className:"flex items-center gap-2",children:[l.has(x)?a.jsx(fr,{className:"w-5 h-5 text-bambu-gray"}):a.jsx(ks,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:x.replace(/-/g," ")}),a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-2 py-0.5 rounded-full text-bambu-gray",children:v.length})]})}),l.has(x)&&a.jsx(Et,{className:"pt-0 space-y-2",children:v.map(({path:S,method:N,spec:T})=>a.jsx(JKe,{path:S,method:N,spec:T,schema:e,apiKey:t},`${N}-${S}`))})]},x))})]})}const tXe=["general","network","plugs","email","notifications","filament","apikeys","virtual-printer","users","backup"];function nXe(){const t=an(),e=Ec(),[n,r]=RR(),{t:i,i18n:s}=Yt(),{showToast:o}=Tn(),{authEnabled:l,user:c,refreshAuth:u}=Ir(),{mode:d,darkStyle:h,darkBackground:p,darkAccent:m,lightStyle:b,lightBackground:y,lightAccent:x,setDarkStyle:v,setDarkBackground:S,setDarkAccent:N,setLightStyle:T,setLightBackground:M,setLightAccent:A}=Dm(),[k,R]=_.useState(null),[C,P]=_.useState(!1),[U,F]=_.useState(null),[H,D]=_.useState(!1),[$,G]=_.useState(null),[I,K]=_.useState(null),[Q,oe]=_.useState(!1),[B,W]=_.useState(QW()),J=n.get("tab"),ne=J&&tXe.includes(J)?J:"general",[me,fe]=_.useState(ne),de=ie=>{fe(ie),ie==="general"?n.delete("tab"):n.set("tab",ie),r(n,{replace:!0})},[Re,se]=_.useState(!1),[ke,Fe]=_.useState(""),[ce,Ve]=_.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0}),[V,Y]=_.useState(null),[ue,q]=_.useState(null),[re,X]=_.useState(""),[le,pe]=_.useState(!1),[ee,z]=_.useState(!1),[O,Z]=_.useState(null),[ge,Ce]=_.useState(!1),[_e,Te]=_.useState(!1),[we,$e]=_.useState(!1),[Ge,ze]=_.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[be,Me]=_.useState(!1),[Be,Ae]=_.useState(!1),[qe,ve]=_.useState(!1),[et,Ee]=_.useState(null),[Ye,je]=_.useState(null),[Pe,ye]=_.useState(null),[Qe,yt]=_.useState(!1),[at,Ut]=_.useState({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),[zt,Ie]=_.useState(!1),[vt,Gt]=_.useState(null),[dn,fn]=_.useState(null),[vn,dr]=_.useState({name:"",description:"",permissions:[]}),[ar,kn]=_.useState(new Set),[Bn,Hr]=_.useState(null),[Ma,De]=_.useState(!1),[tt,ht]=_.useState({}),[mt,ut]=_.useState({}),Dt=ie=>{W(ie),Zfe(ie),o(i("settings.toast.settingsSaved"),"success")},he=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},{data:Le,isLoading:Ke}=it({queryKey:["settings"],queryFn:ae.getSettings}),{data:Ue,isLoading:Se}=it({queryKey:["smart-plugs"],queryFn:ae.getSmartPlugs}),{data:nt,isLoading:xt}=it({queryKey:["smart-plugs-energy",Ue?.map(ie=>ie.id)],queryFn:async()=>{if(!Ue||Ue.length===0)return null;const ie=await Promise.all(Ue.filter(Ca=>Ca.enabled).map(async Ca=>{try{const fs=await ae.getSmartPlugStatus(Ca.id);return{plug:Ca,status:fs}}catch{return{plug:Ca,status:null}}}));let kt=0,Hn=0,ir=0,jo=0,cd=0;for(const{plug:Ca,status:fs}of ie){const r2=Ca.plug_type==="mqtt"&&fs?.energy?.power!=null;(fs?.reachable||r2)&&fs?.energy&&(cd++,fs.energy?.power!=null&&(kt+=fs.energy.power),fs.energy?.today!=null&&(Hn+=fs.energy.today),fs.energy?.yesterday!=null&&(ir+=fs.energy.yesterday),fs.energy?.total!=null&&(jo+=fs.energy.total))}return{totalPower:kt,totalToday:Hn,totalYesterday:ir,totalLifetime:jo,reachableCount:cd,totalPlugs:Ue.filter(Ca=>Ca.enabled).length}},enabled:me==="plugs"&&!!Ue&&Ue.length>0,refetchInterval:me==="plugs"?1e4:!1}),{data:rt,isLoading:Ct}=it({queryKey:["notification-providers"],queryFn:ae.getNotificationProviders}),{data:It,isLoading:Rt}=it({queryKey:["api-keys"],queryFn:ae.getAPIKeys}),Tt=dt({mutationFn:ie=>ae.createAPIKey(ie),onSuccess:ie=>{Y(ie.key||null),se(!1),Fe(""),t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyCreated"))},onError:ie=>{o(`Failed to create API key: ${ie.message}`,"error")}}),mn=dt({mutationFn:ie=>ae.deleteAPIKey(ie),onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyDeleted"))},onError:ie=>{o(`Failed to delete API key: ${ie.message}`,"error")}}),{data:Bt}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:pn,isLoading:Mn}=it({queryKey:["notification-templates"],queryFn:ae.getNotificationTemplates}),{data:jn}=it({queryKey:["virtual-printer-settings"],queryFn:S1.getSettings,refetchInterval:1e4}),Kt=jn?.status?.running??!1,{data:Qt}=it({queryKey:["ffmpeg-status"],queryFn:ae.checkFfmpeg}),{data:Zt}=it({queryKey:["version"],queryFn:ae.getVersion}),{data:cn,refetch:$r,isRefetching:Qn}=it({queryKey:["updateCheck"],queryFn:ae.checkForUpdates,staleTime:300*1e3}),{data:ai,refetch:gt}=it({queryKey:["updateStatus"],queryFn:ae.getUpdateStatus,refetchInterval:ie=>{const kt=ie.state.data;return kt?.status==="downloading"||kt?.status==="installing"?1e3:!1}}),{data:jt}=it({queryKey:["mqtt-status"],queryFn:ae.getMQTTStatus,refetchInterval:me==="network"?5e3:!1}),{data:gn}=it({queryKey:["github-backup-status"],queryFn:ae.getGitHubBackupStatus}),{data:Nt}=it({queryKey:["cloud-status"],queryFn:ae.getCloudStatus}),{data:un={advanced_auth_enabled:!1,smtp_configured:!1}}=it({queryKey:["advancedAuthStatus"],queryFn:()=>ae.getAdvancedAuthStatus()}),{hasPermission:In}=Ir(),{data:rr=[],isLoading:ua}=it({queryKey:["users"],queryFn:()=>ae.getUsers(),enabled:l&&In("users:read")}),{data:Si=[],isLoading:Jt}=it({queryKey:["groups"],queryFn:()=>ae.getGroups(),enabled:l&&In("groups:read")}),{data:wn}=it({queryKey:["permissions"],queryFn:()=>ae.getPermissions(),enabled:l&&In("groups:read")}),Ea=dt({mutationFn:ie=>ae.createUser(ie),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Ae(!1),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userCreated"))},onError:ie=>{o(ie.message,"error")}}),Ta=dt({mutationFn:({id:ie,data:kt})=>ae.updateUser(ie,kt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),ve(!1),Ee(null),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userUpdated"))},onError:ie=>{o(ie.message,"error")}}),si=dt({mutationFn:({id:ie,deleteItems:kt})=>ae.deleteUser(ie,kt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),o(i("settings.toast.userDeleted")),je(null),ye(null)},onError:ie=>{o(ie.message,"error")}}),yl=dt({mutationFn:ie=>ae.resetUserPassword({user_id:ie}),onSuccess:ie=>{o(ie.message,"success")},onError:ie=>{o(ie.message,"error")}}),Pc=async ie=>{je(ie),yt(!0);try{const kt=await ae.getUserItemsCount(ie);ye(kt)}catch{ye({archives:0,queue_items:0,library_files:0})}finally{yt(!1)}},us=dt({mutationFn:ie=>ae.createGroup(ie),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),Ie(!1),da(),o(i("settings.toast.groupCreated"))},onError:ie=>{o(ie.message,"error")}}),ds=dt({mutationFn:({id:ie,data:kt})=>ae.updateGroup(ie,kt),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),Gt(null),da(),o(i("settings.toast.groupUpdated"))},onError:ie=>{o(ie.message,"error")}}),jc=dt({mutationFn:ie=>ae.deleteGroup(ie),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),o(i("settings.toast.groupDeleted"))},onError:ie=>{o(ie.message,"error")}}),hs=()=>{const ie=un?.advanced_auth_enabled||!1;if(!at.username){o(i("settings.toast.fillRequiredFields"),"error");return}if(ie&&!at.email){o("Email is required when advanced authentication is enabled","error");return}if(!ie){if(!at.password){o(i("settings.toast.fillRequiredFields"),"error");return}if(at.password!==at.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(at.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}}Ea.mutate({username:at.username,password:ie?void 0:at.password,email:at.email||void 0,role:at.role,group_ids:at.group_ids.length>0?at.group_ids:void 0})},Po=ie=>{if(at.password){if(at.password!==at.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(at.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}}const kt={username:at.username||void 0,password:at.password||void 0,role:at.role,group_ids:at.group_ids};kt.password||delete kt.password,Ta.mutate({id:ie,data:kt})},Aa=ie=>{Ee(ie.id),Ut({username:ie.username,password:"",email:ie.email||"",confirmPassword:"",role:ie.role,group_ids:ie.groups?.map(kt=>kt.id)||[]}),ve(!0)},_r=ie=>{Ut(kt=>({...kt,group_ids:kt.group_ids.includes(ie)?kt.group_ids.filter(Hn=>Hn!==ie):[...kt.group_ids,ie]}))},da=()=>{dr({name:"",description:"",permissions:[]}),kn(new Set)},eo=()=>{if(!vn.name.trim()){o(i("settings.toast.enterGroupName"),"error");return}us.mutate({name:vn.name,description:vn.description||void 0,permissions:vn.permissions})},Qr=()=>{if(vt){if(!vn.name.trim()){o(i("settings.toast.enterGroupName"),"error");return}ds.mutate({id:vt.id,data:{name:vn.name!==vt.name?vn.name:void 0,description:vn.description,permissions:vn.permissions}})}},Vb=ie=>{Gt(ie),dr({name:ie.name,description:ie.description||"",permissions:ie.permissions});const kt=new Set;wn?.categories.forEach(Hn=>{Hn.permissions.some(ir=>ie.permissions.includes(ir.value))&&kt.add(Hn.name)}),kn(kt)},Um=ie=>{kn(kt=>{const Hn=new Set(kt);return Hn.has(ie)?Hn.delete(ie):Hn.add(ie),Hn})},Av=ie=>{dr(kt=>{const Hn=kt.permissions.includes(ie)?kt.permissions.filter(ir=>ir!==ie):[...kt.permissions,ie];return{...kt,permissions:Hn}})},Bm=(ie,kt)=>{dr(Hn=>{const ir=ie.permissions.map(Ca=>Ca.value),jo=Hn.permissions.filter(Ca=>!ir.includes(Ca)),cd=kt?[...jo,...ir]:jo;return{...Hn,permissions:cd}})},ad=ie=>ie.permissions.every(kt=>vn.permissions.includes(kt.value)),Gb=ie=>{const kt=ie.permissions.filter(Hn=>vn.permissions.includes(Hn.value));return kt.length>0&&kt.length{ie.is_docker?o(ie.message,"error"):gt()}}),[js,sd]=_.useState(null),Dc=dt({mutationFn:ae.testAllNotificationProviders,onSuccess:ie=>{sd(ie),t.invalidateQueries({queryKey:["notification-providers"]}),ie.failed===0?o(`All ${ie.tested} providers tested successfully!`,"success"):o(`${ie.success}/${ie.tested} providers succeeded`,ie.failed>0?"error":"success")},onError:ie=>{o(`Failed to test providers: ${ie.message}`,"error")}}),Xh=dt({mutationFn:async ie=>{if(!Ue)return{success:0,failed:0};const kt=Ue.filter(ir=>ir.enabled),Hn=await Promise.all(kt.map(async ir=>{try{return await ae.controlSmartPlug(ir.id,ie),{success:!0}}catch{return{success:!1}}}));return{success:Hn.filter(ir=>ir.success).length,failed:Hn.filter(ir=>!ir.success).length}},onSuccess:(ie,kt)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),ie.failed===0?o(`All ${ie.success} plugs turned ${kt}`,"success"):o(`${ie.success} plugs turned ${kt}, ${ie.failed} failed`,"error")},onError:ie=>{o(`Failed: ${ie.message}`,"error")}}),Rc=_.useRef(null),od=_.useRef(!1),ld=_.useRef(!0);_.useEffect(()=>{if(Le&&!k){const ie={...Le,external_url:Le.external_url||window.location.origin};R(ie),setTimeout(()=>{ld.current=!1},100)}},[Le,k]);const Yh=dt({mutationFn:ae.updateSettings,onSuccess:ie=>{t.setQueryData(["settings"],ie),R(ie),t.invalidateQueries({queryKey:["archiveStats"]}),o(i("settings.toast.settingsSaved"),"success")},onError:ie=>{o(`Failed to save: ${ie.message}`,"error")},onSettled:()=>{od.current=!1}}),qb=dt({mutationFn:({id:ie,data:kt})=>ae.updatePrinter(ie,kt),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o(i("settings.toast.cameraSettingsSaved"),"success")},onError:ie=>{o(`Failed to update printer: ${ie.message}`,"error")}});_.useEffect(()=>{if(!(ld.current||!k||!Le||!(Le.auto_archive!==k.auto_archive||Le.save_thumbnails!==k.save_thumbnails||Le.capture_finish_photo!==k.capture_finish_photo||Le.default_filament_cost!==k.default_filament_cost||Le.currency!==k.currency||Le.energy_cost_per_kwh!==k.energy_cost_per_kwh||Le.energy_tracking_mode!==k.energy_tracking_mode||Le.check_updates!==k.check_updates||(Le.check_printer_firmware??!0)!==(k.check_printer_firmware??!0)||Le.notification_language!==k.notification_language||Le.ams_humidity_good!==k.ams_humidity_good||Le.ams_humidity_fair!==k.ams_humidity_fair||Le.ams_temp_good!==k.ams_temp_good||Le.ams_temp_fair!==k.ams_temp_fair||Le.ams_history_retention_days!==k.ams_history_retention_days||Le.per_printer_mapping_expanded!==k.per_printer_mapping_expanded||Le.date_format!==k.date_format||Le.time_format!==k.time_format||Le.default_printer_id!==k.default_printer_id||Le.ftp_retry_enabled!==k.ftp_retry_enabled||Le.ftp_retry_count!==k.ftp_retry_count||Le.ftp_retry_delay!==k.ftp_retry_delay||Le.ftp_timeout!==k.ftp_timeout||Le.mqtt_enabled!==k.mqtt_enabled||Le.mqtt_broker!==k.mqtt_broker||Le.mqtt_port!==k.mqtt_port||Le.mqtt_username!==k.mqtt_username||Le.mqtt_password!==k.mqtt_password||Le.mqtt_topic_prefix!==k.mqtt_topic_prefix||Le.mqtt_use_tls!==k.mqtt_use_tls||Le.external_url!==k.external_url||Le.ha_enabled!==k.ha_enabled||Le.ha_url!==k.ha_url||Le.ha_token!==k.ha_token||(Le.library_archive_mode??"ask")!==(k.library_archive_mode??"ask")||Number(Le.library_disk_warning_gb??5)!==Number(k.library_disk_warning_gb??5)||(Le.camera_view_mode??"window")!==(k.camera_view_mode??"window")||(Le.preferred_slicer??"bambu_studio")!==(k.preferred_slicer??"bambu_studio")||Le.prometheus_enabled!==k.prometheus_enabled||Le.prometheus_token!==k.prometheus_token))&&!od.current)return Rc.current&&clearTimeout(Rc.current),Rc.current=setTimeout(()=>{if(od.current)return;od.current=!0;const kt={auto_archive:k.auto_archive,save_thumbnails:k.save_thumbnails,capture_finish_photo:k.capture_finish_photo,default_filament_cost:k.default_filament_cost,currency:k.currency,energy_cost_per_kwh:k.energy_cost_per_kwh,energy_tracking_mode:k.energy_tracking_mode,check_updates:k.check_updates,check_printer_firmware:k.check_printer_firmware,notification_language:k.notification_language,ams_humidity_good:k.ams_humidity_good,ams_humidity_fair:k.ams_humidity_fair,ams_temp_good:k.ams_temp_good,ams_temp_fair:k.ams_temp_fair,ams_history_retention_days:k.ams_history_retention_days,per_printer_mapping_expanded:k.per_printer_mapping_expanded,date_format:k.date_format,time_format:k.time_format,default_printer_id:k.default_printer_id,ftp_retry_enabled:k.ftp_retry_enabled,ftp_retry_count:k.ftp_retry_count,ftp_retry_delay:k.ftp_retry_delay,ftp_timeout:k.ftp_timeout,mqtt_enabled:k.mqtt_enabled,mqtt_broker:k.mqtt_broker,mqtt_port:k.mqtt_port,mqtt_username:k.mqtt_username,mqtt_password:k.mqtt_password,mqtt_topic_prefix:k.mqtt_topic_prefix,mqtt_use_tls:k.mqtt_use_tls,external_url:k.external_url,ha_enabled:k.ha_enabled,ha_url:k.ha_url,ha_token:k.ha_token,library_archive_mode:k.library_archive_mode,library_disk_warning_gb:k.library_disk_warning_gb,camera_view_mode:k.camera_view_mode,preferred_slicer:k.preferred_slicer,prometheus_enabled:k.prometheus_enabled,prometheus_token:k.prometheus_token};Yh.mutate(kt)},500),()=>{Rc.current&&clearTimeout(Rc.current)}},[k,Le,Yh]);const Sn=_.useCallback((ie,kt)=>{R(Hn=>Hn?{...Hn,[ie]:kt}:null)},[]),t2=async(ie,kt,Hn)=>{if(!kt){o(i("settings.toast.enterCameraUrl"),"error");return}ut(ir=>({...ir,[ie]:!0})),ht(ir=>({...ir,[ie]:null}));try{const ir=await ae.testExternalCamera(ie,kt,Hn);ht(jo=>({...jo,[ie]:ir})),ir.success?o(i("settings.toast.cameraConnected",{resolution:ir.resolution||""}),"success"):o(ir.error||i("settings.toast.connectionFailed"),"error")}catch(ir){const jo=ir instanceof Error?ir.message:i("settings.toast.testFailed");ht(cd=>({...cd,[ie]:{success:!1,error:jo}})),o(jo,"error")}finally{ut(ir=>({...ir,[ie]:!1}))}},[Wb,Hm]=_.useState({}),Kb=_.useRef({}),Cv=_.useRef(new Set);_.useEffect(()=>{if(Bt){const ie={};Bt.forEach(kt=>{kt.external_camera_url&&!Cv.current.has(kt.id)&&(ie[kt.id]=kt.external_camera_url,Cv.current.add(kt.id))}),Object.keys(ie).length>0&&Hm(kt=>({...kt,...ie}))}},[Bt]);const n2=(ie,kt)=>{Hm(Hn=>({...Hn,[ie]:kt})),Kb.current[ie]&&clearTimeout(Kb.current[ie]),Kb.current[ie]=setTimeout(()=>{qb.mutate({id:ie,data:{external_camera_url:kt||null}})},800)},Pv=(ie,kt)=>{const Hn={};kt.type!==void 0&&(Hn.external_camera_type=kt.type||null),kt.enabled!==void 0&&(Hn.external_camera_enabled=kt.enabled),qb.mutate({id:ie,data:Hn})};return Ke||!k?a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"mb-8",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:i("settings.title")}),a.jsx("p",{className:"text-bambu-gray",children:i("settings.configureBambuddy")})]}),a.jsxs("div",{className:"flex flex-wrap gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>de("general"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${me==="general"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:i("settings.tabs.general")}),a.jsxs("button",{onClick:()=>de("plugs"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(sl,{className:"w-4 h-4"}),i("settings.tabs.smartPlugs"),Ue&&Ue.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Ue.length})]}),a.jsxs("button",{onClick:()=>de("email"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="email"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Q0,{className:"w-4 h-4"}),i("settings.tabs.globalEmail")||"Global Email",un?.advanced_auth_enabled&&a.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),a.jsxs("button",{onClick:()=>de("notifications"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(kg,{className:"w-4 h-4"}),i("settings.tabs.notifications"),rt&&rt.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:rt.length})]}),a.jsxs("button",{onClick:()=>de("filament"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Rue,{className:"w-4 h-4"}),i("settings.tabs.filament")]}),a.jsxs("button",{onClick:()=>de("network"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Eg,{className:"w-4 h-4"}),i("settings.tabs.network"),a.jsx("span",{className:`w-2 h-2 rounded-full ${jt?.enabled?"bg-green-400":"bg-gray-500"}`})]}),a.jsxs("button",{onClick:()=>de("apikeys"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Yo,{className:"w-4 h-4"}),i("settings.tabs.apiKeys"),It&&It.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:It.length})]}),a.jsxs("button",{onClick:()=>de("virtual-printer"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(jr,{className:"w-4 h-4"}),i("settings.tabs.virtualPrinter"),a.jsx("span",{className:`w-2 h-2 rounded-full ${Kt?"bg-green-400":"bg-gray-500"}`})]}),a.jsxs("button",{onClick:()=>de("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(zf,{className:"w-4 h-4"}),i("settings.tabs.users"),l&&a.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),a.jsxs("button",{onClick:()=>de("backup"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Au,{className:"w-4 h-4"}),i("settings.tabs.backup"),a.jsx("span",{className:`w-2 h-2 rounded-full ${Nt?.is_authenticated&&gn?.configured&&gn?.enabled?"bg-green-400":"bg-gray-500"}`})]})]}),me==="general"&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[a.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-xl",children:[a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.general")})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(gh,{className:"w-4 h-4 inline mr-1"}),i("settings.language")]}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:s.language,onChange:ie=>{s.changeLanguage(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:PU.map(ie=>a.jsxs("option",{value:ie.code,children:[ie.nativeName," (",ie.name,")"]},ie.code))}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.languageDescription")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultView")}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:B,onChange:ie=>Dt(ie.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:J0.map(ie=>a.jsx("option",{value:ie.to,children:i(ie.labelKey)},ie.id))}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.defaultViewDescription")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date Format"}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k.date_format||"system",onChange:ie=>Sn("date_format",ie.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"system",children:i("settings.systemDefault")}),a.jsx("option",{value:"us",children:"US (MM/DD/YYYY)"}),a.jsx("option",{value:"eu",children:"EU (DD/MM/YYYY)"}),a.jsx("option",{value:"iso",children:"ISO (YYYY-MM-DD)"})]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Time Format"}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k.time_format||"system",onChange:ie=>Sn("time_format",ie.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"system",children:i("settings.systemDefault")}),a.jsx("option",{value:"12h",children:"12-hour (3:30 PM)"}),a.jsx("option",{value:"24h",children:"24-hour (15:30)"})]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default Printer"}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k.default_printer_id??"",onChange:ie=>Sn("default_printer_id",ie.target.value?Number(ie.target.value):null),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"",children:i("settings.noDefaultPrinter")}),Bt?.map(ie=>a.jsx("option",{value:ie.id,children:ie.name},ie.id))]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Pre-select this printer for uploads, reprints, and other operations."})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.preferredSlicer")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k.preferred_slicer??"bambu_studio",onChange:ie=>Sn("preferred_slicer",ie.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"bambu_studio",children:"Bambu Studio"}),a.jsx("option",{value:"orcaslicer",children:"OrcaSlicer"})]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.preferredSlicerDescription")})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.sidebarOrder")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Drag items in the sidebar to reorder. Reset to default order here."})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:he,children:[a.jsx(Bu,{className:"w-4 h-4"}),"Reset"]})]})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(zW,{className:"w-5 h-5"}),"Appearance"]})}),a.jsxs(Et,{className:"space-y-6",children:[a.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${d==="dark"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Dark Mode",d==="dark"&&a.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),a.jsxs("select",{value:p,onChange:ie=>{S(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"neutral",children:"Neutral"}),a.jsx("option",{value:"warm",children:"Warm"}),a.jsx("option",{value:"cool",children:"Cool"}),a.jsx("option",{value:"oled",children:"OLED Black"}),a.jsx("option",{value:"slate",children:"Slate Blue"}),a.jsx("option",{value:"forest",children:"Forest Green"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),a.jsxs("select",{value:m,onChange:ie=>{N(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"green",children:"Green"}),a.jsx("option",{value:"teal",children:"Teal"}),a.jsx("option",{value:"blue",children:"Blue"}),a.jsx("option",{value:"orange",children:"Orange"}),a.jsx("option",{value:"purple",children:"Purple"}),a.jsx("option",{value:"red",children:"Red"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),a.jsxs("select",{value:h,onChange:ie=>{v(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"classic",children:"Classic"}),a.jsx("option",{value:"glow",children:"Glow"}),a.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),a.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${d==="light"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Light Mode",d==="light"&&a.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),a.jsxs("select",{value:y,onChange:ie=>{M(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"neutral",children:"Neutral"}),a.jsx("option",{value:"warm",children:"Warm"}),a.jsx("option",{value:"cool",children:"Cool"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),a.jsxs("select",{value:x,onChange:ie=>{A(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"green",children:"Green"}),a.jsx("option",{value:"teal",children:"Teal"}),a.jsx("option",{value:"blue",children:"Blue"}),a.jsx("option",{value:"orange",children:"Orange"}),a.jsx("option",{value:"purple",children:"Purple"}),a.jsx("option",{value:"red",children:"Red"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),a.jsxs("select",{value:b,onChange:ie=>{T(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"classic",children:"Classic"}),a.jsx("option",{value:"glow",children:"Glow"}),a.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Toggle between dark and light mode using the sun/moon icon in the sidebar."})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.archiveSettings")})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:"Auto-archive prints"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically save 3MF files when prints complete"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.auto_archive,onChange:ie=>Sn("auto_archive",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.saveThumbnails")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Extract and save preview images from 3MF files"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.save_thumbnails,onChange:ie=>Sn("save_thumbnails",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.captureFinishPhoto")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Take a photo from printer camera when print completes"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.capture_finish_photo,onChange:ie=>Sn("capture_finish_photo",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),k.capture_finish_photo&&Qt&&!Qt.installed&&a.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[a.jsx(En,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-sm",children:[a.jsx("p",{className:"text-yellow-500 font-medium",children:"ffmpeg not installed"}),a.jsxs("p",{className:"text-bambu-gray mt-1",children:["Camera capture requires ffmpeg. Install it via"," ",a.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"brew install ffmpeg"})," (macOS) or"," ",a.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"apt install ffmpeg"})," (Linux)."]})]})]})]})]})]}),a.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-md",children:[a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(KR,{className:"w-5 h-5 text-bambu-green"}),"Camera"]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Camera View Mode"}),a.jsxs("select",{value:k.camera_view_mode??"window",onChange:ie=>Sn("camera_view_mode",ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"window",children:i("settings.newWindow")}),a.jsx("option",{value:"embedded",children:i("settings.embeddedOverlay")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:k.camera_view_mode==="embedded"?"Camera opens in a resizable overlay on the main screen":"Camera opens in a separate browser window"})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:i("settings.externalCameras")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Configure external cameras to replace the built-in printer camera. Supports MJPEG streams, RTSP, HTTP snapshots, and USB cameras (V4L2). When enabled, the external camera is used for live view and finish photos."}),Bt&&Bt.length>0?a.jsx("div",{className:"space-y-3",children:Bt.map(ie=>a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-white font-medium text-sm",children:ie.name}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ie.external_camera_enabled,onChange:kt=>Pv(ie.id,{enabled:kt.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),ie.external_camera_enabled&&a.jsxs("div",{className:"space-y-2 mt-2",children:[a.jsx("input",{type:"text",placeholder:ie.external_camera_type==="usb"?"Device path (/dev/video0)":"Camera URL (rtsp://... or http://...)",value:Wb[ie.id]??ie.external_camera_url??"",onChange:kt=>n2(ie.id,kt.target.value),className:"w-full 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:"flex gap-2",children:[a.jsxs("select",{value:ie.external_camera_type||"mjpeg",onChange:kt=>Pv(ie.id,{type:kt.target.value}),className:"flex-1 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",children:[a.jsx("option",{value:"mjpeg",children:"MJPEG Stream"}),a.jsx("option",{value:"rtsp",children:"RTSP Stream"}),a.jsx("option",{value:"snapshot",children:"HTTP Snapshot"}),a.jsx("option",{value:"usb",children:"USB Camera (V4L2)"})]}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:()=>t2(ie.id,Wb[ie.id]??ie.external_camera_url??"",ie.external_camera_type||"mjpeg"),disabled:mt[ie.id]||!(Wb[ie.id]??ie.external_camera_url),children:mt[ie.id]?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):"Test"})]}),tt[ie.id]&&a.jsx("div",{className:`text-xs flex items-center gap-1 ${tt[ie.id]?.success?"text-green-500":"text-red-500"}`,children:tt[ie.id]?.success?a.jsxs(a.Fragment,{children:[a.jsx(mr,{className:"w-3 h-3"}),"Connected",tt[ie.id]?.resolution&&` (${tt[ie.id]?.resolution})`]}):a.jsxs(a.Fragment,{children:[a.jsx(Zi,{className:"w-3 h-3"}),tt[ie.id]?.error||i("settings.toast.connectionFailed")]})})]})]},ie.id))}):a.jsx("p",{className:"text-xs text-bambu-gray italic",children:i("settings.noPrintersConfigured")})]})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.costTracking")})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default filament cost (per kg)"}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:k.default_filament_cost,onChange:ie=>Sn("default_filament_cost",parseFloat(ie.target.value)||0),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Currency"}),a.jsxs("select",{value:k.currency,onChange:ie=>Sn("currency",ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"USD",children:"USD ($)"}),a.jsx("option",{value:"EUR",children:"EUR (€)"}),a.jsx("option",{value:"GBP",children:"GBP (£)"}),a.jsx("option",{value:"CHF",children:"CHF (Fr.)"}),a.jsx("option",{value:"JPY",children:"JPY (¥)"}),a.jsx("option",{value:"CNY",children:"CNY (¥)"}),a.jsx("option",{value:"CAD",children:"CAD ($)"}),a.jsx("option",{value:"AUD",children:"AUD ($)"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Electricity cost per kWh"}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:k.energy_cost_per_kwh,onChange:ie=>Sn("energy_cost_per_kwh",parseFloat(ie.target.value)||0),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy display mode"}),a.jsxs("select",{value:k.energy_tracking_mode||"total",onChange:ie=>Sn("energy_tracking_mode",ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"print",children:i("settings.printsOnly")}),a.jsx("option",{value:"total",children:i("settings.totalConsumption")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:k.energy_tracking_mode==="print"?"Dashboard shows sum of energy used during prints":"Dashboard shows lifetime energy from smart plugs"})]})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ys,{className:"w-5 h-5 text-bambu-green"}),"File Manager"]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Create Archive Entry When Printing"}),a.jsxs("select",{value:k.library_archive_mode??"ask",onChange:ie=>Sn("library_archive_mode",ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"always",children:i("settings.archiveMode.always")}),a.jsx("option",{value:"never",children:i("settings.archiveMode.never")}),a.jsx("option",{value:"ask",children:i("settings.archiveMode.ask")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"When printing from File Manager, optionally create an archive entry"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Low Disk Space Warning"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:k.library_disk_warning_gb??5,onChange:ie=>Sn("library_disk_warning_gb",parseFloat(ie.target.value)||5),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:"GB"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Show warning when free disk space falls below this threshold"})]})]})]})]}),a.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-sm",children:[a.jsx(qKe,{}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Updates"})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.checkForUpdatesLabel")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically check for new versions on startup"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.check_updates,onChange:ie=>Sn("check_updates",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.checkPrinterFirmware")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Check for printer firmware updates from Bambu Lab"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.check_printer_firmware??!0,onChange:ie=>Sn("check_printer_firmware",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.currentVersion")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",Zt?.version||"..."]})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>$r(),disabled:Qn,children:[Qn?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Or,{className:"w-4 h-4"}),"Check now"]})]}),cn?.update_available?a.jsxs("div",{className:"mt-4 p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:[a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{children:[a.jsxs("p",{className:"text-bambu-green font-medium",children:["Update available: v",cn.latest_version]}),cn.release_name&&cn.release_name!==cn.latest_version&&a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:cn.release_name})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[cn.release_notes&&a.jsx("button",{onClick:()=>Ce(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:"Release Notes"}),cn.release_url&&a.jsx("a",{href:cn.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:i("settings.viewReleaseOnGitHub"),children:a.jsx(Xr,{className:"w-4 h-4"})})]})]}),ai?.status==="downloading"||ai?.status==="installing"?a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{children:ai.message})]}),a.jsx("div",{className:"mt-2 w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${ai.progress}%`}})})]}):ai?.status==="complete"?a.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:ai.message}):ai?.status==="error"?a.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:ai.error||ai.message}):cn?.is_docker?a.jsxs("div",{className:"mt-3 p-3 bg-bambu-dark-tertiary rounded-lg",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:"Update via Docker Compose:"}),a.jsx("code",{className:"block text-xs bg-bambu-dark p-2 rounded text-bambu-green font-mono",children:"docker compose pull && docker compose up -d"})]}):a.jsxs(Ne,{className:"mt-3",onClick:()=>ha.mutate(),disabled:ha.isPending,children:[ha.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(wi,{className:"w-4 h-4"}),"Install Update"]})]}):cn?.error?a.jsxs("div",{className:"mt-2 p-2 bg-red-500/10 border border-red-500/30 rounded text-sm text-red-400",children:["Failed to check for updates: ",cn.error]}):cn&&!cn.update_available?a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:"You're running the latest version"}):null]})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.dataManagement")})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.clearNotificationLogs")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.clearNotificationLogsDescription")})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>pe(!0),children:[a.jsx(ln,{className:"w-4 h-4"}),i("common.clear")]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.resetUiPreferences")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.resetUiPreferencesDescription")})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>z(!0),children:[a.jsx(ln,{className:"w-4 h-4"}),"Reset"]})]}),a.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:"Backup & Restore"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Export/import settings and configure GitHub backup"})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>de("backup"),children:[a.jsx(Au,{className:"w-4 h-4"}),"Go to Backup"]})]})]})]})]})]}),me==="network"&&k&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(gh,{className:"w-5 h-5 text-blue-400"}),"External URL"]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"The external URL where Bambuddy is accessible. Used for notification images and external integrations."}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bambuddy URL"}),a.jsx("input",{type:"text",value:k.external_url??"",onChange:ie=>Sn("external_url",ie.target.value),placeholder:"http://192.168.1.100:8000",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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Include protocol and port (e.g., http://192.168.1.100:8000)"})]})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Or,{className:"w-5 h-5 text-blue-400"}),"FTP Retry"]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Retry FTP operations when printer WiFi is unreliable. Applies to 3MF downloads, print uploads, timelapse downloads, and firmware updates."}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableRetry")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically retry failed FTP operations"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.ftp_retry_enabled??!0,onChange:ie=>Sn("ftp_retry_enabled",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),k.ftp_retry_enabled&&a.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry attempts"}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:k.ftp_retry_count??3,onChange:ie=>Sn("ftp_retry_count",parseInt(ie.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[1,2,3,4,5,6,7,8,9,10].map(ie=>a.jsxs("option",{value:ie,children:[ie," ",ie===1?"time":"times"]},ie))}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry delay"}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:k.ftp_retry_delay??2,onChange:ie=>Sn("ftp_retry_delay",parseInt(ie.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[1,2,3,5,10,15,20,30].map(ie=>a.jsxs("option",{value:ie,children:[ie," ",ie===1?"second":"seconds"]},ie))}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Connection timeout"}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:k.ftp_timeout??30,onChange:ie=>Sn("ftp_timeout",parseInt(ie.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[10,15,20,30,45,60,90,120].map(ie=>a.jsxs("option",{value:ie,children:[ie," seconds"]},ie))}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Increase for printers with weak WiFi"})]})]})]})]})]}),a.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Hy,{className:"w-5 h-5 text-bambu-green"}),"Home Assistant"]}),k.ha_enabled&&Bn&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${Bn.success?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:`text-sm ${Bn.success?"text-green-400":"text-red-400"}`,children:Bn.success?"Connected":"Disconnected"})]})]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Connect to Home Assistant to control smart plugs via HA's REST API. Supports switch, light, input_boolean, and script entities."}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-white",children:i("settings.enableHomeAssistant")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.homeAssistantDescription")}),k.ha_env_managed&&a.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[a.jsx(kf,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:i("settings.autoEnabledViaEnv")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.ha_enabled??!1,onChange:ie=>Sn("ha_enabled",ie.target.checked),disabled:k.ha_env_managed,className:"sr-only peer"}),a.jsx("div",{className:`w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green ${k.ha_env_managed?"opacity-60 cursor-not-allowed":""}`})]})]}),k.ha_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Home Assistant URL",k.ha_url_from_env&&a.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:i("settings.environmentManagedLabel")})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",value:k.ha_url??"",onChange:ie=>Sn("ha_url",ie.target.value),placeholder:"http://192.168.1.100:8123",disabled:k.ha_url_from_env,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 ${k.ha_url_from_env?"opacity-60 cursor-not-allowed":""}`}),k.ha_url_from_env&&a.jsx(kf,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),k.ha_url_from_env&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.urlFromEnvReadOnly")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Long-Lived Access Token",k.ha_token_from_env&&a.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:i("settings.environmentManagedLabel")})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"password",value:k.ha_token??"",onChange:ie=>Sn("ha_token",ie.target.value),placeholder:"eyJ0eXAiOiJKV1QiLC...",disabled:k.ha_token_from_env,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 ${k.ha_token_from_env?"opacity-60 cursor-not-allowed":""}`}),k.ha_token_from_env&&a.jsx(kf,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),k.ha_token_from_env?a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.tokenFromEnvReadOnly")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Create a token in HA: Profile → Long-Lived Access Tokens → Create Token"})]}),k.ha_url&&k.ha_token&&a.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:a.jsxs(Ne,{variant:"secondary",size:"sm",disabled:Ma,onClick:async()=>{De(!0),Hr(null);try{const ie=await ae.testHAConnection(k.ha_url,k.ha_token);Hr(ie)}catch(ie){Hr({success:!1,message:null,error:ie instanceof Error?ie.message:i("common.unknownError")})}finally{De(!1)}},children:[Ma?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Eg,{className:"w-4 h-4"}),i("settings.testConnection")]})})]})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Eg,{className:"w-5 h-5 text-blue-400"}),"MQTT Publishing"]}),jt?.enabled&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${jt.connected?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:`text-sm ${jt.connected?"text-green-400":"text-red-400"}`,children:jt.connected?"Connected":"Disconnected"})]})]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish BamBuddy events to an external MQTT broker for integration with Node-RED, Home Assistant, and other automation systems."}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableMqtt")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish events to external MQTT broker"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.mqtt_enabled??!1,onChange:ie=>Sn("mqtt_enabled",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),k.mqtt_enabled&&a.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Broker hostname"}),a.jsx("input",{type:"text",value:k.mqtt_broker??"",onChange:ie=>Sn("mqtt_broker",ie.target.value),placeholder:"mqtt.example.com or 192.168.1.100",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"})]}),a.jsxs("div",{className:"flex items-end gap-4",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Port"}),a.jsx("input",{type:"number",min:"1",max:"65535",value:k.mqtt_port??1883,onChange:ie=>Sn("mqtt_port",Math.min(65535,Math.max(1,parseInt(ie.target.value)||1883))),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex items-center gap-3 pb-2",children:[a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.mqtt_use_tls??!1,onChange:ie=>{const kt=ie.target.checked;Sn("mqtt_use_tls",kt);const Hn=k.mqtt_port??1883;kt&&Hn===1883?Sn("mqtt_port",8883):!kt&&Hn===8883&&Sn("mqtt_port",1883)},className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]}),a.jsx("span",{className:"text-white text-sm",children:i("settings.useTls")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username (optional)"}),a.jsx("input",{type:"text",value:k.mqtt_username??"",onChange:ie=>Sn("mqtt_username",ie.target.value),placeholder:i("settings.leaveEmptyForAnonymous"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password (optional)"}),a.jsx("input",{type:"password",value:k.mqtt_password??"",onChange:ie=>Sn("mqtt_password",ie.target.value),placeholder:i("settings.leaveEmptyForAnonymous"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic prefix"}),a.jsx("input",{type:"text",value:k.mqtt_topic_prefix??"bambuddy",onChange:ie=>Sn("mqtt_topic_prefix",ie.target.value),placeholder:"bambuddy",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"}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["Topics will be: ",k.mqtt_topic_prefix||"bambuddy","/printers//status, etc."]})]}),jt&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:`w-2 h-2 rounded-full ${jt.connected?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:"text-bambu-gray",children:jt.connected?a.jsxs(a.Fragment,{children:[i("settings.mqttConnectedTo")," ",a.jsxs("span",{className:"text-white",children:[jt.broker,":",jt.port]})]}):i("settings.spoolmanDisconnected")})]})})]})]})]})]}),a.jsx("div",{className:"flex-1 lg:max-w-md space-y-4",children:a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Pj,{className:"w-5 h-5 text-orange-400"}),"Prometheus Metrics"]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Expose printer metrics at ",a.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"/api/v1/metrics"})," for Prometheus/Grafana monitoring."]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableMetricsEndpoint")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.prometheusDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.prometheus_enabled??!1,onChange:ie=>Sn("prometheus_enabled",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),k.prometheus_enabled&&a.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bearer Token (optional)"}),a.jsx("input",{type:"password",value:k.prometheus_token??"",onChange:ie=>Sn("prometheus_token",ie.target.value),placeholder:i("settings.leaveEmptyForNoAuth"),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"}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["If set, requests must include ",a.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"Authorization: Bearer "})]})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-white mb-2",children:i("settings.availableMetrics")}),a.jsxs("div",{className:"text-xs text-bambu-gray space-y-1",children:[a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_connected"})," - Connection status"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_state"})," - Printer state (idle/printing/etc)"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_print_progress"})," - Print progress 0-100%"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_bed_temp_celsius"})," - Bed temperature"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_nozzle_temp_celsius"})," - Nozzle temperature"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_prints_total"})," - Total prints by result"]}),a.jsx("p",{className:"text-bambu-gray/70 italic",children:"...and more (layers, fans, queue, filament usage)"})]})]})]})]})]})})]}),Bn&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full mx-4",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[Bn.success?a.jsx(mr,{className:"w-8 h-8 text-green-400"}):a.jsx(Zi,{className:"w-8 h-8 text-red-400"}),a.jsx("h3",{className:"text-lg font-medium text-white",children:Bn.success?"Connection Successful":"Connection Failed"})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:Bn.success?Bn.message||"Successfully connected to Home Assistant.":Bn.error||"Failed to connect to Home Assistant."}),a.jsx("div",{className:"flex justify-end",children:a.jsx(Ne,{variant:"primary",onClick:()=>Hr(null),children:"OK"})})]})}),me==="plugs"&&a.jsxs("div",{className:"max-w-4xl",children:[a.jsxs("div",{className:"flex items-start justify-between mb-6",children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(sl,{className:"w-5 h-5 text-bambu-green"}),"Smart Plugs"]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Connect smart plugs (Tasmota or Home Assistant) to automate power control and track energy usage for your printers."})]}),a.jsxs("div",{className:"flex items-center gap-2 pt-1 shrink-0",children:[Ue&&Ue.filter(ie=>ie.enabled).length>1&&a.jsxs(a.Fragment,{children:[a.jsxs(Ne,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>Z("on"),disabled:Xh.isPending,title:i("settings.turnAllPlugsOn"),children:[Xh.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Ju,{className:"w-4 h-4 text-bambu-green"}),"All On"]}),a.jsxs(Ne,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>Z("off"),disabled:Xh.isPending,title:i("settings.turnAllPlugsOff"),children:[Xh.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Nk,{className:"w-4 h-4 text-red-400"}),"All Off"]})]}),a.jsxs(Ne,{className:"whitespace-nowrap",onClick:()=>{F(null),P(!0)},children:[a.jsx(cr,{className:"w-4 h-4"}),"Add Smart Plug"]})]})]}),Ue&&Ue.length>0&&a.jsxs(St,{className:"mb-6",children:[a.jsx(Pn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(Ah,{className:"w-4 h-4 text-yellow-400"}),"Energy Summary",xt&&a.jsx(ct,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),a.jsx(Et,{children:nt?a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(Ah,{className:"w-3 h-3"}),"Current Power"]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[nt.totalPower.toFixed(1),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"W"})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[nt.reachableCount,"/",nt.totalPlugs," plugs online"]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(ti,{className:"w-3 h-3"}),"Today"]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[nt.totalToday.toFixed(2),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(k?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(nt.totalToday*(k?.energy_cost_per_kwh??0)).toFixed(2)," ",k?.currency]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(Pj,{className:"w-3 h-3"}),"Yesterday"]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[nt.totalYesterday.toFixed(2),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(k?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(nt.totalYesterday*(k?.energy_cost_per_kwh??0)).toFixed(2)," ",k?.currency]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(Nj,{className:"w-3 h-3"}),"Total"]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[nt.totalLifetime.toFixed(1),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(k?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(nt.totalLifetime*(k?.energy_cost_per_kwh??0)).toFixed(2)," ",k?.currency]})]})]}):xt?null:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Enable plugs to see energy summary"})})]}),Se?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Ue&&Ue.length>0?a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ue.map(ie=>a.jsx(DKe,{plug:ie,onEdit:kt=>{F(kt),P(!0)}},ie.id))}):a.jsx(St,{children:a.jsx(Et,{className:"py-12",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(sl,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.noSmartPlugsTitle")}),a.jsx("p",{className:"text-sm mb-4",children:i("settings.noSmartPlugsDescription")}),a.jsxs(Ne,{onClick:()=>{F(null),P(!0)},children:[a.jsx(cr,{className:"w-4 h-4"}),i("settings.addFirstSmartPlug")]})]})})})]}),me==="notifications"&&a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[a.jsxs("div",{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(kg,{className:"w-5 h-5 text-bambu-green"}),i("settings.providers")]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ne,{size:"sm",variant:"secondary",onClick:()=>oe(!0),children:[a.jsx(Y0,{className:"w-4 h-4"}),i("settings.log")]}),rt&&rt.length>0&&a.jsxs(Ne,{size:"sm",variant:"secondary",onClick:()=>{sd(null),Dc.mutate()},disabled:Dc.isPending,children:[Dc.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(kk,{className:"w-4 h-4"}),i("settings.testAll")]}),a.jsxs(Ne,{size:"sm",onClick:()=>{G(null),D(!0)},children:[a.jsx(cr,{className:"w-4 h-4"}),"Add"]})]})]}),a.jsx(St,{className:"mb-4",children:a.jsx(Et,{className:"py-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.notificationLanguage")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.notificationLanguageDescription")})]}),a.jsx("select",{value:k.notification_language||"en",onChange:ie=>Sn("notification_language",ie.target.value),className:"px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green",children:PU.map(ie=>a.jsx("option",{value:ie.code,children:ie.nativeName},ie.code))})]})})}),js&&a.jsx(St,{className:"mb-4",children:a.jsxs(Et,{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm font-medium text-white",children:i("settings.testResults")}),a.jsx("button",{onClick:()=>sd(null),className:"text-bambu-gray hover:text-white text-xs",children:i("common.dismiss")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm mb-2",children:[a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(mr,{className:"w-4 h-4"}),i("settings.testPassedCount",{count:js.success})]}),js.failed>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(Zi,{className:"w-4 h-4"}),i("settings.testFailedCount",{count:js.failed})]})]}),js.results.filter(ie=>!ie.success).length>0&&a.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:js.results.filter(ie=>!ie.success).map(ie=>a.jsxs("div",{className:"text-xs text-red-400",children:[a.jsxs("span",{className:"font-medium",children:[ie.provider_name,":"]})," ",ie.message]},ie.provider_id))})]})}),Ct?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):rt&&rt.length>0?a.jsx("div",{className:"space-y-3",children:rt.map(ie=>a.jsx(LKe,{provider:ie,onEdit:kt=>{G(kt),D(!0)}},ie.id))}):a.jsx(St,{children:a.jsx(Et,{className:"py-8",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(kg,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:i("settings.noProvidersTitle")}),a.jsx("p",{className:"text-xs mb-3",children:i("settings.noProvidersDescription")}),a.jsxs(Ne,{size:"sm",onClick:()=>{G(null),D(!0)},children:[a.jsx(cr,{className:"w-4 h-4"}),i("settings.addProvider")]})]})})})]}),a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-4",children:[a.jsx(ys,{className:"w-5 h-5 text-bambu-green"}),i("settings.messageTemplates")]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:i("settings.messageTemplatesDescription")}),Mn?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):pn&&pn.length>0?a.jsx("div",{className:"space-y-2",children:pn.map(ie=>a.jsx(St,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>K(ie),children:a.jsx(Et,{className:"py-2.5 px-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium text-sm truncate",children:ie.name}),a.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:ie.title_template})]}),a.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:kt=>{kt.stopPropagation(),K(ie)},children:a.jsx(bg,{className:"w-4 h-4 text-bambu-gray"})})]})})},ie.id))}):a.jsx(St,{children:a.jsx(Et,{className:"py-8",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(ys,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:i("settings.noTemplatesAvailable")})]})})})]})]}),me==="apikeys"&&a.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Yo,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiKeys")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiKeysDescription")})]}),a.jsxs(Ne,{size:"sm",onClick:()=>se(!0),className:"flex-shrink-0",children:[a.jsx(cr,{className:"w-4 h-4"}),i("settings.createKey")]})]}),V&&a.jsx(St,{className:"mb-6 border-bambu-green",children:a.jsx(Et,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(mr,{className:"w-5 h-5 text-bambu-green flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:i("settings.apiKeyCreated")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:i("settings.apiKeyCopyWarning")}),a.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark rounded-lg p-2",children:[a.jsx("code",{className:"flex-1 text-sm text-bambu-green font-mono break-all",children:V}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(V);else{const ie=document.createElement("textarea");ie.value=V,ie.style.position="fixed",ie.style.left="-999999px",document.body.appendChild(ie),ie.select(),document.execCommand("copy"),document.body.removeChild(ie)}o(i("settings.toast.keyCopied"))}catch{o(i("settings.toast.copyFailed"),"error")}},children:a.jsx(zl,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex gap-2 mt-3",children:[a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>{X(V),o(i("settings.toast.keyAddedToBrowser"))},children:i("settings.useInApiBrowser")}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>Y(null),children:i("common.dismiss")})]})]})]})})}),Re&&a.jsxs(St,{className:"mb-6",children:[a.jsx(Pn,{children:a.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.createNewApiKey")})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keyName")}),a.jsx("input",{type:"text",value:ke,onChange:ie=>Fe(ie.target.value),placeholder:i("settings.keyNamePlaceholder"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("common.permissions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ce.can_read_status,onChange:ie=>Ve(kt=>({...kt,can_read_status:ie.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.readStatus")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.readStatusDescription")})]})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ce.can_queue,onChange:ie=>Ve(kt=>({...kt,can_queue:ie.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.manageQueue")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.manageQueueDescription")})]})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ce.can_control_printer,onChange:ie=>Ve(kt=>({...kt,can_control_printer:ie.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.controlPrinter")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.controlPrinterDescription")})]})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[a.jsxs(Ne,{onClick:()=>Tt.mutate({name:ke||i("settings.unnamedKey"),...ce}),disabled:Tt.isPending,children:[Tt.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),i("settings.createKey")]}),a.jsx(Ne,{variant:"secondary",onClick:()=>se(!1),children:i("common.cancel")})]})]})]}),Rt?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):It&&It.length>0?a.jsx("div",{className:"space-y-3",children:It.map(ie=>a.jsx(St,{children:a.jsx(Et,{className:"py-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Yo,{className:`w-5 h-5 ${ie.enabled?"text-bambu-green":"text-bambu-gray"}`}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:ie.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[ie.key_prefix,"••••••••",ie.last_used&&` · ${i("settings.lastUsed")}: ${Gg(ie.last_used)}`]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex gap-1 text-xs",children:[ie.can_read_status&&a.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:i("settings.read")}),ie.can_queue&&a.jsx("span",{className:"px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded",children:i("queue.title")}),ie.can_control_printer&&a.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:i("settings.control")})]}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>q(ie.id),children:a.jsx(ln,{className:"w-4 h-4 text-red-400"})})]})]})})},ie.id))}):a.jsx(St,{children:a.jsx(Et,{className:"py-12",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(Yo,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.apiKeysEmptyTitle")}),a.jsx("p",{className:"text-sm mb-4",children:i("settings.apiKeysEmptyDescription")}),a.jsxs(Ne,{onClick:()=>se(!0),children:[a.jsx(cr,{className:"w-4 h-4"}),i("settings.createFirstKey")]})]})})}),a.jsxs(St,{className:"mt-6",children:[a.jsx(Pn,{children:a.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.webhookEndpoints")})}),a.jsxs(Et,{className:"space-y-3 text-sm",children:[a.jsx("p",{className:"text-bambu-gray",children:i("settings.webhookApiKeyHint")}),a.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-blue-400",children:"GET"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/status"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getAllStatus")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-blue-400",children:"GET"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/status/:id"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getSpecificStatus")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-green-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/queue"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.addToQueue")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-orange-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/pause"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.pausePrint")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-orange-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/resume"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.resumePrint")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-red-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/stop"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.stopPrint")]})]})]})]})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"mb-6",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(gh,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiBrowser")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiBrowserDescription")})]}),a.jsx(St,{className:"mb-4",children:a.jsxs(Et,{className:"py-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("settings.apiKeyForTesting")}),a.jsx("input",{type:"text",value:re,onChange:ie=>X(ie.target.value),placeholder:i("settings.apiKeyPlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("settings.apiKeyHint")})]})}),a.jsx(eXe,{apiKey:re})]})]}),me==="virtual-printer"&&a.jsx(WKe,{}),me==="filament"&&k&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[a.jsx("div",{className:"flex-1 lg:max-w-xl",children:a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.amsDisplayThresholds")})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.amsThresholdsDescription")}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(HR,{className:"w-4 h-4 text-blue-400"}),a.jsx("span",{className:"font-medium",children:i("settings.humidity")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodGreen")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0",max:"100",value:k.ams_humidity_good??40,onChange:ie=>Sn("ams_humidity_good",parseInt(ie.target.value)||40),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"}),a.jsx("span",{className:"text-bambu-gray",children:"%"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0",max:"100",value:k.ams_humidity_fair??60,onChange:ie=>Sn("ams_humidity_fair",parseInt(ie.target.value)||60),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"}),a.jsx("span",{className:"text-bambu-gray",children:"%"})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairBad")})]}),a.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(Ek,{className:"w-4 h-4 text-orange-400"}),a.jsx("span",{className:"font-medium",children:i("settings.temperature")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodBlue")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:k.ams_temp_good??28,onChange:ie=>Sn("ams_temp_good",parseFloat(ie.target.value)||28),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"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:k.ams_temp_fair??35,onChange:ie=>Sn("ams_temp_fair",parseFloat(ie.target.value)||35),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"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairHot")})]}),a.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(Au,{className:"w-4 h-4 text-purple-400"}),a.jsx("span",{className:"font-medium",children:i("settings.historyRetention")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keepSensorHistory")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"1",max:"365",value:k.ams_history_retention_days??30,onChange:ie=>Sn("ams_history_retention_days",parseInt(ie.target.value)||30),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:i("common.days")})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.historyRetentionDescription")})]}),a.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(jr,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"font-medium",children:i("settings.printModal")})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-white",children:i("settings.expandCustomMapping")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.expandCustomMappingDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.per_printer_mapping_expanded??!1,onChange:ie=>Sn("per_printer_mapping_expanded",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})]})]})]})}),a.jsx("div",{className:"flex-1 lg:max-w-xl",children:a.jsx(VKe,{})})]}),ue!==null&&a.jsx(er,{title:i("settings.deleteApiKeyTitle"),message:i("settings.deleteApiKeyMessage"),confirmText:i("settings.deleteKey"),variant:"danger",onConfirm:()=>{mn.mutate(ue),q(null)},onCancel:()=>q(null)}),C&&a.jsx(RKe,{plug:U,onClose:()=>{P(!1),F(null)}}),H&&a.jsx(FKe,{provider:$,onClose:()=>{D(!1),G(null)}}),I&&a.jsx(IKe,{template:I,onClose:()=>K(null)}),Q&&a.jsx(BKe,{onClose:()=>oe(!1)}),le&&a.jsx(er,{title:i("settings.clearNotificationLogs"),message:i("settings.clearLogsMessage"),confirmText:i("settings.clearLogs"),variant:"warning",onConfirm:async()=>{pe(!1);try{const ie=await ae.clearNotificationLogs(30);o(ie.message,"success")}catch{o(i("settings.toast.clearLogsFailed"),"error")}},onCancel:()=>pe(!1)}),ee&&a.jsx(er,{title:i("settings.resetUiPreferences"),message:i("settings.resetUiPreferencesMessage"),confirmText:i("settings.resetPreferences"),variant:"default",onConfirm:()=>{z(!1),localStorage.clear(),o(i("settings.toast.uiPreferencesReset"),"success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>z(!1)}),O&&a.jsx(er,{title:`Turn All Plugs ${O==="on"?"On":"Off"}`,message:`This will turn ${O==="on"?"ON":"OFF"} all ${Ue?.filter(ie=>ie.enabled).length||0} enabled smart plugs. ${O==="off"?"Any running printers may be affected!":""}`,confirmText:`Turn All ${O==="on"?"On":"Off"}`,variant:O==="off"?"danger":"warning",onConfirm:()=>{const ie=O;Z(null),Xh.mutate(ie)},onCancel:()=>Z(null)}),ge&&cn?.release_notes&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Ce(!1),children:a.jsxs(St,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:ie=>ie.stopPropagation(),children:[a.jsxs(Pn,{className:"flex flex-row items-center justify-between shrink-0",children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Release Notes - v",cn.latest_version]}),cn.release_name&&cn.release_name!==cn.latest_version&&a.jsx("p",{className:"text-sm text-bambu-gray",children:cn.release_name})]}),a.jsx("button",{onClick:()=>Ce(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsx(Et,{className:"overflow-y-auto flex-1",children:a.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:cn.release_notes})}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[cn.release_url&&a.jsx("a",{href:cn.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:a.jsxs(Ne,{variant:"secondary",className:"w-full",children:[a.jsx(Xr,{className:"w-4 h-4"}),"View on GitHub"]})}),a.jsx(Ne,{onClick:()=>Ce(!1),className:"flex-1",children:"Close"})]})]})}),me==="users"&&a.jsxs("div",{className:"space-y-6",children:[a.jsx(St,{children:a.jsx(Et,{className:"py-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${l?"bg-green-500/20":"bg-gray-500/20"}`,children:l?a.jsx(kf,{className:"w-5 h-5 text-green-400"}):a.jsx(_1,{className:"w-5 h-5 text-gray-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-medium",children:i("settings.authentication")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i(l?"settings.authEnabledDescription":"settings.authDisabledDescription")})]})]}),l?c?.is_admin&&a.jsxs(Ne,{variant:"secondary",onClick:()=>Te(!0),children:[a.jsx(_1,{className:"w-4 h-4"}),i("common.disable")]}):a.jsxs(Ne,{onClick:()=>e("/setup"),children:[a.jsx(kf,{className:"w-4 h-4"}),i("common.enable")]})]})})}),un?.advanced_auth_enabled&&a.jsx(St,{className:"border-blue-500/30 bg-blue-500/5",children:a.jsx(Et,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:a.jsx(Q0,{className:"w-5 h-5 text-blue-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-medium",children:i("settings.email.advancedAuthEnabled")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.email.advancedAuthEnabledDesc")})]})]})})}),l&&a.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"space-y-6",children:[c&&a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(zf,{className:"w-5 h-5 text-bambu-green"}),i("settings.currentUser")]}),a.jsxs(Ne,{size:"sm",variant:"ghost",onClick:()=>$e(!0),children:[a.jsx(Yo,{className:"w-4 h-4"}),i("settings.changePassword")]})]})}),a.jsx(Et,{children:a.jsx("div",{className:"flex items-center justify-between",children:a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium text-lg",children:c.username}),a.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[c.is_admin&&a.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:i("settings.admin")}),c.groups?.map(ie=>a.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${ie.name==="Administrators"?"bg-purple-500/20 text-purple-300":ie.name==="Operators"?"bg-blue-500/20 text-blue-300":ie.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:ie.name},ie.id))]})]})})})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(zf,{className:"w-5 h-5 text-bambu-green"}),i("settings.users")]}),In("users:create")&&a.jsxs(Ne,{size:"sm",onClick:()=>{Ae(!0),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:[a.jsx(cr,{className:"w-4 h-4"}),i("settings.addUser")]})]})}),a.jsx(Et,{children:ua?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):rr.length===0?a.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noUsersFound")}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:rr.map(ie=>a.jsxs("div",{className:"py-3 flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-white font-medium truncate",children:ie.username}),a.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[ie.is_admin&&a.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:i("settings.admin")}),ie.groups?.map(kt=>a.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${kt.name==="Administrators"?"bg-purple-500/20 text-purple-300":kt.name==="Operators"?"bg-blue-500/20 text-blue-300":kt.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:kt.name},kt.id))]})]}),a.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[In("users:update")&&a.jsx(Ne,{size:"sm",variant:"ghost",onClick:()=>Aa(ie),children:a.jsx(bg,{className:"w-4 h-4"})}),In("users:delete")&&ie.id!==c?.id&&a.jsx(Ne,{size:"sm",variant:"ghost",onClick:()=>Pc(ie.id),children:a.jsx(ln,{className:"w-4 h-4"})})]})]},ie.id))})})]})]}),a.jsx("div",{children:a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(fT,{className:"w-5 h-5 text-bambu-green"}),i("settings.groups")]}),In("groups:create")&&a.jsxs(Ne,{size:"sm",onClick:()=>{Ie(!0),da()},children:[a.jsx(cr,{className:"w-4 h-4"}),i("settings.addGroup")]})]})}),a.jsx(Et,{children:Jt?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Si.length===0?a.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noGroupsFound")}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:Si.map(ie=>a.jsxs("div",{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(fT,{className:`w-4 h-4 ${ie.name==="Administrators"?"text-purple-400":ie.name==="Operators"?"text-blue-400":ie.name==="Viewers"?"text-green-400":"text-bambu-gray"}`}),a.jsx("span",{className:"text-white font-medium",children:ie.name}),ie.is_system&&a.jsx("span",{className:"px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:i("settings.system")})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[In("groups:update")&&a.jsx(Ne,{size:"sm",variant:"ghost",onClick:()=>Vb(ie),children:a.jsx(bg,{className:"w-4 h-4"})}),In("groups:delete")&&!ie.is_system&&a.jsx(Ne,{size:"sm",variant:"ghost",onClick:()=>fn(ie.id),children:a.jsx(ln,{className:"w-4 h-4"})})]})]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-6",children:ie.description||i("settings.noDescription")}),a.jsxs("div",{className:"flex items-center gap-4 mt-2 ml-6 text-xs text-bambu-gray",children:[a.jsx("span",{children:i("settings.userCount",{count:ie.user_count})}),a.jsx("span",{children:i("settings.permissionCount",{count:ie.permissions.length})})]})]},ie.id))})})]})})]}),!l&&a.jsx(St,{children:a.jsx(Et,{className:"py-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx(_1,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:i("settings.authDisabledTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4 max-w-md mx-auto",children:i("settings.authDisabledMessage")}),a.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-6 text-left max-w-xs mx-auto",children:[a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(mr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature1")})]}),a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(mr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature2")})]}),a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(mr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature3")})]})]}),a.jsxs(Ne,{onClick:()=>e("/setup"),children:[a.jsx(kf,{className:"w-4 h-4"}),i("settings.enableAuthentication")]})]})})})]}),Be&&!un?.advanced_auth_enabled&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Ae(!1),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsxs(St,{className:"w-full max-w-md",onClick:ie=>ie.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(zf,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.createUser")})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{Ae(!1),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsx(Lt,{className:"w-5 h-5"})})]})}),a.jsxs(Et,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.username")}),a.jsx("input",{type:"text",value:at.username,onChange:ie=>Ut({...at,username:ie.target.value}),className:"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:i("settings.enterUsername"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.password")}),a.jsx("input",{type:"password",value:at.password,onChange:ie=>Ut({...at,password:ie.target.value}),className:"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:i("settings.enterPassword"),autoComplete:"new-password",minLength:6})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),a.jsx("input",{type:"password",value:at.confirmPassword,onChange:ie=>Ut({...at,confirmPassword:ie.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${at.confirmPassword&&at.password!==at.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),at.confirmPassword&&at.password!==at.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Groups"}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[Si.map(ie=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:at.group_ids.includes(ie.id),onChange:()=>_r(ie.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:ie.name}),ie.is_system&&a.jsx("span",{className:"text-xs text-yellow-400",children:"(System)"})]},ie.id)),Si.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>{Ae(!1),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:"Cancel"}),a.jsx(Ne,{onClick:hs,disabled:Ea.isPending||!at.username||!at.password||at.password!==at.confirmPassword||at.password.length<6,children:Ea.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Creating..."]}):a.jsxs(a.Fragment,{children:[a.jsx(cr,{className:"w-4 h-4"}),"Create User"]})})]})]})]})}),Be&&un?.advanced_auth_enabled&&a.jsx($Ke,{formData:at,setFormData:Ut,groups:Si,onClose:()=>{Ae(!1),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},onCreate:hs,isCreating:Ea.isPending,isCreateButtonDisabled:Ea.isPending||!at.username||!at.email}),qe&&et!==null&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{ve(!1),Ee(null),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsxs(St,{className:"w-full max-w-md",onClick:ie=>ie.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(bg,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.editUser")})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{ve(!1),Ee(null),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsx(Lt,{className:"w-5 h-5"})})]})}),a.jsxs(Et,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("settings.username")," ",un?.advanced_auth_enabled&&a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:at.username,onChange:ie=>Ut({...at,username:ie.target.value}),className:"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:i("settings.enterUsername"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("users.form.email")||"Email"," ",un?.advanced_auth_enabled?a.jsx("span",{className:"text-red-400",children:"*"}):a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",i("users.form.optional")||"optional",")"]})]}),a.jsx("input",{type:"email",value:at.email,onChange:ie=>Ut({...at,email:ie.target.value}),className:"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:i("users.form.emailPlaceholder")||"user@example.com",required:un?.advanced_auth_enabled})]}),!un?.advanced_auth_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("users.form.password")||"Password"," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",i("users.form.leaveBlankToKeep")||"leave blank to keep current",")"]})]}),a.jsx("input",{type:"password",value:at.password,onChange:ie=>Ut({...at,password:ie.target.value,confirmPassword:""}),className:"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:i("settings.enterNewPassword"),autoComplete:"new-password",minLength:6})]}),at.password&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),a.jsx("input",{type:"password",value:at.confirmPassword,onChange:ie=>Ut({...at,confirmPassword:ie.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${at.confirmPassword&&at.password!==at.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),at.confirmPassword&&at.password!==at.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),un?.advanced_auth_enabled&&a.jsxs("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3 space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("users.form.passwordManagedByAdvancedAuth")||'Password is managed by Advanced Authentication. Use "Reset Password" to send a new password to the user via email.'}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>et&&yl.mutate(et),disabled:yl.isPending||!at.email,className:"w-full",children:yl.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),i("users.form.resettingPassword")||"Resetting Password..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Bu,{className:"w-4 h-4"}),i("users.form.resetPassword")||"Reset Password"]})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("users.form.groups")||"Groups"}),a.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:Si.map(ie=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:at.group_ids.includes(ie.id),onChange:()=>_r(ie.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:ie.name}),ie.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",i("users.system")||"System",")"]})]},ie.id))})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>{ve(!1),Ee(null),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i("users.modal.cancel")||"Cancel"}),a.jsx(Ne,{onClick:()=>Po(et),disabled:Ta.isPending||!at.username||un?.advanced_auth_enabled&&!at.email||!!(!un?.advanced_auth_enabled&&at.password&&(at.password!==at.confirmPassword||at.password.length<6)),children:Ta.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),i("users.modal.saving")||"Saving..."]}):a.jsxs(a.Fragment,{children:[a.jsx(vs,{className:"w-4 h-4"}),i("users.modal.saveChanges")||"Save Changes"]})})]})]})]})}),Ye!==null&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:()=>{je(null),ye(null)},children:a.jsxs(St,{className:"w-full max-w-md",onClick:ie=>ie.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center gap-2 text-red-400",children:[a.jsx(ln,{className:"w-5 h-5"}),a.jsx("h3",{className:"text-lg font-semibold",children:i("settings.deleteUserTitle")})]})}),a.jsx(Et,{className:"space-y-4",children:Qe?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-bambu-green border-t-transparent"})}):Pe&&Pe.archives+Pe.queue_items+Pe.library_files>0?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-white",children:i("settings.userHasCreated")}),a.jsxs("ul",{className:"list-disc list-inside text-bambu-gray space-y-1",children:[Pe.archives>0&&a.jsxs("li",{children:[Pe.archives," archive",Pe.archives!==1?"s":""]}),Pe.queue_items>0&&a.jsxs("li",{children:[Pe.queue_items," queue item",Pe.queue_items!==1?"s":""]}),Pe.library_files>0&&a.jsxs("li",{children:[Pe.library_files," library file",Pe.library_files!==1?"s":""]})]}),a.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.userItemsQuestion")}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(Ne,{variant:"danger",onClick:()=>si.mutate({id:Ye,deleteItems:!0}),disabled:si.isPending,className:"justify-center",children:"Delete user AND their items"}),a.jsx(Ne,{variant:"secondary",onClick:()=>si.mutate({id:Ye,deleteItems:!1}),disabled:si.isPending,className:"justify-center",children:"Delete user, keep items (become ownerless)"}),a.jsx(Ne,{variant:"ghost",onClick:()=>{je(null),ye(null)},disabled:si.isPending,className:"justify-center",children:"Cancel"})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-white",children:i("settings.deleteUserConfirm")}),a.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.actionCannotBeUndone")}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(Ne,{variant:"ghost",onClick:()=>{je(null),ye(null)},disabled:si.isPending,children:"Cancel"}),a.jsx(Ne,{variant:"danger",onClick:()=>si.mutate({id:Ye,deleteItems:!1}),disabled:si.isPending,children:"Delete User"})]})]})})]})}),(zt||vt)&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Ie(!1),Gt(null),da()},children:a.jsxs(St,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:ie=>ie.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(fT,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:vt?"Edit Group":"Create Group"})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{Ie(!1),Gt(null),da()},children:a.jsx(Lt,{className:"w-5 h-5"})})]})}),a.jsxs(Et,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.groupName")}),a.jsx("input",{type:"text",value:vn.name,onChange:ie=>dr({...vn,name:ie.target.value}),disabled:vt?.is_system,className:"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 disabled:opacity-50",placeholder:i("settings.enterGroupName")}),vt?.is_system&&a.jsx("p",{className:"text-xs text-yellow-400 mt-1",children:i("settings.systemGroupWarning")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Description"}),a.jsx("textarea",{value:vn.description,onChange:ie=>dr({...vn,description:ie.target.value}),rows:2,className:"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 resize-none",placeholder:i("settings.enterDescriptionOptional")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:["Permissions (",vn.permissions.length," selected)"]}),a.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:wn?.categories.map(ie=>a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary cursor-pointer hover:bg-bambu-dark-tertiary transition-colors",onClick:()=>Um(ie.name),children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("button",{type:"button",onClick:kt=>{kt.stopPropagation(),Bm(ie,!ad(ie))},className:`w-5 h-5 rounded border flex items-center justify-center transition-colors ${ad(ie)?"bg-bambu-green border-bambu-green":Gb(ie)?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:(ad(ie)||Gb(ie))&&a.jsx($i,{className:"w-3 h-3 text-white"})}),a.jsx("span",{className:"text-white font-medium",children:ie.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",ie.permissions.filter(kt=>vn.permissions.includes(kt.value)).length,"/",ie.permissions.length,")"]})]}),ar.has(ie.name)?a.jsx(fr,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(ks,{className:"w-4 h-4 text-bambu-gray"})]}),ar.has(ie.name)&&a.jsx("div",{className:"p-3 bg-bambu-dark space-y-2",children:ie.permissions.map(kt=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:vn.permissions.includes(kt.value),onChange:()=>Av(kt.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:kt.label})]},kt.value))})]},ie.name))})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>{Ie(!1),Gt(null),da()},children:"Cancel"}),a.jsx(Ne,{onClick:vt?Qr:eo,disabled:us.isPending||ds.isPending||!vn.name.trim(),children:us.isPending||ds.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),vt?"Saving...":"Creating..."]}):a.jsxs(a.Fragment,{children:[a.jsx(vs,{className:"w-4 h-4"}),vt?"Save Changes":"Create Group"]})})]})]})]})}),dn!==null&&a.jsx(er,{title:i("settings.deleteGroupTitle"),message:i("settings.deleteGroupMessage"),confirmText:i("settings.deleteGroup"),variant:"danger",onConfirm:()=>{jc.mutate(dn),fn(null)},onCancel:()=>fn(null)}),me==="email"&&a.jsx("div",{className:"max-w-2xl",children:a.jsx(YKe,{})}),me==="backup"&&a.jsx(XKe,{}),_e&&a.jsx(er,{title:i("settings.disableAuthenticationTitle"),message:i("settings.disableAuthenticationMessage"),confirmText:i("settings.disableAuthentication"),variant:"danger",onConfirm:async()=>{try{await ae.disableAuth(),o(i("settings.toast.authDisabled"),"success"),await u(),Te(!1),window.location.href="/"}catch(ie){const kt=ie instanceof Error?ie.message:i("settings.toast.authDisableFailed");o(kt,"error")}},onCancel:()=>Te(!1)}),we&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{$e(!1),ze({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsxs(St,{className:"w-full max-w-md",onClick:ie=>ie.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Yo,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.changePassword")})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{$e(!1),ze({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsx(Lt,{className:"w-5 h-5"})})]})}),a.jsxs(Et,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Current Password"}),a.jsx("input",{type:"password",value:Ge.currentPassword,onChange:ie=>ze({...Ge,currentPassword:ie.target.value}),className:"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:i("settings.enterCurrentPassword"),autoComplete:"current-password"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"New Password"}),a.jsx("input",{type:"password",value:Ge.newPassword,onChange:ie=>ze({...Ge,newPassword:ie.target.value}),className:"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:i("settings.enterNewPasswordMin6"),autoComplete:"new-password",minLength:6})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Confirm New Password"}),a.jsx("input",{type:"password",value:Ge.confirmPassword,onChange:ie=>ze({...Ge,confirmPassword:ie.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${Ge.confirmPassword&&Ge.newPassword!==Ge.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),Ge.confirmPassword&&Ge.newPassword!==Ge.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>{$e(!1),ze({currentPassword:"",newPassword:"",confirmPassword:""})},children:"Cancel"}),a.jsx(Ne,{onClick:async()=>{if(Ge.newPassword!==Ge.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(Ge.newPassword.length<6){o(i("settings.toast.passwordTooShort"),"error");return}Me(!0);try{await ae.changePassword(Ge.currentPassword,Ge.newPassword),o(i("settings.toast.passwordChanged"),"success"),$e(!1),ze({currentPassword:"",newPassword:"",confirmPassword:""})}catch(ie){const kt=ie instanceof Error?ie.message:"Failed to change password";o(kt,"error")}finally{Me(!1)}},disabled:be||!Ge.currentPassword||!Ge.newPassword||Ge.newPassword!==Ge.confirmPassword||Ge.newPassword.length<6,children:be?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Changing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Yo,{className:"w-4 h-4"}),"Change Password"]})})]})]})]})})]})}const iie=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},rXe=t=>t.startsWith("HH")?"HF":"S",iXe=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},SR=t=>{const e=["High Flow_","High Flow ","Standard_","Standard ","HF_","HF ","S_","S "];for(const r of e)if(t.startsWith(r))return t.slice(r.length);const n=t.indexOf("_");return n>0?t.slice(n+1):t};function ej({profile:t,onEdit:e,onCopy:n,selectionMode:r,isSelected:i,onToggleSelect:s,note:o}){const l=rXe(t.nozzle_id),c=t.nozzle_diameter,u=()=>{r&&s?s():e()};return a.jsxs("div",{className:"flex items-center gap-2",children:[r&&a.jsx("button",{onClick:s,className:"text-bambu-gray hover:text-white transition-colors p-1",children:i?a.jsx(Xs,{className:"w-4 h-4 text-bambu-green"}):a.jsx(ul,{className:"w-4 h-4"})}),a.jsxs("button",{onClick:u,className:`flex-1 text-left px-3 py-2 bg-bambu-dark rounded hover:bg-bambu-dark-tertiary transition-colors ${i?"ring-1 ring-bambu-green":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-green font-mono text-sm font-bold whitespace-nowrap",children:iie(t.k_value)}),a.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name||"Unnamed"}),o&&a.jsx("span",{title:"Has note",children:a.jsx(HW,{className:"w-3 h-3 text-yellow-500"})}),a.jsxs("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:[l," ",c]})]}),o&&a.jsxs("div",{className:"text-xs mt-0.5 truncate text-yellow-500/70",title:o,children:["Note: ",o.length>50?o.substring(0,50)+"...":o]})]}),!r&&n&&a.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"text-bambu-gray hover:text-white transition-colors p-1",title:"Copy profile",children:a.jsx(zl,{className:"w-4 h-4"})})]})}function tj({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:r=[],isDualNozzle:i=!1,initialNote:s="",initialNoteKey:o=null,onClose:l,onSave:c,onSaveNote:u,hasPermission:d}){const{t:h}=Yt(),{showToast:p}=Tn(),[m,b]=_.useState(t?.name||""),[y,x]=_.useState(t?.k_value?iie(t.k_value):"0.020"),[v,S]=_.useState(t?.filament_id||""),[N,T]=_.useState(t?.nozzle_id?iXe(t.nozzle_id):"HH00"),[M,A]=_.useState(t?.nozzle_diameter||n),[k,R]=_.useState(t?[t.extruder_id]:i?[0,1]:[0]),[C,P]=_.useState(!1),[U,F]=_.useState({current:0,total:0}),[H,D]=_.useState(s),$=ei.useMemo(()=>{const W=new Map;for(const J of r)if(J.filament_id&&!W.has(J.filament_id)){const ne=SR(J.name||"");W.set(J.filament_id,{id:J.filament_id,name:ne||J.filament_id})}return Array.from(W.values()).sort((J,ne)=>J.name.localeCompare(ne.name))},[r]),G=dt({mutationFn:W=>(console.log("[KProfile] Calling API..."),ae.setKProfile(e,W)),onSuccess:W=>{if(console.log("[KProfile] Save success:",W),p(h("kProfiles.toast.profileSaved")),u&&H!==s){let J;H===""&&o?J=o:t&&t.slot_id>0?J=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:J=`name_${m}_${v}`,u(J,H)}P(!0),setTimeout(()=>{P(!1),c()},2500)},onError:W=>{console.error("[KProfile] Save error:",W),p(W.message,"error"),P(!1)}}),I=dt({mutationFn:W=>(console.log("[KProfile] Deleting profile..."),ae.deleteKProfile(e,W)),onSuccess:W=>{console.log("[KProfile] Delete success:",W),p(h("kProfiles.toast.profileDeleted")),P(!0),setTimeout(()=>{P(!1),l()},4e3)},onError:W=>{console.error("[KProfile] Delete error:",W),p(W.message,"error"),P(!1)}}),[K,Q]=_.useState(!1),oe=()=>{t&&I.mutate({slot_id:t.slot_id,extruder_id:t.extruder_id,nozzle_id:t.nozzle_id,nozzle_diameter:t.nozzle_diameter,filament_id:t.filament_id,setting_id:t.setting_id})},B=async W=>{if(W.preventDefault(),i&&!t&&k.length===0){p(h("kProfiles.toast.selectAtLeastOneExtruder"),"error");return}const J=parseFloat(y).toFixed(6),ne=`${N}-${M}`;if(t||k.length===1){const fe={name:m,k_value:J,filament_id:v,nozzle_id:ne,nozzle_diameter:M,extruder_id:t?t.extruder_id:k[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",fe),G.mutate(fe);return}P(!0),F({current:1,total:k.length});const me=k.map(fe=>({name:m,k_value:J,filament_id:v,nozzle_id:ne,nozzle_diameter:M,extruder_id:fe,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${me.length} profiles in batch:`,me);try{if(await ae.setKProfilesBatch(e,me),p(h("kProfiles.toast.profilesSaved",{count:k.length})),u&&H){const fe=`name_${m}_${v}`;u(fe,H)}}catch(fe){console.error("[KProfile] Failed to save batch:",fe),p(h("kProfiles.toast.failedToSaveBatch"),"error"),P(!1),F({current:0,total:0});return}F({current:k.length,total:k.length}),setTimeout(()=>{P(!1),F({current:0,total:0}),c()},3e3)};return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:[a.jsxs(St,{className:"w-full max-w-md relative",children:[C&&a.jsxs("div",{className:"absolute inset-0 bg-bambu-dark-secondary/90 flex flex-col items-center justify-center z-10 rounded-lg",children:[a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),a.jsx("p",{className:"text-white font-medium",children:U.total>1?h("kProfiles.modal.savingExtruder",{current:U.current,total:U.total}):h("kProfiles.modal.syncing")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:h("kProfiles.modal.pleaseWait")})]}),a.jsxs(Et,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:h(t?"kProfiles.modal.editTitle":"kProfiles.modal.addTitle")}),a.jsx("button",{onClick:l,className:"text-bambu-gray hover:text-white transition-colors",disabled:C,children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:B,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h("kProfiles.modal.profileName")}),a.jsx("input",{type:"text",value:m,onChange:W=>b(W.target.value),disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,placeholder:h("kProfiles.modal.profileNamePlaceholder"),required:!t})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h("kProfiles.modal.kValue")}),a.jsx("input",{type:"text",inputMode:"decimal",value:y,onChange:W=>{const J=W.target.value;(J===""||/^\d*\.?\d*$/.test(J))&&x(J)},onBlur:W=>{const J=parseFloat(W.target.value);isNaN(J)||x((Math.trunc(J*1e3)/1e3).toFixed(3))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none font-mono",placeholder:h("kProfiles.modal.kValuePlaceholder"),required:!0}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:h("kProfiles.modal.kValueHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h("kProfiles.modal.filament")}),a.jsxs("select",{value:v,onChange:W=>{const J=W.target.value;if(S(J),!t&&J&&!m){const ne=$.find(me=>me.id===J);ne&&b(`${N==="HH00"?"HF":"S"} ${ne.name}`)}},disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,required:!t,children:[a.jsx("option",{value:"",children:h("kProfiles.modal.selectFilament")}),t?.filament_id&&a.jsx("option",{value:t.filament_id,children:$.find(W=>W.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&$.map(W=>a.jsx("option",{value:W.id,children:W.name},W.id))]}),!t&&$.length===0&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:h("kProfiles.modal.noFilamentsHelp")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h("kProfiles.modal.flowType")}),a.jsxs("select",{value:N,onChange:W=>{const J=W.target.value;if(T(J),!t&&v&&!m){const ne=$.find(me=>me.id===v);ne&&b(`${J==="HS00"?"HF":"S"} ${ne.name}`)}},disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,children:[a.jsx("option",{value:"HH00",children:h("kProfiles.modal.highFlow")}),a.jsx("option",{value:"HS00",children:h("kProfiles.modal.standard")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h("kProfiles.modal.nozzleSize")}),a.jsxs("select",{value:M,onChange:W=>A(W.target.value),disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,children:[a.jsx("option",{value:"0.2",children:"0.2mm"}),a.jsx("option",{value:"0.4",children:"0.4mm"}),a.jsx("option",{value:"0.6",children:"0.6mm"}),a.jsx("option",{value:"0.8",children:"0.8mm"})]})]})]}),i&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h(t?"kProfiles.modal.extruder":"kProfiles.modal.extruders")}),t?a.jsx("div",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white opacity-60",children:t.extruder_id===1?h("kProfiles.modal.left"):h("kProfiles.modal.right")}):a.jsxs("div",{className:"flex gap-4",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.includes(1),onChange:W=>{W.target.checked?R([...k,1]):R(k.filter(J=>J!==1))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),a.jsx("span",{className:"text-white",children:h("kProfiles.modal.left")})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.includes(0),onChange:W=>{W.target.checked?R([...k,0]):R(k.filter(J=>J!==0))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),a.jsx("span",{className:"text-white",children:h("kProfiles.modal.right")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h("kProfiles.modal.notes")}),a.jsx("textarea",{value:H,onChange:W=>D(W.target.value),placeholder:h("kProfiles.modal.notesPlaceholder"),rows:2,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none resize-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:h("kProfiles.modal.notesHelp")})]}),a.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&a.jsx(Ne,{type:"button",variant:"secondary",onClick:()=>Q(!0),disabled:I.isPending||C||!d("kprofiles:delete"),title:d("kprofiles:delete")?void 0:h("kProfiles.permission.noDelete"),className:"text-red-500 hover:bg-red-500/10",children:I.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4"})}),a.jsx(Ne,{type:"button",variant:"secondary",onClick:l,disabled:C,className:"flex-1",children:h("common.cancel")}),a.jsxs(Ne,{type:"submit",disabled:G.isPending||C||!d(t?"kprofiles:update":"kprofiles:create"),title:d(t?"kprofiles:update":"kprofiles:create")?void 0:h(t?"kProfiles.permission.noUpdate":"kProfiles.permission.noCreate"),className:"flex-1",children:[G.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vk,{className:"w-4 h-4"}),h("common.save")]})]})]})]})]}),K&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:a.jsx(St,{className:"w-full max-w-sm",children:a.jsxs(Et,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:a.jsx(ln,{className:"w-5 h-5 text-red-500"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:h("kProfiles.deleteConfirm.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:h("kProfiles.deleteConfirm.cannotUndo")})]})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:h("kProfiles.deleteConfirm.message",{name:t?.name})}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>Q(!1),className:"flex-1",children:h("common.cancel")}),a.jsxs(Ne,{onClick:()=>{Q(!1),oe()},disabled:I.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[I.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4"}),h("common.delete")]})]})]})})})]})}const y1={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function aXe(){const{t}=Yt(),{showToast:e}=Tn(),{hasPermission:n}=Ir(),[r,i]=_.useState(null),[s,o]=_.useState(()=>localStorage.getItem(y1.NOZZLE_DIAMETER)||"0.4"),[l,c]=_.useState(null),[u,d]=_.useState(!1),[h,p]=_.useState(null),[m,b]=_.useState(""),[y,x]=_.useState("all"),[v,S]=_.useState("all"),[N,T]=_.useState(()=>localStorage.getItem(y1.SORT_OPTION)||"name"),[M,A]=_.useState(!1),[k,R]=_.useState(new Set),[C,P]=_.useState(!1),[U,F]=_.useState(!1),H=_.useCallback(X=>`${X.slot_id}_${X.extruder_id}`,[]);_.useEffect(()=>{localStorage.setItem(y1.NOZZLE_DIAMETER,s)},[s]),_.useEffect(()=>{localStorage.setItem(y1.SORT_OPTION,N)},[N]);const{data:D,isLoading:$}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:G,isLoading:I,isFetching:K,error:Q,refetch:oe}=it({queryKey:["kprofiles",r,s],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",r,"nozzle",s);const X=await ae.getKProfiles(r,s);return console.log("[KProfiles] Received profiles:",X?.profiles?.length||0,"profiles"),X},enabled:!!r,retry:!1,staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:B}=it({queryKey:["kprofiles",r,"0.4"],queryFn:()=>ae.getKProfiles(r,"0.4"),enabled:!!r,staleTime:6e4}),{data:W,refetch:J}=it({queryKey:["kprofile-notes",r],queryFn:()=>ae.getKProfileNotes(r),enabled:!!r,staleTime:3e4}),ne=Q?.message?.includes("not connected");_.useEffect(()=>{if(!r&&D&&D.length>0){const X=D.find(le=>le.is_active);X&&i(X.id)}},[r,D]),_.useEffect(()=>{if(r){const X=setTimeout(()=>{oe()},150);return()=>clearTimeout(X)}},[r,s]);const me=D?.filter(X=>X.is_active)||[],fe=ei.useMemo(()=>G?.profiles?G.profiles.filter(le=>{const pe=m.toLowerCase(),ee=!pe||le.name.toLowerCase().includes(pe)||le.filament_id.toLowerCase().includes(pe),z=y==="all"||y==="left"&&le.extruder_id===1||y==="right"&&le.extruder_id===0,O=v==="all"||v==="hf"&&le.nozzle_id.startsWith("HH")||v==="s"&&le.nozzle_id.startsWith("HS");return ee&&z&&O}).sort((le,pe)=>{switch(N){case"k_value":return parseFloat(le.k_value)-parseFloat(pe.k_value);case"filament":return SR(le.name).localeCompare(SR(pe.name));case"name":default:return le.name.localeCompare(pe.name)}}):[],[G?.profiles,m,y,v,N]),de=D?.find(X=>X.id===r),Re=de?.nozzle_count===2;_.useEffect(()=>{const X=le=>{le.target instanceof HTMLInputElement||le.target instanceof HTMLTextAreaElement||le.target instanceof HTMLSelectElement||l||u||h||(le.key==="r"||le.key==="R"?(le.preventDefault(),oe()):le.key==="n"||le.key==="N"?(le.preventDefault(),d(!0)):le.key==="Escape"&&M&&(le.preventDefault(),A(!1),R(new Set)))};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[l,u,h,M,oe]);const se=_.useCallback(()=>{if(!G?.profiles||G.profiles.length===0){e(t("kProfiles.toast.noProfilesToExport"),"error");return}const X={version:1,exported_at:new Date().toISOString(),printer:de?.name||"Unknown",nozzle_diameter:s,profiles:G.profiles.map(z=>({name:z.name,k_value:z.k_value,filament_id:z.filament_id,nozzle_id:z.nozzle_id,nozzle_diameter:z.nozzle_diameter,extruder_id:z.extruder_id}))},le=new Blob([JSON.stringify(X,null,2)],{type:"application/json"}),pe=URL.createObjectURL(le),ee=document.createElement("a");ee.href=pe,ee.download=`kprofiles_${de?.name||"printer"}_${s}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(ee),ee.click(),document.body.removeChild(ee),URL.revokeObjectURL(pe),e(t("kProfiles.toast.exportedProfiles",{count:G.profiles.length}))},[G?.profiles,de,s,e,t]),ke=_.useCallback(()=>{const X=document.createElement("input");X.type="file",X.accept=".json",X.onchange=async le=>{const pe=le.target.files?.[0];if(pe)try{const ee=await pe.text(),z=JSON.parse(ee);if(!z.profiles||!Array.isArray(z.profiles)){e(t("kProfiles.toast.invalidFileFormat"),"error");return}let O=0;for(const Z of z.profiles)if(!(!Z.name||!Z.k_value||!Z.filament_id))try{await ae.setKProfile(r,{name:Z.name,k_value:parseFloat(Z.k_value).toFixed(6),filament_id:Z.filament_id,nozzle_id:Z.nozzle_id||`HH00-${s}`,nozzle_diameter:Z.nozzle_diameter||s,extruder_id:Z.extruder_id??0,slot_id:0}),O++,await new Promise(ge=>setTimeout(ge,500))}catch(ge){console.error("Failed to import profile:",Z.name,ge)}e(t("kProfiles.toast.importedProfiles",{count:O,total:z.profiles.length})),oe()}catch(ee){console.error("Import error:",ee),e(t("kProfiles.toast.failedToParseImport"),"error")}},X.click()},[r,s,e,oe,t]),Fe=_.useCallback(X=>{R(le=>{const pe=new Set(le);return pe.has(X)?pe.delete(X):pe.add(X),pe})},[]),ce=_.useCallback(()=>{R(new Set(fe.map(X=>H(X))))},[fe,H]),Ve=_.useCallback(()=>{k.size!==0&&P(!0)},[k.size]),V=_.useCallback(async()=>{const X=fe.filter(pe=>k.has(H(pe)));F(!0);let le=0;for(const pe of X)try{await ae.deleteKProfile(r,{slot_id:pe.slot_id,extruder_id:pe.extruder_id,nozzle_id:pe.nozzle_id,nozzle_diameter:pe.nozzle_diameter,filament_id:pe.filament_id,setting_id:pe.setting_id}),le++,await new Promise(ee=>setTimeout(ee,300))}catch(ee){console.error("Failed to delete profile:",pe.name,ee)}e(t("kProfiles.toast.profilesDeleted",{count:le})),F(!1),P(!1),A(!1),R(new Set),oe()},[r,k,fe,e,oe,H,t]),Y=_.useCallback(X=>{const le=[];return X.setting_id&&le.push(X.setting_id),le.push(`slot_${X.slot_id}_${X.filament_id}_${X.extruder_id}`),le.push(`name_${X.name}_${X.filament_id}`),le},[]),ue=_.useCallback(async(X,le)=>{if(r)try{await ae.setKProfileNote(r,X,le),J()}catch(pe){console.error("Failed to save note:",pe),e(t("kProfiles.toast.failedToSaveNote"),"error")}},[r,J,e,t]),q=_.useCallback(X=>{if(!W?.notes)return{note:"",key:null};const le=Y(X);for(const pe of le)if(W.notes[pe])return{note:W.notes[pe],key:pe};return{note:"",key:null}},[W,Y]),re=_.useCallback(X=>q(X).note,[q]);return $?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!D||D.length===0?a.jsx(St,{children:a.jsxs(Et,{className:"py-12 text-center",children:[a.jsx(Ti,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noPrintersConfigured")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.addPrinterInSettings")})]})}):me.length===0?a.jsx(St,{children:a.jsxs(Et,{className:"py-12 text-center",children:[a.jsx(jr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noActivePrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.enablePrinterConnection")})]})}):a.jsxs(a.Fragment,{children:[K&&!I&&a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[a.jsx(ct,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),a.jsx("p",{className:"text-white font-medium",children:t("kProfiles.loadingProfiles")})]}),a.jsxs("div",{className:"flex flex-wrap gap-4 mb-6",children:[a.jsxs("div",{className:"flex-1 min-w-48",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.printer")}),a.jsx("select",{value:r||"",onChange:X=>i(parseInt(X.target.value)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:me.map(X=>a.jsx("option",{value:X.id,children:X.name},X.id))})]}),a.jsxs("div",{className:"w-32",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.nozzle")}),a.jsxs("select",{value:s,onChange:X=>o(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"0.2",children:"0.2mm"}),a.jsx("option",{value:"0.4",children:"0.4mm"}),a.jsx("option",{value:"0.6",children:"0.6mm"}),a.jsx("option",{value:"0.8",children:"0.8mm"})]})]}),a.jsxs("div",{className:"flex items-end gap-2",children:[a.jsxs(Ne,{variant:"secondary",onClick:()=>oe(),disabled:K||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noRead"),children:[a.jsx(Or,{className:`w-4 h-4 ${K?"animate-spin":""}`}),t("kProfiles.refresh")]}),a.jsxs(Ne,{onClick:()=>d(!0),disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noCreate"),children:[a.jsx(cr,{className:"w-4 h-4"}),t("kProfiles.addProfile")]})]})]}),a.jsxs("div",{className:"flex flex-wrap gap-4 mb-4",children:[a.jsxs("div",{className:"flex-1 min-w-48 relative",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:m,onChange:X=>b(X.target.value),placeholder:t("kProfiles.searchPlaceholder"),className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),Re&&a.jsx("div",{className:"w-36",children:a.jsxs("select",{value:y,onChange:X=>x(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("kProfiles.allExtruders")}),a.jsx("option",{value:"left",children:t("kProfiles.leftOnly")}),a.jsx("option",{value:"right",children:t("kProfiles.rightOnly")})]})}),a.jsx("div",{className:"w-32",children:a.jsxs("select",{value:v,onChange:X=>S(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("kProfiles.allFlow")}),a.jsx("option",{value:"hf",children:t("kProfiles.hfOnly")}),a.jsx("option",{value:"s",children:t("kProfiles.sOnly")})]})}),a.jsx("div",{className:"w-32",children:a.jsxs("select",{value:N,onChange:X=>T(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"name",children:t("kProfiles.sortName")}),a.jsx("option",{value:"k_value",children:t("kProfiles.sortKValue")}),a.jsx("option",{value:"filament",children:t("kProfiles.sortFilament")})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[a.jsxs(Ne,{variant:"secondary",onClick:se,disabled:!G?.profiles?.length||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noExport"),children:[a.jsx(wi,{className:"w-4 h-4"}),t("kProfiles.export")]}),a.jsxs(Ne,{variant:"secondary",onClick:ke,disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noImport"),children:[a.jsx(Na,{className:"w-4 h-4"}),t("kProfiles.import")]}),a.jsx("div",{className:"flex-1"}),M?a.jsxs(a.Fragment,{children:[a.jsxs(Ne,{variant:"secondary",onClick:ce,children:[a.jsx(Xs,{className:"w-4 h-4"}),t("kProfiles.selectAll")]}),a.jsxs(Ne,{variant:"secondary",onClick:Ve,disabled:k.size===0||!n("kprofiles:delete"),className:"text-red-500 hover:bg-red-500/10",title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[a.jsx(ln,{className:"w-4 h-4"}),t("kProfiles.delete")," (",k.size,")"]}),a.jsxs(Ne,{variant:"secondary",onClick:()=>{A(!1),R(new Set)},children:[a.jsx(Lt,{className:"w-4 h-4"}),t("common.cancel")]})]}):a.jsxs(Ne,{variant:"secondary",onClick:()=>A(!0),disabled:!fe.length||!n("kprofiles:delete"),title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[a.jsx(Xs,{className:"w-4 h-4"}),t("kProfiles.select")]})]}),I?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):ne?a.jsx(St,{children:a.jsxs(Et,{className:"py-12 text-center",children:[a.jsx(fm,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.printerOffline")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.printerOfflineDesc")}),a.jsxs(Ne,{variant:"secondary",onClick:()=>oe(),children:[a.jsx(Or,{className:"w-4 h-4"}),t("common.refresh")]})]})}):fe.length>0?Re?a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.leftExtruder")}),a.jsx("div",{className:"space-y-1",children:fe.filter(X=>X.extruder_id===1).map(X=>a.jsx(ej,{profile:X,onEdit:()=>c(X),onCopy:()=>p(X),selectionMode:M,isSelected:k.has(H(X)),onToggleSelect:()=>Fe(H(X)),note:re(X)},H(X)))})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.rightExtruder")}),a.jsx("div",{className:"space-y-1",children:fe.filter(X=>X.extruder_id===0).map(X=>a.jsx(ej,{profile:X,onEdit:()=>c(X),onCopy:()=>p(X),selectionMode:M,isSelected:k.has(H(X)),onToggleSelect:()=>Fe(H(X)),note:re(X)},H(X)))})]})]}):a.jsx("div",{className:"space-y-1",children:fe.map(X=>a.jsx(ej,{profile:X,onEdit:()=>c(X),onCopy:()=>p(X),selectionMode:M,isSelected:k.has(H(X)),onToggleSelect:()=>Fe(H(X)),note:re(X)},H(X)))}):m||y!=="all"||v!=="all"?a.jsx(St,{children:a.jsxs(Et,{className:"py-12 text-center",children:[a.jsx(Qi,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noMatchingProfiles")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.noMatchingProfilesDesc")})]})}):a.jsx(St,{children:a.jsxs(Et,{className:"py-12 text-center",children:[a.jsx(vk,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noKProfiles")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.noKProfilesDesc",{diameter:s})}),a.jsxs(Ne,{onClick:()=>d(!0),children:[a.jsx(cr,{className:"w-4 h-4"}),t("kProfiles.createFirstProfile")]})]})}),l&&r&&(()=>{const{note:X,key:le}=q(l);return a.jsx(tj,{profile:l,printerId:r,nozzleDiameter:s,existingProfiles:B?.profiles||G?.profiles,isDualNozzle:Re,initialNote:X,initialNoteKey:le,onSaveNote:ue,hasPermission:n,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),c(null),oe()},onSave:()=>{c(null),oe()}})})(),u&&r&&a.jsx(tj,{printerId:r,nozzleDiameter:s,existingProfiles:B?.profiles||G?.profiles,isDualNozzle:Re,onSaveNote:ue,hasPermission:n,onClose:()=>{d(!1),oe()},onSave:()=>{d(!1),oe()}}),h&&r&&a.jsx(tj,{printerId:r,nozzleDiameter:s,existingProfiles:B?.profiles||G?.profiles,isDualNozzle:Re,onSaveNote:ue,hasPermission:n,profile:{...h,slot_id:0,name:`${h.name} (Copy)`},onClose:()=>{p(null),oe()},onSave:()=>{p(null),oe()}}),C&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-sm",children:a.jsxs(Et,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:a.jsx(ln,{className:"w-5 h-5 text-red-500"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:t("kProfiles.bulkDelete.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("kProfiles.bulkDelete.cannotUndo")})]})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:t("kProfiles.bulkDelete.message",{count:k.size})}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>P(!1),disabled:U,className:"flex-1",children:t("common.cancel")}),a.jsxs(Ne,{onClick:V,disabled:U,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[U?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4"}),t("common.delete")]})]})]})})})]})}const aie=["PLA","PETG","ABS","ASA","TPU","PC","PA","PVA","HIPS","PP","PET","NYLON"],sXe={PLA:"E8E8E8",PETG:"4A90D9",ABS:"E67E22",ASA:"D35400",TPU:"9B59B6",PC:"BDC3C7",PA:"2ECC71",NYLON:"2ECC71",PVA:"F1C40F",HIPS:"95A5A6",PP:"ECF0F1",PET:"3498DB"};function oXe(t){const e=t.toUpperCase();for(const n of aie)if(new RegExp(`\\b${n}\\b`).test(e))return n;return null}function lXe(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const r of aie){const i=n.indexOf(r);if(i>0){const s=e.slice(0,i).trim();if(s&&s.length>1)return s}}return null}function nj({preset:t,onDelete:e,onExpand:n,isExpanded:r}){const{t:i}=Yt(),{hasPermission:s}=Ir(),o=t.filament_type||oXe(t.name),l=t.filament_vendor||lXe(t.name);let c=null,u=!1;if(t.default_filament_colour)try{const d=JSON.parse(t.default_filament_colour),h=Array.isArray(d)?d[0]:d;typeof h=="string"&&/^#?[0-9a-fA-F]{6,8}$/.test(h.replace("#",""))&&(c=h.replace("#","").slice(0,6),u=!0)}catch{const d=t.default_filament_colour;/^#?[0-9a-fA-F]{6,8}$/.test(d.replace("#",""))&&(c=d.replace("#","").slice(0,6),u=!0)}return!c&&o&&(c=sXe[o.toUpperCase()]||null),a.jsx(St,{className:"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80 transition-colors",children:a.jsxs(Et,{className:"p-3",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[t.preset_type==="filament"&&a.jsx("div",{className:`w-4 h-4 rounded-full border border-white/20 flex-shrink-0 ${!u&&!c?"opacity-25":u?"":"opacity-50"}`,style:{backgroundColor:c?`#${c}`:"#666"}}),a.jsx("span",{className:"text-sm font-medium text-white truncate",children:t.name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:o}),l&&a.jsx("span",{className:"text-xs text-bambu-gray",children:l}),a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400",children:i("profiles.localProfiles.badge")})]})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s("settings:update")&&a.jsx("button",{onClick:()=>e(t.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:i("profiles.localProfiles.delete"),children:a.jsx(ln,{className:"w-3.5 h-3.5"})}),a.jsx("button",{onClick:()=>n(r?null:t.id),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r?a.jsx(zu,{className:"w-3.5 h-3.5"}):a.jsx(fr,{className:"w-3.5 h-3.5"})})]})]}),r&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary text-xs space-y-1.5",children:[o&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.filamentType")}),a.jsx("span",{className:"text-white",children:o})]}),l&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.vendor")}),a.jsx("span",{className:"text-white",children:l})]}),t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.nozzleTemp")}),a.jsxs("span",{className:"text-white",children:[t.nozzle_temp_min,"–",t.nozzle_temp_max,"°C"]})]}),t.filament_cost&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.cost")}),a.jsx("span",{className:"text-white",children:t.filament_cost})]}),t.filament_density&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.density")}),a.jsxs("span",{className:"text-white",children:[t.filament_density," g/cm³"]})]}),t.pressure_advance&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.pressureAdvance")}),a.jsx("span",{className:"text-white",children:t.pressure_advance})]}),t.compatible_printers&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.compatiblePrinters")}),a.jsx("span",{className:"text-white truncate ml-2",children:(()=>{try{return JSON.parse(t.compatible_printers).join(", ")}catch{return t.compatible_printers}})()})]}),t.inherits&&t.inherits!==t.name&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.inheritsFrom")}),a.jsx("span",{className:"text-white truncate ml-2",children:t.inherits})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.source")}),a.jsx("span",{className:"text-white capitalize",children:t.source})]})]})]})})}function cXe(){const{t}=Yt(),{hasPermission:e}=Ir(),n=an(),{showToast:r}=Tn(),[i,s]=_.useState(""),[o,l]=_.useState(null),[c,u]=_.useState(!1),[d,h]=_.useState(null),{data:p,isLoading:m}=it({queryKey:["localPresets"],queryFn:()=>ae.getLocalPresets()}),b=dt({mutationFn:async k=>{const R=[];for(const C of Array.from(k)){const P=new FormData;P.append("file",C),R.push(await ae.importLocalPresets(P))}return R},onSuccess:k=>{n.invalidateQueries({queryKey:["localPresets"]});let R=0,C=0,P=0;for(const U of k)R+=U.imported,C+=U.skipped,P+=U.errors.length;R>0&&r(t("profiles.localProfiles.toast.importSuccess",{count:R})),C>0&&r(t("profiles.localProfiles.toast.importSkipped",{count:C}),"warning"),P>0&&r(t("profiles.localProfiles.toast.importError",{count:P}),"error")},onError:k=>{r(k.message,"error")}}),y=dt({mutationFn:k=>ae.deleteLocalPreset(k),onSuccess:()=>{n.invalidateQueries({queryKey:["localPresets"]}),h(null),r(t("profiles.localProfiles.toast.deleted"))}}),x=_.useCallback(k=>{!k||k.length===0||b.mutate(k)},[b]),v=_.useCallback(k=>{k.preventDefault(),u(!1),x(k.dataTransfer.files)},[x]),S=_.useCallback(k=>{if(!i)return k;const R=i.toLowerCase();return k.filter(C=>C.name.toLowerCase().includes(R)||C.filament_type?.toLowerCase().includes(R)||C.filament_vendor?.toLowerCase().includes(R))},[i]),N=_.useMemo(()=>S(p?.filament||[]),[p?.filament,S]),T=_.useMemo(()=>S(p?.printer||[]),[p?.printer,S]),M=_.useMemo(()=>S(p?.process||[]),[p?.process,S]),A=N.length+T.length+M.length;return m?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"space-y-6",children:[e("settings:update")&&a.jsxs("div",{onDragOver:k=>{k.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:v,className:`relative border-2 border-dashed rounded-lg p-6 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("input",{type:"file",accept:".json,.zip,.orca_filament,.bbscfg,.bbsflmt",multiple:!0,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer",onChange:k=>x(k.target.files)}),b.isPending?a.jsxs("div",{className:"flex items-center justify-center gap-2",children:[a.jsx(ct,{className:"w-5 h-5 text-bambu-green animate-spin"}),a.jsx("span",{className:"text-bambu-gray",children:t("profiles.localProfiles.importing")})]}):a.jsxs(a.Fragment,{children:[a.jsx(Na,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-white font-medium",children:t("profiles.localProfiles.import")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("profiles.localProfiles.importDesc")})]})]}),A>0&&a.jsxs("div",{className:"relative",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:i,onChange:k=>s(k.target.value),placeholder:t("profiles.localProfiles.search"),className:"w-full pl-9 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),A===0&&!m&&a.jsxs("div",{className:"text-center py-12",children:[a.jsx(Sb,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3 opacity-50"}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.localProfiles.noPresets")}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:t("profiles.localProfiles.importDesc")})]}),A>0&&a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[N.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(gk,{className:"w-4 h-4 text-bambu-green"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",N.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:N.map(k=>a.jsx(nj,{preset:k,onDelete:R=>h(R),onExpand:l,isExpanded:o===k.id},k.id))})]}),M.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(is,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",M.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:M.map(k=>a.jsx(nj,{preset:k,onDelete:R=>h(R),onExpand:l,isExpanded:o===k.id},k.id))})]}),T.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Hu,{className:"w-4 h-4 text-orange-400"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",T.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:T.map(k=>a.jsx(nj,{preset:k,onDelete:R=>h(R),onExpand:l,isExpanded:o===k.id},k.id))})]})]}),d!==null&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-6 max-w-sm mx-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Ti,{className:"w-5 h-5 text-red-400"}),a.jsx("h3",{className:"text-white font-medium",children:t("profiles.localProfiles.deleteConfirmTitle")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:t("profiles.localProfiles.deleteConfirm")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>h(null),children:t("profiles.localProfiles.cancel")}),a.jsxs(Ne,{variant:"danger",size:"sm",onClick:()=>y.mutate(d),disabled:y.isPending,children:[y.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4"}),t("profiles.localProfiles.delete")]})]})]})})]})}function MF(t,e){const n=`${t} ${e||""}`,r=n.match(/@?\s*(?:BBL\s+)?(?:Bambu\s+Lab\s+)?([XPAH][1-9][A-Z]?(?:\s*(?:Carbon|mini))?|H2D)/i),i=r?r[1].trim():null,s=n.match(/(\d+\.?\d*)\s*(?:mm\s*)?nozzle|nozzle\s*(\d+\.?\d*)/i),o=s?(s[1]||s[2])+"mm":null,l=n.match(/(\d+\.?\d*)mm\s*(?:Standard|Fine|Extra Fine|Draft|Quality)?/i),c=l?l[1]+"mm":null,u=n.match(/\b(PLA|PETG|ABS|ASA|TPU|PC|PA|PVA|HIPS|PP|PET(?:-?CF)?|PA(?:-?CF)?|PLA(?:-?CF)?)\b/i),d=u?u[1].toUpperCase():null;return{printer:i,nozzle:o,layerHeight:c,filamentType:d}}function zy(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function uXe(t,e){const n=zi(t);if(!n)return"";const i=new Date().getTime()-n.getTime(),s=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return s<1?e("profiles.time.justNow"):s<60?e("profiles.time.minsAgo",{count:s}):o<24?e("profiles.time.hoursAgo",{count:o}):l<7?e("profiles.time.daysAgo",{count:l}):n.toLocaleDateString()}function dXe({onSuccess:t,t:e}){const{showToast:n}=Tn(),[r,i]=_.useState("email"),[s,o]=_.useState(""),[l,c]=_.useState(""),[u,d]=_.useState(""),[h,p]=_.useState(""),[m,b]=_.useState("global"),[y,x]=_.useState(null),[v,S]=_.useState(null),N=dt({mutationFn:()=>ae.cloudLogin(s,l,m),onSuccess:R=>{R.success?(n(e("profiles.login.toast.loggedIn")),t()):R.needs_verification?(x(R.verification_type||"email"),S(R.tfa_key||null),R.verification_type==="totp"?n(e("profiles.login.toast.enterTotp")):n(e("profiles.login.toast.codeSent")),i("code")):n(R.message,"error")},onError:R=>n(R.message,"error")}),T=dt({mutationFn:()=>ae.cloudVerify(s,u,v||void 0),onSuccess:R=>{R.success?(n(e("profiles.login.toast.loggedIn")),t()):n(R.message,"error")},onError:R=>n(R.message,"error")}),M=dt({mutationFn:()=>ae.cloudSetToken(h),onSuccess:()=>{n(e("profiles.login.toast.tokenSet")),t()},onError:R=>n(R.message,"error")}),A=R=>{R.preventDefault(),r==="email"?N.mutate():r==="code"?T.mutate():r==="token"&&M.mutate()},k=N.isPending||T.isPending||M.isPending;return a.jsx(St,{className:"max-w-md mx-auto",children:a.jsxs(Et,{children:[a.jsxs("div",{className:"text-center mb-6",children:[a.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-bambu-green/20 mb-3",children:a.jsx(pk,{className:"w-6 h-6 text-bambu-green"})}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:e("profiles.login.title")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:e("profiles.login.subtitle")})]}),a.jsxs("form",{onSubmit:A,className:"space-y-4",children:[r==="email"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.email")}),a.jsx("input",{type:"email",value:s,onChange:R=>o(R.target.value),className:"w-full px-3 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",placeholder:"your@email.com",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.password")}),a.jsx("input",{type:"password",value:l,onChange:R=>c(R.target.value),className:"w-full px-3 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",placeholder:"••••••••",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.region")}),a.jsxs("select",{value:m,onChange:R=>b(R.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"global",children:e("profiles.login.regionGlobal")}),a.jsx("option",{value:"china",children:e("profiles.login.regionChina")})]})]})]}),r==="code"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e(y==="totp"?"profiles.login.totpCode":"profiles.login.verificationCode")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:y==="totp"?e("profiles.login.enterTotpHint"):e("profiles.login.checkEmail",{email:s})}),a.jsx("input",{type:"text",value:u,onChange:R=>d(R.target.value.replace(/\D/g,"").slice(0,6)),className:"w-full px-3 py-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-center text-2xl tracking-widest font-mono focus:border-bambu-green focus:outline-none",placeholder:"000000",maxLength:6,required:!0})]}),r==="token"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.accessToken")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:e("profiles.login.accessTokenHint")}),a.jsx("textarea",{value:h,onChange:R=>p(R.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs font-mono placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none resize-none",placeholder:"eyJ...",rows:4,required:!0})]}),a.jsxs("div",{className:"flex gap-2",children:[r==="code"&&a.jsx(Ne,{type:"button",variant:"secondary",onClick:()=>i("email"),className:"flex-1",children:e("profiles.login.back")}),a.jsxs(Ne,{type:"submit",disabled:k,className:"flex-1",children:[k?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(QU,{className:"w-4 h-4"}),e(r==="email"?"profiles.login.loginButton":r==="code"?"profiles.login.verifyButton":"profiles.login.setTokenButton")]})]}),r==="email"&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("button",{type:"button",onClick:()=>i("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[a.jsx(Yo,{className:"w-4 h-4"}),e("profiles.login.useToken")]})}),r==="token"&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("button",{type:"button",onClick:()=>i("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[a.jsx(QU,{className:"w-4 h-4"}),e("profiles.login.useEmail")]})})]})]})})}function og({label:t,value:e,options:n,onChange:r}){const[i,s]=_.useState(!1),o=n.find(l=>l.value===e);return a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>s(!i),className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white hover:border-bambu-gray-dark transition-colors",children:[a.jsxs("span",{className:"text-bambu-gray",children:[t,":"]}),a.jsx("span",{children:o?.label||"All"}),a.jsx(fr,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"rotate-180":""}`})]}),i&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>s(!1)}),a.jsx("div",{className:"absolute top-full left-0 mt-1 min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 py-1 max-h-60 overflow-y-auto",children:n.map(l=>a.jsxs("button",{onClick:()=>{r(l.value),s(!1)},className:`w-full px-3 py-2 text-left text-sm flex items-center justify-between hover:bg-bambu-dark-tertiary transition-colors ${e===l.value?"text-bambu-green":"text-white"}`,children:[a.jsx("span",{children:l.label}),l.count!==void 0&&a.jsx("span",{className:"text-bambu-gray text-xs",children:l.count})]},l.value))})]})]})}function hXe(){const[t,e]=_.useState(!1);_.useEffect(()=>{const r=()=>{e(window.scrollY>300)};return window.addEventListener("scroll",r),()=>window.removeEventListener("scroll",r)},[]);const n=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?a.jsx("button",{onClick:n,className:"fixed bottom-6 right-6 p-3 bg-bambu-green hover:bg-bambu-green-light text-white rounded-full shadow-lg shadow-bambu-green/25 transition-all z-40","aria-label":"Scroll to top",children:a.jsx(Hg,{className:"w-5 h-5"})}):null}function rj({setting:t,onClick:e,onDuplicate:n,compareMode:r,isCompareSelected:i,compareIndex:s,compareDisabled:o,t:l}){const c=MF(t.name),u=zy(t.setting_id);return a.jsxs("div",{className:"flex items-center gap-2 group",children:[a.jsx("button",{onClick:e,disabled:o,className:`flex-1 text-left px-3 py-2 rounded transition-colors ${i?"bg-blue-500/20 border border-blue-500/50":o?"bg-bambu-dark/50 opacity-40 cursor-not-allowed":"bg-bambu-dark hover:bg-bambu-dark-tertiary"} ${r&&!o?"cursor-pointer":""}`,children:a.jsxs("div",{className:"flex items-center gap-2",children:[i&&s!==void 0&&a.jsx("span",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-blue-500 text-white text-xs flex items-center justify-center font-medium",children:s+1}),!i&&u&&a.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:l("profiles.presets.myPreset")}),a.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),c.filamentType&&t.type==="filament"&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.filamentType}),c.layerHeight&&t.type==="process"&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.layerHeight}),c.printer&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.printer})]})}),a.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"opacity-0 group-hover:opacity-100 text-bambu-gray hover:text-white transition-all p-1",title:l("profiles.presets.duplicate"),children:a.jsx(zl,{className:"w-4 h-4"})})]})}function NR(t,e=0){const n=" ".repeat(e);if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string"){if(t.includes("\\n")||t.includes(` + `,children:a.jsxs("div",{className:"flex items-center gap-4 p-4",children:[R&&d&&a.jsx("button",{onClick:P=>{P.stopPropagation(),d()},className:`flex items-center justify-center w-6 h-6 rounded border transition-colors ${u?"bg-bambu-green border-bambu-green text-white":"border-white/30 bg-black/30 hover:border-bambu-green/50"}`,children:u&&a.jsx($i,{className:"w-4 h-4"})}),R?a.jsx("div",{...x,...v,className:"flex items-center justify-center w-10 h-10 md:w-8 md:h-8 rounded-lg bg-bambu-dark cursor-grab active:cursor-grabbing hover:bg-bambu-dark-tertiary transition-colors touch-manipulation",children:a.jsx(Vg,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}):e!==void 0?a.jsxs("div",{className:"flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark text-bambu-gray text-sm font-medium",children:["#",e]}):a.jsx("div",{className:"w-8"}),a.jsx("div",{className:"w-14 h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:t.archive_thumbnail?a.jsx("img",{src:t.plate_id!=null?ae.getArchivePlateThumbnail(t.archive_id,t.plate_id):ae.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?a.jsx("img",{src:t.plate_id!=null?ae.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):ae.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",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(is,{className:"w-6 h-6"})})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:t.archive_name||t.library_file_name||`File #${t.archive_id||t.library_file_id}`}),t.archive_id?a.jsx(Bs,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:b("queue.viewArchive"),children:a.jsx(Xr,{className:"w-3.5 h-3.5"})}):t.library_file_id?a.jsx(Bs,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:b("queue.viewInFileManager"),children:a.jsx(Xr,{className:"w-3.5 h-3.5"})}):null]}),a.jsxs("div",{className:"flex items-center gap-3 text-sm text-bambu-gray",children:[a.jsxs("span",{className:`flex items-center gap-1.5 ${t.printer_id===null&&!t.target_model?"text-orange-400":""} ${t.target_model?"text-blue-400":""}`,children:[a.jsx(jr,{className:"w-3.5 h-3.5"}),t.target_model?`${b("queue.filter.any")} ${t.target_model}${t.target_location?` @ ${t.target_location}`:""}${t.required_filament_types?.length?` (${t.required_filament_types.join(", ")})`:""}`:t.printer_id===null?b("queue.filter.unassigned"):t.printer_name||`${b("common.printer")} #${t.printer_id}`]}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(wu,{className:"w-3.5 h-3.5"}),rie(t.print_time_seconds)]}),t.created_by_username&&a.jsxs("span",{className:"flex items-center gap-1.5",title:b("queue.addedBy",{name:t.created_by_username}),children:[a.jsx($u,{className:"w-3.5 h-3.5"}),t.created_by_username]}),R&&!t.manual_start&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(tr,{className:"w-3.5 h-3.5"}),gKe(t.scheduled_time,c,b)]})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[t.manual_start&&a.jsxs("span",{className:"text-xs px-2 py-0.5 bg-purple-500/10 text-purple-400 rounded-full border border-purple-500/20 flex items-center gap-1",children:[a.jsx(LW,{className:"w-3 h-3"}),b("queue.badges.staged")]}),t.require_previous_success&&a.jsx("span",{className:"text-xs px-2 py-0.5 bg-orange-500/10 text-orange-400 rounded-full border border-orange-500/20",children:b("queue.badges.requiresPrevious")}),t.auto_off_after&&a.jsxs("span",{className:"text-xs px-2 py-0.5 bg-blue-500/10 text-blue-400 rounded-full border border-blue-500/20 flex items-center gap-1",children:[a.jsx(Ju,{className:"w-3 h-3"}),b("queue.badges.autoPowerOff")]})]}),k&&a.jsxs("div",{className:"mt-3",children:[a.jsx("div",{className:"h-2 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full bg-gradient-to-r from-blue-500 to-blue-400 animate-pulse w-full opacity-50"})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:b("queue.printingInProgress")})]}),t.waiting_reason&&t.status==="pending"&&a.jsxs("p",{className:"text-xs text-purple-400 mt-2 flex items-start gap-1",children:[a.jsx(Ti,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),a.jsx("span",{children:t.waiting_reason})]}),t.error_message&&a.jsxs("p",{className:"text-xs text-red-400 mt-2 flex items-center gap-1",children:[a.jsx(Ti,{className:"w-3 h-3"}),t.error_message]})]}),a.jsx(bKe,{status:t.status,waitingReason:t.waiting_reason,printerState:m,t:b}),a.jsxs("div",{className:"flex items-center gap-1",children:[k&&a.jsx(Ne,{variant:"ghost",size:"sm",onClick:s,disabled:!h("printers:control"),title:h("printers:control")?b("queue.actions.stopPrint"):b("queue.permissions.noStopPrint"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:a.jsx(bue,{className:"w-4 h-4"})}),R&&a.jsxs(a.Fragment,{children:[t.manual_start&&a.jsx(Ne,{variant:"ghost",size:"sm",onClick:l,disabled:!h("printers:control"),title:h("printers:control")?b("queue.actions.startPrint"):b("queue.permissions.noStartPrint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:a.jsx(Eo,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:n,disabled:!p("queue","update",t.created_by_id),title:p("queue","update",t.created_by_id)?b("common.edit"):b("queue.permissions.noEdit"),children:a.jsx(Ji,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:r,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?b("common.cancel"):b("queue.permissions.noCancel"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:a.jsx(Lt,{className:"w-4 h-4"})})]}),C&&a.jsxs(a.Fragment,{children:[a.jsx(Ne,{variant:"ghost",size:"sm",onClick:o,disabled:!h("queue:create"),title:h("queue:create")?b("queue.actions.requeue"):b("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10",children:a.jsx(Or,{className:"w-4 h-4"})}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:i,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?b("common.remove"):b("queue.permissions.noRemove"),children:a.jsx(ln,{className:"w-4 h-4"})})]})]})]})})}function yKe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),{hasPermission:r,hasAnyPermission:i,canModify:s}=Ir(),[o,l]=_.useState(null),[c,u]=_.useState(""),[d,h]=_.useState(""),[p,m]=_.useState(!1),[b,y]=_.useState(null),[x,v]=_.useState(null),[S,N]=_.useState(null),[T,M]=_.useState([]),[A,k]=_.useState(!1),[R,C]=_.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[P,U]=_.useState(()=>{const ee=localStorage.getItem("queue.historySortAsc");return ee!==null?ee==="true":!1}),[F,H]=_.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[D,$]=_.useState(()=>{const ee=localStorage.getItem("queue.pendingSortAsc");return ee!==null?ee==="true":!0});_.useEffect(()=>{localStorage.setItem("queue.historySortBy",R)},[R]),_.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(P))},[P]),_.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",F)},[F]),_.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(D))},[D]);const G=jre(sk(QM,{activationConstraint:{distance:8}}),sk(YM,{coordinateGetter:tie})),{data:I}=it({queryKey:["settings"],queryFn:ae.getSettings}),K=I?.time_format||"system",{data:Q,isLoading:oe}=it({queryKey:["queue",o,c],queryFn:()=>ae.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:B}=it({queryKey:["printers"],queryFn:()=>ae.getPrinters()}),W=dt({mutationFn:ee=>ae.cancelQueueItem(ee),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),J=dt({mutationFn:ee=>ae.removeFromQueue(ee),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),ne=dt({mutationFn:ee=>ae.stopQueueItem(ee),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),me=dt({mutationFn:ee=>ae.startQueueItem(ee),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),fe=dt({mutationFn:ee=>ae.reorderQueue(ee),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),de=dt({mutationFn:async()=>{const ee=Q?.filter(z=>["completed","failed","skipped","cancelled"].includes(z.status))||[];for(const z of ee)await ae.removeFromQueue(z.id);return ee.length},onSuccess:ee=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:ee}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),Re=dt({mutationFn:ee=>ae.bulkUpdateQueue(ee),onSuccess:ee=>{e.invalidateQueries({queryKey:["queue"]}),M([]),k(!1),n(ee.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),se=dt({mutationFn:async ee=>{for(const z of ee)await ae.cancelQueueItem(z);return ee.length},onSuccess:ee=>{e.invalidateQueries({queryKey:["queue"]}),M([]),n(t("queue.toast.bulkCancelled",{count:ee}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),ke=ee=>{M(z=>z.includes(ee)?z.filter(O=>O!==ee):[...z,ee])},Fe=_.useMemo(()=>{const ee=new Set;return B?.forEach(z=>{z.location&&ee.add(z.location)}),Q?.forEach(z=>{z.target_location&&ee.add(z.target_location)}),Array.from(ee).sort()},[B,Q]),ce=_.useCallback(ee=>d?ee.target_location?ee.target_location===d:ee.printer_id?B?.find(O=>O.id===ee.printer_id)?.location===d:!1:!0,[d,B]),Ve=_.useMemo(()=>{let ee=Q?.filter(O=>O.status==="pending")||[];d&&(ee=ee.filter(ce));const z=O=>{if(!O.scheduled_time)return 0;const Z=new Date(O.scheduled_time).getTime(),ge=Date.now()+4320*60*60*1e3;return Z>ge?0:Z};return[...ee].sort((O,Z)=>{let ge;if(F==="name"){const Ce=O.archive_name||O.library_file_name||"",_e=Z.archive_name||Z.library_file_name||"";ge=Ce.localeCompare(_e)}else F==="printer"?ge=(O.printer_name||"").localeCompare(Z.printer_name||""):F==="time"?ge=z(O)-z(Z):ge=O.position-Z.position;return D?ge:-ge})},[Q,F,D,ce,d]),V=()=>{const ee=Ve.map(z=>z.id);T.length===ee.length?M([]):M(ee)},Y=_.useMemo(()=>{let ee=Q?.filter(z=>z.status==="printing")||[];return d&&(ee=ee.filter(ce)),ee},[Q,d,ce]),ue=_.useMemo(()=>{const ee=new Set;return Y.forEach(z=>{z.printer_id&&ee.add(z.printer_id)}),Array.from(ee)},[Y]),q=BR({queries:ue.map(ee=>({queryKey:["printerStatus",ee],queryFn:()=>ae.getPrinterStatus(ee),refetchInterval:5e3}))}),re=_.useMemo(()=>{const ee={};return ue.forEach((z,O)=>{const Z=q[O];Z?.data?.state&&(ee[z]=Z.data.state)}),ee},[ue,q]),X=_.useMemo(()=>{let ee=Q?.filter(z=>["completed","failed","skipped","cancelled"].includes(z.status))||[];return d&&(ee=ee.filter(ce)),[...ee].sort((z,O)=>{let Z;if(R==="name"){const ge=z.archive_name||z.library_file_name||"",Ce=O.archive_name||O.library_file_name||"";Z=ge.localeCompare(Ce)}else R==="printer"?Z=(z.printer_name||"").localeCompare(O.printer_name||""):Z=new Date(O.completed_at||O.created_at).getTime()-new Date(z.completed_at||z.created_at).getTime();return P?-Z:Z})},[Q,R,P,ce,d]),le=_.useMemo(()=>Ve.reduce((ee,z)=>ee+(z.print_time_seconds||0),0),[Ve]),pe=ee=>{const{active:z,over:O}=ee;if(!O||z.id===O.id)return;const Z=Ve.findIndex(Ce=>Ce.id===z.id),ge=Ve.findIndex(Ce=>Ce.id===O.id);if(Z!==-1&&ge!==-1){const _e=e2(Ve,Z,ge).map((Te,we)=>({id:Te.id,position:we+1}));fe.mutate(_e)}};return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsx("div",{className:"flex items-center justify-between mb-8",children:a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx(FW,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-8",children:[a.jsx(St,{className:"bg-gradient-to-br from-blue-500/10 to-transparent border-blue-500/20",children:a.jsx(Et,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center",children:a.jsx(Eo,{className:"w-5 h-5 text-blue-400"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:Y.length}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.printing")})]})]})})}),a.jsx(St,{className:"bg-gradient-to-br from-yellow-500/10 to-transparent border-yellow-500/20",children:a.jsx(Et,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-yellow-500/20 flex items-center justify-center",children:a.jsx(tr,{className:"w-5 h-5 text-yellow-400"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:Ve.length}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.queued")})]})]})})}),a.jsx(St,{className:"bg-gradient-to-br from-bambu-green/10 to-transparent border-bambu-green/20",children:a.jsx(Et,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-bambu-green/20 flex items-center justify-center",children:a.jsx(wu,{className:"w-5 h-5 text-bambu-green"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:rie(le)}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.totalTime")})]})]})})}),a.jsx(St,{className:"bg-gradient-to-br from-gray-500/10 to-transparent border-gray-500/20",children:a.jsx(Et,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-gray-500/20 flex items-center justify-center",children:a.jsx(mr,{className:"w-5 h-5 text-gray-400"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:X.length}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.history")})]})]})})})]}),a.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:o===-1?"unassigned":o||"",onChange:ee=>{const z=ee.target.value;l(z==="unassigned"?-1:z===""?null:Number(z))},children:[a.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),a.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),B?.map(ee=>a.jsx("option",{value:ee.id,children:ee.name},ee.id))]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c,onChange:ee=>u(ee.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allStatus")}),a.jsx("option",{value:"pending",children:t("queue.status.pending")}),a.jsx("option",{value:"printing",children:t("queue.status.printing")}),a.jsx("option",{value:"completed",children:t("queue.status.completed")}),a.jsx("option",{value:"failed",children:t("queue.status.failed")}),a.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),a.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),Fe.length>0&&a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:d,onChange:ee=>h(ee.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allLocations")}),Fe.map(ee=>a.jsx("option",{value:ee,children:ee},ee))]}),a.jsx("div",{className:"flex-1"}),X.length>0&&a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>m(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[a.jsx(ln,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),oe?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):Q?.length===0?a.jsxs(St,{className:"p-12 text-center border-dashed",children:[a.jsx(ti,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),a.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),a.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):a.jsxs("div",{className:"space-y-8",children:[Y.length>0&&a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-4 flex items-center gap-2",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),a.jsx("div",{className:"space-y-3",children:Y.map(ee=>a.jsx(JP,{item:ee,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>N({type:"stop",item:ee}),onRequeue:()=>{},onStart:()=>{},timeFormat:K,hasPermission:r,canModify:s,printerState:ee.printer_id?re[ee.printer_id]:null,t},ee.id))})]}),Ve.length>0&&a.jsxs("div",{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(tr,{className:"w-5 h-5 text-yellow-400"}),t("queue.sections.queued"),a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:Ve.length}),")"]}),a.jsx("span",{className:"text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-3 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:F,onChange:ee=>H(ee.target.value),children:[a.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),a.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>$(!D),title:t(D?"common.ascending":"common.descending"),className:"px-2",children:D?a.jsx(Hg,{className:"w-4 h-4"}):a.jsx(X0,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-bambu-dark rounded-lg",children:[a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:V,className:"flex items-center gap-2",children:[T.length===Ve.length&&Ve.length>0?a.jsx(Xs,{className:"w-4 h-4 text-bambu-green"}):a.jsx(ul,{className:"w-4 h-4"}),T.length===Ve.length&&Ve.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),T.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:T.length})}),a.jsx("div",{className:"h-4 w-px bg-bambu-dark-tertiary"}),a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:()=>k(!0),className:"flex items-center gap-2 text-bambu-green hover:text-bambu-green-light",disabled:!i("queue:update_own","queue:update_all"),title:i("queue:update_own","queue:update_all")?void 0:t("queue.permissions.noEditItems"),children:[a.jsx(Ji,{className:"w-4 h-4"}),t("queue.bulkEdit.editSelected")]}),a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:()=>se.mutate(T),className:"flex items-center gap-2 text-red-400 hover:text-red-300",disabled:se.isPending||!i("queue:delete_own","queue:delete_all"),title:i("queue:delete_own","queue:delete_all")?void 0:t("queue.permissions.noCancelItems"),children:[a.jsx(Lt,{className:"w-4 h-4"}),t("queue.bulkEdit.cancelSelected")]})]})]}),a.jsx(Xre,{sensors:G,collisionDetection:Lre,onDragEnd:pe,children:a.jsx(Zre,{items:Ve.map(ee=>ee.id),strategy:aKe,children:a.jsx("div",{className:"space-y-3",children:Ve.map((ee,z)=>a.jsx(JP,{item:ee,position:z+1,onEdit:()=>y(ee),onCancel:()=>N({type:"cancel",item:ee}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>me.mutate(ee.id),timeFormat:K,isSelected:T.includes(ee.id),onToggleSelect:()=>ke(ee.id),hasPermission:r,canModify:s,t},ee.id))})})})]}),X.length>0&&a.jsxs("div",{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(mr,{className:"w-5 h-5 text-bambu-gray"}),t("queue.sections.history"),a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:X.length}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-3 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:R,onChange:ee=>C(ee.target.value),children:[a.jsx("option",{value:"date",children:t("queue.sort.byDate")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>U(!P),title:t(P?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:P?a.jsx(Hg,{className:"w-4 h-4"}):a.jsx(X0,{className:"w-4 h-4"})})]})]}),a.jsx("div",{className:"space-y-3",children:X.slice(0,20).map((ee,z)=>a.jsx(JP,{item:ee,position:z+1,onEdit:()=>{},onCancel:()=>{},onRemove:()=>N({type:"remove",item:ee}),onStop:()=>{},onRequeue:()=>v(ee),onStart:()=>{},timeFormat:K,hasPermission:r,canModify:s,t},ee.id))})]})]}),b&&a.jsx(Ou,{mode:"edit-queue-item",archiveId:b.archive_id??void 0,libraryFileId:b.library_file_id??void 0,archiveName:b.archive_name||b.library_file_name||`File #${b.archive_id||b.library_file_id}`,queueItem:b,onClose:()=>y(null)}),x&&a.jsx(Ou,{mode:"add-to-queue",archiveId:x.archive_id??void 0,libraryFileId:x.library_file_id??void 0,archiveName:x.archive_name||x.library_file_name||`File #${x.archive_id||x.library_file_id}`,onClose:()=>v(null)}),S&&a.jsx(er,{title:S.type==="cancel"?t("queue.confirm.cancelTitle"):S.type==="stop"?t("queue.confirm.stopTitle"):t("queue.confirm.removeTitle"),message:S.type==="cancel"?t("queue.confirm.cancelMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):S.type==="stop"?t("queue.confirm.stopMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):t("queue.confirm.removeMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisItem")}),confirmText:S.type==="cancel"?t("queue.confirm.cancelButton"):S.type==="stop"?t("queue.confirm.stopButton"):t("common.remove"),variant:"danger",onConfirm:()=>{S.type==="cancel"?W.mutate(S.item.id):S.type==="stop"?ne.mutate(S.item.id):J.mutate(S.item.id),N(null)},onCancel:()=>N(null)}),p&&a.jsx(er,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:X.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{de.mutate(),m(!1)},onCancel:()=>m(!1)}),A&&a.jsx(xKe,{selectedCount:T.length,printers:B?.map(ee=>({id:ee.id,name:ee.name}))||[],onSave:ee=>{Object.keys(ee).length>0&&Re.mutate({item_ids:T,...ee})},onClose:()=>k(!1),isSaving:Re.isPending,t})]})}function vKe({printDates:t,months:e=3}){const n=_.useRef(null),[r,i]=_.useState(0);_.useEffect(()=>{const S=n.current;if(!S)return;const N=new ResizeObserver(T=>{const M=T[0]?.contentRect.width||0;i(M)});return N.observe(S),()=>N.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=_.useMemo(()=>{const S={};t.forEach(U=>{const F=U.split("T")[0];S[F]=(S[F]||0)+1});const N=new Date,T=new Date(N);T.setMonth(T.getMonth()-e),T.setDate(T.getDate()-T.getDay());const M=[],A=[];let k=[],R=-1;const C=new Date(T);let P=0;for(;C<=N;)C.getDay()===0&&k.length>0&&(M.push(k),k=[],P++),C.getMonth()!==R&&(A.push({month:C.toLocaleDateString("en-US",{month:"short"}),weekIndex:P}),R=C.getMonth()),k.push(new Date(C)),C.setDate(C.getDate()+1);return k.length>0&&M.push(k),{weeks:M,monthLabels:A,printCounts:S}},[t,e]),c=Math.max(1,...Object.values(l)),u=S=>{if(S===0)return"bg-bambu-dark";const N=S/c;return N<=.25?"bg-bambu-green/30":N<=.5?"bg-bambu-green/50":N<=.75?"bg-bambu-green/75":"bg-bambu-green"},d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=s.length,p=32,m=2,b=r-p-16,y=h>0?Math.floor((b-(h-1)*m)/h):12,x=Math.max(8,Math.min(20,y)),v=x<=10?10:12;return a.jsx("div",{ref:n,className:"w-full flex justify-center",children:r>0&&a.jsxs("div",{children:[a.jsx("div",{className:"flex mb-1",style:{marginLeft:p+4},children:o.map(({month:S,weekIndex:N},T)=>a.jsx("div",{className:"text-bambu-gray",style:{fontSize:v,marginLeft:T===0?0:`${(N-(o[T-1]?.weekIndex||0))*(x+m)-24}px`},children:S},T))}),a.jsxs("div",{className:"flex",style:{gap:m},children:[a.jsx("div",{className:"flex flex-col",style:{gap:m,marginRight:4,width:p},children:d.map((S,N)=>a.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:x,fontSize:v,visibility:N%2===1?"visible":"hidden"},children:S},S))}),s.map((S,N)=>a.jsx("div",{className:"flex flex-col",style:{gap:m},children:[0,1,2,3,4,5,6].map(T=>{const M=S.find(C=>C.getDay()===T);if(!M)return a.jsx("div",{style:{width:x,height:x}},T);const A=M.toISOString().split("T")[0],k=l[A]||0,R=A===new Date().toISOString().split("T")[0];return a.jsx("div",{className:`rounded-sm ${u(k)} ${R?"ring-1 ring-white":""}`,style:{width:x,height:x},title:`${M.toLocaleDateString()}: ${k} print${k!==1?"s":""}`},T)})},N))]}),a.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:v},children:[a.jsx("span",{children:"Less"}),a.jsxs("div",{className:"flex",style:{gap:m},children:[a.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:x,height:x}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:x,height:x}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:x,height:x}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:x,height:x}}),a.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:x,height:x}})]}),a.jsx("span",{children:"More"})]})]})})}const x1=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"];function wKe(t){const e=new Date;switch(t){case"7d":return new Date(e.getTime()-10080*60*1e3);case"30d":return new Date(e.getTime()-720*60*60*1e3);case"90d":return new Date(e.getTime()-2160*60*60*1e3);case"365d":return new Date(e.getTime()-365*24*60*60*1e3);case"all":return new Date(0)}}function _Ke({archives:t,currency:e="$"}){const[n,r]=_.useState("30d"),i=_.useMemo(()=>{const m=wKe(n);return t.filter(b=>(zi(b.completed_at||b.created_at)||new Date(0))>=m)},[t,n]),s=_.useMemo(()=>{const m=new Map;return i.forEach(b=>{const y=zi(b.completed_at||b.created_at)||new Date,x=`${y.getFullYear()}-${String(y.getMonth()+1).padStart(2,"0")}-${String(y.getDate()).padStart(2,"0")}`,v=m.get(x)||{date:x,filament:0,cost:0,prints:0};v.filament+=b.filament_used_grams||0,v.cost+=b.cost||0,v.prints+=b.quantity||1,m.set(x,v)}),Array.from(m.values()).sort((b,y)=>b.date.localeCompare(y.date)).map(b=>({...b,dateLabel:new Date(b.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[i]),o=_.useMemo(()=>{if(n==="7d"||n==="30d")return s;const m=new Map;return i.forEach(b=>{const y=zi(b.completed_at||b.created_at)||new Date,x=new Date(y);x.setDate(y.getDate()-y.getDay());const v=`${x.getFullYear()}-${String(x.getMonth()+1).padStart(2,"0")}-${String(x.getDate()).padStart(2,"0")}`,S=m.get(v)||{week:v,filament:0,cost:0,prints:0};S.filament+=b.filament_used_grams||0,S.cost+=b.cost||0,S.prints+=b.quantity||1,m.set(v,S)}),Array.from(m.values()).sort((b,y)=>b.week.localeCompare(y.week)).map(b=>({date:b.week,dateLabel:`Week of ${new Date(b.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...b}))},[i,s,n]),l=_.useMemo(()=>{const m=new Map;return i.forEach(b=>{const x=(b.filament_type||"Unknown").split(", ");x.forEach(v=>{const S=(b.filament_used_grams||0)/x.length;m.set(v,(m.get(v)||0)+S)})}),Array.from(m.entries()).map(([b,y])=>({name:b,value:Math.round(y)})).sort((b,y)=>y.value-b.value)},[i]),c=_.useMemo(()=>{const m=new Date,b=[];for(let y=5;y>=0;y--){const x=new Date(m.getFullYear(),m.getMonth()-y,1),v=new Date(m.getFullYear(),m.getMonth()-y+1,0),S=x.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),N=t.filter(T=>{const M=zi(T.completed_at||T.created_at)||new Date(0);return M>=x&&M<=v});b.push({month:S,filament:Math.round(N.reduce((T,M)=>T+(M.filament_used_grams||0),0)),cost:N.reduce((T,M)=>T+(M.cost||0),0),prints:N.reduce((T,M)=>T+(M.quantity||1),0)})}return b},[t]),u=n==="7d"||n==="30d"?s:o,d=i.reduce((m,b)=>m+(b.filament_used_grams||0),0),h=i.reduce((m,b)=>m+(b.cost||0),0),p=i.reduce((m,b)=>m+(b.quantity||1),0);return a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:"Filament Usage Trends"}),a.jsx("div",{className:"flex gap-1 bg-bambu-dark rounded-lg p-1",children:["7d","30d","90d","365d","all"].map(m=>a.jsx("button",{onClick:()=>r(m),className:`px-3 py-1 text-sm rounded-md transition-colors ${n===m?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:m==="all"?"All":m.replace("d","D")},m))})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Period Filament"}),a.jsxs("p",{className:"text-2xl font-bold text-white",children:[(d/1e3).toFixed(2),"kg"]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[d.toFixed(0),"g total"]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Period Cost"}),a.jsxs("p",{className:"text-2xl font-bold text-white",children:[e,h.toFixed(2)]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[p," prints"]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Avg per Print"}),a.jsxs("p",{className:"text-2xl font-bold text-white",children:[p>0?(d/p).toFixed(0):0,"g"]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,p>0?(h/p).toFixed(2):"0.00"," avg"]})]})]}),u.length>0?a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Usage Over Time"}),a.jsx(F1,{width:"100%",height:250,children:a.jsxs(i8e,{data:u,children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),a.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),a.jsx(lN,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(uN,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),a.jsx(dN,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:m=>`${m}g`}),a.jsx(z1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:m=>[`${Number(m??0).toFixed(0)}g`,"Filament"]}),a.jsx(bee,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):a.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:"No data for selected time range"}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"By Filament Type"}),l.length>0?a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(F1,{width:160,height:160,children:a.jsxs(n8e,{children:[a.jsx(BJ,{data:l,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:l.map((m,b)=>a.jsx(yv,{fill:x1[b%x1.length]},`cell-${b}`))}),a.jsx(z1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:m=>[`${m??0}g`,"Usage"]})]})}),a.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:l.map((m,b)=>{const y=l.reduce((v,S)=>v+S.value,0),x=y>0?(m.value/y*100).toFixed(0):0;return a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:x1[b%x1.length]}}),a.jsx("span",{className:"text-white truncate flex-1",children:m.name}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[x,"%"]})]},m.name)})})]}):a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:"No filament data"})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Monthly Comparison"}),a.jsx(F1,{width:"100%",height:200,children:a.jsxs(VBe,{data:c,children:[a.jsx(lN,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(uN,{dataKey:"month",stroke:"#9ca3af",tick:{fontSize:12}}),a.jsx(dN,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:m=>`${m}g`}),a.jsx(z1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:(m,b)=>[b==="filament"?`${m??0}g`:b==="cost"?`${e}${Number(m??0).toFixed(2)}`:m??0,b==="filament"?"Filament":b==="cost"?"Cost":"Prints"]}),a.jsx(eL,{}),a.jsx(WJ,{dataKey:"filament",name:"Filament (g)",fill:"#00ae42",radius:[4,4,0,0]})]})})]})]})]})}function SKe({id:t,title:e,component:n,isHidden:r,size:i,onToggleVisibility:s,onToggleSize:o}){const{attributes:l,listeners:c,setNodeRef:u,transform:d,transition:h,isDragging:p}=eie({id:t}),m={transform:xb.Transform.toString(d),transition:h,opacity:p?.5:1};return r?null:a.jsxs("div",{ref:u,style:{...m,gridColumn:`span ${i}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${p?"ring-2 ring-bambu-green shadow-lg":""}`,children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{...l,...c,className:"cursor-grab active:cursor-grabbing p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Drag to reorder",children:a.jsx(Vg,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),a.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:`Size: ${i===1?"1/4":i===2?"1/2":"Full"} - Click to cycle`,children:i===4?a.jsx(VR,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):a.jsx($R,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),a.jsx("button",{onClick:s,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:a.jsx(bk,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),a.jsx("div",{className:"p-4",children:typeof n=="function"?n(i):n})]})}function NKe({widgets:t,storageKey:e,columns:n=4,hideControls:r=!1,onResetLayout:i,renderControls:s}){const o=()=>{const T={};return t.forEach(M=>{T[M.id]=M.defaultSize||4}),T},[l,c]=_.useState(()=>{const T=localStorage.getItem(e);if(T)try{const M=JSON.parse(T);return M.sizes||(M.sizes=o()),M}catch{}return{order:t.map(M=>M.id),hidden:t.filter(M=>M.defaultVisible===!1).map(M=>M.id),sizes:o()}}),[u,d]=_.useState(!1);_.useEffect(()=>{const T=()=>d(M=>!M);return window.addEventListener("toggle-hidden-panel",T),()=>window.removeEventListener("toggle-hidden-panel",T)},[]),_.useEffect(()=>{localStorage.setItem(e,JSON.stringify(l))},[l,e]),_.useEffect(()=>{const M=t.map(A=>A.id).filter(A=>!l.order.includes(A));M.length>0&&c(A=>({...A,order:[...A.order,...M]}))},[t,l.order]);const h=jre(sk(QM,{activationConstraint:{distance:8}}),sk(YM,{coordinateGetter:tie})),p=T=>{const{active:M,over:A}=T;A&&M.id!==A.id&&c(k=>{const R=k.order.indexOf(M.id),C=k.order.indexOf(A.id);return{...k,order:e2(k.order,R,C)}})},m=T=>{c(M=>({...M,hidden:M.hidden.includes(T)?M.hidden.filter(A=>A!==T):[...M.hidden,T]}))},b=T=>{c(M=>{const A=M.sizes[T]||4,k=A===1?2:A===2?4:1;return{...M,sizes:{...M.sizes,[T]:k}}})},y=()=>{const T={order:t.map(M=>M.id),hidden:t.filter(M=>M.defaultVisible===!1).map(M=>M.id),sizes:o()};c(T),i?.()},x=l.order.map(T=>t.find(M=>M.id===T)).filter(Boolean),v=x.filter(T=>!l.hidden.includes(T.id)),S=x.filter(T=>l.hidden.includes(T.id)),N=s?.({hiddenCount:S.length,showHiddenPanel:u,setShowHiddenPanel:d,resetLayout:y});return a.jsxs("div",{className:"space-y-4",children:[N,!r&&!s&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:y,children:[a.jsx(Bu,{className:"w-4 h-4"}),"Reset Layout"]}),S.length>0&&a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>d(!u),children:[a.jsx(gc,{className:"w-4 h-4"}),S.length," Hidden"]})]}),u&&S.length>0&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(T=>a.jsxs("button",{onClick:()=>m(T.id),className:"px-3 py-1.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded-lg text-sm text-white transition-colors flex items-center gap-2",children:[a.jsx(gc,{className:"w-3 h-3"}),T.title]},T.id))})]}),a.jsx(Xre,{sensors:h,collisionDetection:Lre,onDragEnd:p,children:a.jsx(Zre,{items:v.map(T=>T.id),strategy:kF,children:a.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${n}, minmax(0, 1fr))`},children:v.map(T=>a.jsx(SKe,{id:T.id,title:T.title,component:T.component,isHidden:l.hidden.includes(T.id),size:l.sizes[T.id]||2,onToggleVisibility:()=>m(T.id),onToggleSize:()=>b(T.id)},T.id))})})}),v.length===0&&a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx("p",{children:"All widgets are hidden."}),a.jsx(Ne,{className:"mt-4",onClick:y,children:"Reset Layout"})]})]})}function kKe({stats:t,currency:e,t:n}){return a.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:a.jsx(bc,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.totalPrints")}),a.jsx("p",{className:"text-xl font-bold text-white",children:t?.total_prints||0})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-blue-400",children:a.jsx(tr,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.printTime")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_print_time_hours.toFixed(1)||0,"h"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-orange-400",children:a.jsx(bc,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentUsed")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[((t?.total_filament_grams||0)/1e3).toFixed(2),"kg"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-green-400",children:a.jsx(Nj,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentCost")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_cost.toFixed(2)||"0.00"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-400",children:a.jsx(Ah,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyUsed")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_energy_kwh.toFixed(2)||"0.00"," kWh"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-500",children:a.jsx(Nj,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyCost")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_energy_cost.toFixed(2)||"0.00"]})]})]})]})}function MKe({stats:t,printerMap:e,size:n=1,t:r}){const i=t?.total_prints?Math.round(t.successful_prints/t.total_prints*100):0,s=n===1?112:n===2?128:144,o=s/2-8,l=o*2*Math.PI;return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:s,height:s},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${i/100*l} ${l}`})]}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i,"%"]})})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(mr,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Zi,{className:"w-4 h-4 text-status-error flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.failed_prints||0})]})]}),n>=2&&t?.prints_by_printer&&Object.keys(t.prints_by_printer).length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),a.jsx("div",{className:`grid gap-x-6 gap-y-1 ${n===4?"grid-cols-3":"grid-cols-2"}`,style:{width:"fit-content"},children:Object.entries(t.prints_by_printer).map(([c,u])=>a.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(c)||`${r("common.printer")} ${c}`}),a.jsx("span",{className:"text-white font-medium",children:u})]},c))})]})]})]})}function EKe({stats:t,printerMap:e,size:n=1,t:r}){const i=t?.average_time_accuracy;if(i==null)return a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,i))-50)/100*100,c=(y=>y>=95&&y<=105?"#00ae42":y>105?"#3b82f6":"#f97316")(i),u=i-100,d=n===1?112:n===2?128:144,h=d/2-8,p=h*2*Math.PI,m=n===1?3:n===2?6:999,b=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,m):[];return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:d,height:d},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:d/2,cy:d/2,r:h,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:d/2,cy:d/2,r:h,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*p} ${p}`})]}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),a.jsxs("span",{className:`text-xs ${u>=0?"text-blue-400":"text-orange-400"}`,children:[u>=0?"+":"",u.toFixed(0),"%"]})]})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[a.jsx($W,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{children:r("stats.perfectEstimate")})]}),b.length>0&&a.jsx("div",{className:`mt-2 ${n===4?"grid grid-cols-3 gap-x-6 gap-y-1":n===2?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,style:{width:"fit-content"},children:b.map(([y,x])=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(y)||`${r("common.printer")} ${y}`}),a.jsxs("span",{className:`font-medium ${x>=95&&x<=105?"text-status-ok":x>105?"text-blue-400":"text-status-warning"}`,children:[x.toFixed(0),"%"]})]},y))})]})]})}function TKe({stats:t,size:e=1,t:n}){if(!t?.prints_by_filament_type||Object.keys(t.prints_by_filament_type).length===0)return a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noFilamentData")});const r=Object.entries(t.prints_by_filament_type).sort(([,l],[,c])=>c-l),i=e===1?5:e===2?8:999,s=r.slice(0,i),o=r.length>i;return e===4&&s.length>4?a.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-white truncate max-w-[120px]",children:l}),a.jsx("span",{className:"text-bambu-gray",children:c})]}),a.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:a.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)})}):a.jsxs("div",{className:"space-y-3",children:[s.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-white",children:l}),a.jsxs("span",{className:"text-bambu-gray",children:[c," ",n("common.prints")]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:a.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)}),o&&a.jsx("p",{className:"text-xs text-bambu-gray text-center pt-1",children:n("common.more",{count:r.length-i})})]})}function AKe({printDates:t,size:e=2}){const n=e===1?3:e===2?6:12;return a.jsx(vKe,{printDates:t,months:n})}function CKe({stats:t,printerMap:e,t:n}){return!t?.prints_by_printer||Object.keys(t.prints_by_printer).length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrinterData")}):a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:Object.entries(t.prints_by_printer).map(([r,i])=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("div",{className:"p-2 bg-bambu-dark-tertiary rounded-lg",children:a.jsx(jr,{className:"w-4 h-4 text-bambu-green"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium text-sm",children:e.get(r)||`${n("common.printer")} ${r}`}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[i," ",n("common.prints")]})]})]},r))})}function PKe({archives:t,currency:e,t:n}){return!t||t.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrintData")}):a.jsx(_Ke,{archives:t,currency:e})}function jKe({size:t=1,t:e}){const{data:n,isLoading:r}=it({queryKey:["failureAnalysis"],queryFn:()=>ae.getFailureAnalysis({days:30})});if(r)return a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!n||n.total_prints===0)return a.jsx("p",{className:"text-bambu-gray text-center py-4",children:e("stats.noPrintDataLast30Days")});const i=t===1?5:t===2?8:999,s=Object.entries(n.failures_by_reason).sort(([,c],[,u])=>u-c),o=s.slice(0,i),l=s.length>i;return a.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[a.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[a.jsx("div",{className:"flex items-center gap-4",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(En,{className:`w-5 h-5 ${n.failure_rate>20?"text-status-error":n.failure_rate>10?"text-status-warning":"text-status-ok"}`}),a.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[n.failure_rate.toFixed(1),"%"]})]})}),a.jsx("div",{className:"text-sm text-bambu-gray mt-1",children:e("stats.failedPrintsCount",{failed:n.failed_prints,total:n.total_prints})}),n.trend&&n.trend.length>=2&&a.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(GW,{className:`w-4 h-4 ${n.trend[n.trend.length-1].failure_rate0&&a.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?e("stats.failureReasons"):e("stats.topFailureReasons")}),a.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:o.map(([c,u])=>a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:c||e("common.unknown")}),a.jsx("span",{className:"text-bambu-gray ml-2",children:u})]},c))}),l&&a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:e("common.more",{count:s.length-i})})]})]})}function DKe(){const{t}=Yt(),{showToast:e}=Tn(),{hasPermission:n}=Ir(),[r,i]=_.useState(!1),[s,o]=_.useState(!1),[l,c]=_.useState(0),[u,d]=_.useState(0),[h,p]=_.useState(!1);_.useEffect(()=>{const C=()=>{try{const U=localStorage.getItem("bambusy-dashboard-layout");if(U){const F=JSON.parse(U);d(F.hidden?.length||0)}}catch{d(0)}};C(),window.addEventListener("storage",C);const P=setInterval(C,500);return()=>{window.removeEventListener("storage",C),clearInterval(P)}},[l]);const{data:m,isLoading:b,refetch:y}=it({queryKey:["archiveStats"],queryFn:ae.getArchiveStats}),{data:x}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:v}=it({queryKey:["archives"],queryFn:()=>ae.getArchives(void 0,void 0,1e3,0)}),{data:S}=it({queryKey:["settings"],queryFn:ae.getSettings}),N=async C=>{o(!1),i(!0);try{const{blob:P,filename:U}=await ae.exportStats({format:C,days:90}),F=URL.createObjectURL(P),H=document.createElement("a");H.href=F,H.download=U,H.click(),URL.revokeObjectURL(F),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{i(!1)}},T=async()=>{p(!0);try{const C=await ae.recalculateCosts();await y(),e(t("stats.recalculatedCosts",{count:C.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{p(!1)}},M=S?.currency||"$",A=new Map(x?.map(C=>[String(C.id),C.name])||[]),k=v?.map(C=>C.created_at)||[];if(b)return a.jsx("div",{className:"p-4 md:p-8",children:a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const R=[{id:"quick-stats",title:t("stats.quickStats"),component:a.jsx(kKe,{stats:m,currency:M,t}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:C=>a.jsx(MKe,{stats:m,printerMap:A,size:C,t}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:C=>a.jsx(EKe,{stats:m,printerMap:A,size:C,t}),defaultSize:1},{id:"filament-types",title:t("stats.filamentTypes"),component:C=>a.jsx(TKe,{stats:m,size:C,t}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:C=>a.jsx(jKe,{size:C,t}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:C=>a.jsx(AKe,{printDates:k,size:C}),defaultSize:2},{id:"prints-by-printer",title:t("stats.printsByPrinter"),component:a.jsx(CKe,{stats:m,printerMap:A,t}),defaultSize:2},{id:"filament-trends",title:t("stats.filamentTrends"),component:a.jsx(PKe,{archives:v||[],currency:M,t}),defaultSize:4}];return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("stats.title")}),a.jsx("p",{className:"text-bambu-gray",children:t("stats.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&a.jsxs(Ne,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[a.jsx(gc,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),a.jsxs(Ne,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout"),c(C=>C+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[a.jsx(Bu,{className:"w-4 h-4"}),t("stats.resetLayout")]}),a.jsxs(Ne,{variant:"secondary",onClick:T,disabled:h||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[h?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Zce,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),a.jsxs("div",{className:"relative",children:[a.jsxs(Ne,{variant:"secondary",onClick:()=>o(!s),disabled:r,children:[r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(eS,{className:"w-4 h-4"}),t("stats.exportStats")]}),s&&a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20",children:[a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg",onClick:()=>N("csv"),children:[a.jsx(ys,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg",onClick:()=>N("xlsx"),children:[a.jsx(eS,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]})]})]}),a.jsx(NKe,{widgets:R,storageKey:"bambusy-dashboard-layout",hideControls:!0},l)]})}function RKe({plug:t,onEdit:e}){const{t:n}=Yt(),r=an(),{showToast:i}=Tn(),[s,o]=_.useState(!1),[l,c]=_.useState(!1),[u,d]=_.useState(!1),[h,p]=_.useState(!1),{data:m,isLoading:b}=it({queryKey:["smart-plug-status",t.id],queryFn:()=>ae.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:y}=it({queryKey:["printers"],queryFn:ae.getPrinters}),x=y?.find(P=>P.id===t.printer_id),v=dt({mutationFn:P=>ae.controlSmartPlug(t.id,P),onMutate:async P=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const U=r.getQueryData(["smart-plug-status",t.id]),F=P==="on"?"ON":P==="off"||m?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],H=>({...H,state:F})),{previousStatus:U}},onError:(P,U,F)=>{F?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],F.previousStatus),i(`Failed to turn ${U} "${t.name}"`,"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),S=dt({mutationFn:P=>ae.updateSmartPlug(t.id,P),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),N=dt({mutationFn:()=>ae.deleteSmartPlug(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),T=m?.state==="ON",M=t.plug_type==="mqtt"&&m?.energy?.power!==null&&m?.energy?.power!==void 0,A=(m?.reachable??!1)||M,k=v.isPending,C=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const P=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${P}/`:`http://${P}/`})();return a.jsxs(a.Fragment,{children:[a.jsx(St,{className:"relative",children:a.jsxs(Et,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?A?"bg-teal-500/20":"bg-red-500/20":A?T?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?a.jsx(GR,{className:`w-5 h-5 ${A?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?a.jsx(Hy,{className:`w-5 h-5 ${A?T?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):a.jsx(sl,{className:`w-5 h-5 ${A?T?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",title:t.plug_type==="mqtt"?t.mqtt_topic??void 0:t.plug_type==="homeassistant"?t.ha_entity_id??void 0:t.ip_address??void 0,children:t.plug_type==="mqtt"?t.mqtt_topic:t.plug_type==="homeassistant"?t.ha_entity_id:t.ip_address})]})]}),a.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[b?a.jsx(ct,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?a.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[a.jsx("span",{className:"px-1.5 py-0.5 bg-teal-500/20 text-teal-400 text-[10px] font-medium rounded flex-shrink-0",children:"MQTT"}),A&&a.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),a.jsx("span",{className:A?T?"text-status-ok":"text-bambu-gray":"text-status-error",children:A?m?.state||"?":"Offline"})]}):A?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx(Eg,{className:"w-4 h-4 text-status-ok"}),a.jsx("span",{className:T?"text-status-ok":"text-bambu-gray",children:m?.state||"Unknown"})]}):a.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[a.jsx(fm,{className:"w-4 h-4"}),a.jsx("span",{children:n("smartPlugs.offline")})]}),C&&a.jsxs("a",{href:C,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 px-2 py-0.5 bg-bambu-dark hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white text-xs rounded-full transition-colors",title:n("smartPlugs.openPlugAdminPage"),children:[a.jsx(Xr,{className:"w-3 h-3"}),n("smartPlugs.admin")]})]})]}),x&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Linked to: "}),a.jsx("span",{className:"text-sm text-white",children:x.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded-full",children:[a.jsx(gc,{className:"w-3 h-3"}),"Monitor Only"]}),t.power_alert_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded-full",children:[a.jsx(kg,{className:"w-3 h-3"}),"Alerts"]}),t.schedule_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded-full",children:[a.jsx(ti,{className:"w-3 h-3"}),t.schedule_on_time&&t.schedule_off_time?`${t.schedule_on_time} - ${t.schedule_off_time}`:t.schedule_on_time?`On ${t.schedule_on_time}`:`Off ${t.schedule_off_time}`]})]}),t.plug_type!=="mqtt"&&a.jsxs("div",{className:"flex gap-2 mb-3",children:[a.jsxs(Ne,{size:"sm",variant:T?"primary":"secondary",disabled:!A||k,onClick:()=>c(!0),className:"flex-1",children:[k?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Ju,{className:"w-4 h-4"}),"On"]}),a.jsxs(Ne,{size:"sm",variant:T?"secondary":"primary",disabled:!A||k,onClick:()=>d(!0),className:"flex-1",children:[k?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Nk,{className:"w-4 h-4"}),"Off"]})]}),t.plug_type==="mqtt"&&m?.energy&&a.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[m.energy.power!==null&&m.energy.power!==void 0&&a.jsxs("div",{className:"flex-1 text-center",children:[a.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(m.energy.power),"W"]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Power"})]}),m.energy.today!==null&&m.energy.today!==void 0&&a.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-lg font-semibold text-white",children:m.energy.today.toFixed(2)}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"kWh Today"})]})]}),a.jsxs("button",{onClick:()=>p(!h),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Hu,{className:"w-4 h-4"}),t.plug_type==="mqtt"?"Settings":"Automation Settings"]}),a.jsx("span",{children:h?"-":"+"})]}),h&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(wk,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Show in Switchbar"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:P=>S.mutate({show_in_switchbar:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.plug_type!=="mqtt"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Enabled"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Enable automation for this plug"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.enabled,onChange:P=>S.mutate({enabled:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Auto On"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn on when print starts"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:P=>S.mutate({auto_on:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Auto Off"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn off when print completes (one-shot)"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:P=>S.mutate({auto_off:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.auto_off&&a.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white mb-2",children:"Turn Off Delay Mode"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:()=>S.mutate({off_delay_mode:"time"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="time"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(tr,{className:"w-4 h-4"}),"Time"]}),a.jsxs("button",{onClick:()=>S.mutate({off_delay_mode:"temperature"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="temperature"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(Ek,{className:"w-4 h-4"}),"Temp"]})]})]}),t.off_delay_mode==="time"?a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Delay (minutes)"}),a.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:P=>S.mutate({off_delay_minutes:parseInt(P.target.value)||5}),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"})]}):a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Temperature threshold (C)"}),a.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:P=>S.mutate({off_temp_threshold:parseInt(P.target.value)||70}),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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Turns off when nozzle cools below this temperature"})]})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Ne,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(bg,{className:"w-4 h-4"}),"Edit"]}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(ln,{className:"w-4 h-4"})})]})]})]})}),s&&a.jsx(er,{title:n("smartPlugs.deleteSmartPlug"),message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{N.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&a.jsx(er,{title:n("smartPlugs.turnOnSmartPlug"),message:`Are you sure you want to turn on "${t.name}"?`,confirmText:n("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{v.mutate("on"),c(!1)},onCancel:()=>c(!1)}),u&&a.jsx(er,{title:n("smartPlugs.turnOffSmartPlug"),message:`Are you sure you want to turn off "${t.name}"? This will cut power to the connected device.`,confirmText:n("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{v.mutate("off"),d(!1)},onCancel:()=>d(!1)})]})}function OKe({plug:t,onClose:e}){const{t:n}=Yt(),r=an(),i=!!t,[s,o]=_.useState(t?.plug_type||"tasmota"),[l,c]=_.useState(t?.name||""),[u,d]=_.useState(t?.ip_address||""),[h,p]=_.useState(t?.username||""),[m,b]=_.useState(t?.password||""),[y,x]=_.useState(t?.ha_entity_id||""),[v,S]=_.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[N,T]=_.useState(t?.mqtt_power_path||""),[M,A]=_.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[k,R]=_.useState(t?.mqtt_energy_topic||""),[C,P]=_.useState(t?.mqtt_energy_path||""),[U,F]=_.useState((t?.mqtt_energy_multiplier??1).toString()),[H,D]=_.useState(t?.mqtt_state_topic||""),[$,G]=_.useState(t?.mqtt_state_path||""),[I,K]=_.useState(t?.mqtt_state_on_value||""),[Q,oe]=_.useState(t?.ha_power_entity||""),[B,W]=_.useState(t?.ha_energy_today_entity||""),[J,ne]=_.useState(t?.ha_energy_total_entity||""),[me,fe]=_.useState(""),[de,Re]=_.useState(""),[se,ke]=_.useState(!1),Fe=_.useRef(null),[ce,Ve]=_.useState(""),[V,Y]=_.useState(!1),ue=_.useRef(null),[q,re]=_.useState(""),[X,le]=_.useState(!1),pe=_.useRef(null),[ee,z]=_.useState(""),[O,Z]=_.useState(!1),ge=_.useRef(null),[Ce,_e]=_.useState(t?.printer_id||null),[Te,we]=_.useState(null),[$e,Ge]=_.useState(null),[ze,be]=_.useState(t?.power_alert_enabled||!1),[Me,Be]=_.useState(t?.power_alert_high?.toString()||""),[Ae,qe]=_.useState(t?.power_alert_low?.toString()||""),[ve,et]=_.useState(t?.schedule_enabled||!1),[Ee,Ye]=_.useState(t?.schedule_on_time||""),[je,Pe]=_.useState(t?.schedule_off_time||""),[ye,Qe]=_.useState(t?.show_in_switchbar||!1),[yt,at]=_.useState(t?.show_on_printer_card??!0),[Ut,zt]=_.useState(!1),[Ie,vt]=_.useState({scanned:0,total:0}),[Gt,dn]=_.useState([]),fn=_.useRef(null),{data:vn}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:dr}=it({queryKey:["smart-plugs"],queryFn:ae.getSmartPlugs}),{data:ar}=it({queryKey:["settings"],queryFn:ae.getSettings}),kn=!!(ar?.ha_enabled&&ar?.ha_url&&ar?.ha_token);_.useEffect(()=>{const Se=setTimeout(()=>{Re(me)},300);return()=>clearTimeout(Se)},[me]),_.useEffect(()=>{const Se=nt=>{Fe.current&&!Fe.current.contains(nt.target)&&ke(!1),ue.current&&!ue.current.contains(nt.target)&&Y(!1),pe.current&&!pe.current.contains(nt.target)&&le(!1),ge.current&&!ge.current.contains(nt.target)&&Z(!1)};return document.addEventListener("mousedown",Se),()=>document.removeEventListener("mousedown",Se)},[]);const{data:Bn,isLoading:Hr,error:Ma}=it({queryKey:["ha-entities",de],queryFn:()=>ae.getHAEntities(de||void 0),enabled:s==="homeassistant"&&kn,retry:!1,staleTime:0}),{data:De}=it({queryKey:["ha-sensor-entities"],queryFn:ae.getHASensorEntities,enabled:s==="homeassistant"&&kn,retry:!1,staleTime:0});_.useEffect(()=>{const Se=nt=>{nt.key==="Escape"&&e()};return window.addEventListener("keydown",Se),()=>{window.removeEventListener("keydown",Se),fn.current&&clearInterval(fn.current)}},[e]);const tt=async()=>{zt(!0),dn([]),vt({scanned:0,total:0}),Ge(null);try{await ae.startTasmotaScan();const Se=async()=>{try{const nt=await ae.getTasmotaScanStatus();vt({scanned:nt.scanned,total:nt.total});const xt=await ae.getDiscoveredTasmotaDevices();dn(xt),nt.running||(zt(!1),fn.current&&(clearInterval(fn.current),fn.current=null))}catch(nt){console.error("Polling error:",nt)}};await Se(),fn.current=setInterval(Se,500)}catch(Se){zt(!1);const nt=Se instanceof Error?Se.message:typeof Se=="string"?Se:JSON.stringify(Se);Ge(nt||"Failed to start scan")}},ht=async()=>{try{await ae.stopTasmotaScan()}catch{}zt(!1),fn.current&&(clearInterval(fn.current),fn.current=null)},mt=Se=>{d(Se.ip_address),c(Se.name),we(null)},ut=dt({mutationFn:()=>ae.testSmartPlugConnection(u,h||null,m||null),onSuccess:Se=>{we(Se),Ge(null),!l&&Se.device_name&&c(Se.device_name)},onError:Se=>{we(null),Ge(Se.message)}}),Dt=dt({mutationFn:Se=>ae.createSmartPlug(Se),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:Se=>{Ge(Se.message)}}),he=dt({mutationFn:Se=>ae.updateSmartPlug(t.id,Se),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:Se=>{Ge(Se.message)}}),Le=vn?.filter(Se=>s==="tasmota"?!dr?.some(xt=>xt.printer_id===Se.id&&xt.id!==t?.id&&xt.plug_type==="tasmota"):!0),Ke=Se=>{if(Se.preventDefault(),Ge(null),!l.trim()){Ge("Name is required");return}if(s==="tasmota"&&!u.trim()){Ge("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!y){Ge("Entity is required for Home Assistant plugs");return}if(s==="mqtt"){const xt=v.trim(),rt=k.trim(),Ct=H.trim();if(!xt&&!rt&&!Ct){Ge("At least one MQTT topic must be configured for power, energy, or state monitoring");return}}const nt={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?u.trim():null,ha_entity_id:s==="homeassistant"?y:null,ha_power_entity:s==="homeassistant"&&Q||null,ha_energy_today_entity:s==="homeassistant"&&B||null,ha_energy_total_entity:s==="homeassistant"&&J||null,mqtt_power_topic:s==="mqtt"&&v.trim()||null,mqtt_power_path:s==="mqtt"&&N.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(M)||1,mqtt_energy_topic:s==="mqtt"&&k.trim()||null,mqtt_energy_path:s==="mqtt"&&C.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat(U)||1,mqtt_state_topic:s==="mqtt"&&H.trim()||null,mqtt_state_path:s==="mqtt"&&$.trim()||null,mqtt_state_on_value:s==="mqtt"&&I.trim()||null,username:s==="tasmota"&&h.trim()||null,password:s==="tasmota"&&m.trim()||null,printer_id:Ce,power_alert_enabled:ze,power_alert_high:Me?parseFloat(Me):null,power_alert_low:Ae?parseFloat(Ae):null,schedule_enabled:ve,schedule_on_time:Ee||null,schedule_off_time:je||null,show_in_switchbar:ye,show_on_printer_card:yt};i?he.mutate(nt):Dt.mutate(nt)},Ue=Dt.isPending||he.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:Se=>Se.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:i?"Edit Smart Plug":"Add Smart Plug"}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Ke,className:"p-6 space-y-4 overflow-y-auto",children:[$e&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:$e}),!i&&a.jsxs("div",{className:"flex gap-2 mb-2",children:[a.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),we(null),Ge(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="tasmota"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(sl,{className:"w-4 h-4"}),"Tasmota"]}),a.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),we(null),Ge(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="homeassistant"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(Hy,{className:"w-4 h-4"}),"HA"]}),a.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),we(null),Ge(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="mqtt"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(GR,{className:"w-4 h-4"}),"MQTT"]})]}),!i&&s==="tasmota"&&a.jsxs("div",{className:"space-y-3",children:[Ut?a.jsxs(Ne,{type:"button",variant:"secondary",onClick:ht,className:"w-full",children:[a.jsx(Lt,{className:"w-4 h-4"}),"Stop Scanning"]}):a.jsxs(Ne,{type:"button",variant:"primary",onClick:tt,className:"w-full",children:[a.jsx(Qi,{className:"w-4 h-4"}),"Discover Tasmota Devices"]}),Ut&&Ie.total>0&&a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:n("smartPlugs.addSmartPlug.scanningNetwork")}),a.jsxs("span",{children:[Ie.scanned," / ",Ie.total]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Ie.scanned/Ie.total*100}%`}})})]}),Gt.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Found ",Gt.length," device(s) - click to select:"]}),a.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:Gt.map(Se=>a.jsxs("button",{type:"button",onClick:()=>mt(Se),className:"w-full flex items-center justify-between p-2 bg-bambu-dark hover:bg-bambu-dark-tertiary rounded-lg transition-colors text-left border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(sl,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:Se.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:Se.ip_address})]})]}),Se.state&&a.jsxs("span",{className:`flex items-center gap-1 text-xs ${Se.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[a.jsx(Ju,{className:"w-3 h-3"}),Se.state]})]},Se.ip_address))})]}),!Ut&&Gt.length===0&&Ie.total>0&&a.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:"No Tasmota devices found on your network"})]}),s==="homeassistant"&&a.jsxs("div",{className:"space-y-3",children:[!kn&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:["Home Assistant is not configured. Set it up in"," ",a.jsx("span",{className:"font-medium",children:"Settings → Network → Home Assistant"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:"Select Entity *"}),a.jsx("select",{disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed opacity-50",children:a.jsx("option",{children:n("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),kn&&a.jsxs(a.Fragment,{children:[Hr&&a.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[a.jsx(ct,{className:"w-5 h-5 animate-spin mr-2"}),"Loading entities..."]}),Ma&&a.jsxs("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:["Failed to load entities: ",Ma.message]}),(()=>{const Se=dr?.filter(rt=>rt.ha_entity_id&&rt.id!==t?.id).map(rt=>rt.ha_entity_id)||[],nt=(Bn||[]).filter(rt=>!Se.includes(rt.entity_id)),xt=Bn?.find(rt=>rt.entity_id===y);return a.jsxs("div",{ref:Fe,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Select Entity *"}),a.jsxs("div",{className:"relative",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:se?me:xt?`${xt.friendly_name} (${xt.entity_id})`:"",onChange:rt=>{fe(rt.target.value),se||ke(!0)},onFocus:()=>{ke(!0),fe("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEntities"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),y&&!se&&a.jsx("button",{type:"button",onClick:()=>{x(""),fe("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Lt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),Hr&&a.jsx(ct,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),se&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[Hr&&a.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Loading..."]}),!Hr&&nt.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:de?`No entities found matching "${de}"`:"No entities available"}),!Hr&&nt.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{x(rt.entity_id),ke(!1),fe(""),l||c(rt.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${rt.entity_id===y?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[a.jsx("span",{children:rt.entity_id}),a.jsx("span",{className:rt.state==="on"?"text-bambu-green":"",children:rt.state})]})]},rt.entity_id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:de?`Searching all entities (${nt.length} found)`:`Showing switch, light, input_boolean (${nt.length} available)`})]})})(),y&&De&&De.length>0&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium mb-1",children:"Energy Monitoring (Optional)"}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Search and select sensors that provide power/energy data."})]}),(()=>{const Se=De.filter(rt=>rt.unit_of_measurement==="W"||rt.unit_of_measurement==="kW"||rt.unit_of_measurement==="mW"),nt=ce?Se.filter(rt=>rt.entity_id.toLowerCase().includes(ce.toLowerCase())||rt.friendly_name.toLowerCase().includes(ce.toLowerCase())):Se,xt=De.find(rt=>rt.entity_id===Q);return a.jsxs("div",{ref:ue,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Power Sensor (W)"}),a.jsxs("div",{className:"relative",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:V?ce:xt?`${xt.friendly_name} (${xt.state} ${xt.unit_of_measurement})`:"",onChange:rt=>{Ve(rt.target.value),V||Y(!0)},onFocus:()=>{Y(!0),Ve("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchPowerSensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),Q&&!V&&a.jsx("button",{type:"button",onClick:()=>{oe(""),Ve("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Lt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),V&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{oe(""),Y(!1),Ve("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),nt.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{oe(rt.entity_id),Y(!1),Ve("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${rt.entity_id===Q?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[rt.entity_id," • ",rt.state," ",rt.unit_of_measurement]})]},rt.entity_id)),nt.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const Se=De.filter(rt=>rt.unit_of_measurement==="kWh"||rt.unit_of_measurement==="Wh"||rt.unit_of_measurement==="MWh"),nt=q?Se.filter(rt=>rt.entity_id.toLowerCase().includes(q.toLowerCase())||rt.friendly_name.toLowerCase().includes(q.toLowerCase())):Se,xt=De.find(rt=>rt.entity_id===B);return a.jsxs("div",{ref:pe,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy Today (kWh)"}),a.jsxs("div",{className:"relative",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:X?q:xt?`${xt.friendly_name} (${xt.state} ${xt.unit_of_measurement})`:"",onChange:rt=>{re(rt.target.value),X||le(!0)},onFocus:()=>{le(!0),re("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),B&&!X&&a.jsx("button",{type:"button",onClick:()=>{W(""),re("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Lt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),X&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{W(""),le(!1),re("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),nt.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{W(rt.entity_id),le(!1),re("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${rt.entity_id===B?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[rt.entity_id," • ",rt.state," ",rt.unit_of_measurement]})]},rt.entity_id)),nt.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const Se=De.filter(rt=>rt.unit_of_measurement==="kWh"||rt.unit_of_measurement==="Wh"||rt.unit_of_measurement==="MWh"),nt=ee?Se.filter(rt=>rt.entity_id.toLowerCase().includes(ee.toLowerCase())||rt.friendly_name.toLowerCase().includes(ee.toLowerCase())):Se,xt=De.find(rt=>rt.entity_id===J);return a.jsxs("div",{ref:ge,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Total Energy (kWh)"}),a.jsxs("div",{className:"relative",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:O?ee:xt?`${xt.friendly_name} (${xt.state} ${xt.unit_of_measurement})`:"",onChange:rt=>{z(rt.target.value),O||Z(!0)},onFocus:()=>{Z(!0),z("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),J&&!O&&a.jsx("button",{type:"button",onClick:()=>{ne(""),z("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Lt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),O&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{ne(""),Z(!1),z("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),nt.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{ne(rt.entity_id),Z(!1),z("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${rt.entity_id===J?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[rt.entity_id," • ",rt.state," ",rt.unit_of_measurement]})]},rt.entity_id)),nt.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})()]})]})]}),s==="mqtt"&&a.jsxs("div",{className:"space-y-3",children:[!ar?.mqtt_broker&&a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:["MQTT broker not configured. Set broker address in"," ",a.jsx("span",{className:"font-medium",children:"Settings → Network → MQTT Publishing"})," ","(you don't need to enable publishing, just fill in the broker details)."]}),ar?.mqtt_broker&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:"Monitor Only"}),a.jsx("p",{className:"text-xs opacity-80",children:"MQTT plugs receive power/energy data via MQTT subscription. On/off control is not available - use your MQTT broker or home automation system."})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-white font-medium text-sm",children:"Power Monitoring"}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),a.jsx("input",{type:"text",value:v,onChange:Se=>S(Se.target.value),placeholder:"zigbee2mqtt/shelly-working-room",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),a.jsx("input",{type:"text",value:N,onChange:Se=>T(Se.target.value),placeholder:"power_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),a.jsx("input",{type:"text",value:M,onChange:Se=>A(Se.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:['JSON path extracts value from JSON payload (e.g., "power_l1"). Leave empty if topic publishes raw numeric values.',a.jsx("br",{}),"Use multiplier 0.001 for mW→W, 1000 for kW→W."]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:["Energy Monitoring ",a.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),a.jsx("input",{type:"text",value:k,onChange:Se=>R(Se.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),a.jsx("input",{type:"text",value:C,onChange:Se=>P(Se.target.value),placeholder:"energy_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),a.jsx("input",{type:"text",value:U,onChange:Se=>F(Se.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",a.jsx("br",{}),"Use multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh."]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:["State Monitoring ",a.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),a.jsx("input",{type:"text",value:H,onChange:Se=>D(Se.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),a.jsx("input",{type:"text",value:$,onChange:Se=>G(Se.target.value),placeholder:"state_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"ON Value"}),a.jsx("input",{type:"text",value:I,onChange:Se=>K(Se.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.mqttStateOnValue"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",a.jsx("br",{}),'ON value: the exact string that means "ON". Leave empty for auto-detect (ON, true, 1).']})]})]})]}),s==="tasmota"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"IP Address *"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:u,onChange:Se=>{d(Se.target.value),we(null)},placeholder:"192.168.1.100",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsxs(Ne,{type:"button",variant:"secondary",onClick:()=>ut.mutate(),disabled:!u.trim()||ut.isPending,children:[ut.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Eg,{className:"w-4 h-4"}),"Test"]})]})]}),s==="tasmota"&&Te&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${Te.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:Te.success?a.jsxs(a.Fragment,{children:[a.jsx(mr,{className:"w-5 h-5"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium",children:"Connected!"}),a.jsxs("p",{className:"text-sm opacity-80",children:[Te.device_name&&`Device: ${Te.device_name} - `,"State: ",Te.state]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx(fm,{className:"w-5 h-5"}),a.jsx("span",{children:n("smartPlugs.addSmartPlug.connectionFailed")})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:l,onChange:Se=>c(Se.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.plugName"),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"})]}),s==="tasmota"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username"}),a.jsx("input",{type:"text",value:h,onChange:Se=>p(Se.target.value),placeholder:"admin",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password"}),a.jsx("input",{type:"password",value:m,onChange:Se=>b(Se.target.value),placeholder:"********",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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:"Leave empty if your Tasmota device doesn't require authentication"})]}),s!=="mqtt"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Link to Printer"}),a.jsxs("select",{value:Ce??"",onChange:Se=>_e(Se.target.value?Number(Se.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:"No printer (manual control only)"}),Le?.map(Se=>a.jsx("option",{value:Se.id,children:Se.name},Se.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Linking enables automatic on/off when prints start/complete"})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(kg,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:"Power Alerts"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ze,onChange:Se=>be(Se.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),ze&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if above (W)"}),a.jsx("input",{type:"number",value:Me,onChange:Se=>Be(Se.target.value),placeholder:"e.g. 200",min:"0",max:"5000",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if below (W)"}),a.jsx("input",{type:"number",value:Ae,onChange:Se=>qe(Se.target.value),placeholder:"e.g. 10",min:"0",max:"5000",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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Get notified when power consumption crosses these thresholds. Leave empty to disable that direction."})]})]}),s!=="mqtt"&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tr,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:"Daily Schedule"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ve,onChange:Se=>et(Se.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),ve&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn On at"}),a.jsx("input",{type:"time",value:Ee,onChange:Se=>Ye(Se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn Off at"}),a.jsx("input",{type:"time",value:je,onChange:Se=>Pe(Se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Automatically turn the plug on/off at these times daily. Leave empty to skip that action."})]})]}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(wk,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:"Show in Switchbar"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ye,onChange:Se=>Qe(Se.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),s==="homeassistant"&&a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(gc,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:"Show on Printer Card"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Display button on printer card"})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:yt,onChange:Se=>at(Se.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Ne,{type:"submit",disabled:Ue,className:"flex-1",children:[Ue?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function $n({checked:t,onChange:e,disabled:n}){const r=i=>{i.preventDefault(),i.stopPropagation(),n||e(!t)};return a.jsx("button",{type:"button",role:"switch","aria-checked":t,disabled:n,onClick:r,className:`relative inline-flex w-11 h-7 md:w-9 md:h-5 rounded-full transition-colors flex-shrink-0 focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${n?"bg-bambu-dark-tertiary/50 cursor-not-allowed opacity-50":t?"bg-bambu-green cursor-pointer":"bg-bambu-dark-tertiary cursor-pointer hover:bg-bambu-dark-tertiary/80"}`,children:a.jsx("span",{className:`pointer-events-none absolute top-[3px] md:top-[2px] left-[3px] md:left-[2px] w-5 h-5 md:w-4 md:h-4 bg-white rounded-full shadow transition-transform duration-200 ease-in-out ${t?"translate-x-4":"translate-x-0"}`})})}const LKe={callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook"};function FKe({provider:t,onEdit:e}){const n=an(),[r,i]=_.useState(!1),[s,o]=_.useState(!1),[l,c]=_.useState(null),{data:u}=it({queryKey:["printers"],queryFn:ae.getPrinters}),d=u?.find(y=>y.id===t.printer_id),h=dt({mutationFn:y=>ae.updateNotificationProvider(t.id,y),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),p=dt({mutationFn:()=>ae.deleteNotificationProvider(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),m=dt({mutationFn:()=>ae.testNotificationProvider(t.id),onSuccess:y=>{c(y),n.invalidateQueries({queryKey:["notification-providers"]})},onError:y=>{c({success:!1,message:y.message})}}),b=y=>y||"";return a.jsxs(a.Fragment,{children:[a.jsx(St,{className:"relative",children:a.jsxs(Et,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:a.jsx(kg,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("h3",{className:"font-medium text-white",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray",children:LKe[t.provider_type]||t.provider_type})]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&a.jsxs("span",{className:"text-xs text-status-ok hidden sm:inline",children:["Last: ",Gg(t.last_success)]}),t.last_error&&t.last_error_at&&(!t.last_success||(zi(t.last_error_at)?.getTime()||0)>(zi(t.last_success)?.getTime()||0))&&a.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:"Error"}),a.jsx($n,{checked:t.enabled,onChange:y=>h.mutate({enabled:y})})]})]}),d&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Printer: "}),a.jsx("span",{className:"text-sm text-white",children:d.name})]}),!d&&!t.printer_id&&a.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"All printers"})}),a.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded",children:"Start"}),t.on_plate_not_empty&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-600/20 text-rose-300 text-xs rounded",children:"Plate Check"}),t.on_print_complete&&a.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:"Complete"}),t.on_print_failed&&a.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:"Failed"}),t.on_print_stopped&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:"Stopped"}),t.on_print_progress&&a.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:"Progress"}),t.on_printer_offline&&a.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:"Offline"}),t.on_printer_error&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:"Error"}),t.on_filament_low&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-500/20 text-cyan-400 text-xs rounded",children:"Low Filament"}),t.on_maintenance_due&&a.jsx("span",{className:"px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded",children:"Maintenance"}),t.on_ams_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-600/20 text-blue-300 text-xs rounded",children:"AMS Humidity"}),t.on_ams_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-600/20 text-orange-300 text-xs rounded",children:"AMS Temp"}),t.on_ams_ht_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-600/20 text-cyan-300 text-xs rounded",children:"AMS-HT Humidity"}),t.on_ams_ht_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-amber-600/20 text-amber-300 text-xs rounded",children:"AMS-HT Temp"}),t.quiet_hours_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[a.jsx(tS,{className:"w-3 h-3"}),"Quiet"]}),t.daily_digest_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[a.jsx(ti,{className:"w-3 h-3"}),"Digest ",t.daily_digest_time]})]}),a.jsx("div",{className:"mb-3",children:a.jsxs(Ne,{size:"sm",variant:"secondary",disabled:m.isPending,onClick:()=>{c(null),m.mutate()},className:"w-full",children:[m.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(kk,{className:"w-4 h-4"}),"Send Test Notification"]})}),l&&a.jsxs("div",{className:`mb-3 p-2 rounded-lg flex items-center gap-2 text-sm ${l.success?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[l.success?a.jsx(mr,{className:"w-4 h-4"}):a.jsx(Zi,{className:"w-4 h-4"}),a.jsx("span",{children:l.message})]}),a.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors border-t border-bambu-dark-tertiary",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Hu,{className:"w-4 h-4"}),"Event Settings"]}),s?a.jsx(zu,{className:"w-4 h-4"}):a.jsx(fr,{className:"w-4 h-4"})]}),s&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Enabled"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Send notifications from this provider"})]}),a.jsx($n,{checked:t.enabled,onChange:y=>h.mutate({enabled:y})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Events"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Started"}),a.jsx($n,{checked:t.on_print_start,onChange:y=>h.mutate({on_print_start:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Plate Not Empty"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Objects detected before print"})]}),a.jsx($n,{checked:t.on_plate_not_empty??!0,onChange:y=>h.mutate({on_plate_not_empty:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Completed"}),a.jsx($n,{checked:t.on_print_complete,onChange:y=>h.mutate({on_print_complete:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Failed"}),a.jsx($n,{checked:t.on_print_failed,onChange:y=>h.mutate({on_print_failed:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Stopped"}),a.jsx($n,{checked:t.on_print_stopped,onChange:y=>h.mutate({on_print_stopped:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Progress Milestones"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify at 25%, 50%, 75%"})]}),a.jsx($n,{checked:t.on_print_progress,onChange:y=>h.mutate({on_print_progress:y})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Printer Status"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Printer Offline"}),a.jsx($n,{checked:t.on_printer_offline,onChange:y=>h.mutate({on_printer_offline:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Printer Error"}),a.jsx($n,{checked:t.on_printer_error,onChange:y=>h.mutate({on_printer_error:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Low Filament"}),a.jsx($n,{checked:t.on_filament_low,onChange:y=>h.mutate({on_filament_low:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Maintenance Due"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify when maintenance is needed"})]}),a.jsx($n,{checked:t.on_maintenance_due??!1,onChange:y=>h.mutate({on_maintenance_due:y})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS Alarms"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS Humidity High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS humidity exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_humidity_high??!1,onChange:y=>h.mutate({on_ams_humidity_high:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS Temperature High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS temperature exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_temperature_high??!1,onChange:y=>h.mutate({on_ams_temperature_high:y})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS-HT Alarms"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS-HT Humidity High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT humidity exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_ht_humidity_high??!1,onChange:y=>h.mutate({on_ams_ht_humidity_high:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS-HT Temperature High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT temperature exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_ht_temperature_high??!1,onChange:y=>h.mutate({on_ams_ht_temperature_high:y})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Queue"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Added"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job added to queue"})]}),a.jsx($n,{checked:t.on_queue_job_added??!1,onChange:y=>h.mutate({on_queue_job_added:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Assigned"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Model-based job assigned to printer"})]}),a.jsx($n,{checked:t.on_queue_job_assigned??!1,onChange:y=>h.mutate({on_queue_job_assigned:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Started"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Queue job started printing"})]}),a.jsx($n,{checked:t.on_queue_job_started??!1,onChange:y=>h.mutate({on_queue_job_started:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Waiting"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job waiting for filament"})]}),a.jsx($n,{checked:t.on_queue_job_waiting??!0,onChange:y=>h.mutate({on_queue_job_waiting:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Skipped"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job skipped (previous failed)"})]}),a.jsx($n,{checked:t.on_queue_job_skipped??!0,onChange:y=>h.mutate({on_queue_job_skipped:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Failed"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job failed to start"})]}),a.jsx($n,{checked:t.on_queue_job_failed??!0,onChange:y=>h.mutate({on_queue_job_failed:y})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Queue Complete"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"All queue jobs finished"})]}),a.jsx($n,{checked:t.on_queue_completed??!1,onChange:y=>h.mutate({on_queue_completed:y})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tS,{className:"w-4 h-4 text-purple-400"}),a.jsx("p",{className:"text-sm text-white",children:"Quiet Hours"})]}),a.jsx($n,{checked:t.quiet_hours_enabled,onChange:y=>h.mutate({quiet_hours_enabled:y})})]}),t.quiet_hours_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:"No notifications during these hours"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tr,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-white",children:[b(t.quiet_hours_start)||"22:00"," - ",b(t.quiet_hours_end)||"07:00"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change quiet hours"})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ti,{className:"w-4 h-4 text-emerald-400"}),a.jsx("p",{className:"text-sm text-white",children:"Daily Digest"})]}),a.jsx($n,{checked:t.daily_digest_enabled,onChange:y=>h.mutate({daily_digest_enabled:y})})]}),t.daily_digest_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tr,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-white",children:["Send at ",b(t.daily_digest_time)||"08:00"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change digest time"})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Ne,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(bg,{className:"w-4 h-4"}),"Edit"]}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:()=>i(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(ln,{className:"w-4 h-4"})})]})]})]})}),r&&a.jsx(er,{title:"Delete Notification Provider",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{p.mutate(),i(!1)},onCancel:()=>i(!1)})]})}const P9=[{value:"email",label:"Email",description:"SMTP email notifications"},{value:"telegram",label:"Telegram",description:"Notifications via Telegram bot"},{value:"discord",label:"Discord",description:"Send to Discord channel via webhook"},{value:"ntfy",label:"ntfy",description:"Free, self-hostable push notifications"},{value:"pushover",label:"Pushover",description:"Simple, reliable push notifications"},{value:"callmebot",label:"CallMeBot/WhatsApp",description:"Free WhatsApp notifications via CallMeBot"},{value:"webhook",label:"Webhook",description:"Generic HTTP POST to any URL"}];function IKe({provider:t,onClose:e}){const n=an(),r=!!t,[i,s]=_.useState(t?.name||""),[o,l]=_.useState(t?.provider_type||"email"),[c,u]=_.useState(t?.printer_id||null),[d,h]=_.useState(t?.quiet_hours_enabled||!1),[p,m]=_.useState(t?.quiet_hours_start||"22:00"),[b,y]=_.useState(t?.quiet_hours_end||"07:00"),[x,v]=_.useState(t?.daily_digest_enabled||!1),[S,N]=_.useState(t?.daily_digest_time||"08:00"),[T,M]=_.useState(t?.on_print_start??!1),[A,k]=_.useState(t?.on_print_complete??!0),[R,C]=_.useState(t?.on_print_failed??!0),[P,U]=_.useState(t?.on_print_stopped??!0),[F,H]=_.useState(t?.on_print_progress??!1),[D,$]=_.useState(t?.on_printer_offline??!1),[G,I]=_.useState(t?.on_printer_error??!1),[K,Q]=_.useState(t?.on_filament_low??!1),[oe,B]=_.useState(t?.on_maintenance_due??!1),[W,J]=_.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([q,re])=>[q,String(re)])):{}),[ne,me]=_.useState(null),[fe,de]=_.useState(null),{data:Re}=it({queryKey:["printers"],queryFn:ae.getPrinters});_.useEffect(()=>{const q=re=>{re.key==="Escape"&&e()};return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[e]);const se=dt({mutationFn:()=>ae.testNotificationConfig({provider_type:o,config:W}),onSuccess:q=>{me(q),de(null)},onError:q=>{me({success:!1,message:q.message})}}),ke=dt({mutationFn:q=>ae.createNotificationProvider(q),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:q=>{de(q.message)}}),Fe=dt({mutationFn:q=>ae.updateNotificationProvider(t.id,q),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:q=>{de(q.message)}}),ce=q=>{if(q.preventDefault(),de(null),!i.trim()){de("Name is required");return}const re=Y(o);for(const le of re)if(!W[le.key]?.trim()){de(`${le.label} is required`);return}const X={name:i.trim(),provider_type:o,config:W,printer_id:c,quiet_hours_enabled:d,quiet_hours_start:d?p:null,quiet_hours_end:d?b:null,daily_digest_enabled:x,daily_digest_time:x?S:null,on_print_start:T,on_print_complete:A,on_print_failed:R,on_print_stopped:P,on_print_progress:F,on_printer_offline:D,on_printer_error:G,on_filament_low:K,on_maintenance_due:oe};r?Fe.mutate(X):ke.mutate(X)},Ve=ke.isPending||Fe.isPending,V=q=>{switch(q){case"callmebot":return[{key:"phone",label:"Phone Number",placeholder:"+1234567890",type:"text",required:!0},{key:"apikey",label:"API Key",placeholder:"Your CallMeBot API key",type:"text",required:!0}];case"ntfy":return[{key:"server",label:"Server URL",placeholder:"https://ntfy.sh",type:"text",required:!1},{key:"topic",label:"Topic",placeholder:"my-bambuddy",type:"text",required:!0},{key:"auth_token",label:"Auth Token",placeholder:"Optional authentication",type:"password",required:!1}];case"pushover":return[{key:"user_key",label:"User Key",placeholder:"Your Pushover user key",type:"text",required:!0},{key:"app_token",label:"App Token",placeholder:"Your Pushover app token",type:"text",required:!0},{key:"priority",label:"Priority",placeholder:"0 (normal)",type:"number",required:!1}];case"telegram":return[{key:"bot_token",label:"Bot Token",placeholder:"Bot token from @BotFather",type:"password",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"Your chat or group ID",type:"text",required:!0}];case"email":return[{key:"smtp_server",label:"SMTP Server",placeholder:"smtp.gmail.com",type:"text",required:!0},{key:"smtp_port",label:"SMTP Port",placeholder:"587",type:"number",required:!1},{key:"security",label:"Security",type:"select",required:!1,options:[{value:"starttls",label:"STARTTLS (Port 587)"},{value:"ssl",label:"SSL/TLS (Port 465)"},{value:"none",label:"None (Port 25)"}]},{key:"auth_enabled",label:"Authentication",type:"select",required:!1,options:[{value:"true",label:"Enabled"},{value:"false",label:"Disabled"}]},{key:"username",label:"Username",placeholder:"your@email.com",type:"text",required:!1},{key:"password",label:"Password",placeholder:"App password",type:"password",required:!1},{key:"from_email",label:"From Email",placeholder:"your@email.com",type:"text",required:!0},{key:"to_email",label:"To Email",placeholder:"recipient@email.com",type:"text",required:!0}];case"discord":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://discord.com/api/webhooks/...",type:"text",required:!0}];case"webhook":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://example.com/webhook",type:"text",required:!0},{key:"payload_format",label:"Payload Format",type:"select",required:!1,options:[{value:"generic",label:"Generic JSON"},{value:"slack",label:"Slack / Mattermost"}]},{key:"auth_header",label:"Authorization",placeholder:"Bearer token (optional)",type:"password",required:!1},{key:"field_title",label:"Title Field Name",placeholder:"title",type:"text",required:!1,showIf:re=>re.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:re=>re.payload_format!=="slack"}];default:return[]}},Y=q=>V(q).filter(re=>re.required),ue=V(o);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg my-8 max-h-[90vh] overflow-y-auto",onClick:q=>q.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r?"Edit Notification Provider":"Add Notification Provider"}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:ce,className:"p-6 space-y-4",children:[fe&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:fe}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:i,onChange:q=>s(q.target.value),placeholder:"My Notifications",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Provider Type *"}),a.jsx("select",{value:o,onChange:q=>{l(q.target.value),J({}),me(null)},disabled:r,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 disabled:opacity-50",children:P9.map(q=>a.jsx("option",{value:q.value,children:q.label},q.value))}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:P9.find(q=>q.value===o)?.description})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Configuration"}),ue.filter(q=>!("showIf"in q)||q.showIf?.(W)!==!1).map(q=>a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[q.label," ",q.required&&"*"]}),q.type==="select"&&"options"in q&&q.options?a.jsx("select",{value:W[q.key]||q.options[0]?.value||"",onChange:re=>{J({...W,[q.key]:re.target.value}),me(null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:q.options.map(re=>a.jsx("option",{value:re.value,children:re.label},re.value))}):a.jsx("input",{type:q.type,value:W[q.key]||"",onChange:re=>{J({...W,[q.key]:re.target.value}),me(null)},placeholder:q.placeholder,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"})]},q.key))]}),a.jsx("div",{className:"flex gap-2",children:a.jsxs(Ne,{type:"button",variant:"secondary",onClick:()=>{me(null),se.mutate()},disabled:se.isPending||!W[Y(o)[0]?.key],className:"flex-1",children:[se.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(kk,{className:"w-4 h-4"}),"Test Configuration"]})}),ne&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${ne.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:ne.success?a.jsxs(a.Fragment,{children:[a.jsx(mr,{className:"w-5 h-5"}),a.jsx("span",{children:ne.message})]}):a.jsxs(a.Fragment,{children:[a.jsx(Zi,{className:"w-5 h-5"}),a.jsx("span",{children:ne.message})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Printer Filter"}),a.jsxs("select",{value:c??"",onChange:q=>u(q.target.value?Number(q.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:"All printers"}),Re?.map(q=>a.jsx("option",{value:q.id,children:q.name},q.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Only send notifications for events from this printer"})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("label",{className:"text-sm text-white",children:"Quiet Hours (Do Not Disturb)"}),a.jsx($n,{checked:d,onChange:h})]}),d&&a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Start"}),a.jsx("input",{type:"time",value:p,onChange:q=>m(q.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"End"}),a.jsx("input",{type:"time",value:b,onChange:q=>y(q.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"})]})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white",children:"Daily Digest"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"})]}),a.jsx($n,{checked:x,onChange:v})]}),x&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Send digest at"}),a.jsx("input",{type:"time",value:S,onChange:q=>N(q.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Events will be collected and sent as a single summary at this time"})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Notification Events"}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Print Events"}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Start"}),a.jsx($n,{checked:T,onChange:M})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Complete"}),a.jsx($n,{checked:A,onChange:k})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Failed"}),a.jsx($n,{checked:R,onChange:C})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Stopped"}),a.jsx($n,{checked:P,onChange:U})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:"Progress"}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:"(25%, 50%, 75%)"})]}),a.jsx($n,{checked:F,onChange:H})]})]})]}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Printer Status"}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Offline"}),a.jsx($n,{checked:D,onChange:$})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Error"}),a.jsx($n,{checked:G,onChange:I})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Low Filament"}),a.jsx($n,{checked:K,onChange:Q})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Maintenance"}),a.jsx($n,{checked:oe,onChange:B})]})]})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Ne,{type:"submit",disabled:Ve,className:"flex-1",children:[Ve?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function zKe({template:t,onClose:e}){const n=an(),r=_.useRef(null),[i,s]=_.useState(t.title_template),[o,l]=_.useState(t.body_template),[c,u]=_.useState(null),[d,h]=_.useState(!0),{data:p}=it({queryKey:["template-variables"],queryFn:ae.getTemplateVariables}),m=p?.find(M=>M.event_type===t.event_type),{data:b,isLoading:y}=it({queryKey:["template-preview",t.event_type,i,o],queryFn:()=>ae.previewTemplate({event_type:t.event_type,title_template:i,body_template:o}),enabled:d&&i.length>0&&o.length>0});_.useEffect(()=>{const M=A=>{A.key==="Escape"&&e()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[e]);const x=dt({mutationFn:M=>ae.updateNotificationTemplate(t.id,M),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:M=>{u(M.message)}}),v=dt({mutationFn:()=>ae.resetNotificationTemplate(t.id),onSuccess:M=>{s(M.title_template),l(M.body_template),n.invalidateQueries({queryKey:["notification-templates"]})},onError:M=>{u(M.message)}}),S=M=>{if(M.preventDefault(),u(null),!i.trim()){u("Title is required");return}if(!o.trim()){u("Body is required");return}x.mutate({title_template:i,body_template:o})},N=M=>{const A=r.current;if(!A)return;const k=A.selectionStart,R=A.selectionEnd,C=o,P=C.substring(0,k),U=C.substring(R),F=P+`{${M}}`+U;l(F),setTimeout(()=>{A.focus();const H=k+M.length+2;A.setSelectionRange(H,H)},0)},T=i!==t.title_template||o!==t.body_template;return a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-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 shrink-0",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Edit Template: ",t.name]}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("form",{onSubmit:S,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[c&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:c}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Title"}),a.jsx("input",{type:"text",value:i,onChange:M=>s(M.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green",placeholder:"Notification title..."})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Body"}),a.jsx("textarea",{ref:r,value:o,onChange:M=>l(M.target.value),rows:4,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green font-mono text-sm resize-none",placeholder:"Notification body..."})]}),m&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:"Available Variables"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:m.variables.map(M=>a.jsxs("button",{type:"button",onClick:()=>N(M),className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs text-bambu-gray hover:text-white transition-colors",children:[a.jsx(cr,{className:"w-3 h-3"}),M]},M))}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:"Click to insert at cursor position in body"})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[a.jsx(gc,{className:"w-4 h-4"}),"Live Preview"]}),a.jsx("button",{type:"button",onClick:()=>h(!d),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:d?"Hide":"Show"})]}),d&&a.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:y?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Loading preview..."]}):b?a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Title:"}),a.jsx("div",{className:"text-white font-medium",children:b.title})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Body:"}),a.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:b.body})]})]}):a.jsx("div",{className:"text-bambu-gray text-sm",children:"Enter template content to see preview"})})]})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[a.jsxs(Ne,{type:"button",variant:"ghost",onClick:()=>v.mutate(),disabled:v.isPending,className:"text-orange-400 hover:text-orange-300",children:[v.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(Bu,{className:"w-4 h-4 mr-2"}),"Reset to Default"]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:e,children:"Cancel"}),a.jsxs(Ne,{onClick:S,disabled:x.isPending||!T,children:[x.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(vs,{className:"w-4 h-4 mr-2"}),"Save"]})]})]})]})})}const UKe={print_start:"Print Started",print_complete:"Print Complete",print_failed:"Print Failed",print_stopped:"Print Stopped",print_progress:"Progress",printer_offline:"Printer Offline",printer_error:"Printer Error",filament_low:"Low Filament",maintenance_due:"Maintenance Due",test:"Test"},BKe={print_start:"text-blue-400",print_complete:"text-bambu-green",print_failed:"text-red-400",print_stopped:"text-orange-400",print_progress:"text-yellow-400",printer_offline:"text-gray-400",printer_error:"text-rose-400",filament_low:"text-cyan-400",maintenance_due:"text-purple-400",test:"text-bambu-gray"};function HKe({onClose:t}){const e=an(),{showToast:n}=Tn(),[r,i]=_.useState(7),[s,o]=_.useState(null),[l,c]=_.useState(!1),{data:u}=it({queryKey:["settings"],queryFn:ae.getSettings}),d=u?.time_format||"system",{data:h,isLoading:p,refetch:m,isRefetching:b}=it({queryKey:["notification-logs",r,l],queryFn:()=>ae.getNotificationLogs({days:r,limit:100,success:l?!1:void 0})}),{data:y}=it({queryKey:["notification-log-stats",r],queryFn:()=>ae.getNotificationLogStats(r)}),x=dt({mutationFn:()=>ae.clearNotificationLogs(30),onSuccess:S=>{n(S.message,"success"),e.invalidateQueries({queryKey:["notification-logs"]}),e.invalidateQueries({queryKey:["notification-log-stats"]})},onError:S=>{n(`Failed to clear logs: ${S.message}`,"error")}}),v=S=>{const N=zi(S);if(!N)return"";const M=new Date().getTime()-N.getTime();return M<6e4?"Just now":M<36e5?`${Math.floor(M/6e4)}m ago`:M<864e5?`${Math.floor(M/36e5)}h ago`:N.toLocaleDateString()+" "+ime(N,d)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg w-full max-w-3xl max-h-[85vh] flex flex-col",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Y0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Notification Log"})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),y&&a.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:a.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[a.jsxs("span",{className:"text-bambu-gray",children:["Last ",r," days: ",a.jsx("span",{className:"text-white font-medium",children:y.total})," notifications"]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(mr,{className:"w-4 h-4"}),y.success_count," sent"]}),y.failure_count>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(Zi,{className:"w-4 h-4"}),y.failure_count," failed"]})]})}),a.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[a.jsxs("select",{value:r,onChange:S=>i(Number(S.target.value)),className:"px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green",children:[a.jsx("option",{value:1,children:"Last 24 hours"}),a.jsx("option",{value:7,children:"Last 7 days"}),a.jsx("option",{value:30,children:"Last 30 days"}),a.jsx("option",{value:90,children:"Last 90 days"})]}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:l,onChange:S=>c(S.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),"Show failed only"]}),a.jsx("div",{className:"flex-1"}),a.jsxs(Ne,{size:"sm",variant:"secondary",onClick:()=>m(),disabled:b,children:[b?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Or,{className:"w-4 h-4"}),"Refresh"]}),a.jsxs(Ne,{size:"sm",variant:"secondary",onClick:()=>x.mutate(),disabled:x.isPending,className:"text-red-400 hover:text-red-300",children:[x.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4"}),"Clear Old"]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:p?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):h&&h.length>0?a.jsx("div",{className:"space-y-2",children:h.map(S=>a.jsx($Ke,{log:S,isExpanded:s===S.id,onToggle:()=>o(s===S.id?null:S.id),formatDate:v,formatFullDate:N=>qg(N,d)},S.id))}):a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(Y0,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:l?"No failed notifications":"No notifications logged"})]})})]})})}function $Ke({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:i}){return a.jsxs("div",{className:`border rounded-lg overflow-hidden transition-colors ${t.success?"border-bambu-dark-tertiary bg-bambu-dark/30":"border-red-500/30 bg-red-500/5"}`,children:[a.jsxs("button",{className:"w-full px-3 py-2 flex items-center gap-3 text-left hover:bg-bambu-dark/50 transition-colors",onClick:n,children:[t.success?a.jsx(mr,{className:"w-4 h-4 text-bambu-green shrink-0"}):a.jsx(Zi,{className:"w-4 h-4 text-red-400 shrink-0"}),a.jsx("span",{className:`text-xs font-medium ${BKe[t.event_type]||"text-bambu-gray"}`,children:UKe[t.event_type]||t.event_type}),a.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||"Unknown Provider"}),t.printer_name&&a.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),a.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?a.jsx(zu,{className:"w-4 h-4 text-bambu-gray shrink-0"}):a.jsx(fr,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&a.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Title"}),a.jsx("p",{className:"text-sm text-white",children:t.title})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Message"}),a.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-red-400 mb-1",children:"Error"}),a.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),a.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[a.jsxs("span",{children:["Provider: ",t.provider_type]}),a.jsxs("span",{children:["Time: ",i(t.created_at)]})]})]})]})}function VKe({formData:t,setFormData:e,groups:n,onClose:r,onCreate:i,isCreating:s,isCreateButtonDisabled:o}){const{t:l}=Yt();_.useEffect(()=>{const u=d=>{d.key==="Escape"&&r()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[r]);const c=u=>{e({...t,group_ids:t.group_ids.includes(u)?t.group_ids.filter(d=>d!==u):[...t.group_ids,u]})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:r,children:a.jsxs(St,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(zf,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:l("users.modal.createUser")})]}),a.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:l("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:r,children:a.jsx(Lt,{className:"w-5 h-5"})})]})}),a.jsxs(Et,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.username")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:t.username,onChange:u=>e({...t,username:u.target.value}),className:"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:l("users.form.usernamePlaceholder"),autoComplete:"username",required:!0})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.email")||"Email"," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"email",value:t.email,onChange:u=>e({...t,email:u.target.value}),className:"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:l("users.form.emailPlaceholder")||"user@example.com",required:!0})]}),a.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.form.autoGeneratedPassword")||"A secure password will be automatically generated and emailed to the user."})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:l("users.form.groups")}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[n.map(u=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.group_ids.includes(u.id),onChange:()=>c(u.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:u.name}),u.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",l("users.system"),")"]})]},u.id)),n.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:r,children:l("users.modal.cancel")}),a.jsx(Ne,{onClick:i,disabled:o,children:s?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),l("users.modal.creating")]}):a.jsxs(a.Fragment,{children:[a.jsx(cr,{className:"w-4 h-4"}),l("users.modal.createUser")]})})]})]})]})})}function GKe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),[r,i]=_.useState(!1),[s,o]=_.useState(""),[l,c]=_.useState("auto"),[u,d]=_.useState(!1),[h,p]=_.useState(!0),[m,b]=_.useState("all"),[y,x]=_.useState(!1),[v,S]=_.useState(!1),{data:N,isLoading:T}=it({queryKey:["spoolman-settings"],queryFn:ae.getSpoolmanSettings}),{data:M,isLoading:A,refetch:k}=it({queryKey:["spoolman-status"],queryFn:ae.getSpoolmanStatus,refetchInterval:3e4}),{data:R}=it({queryKey:["printers"],queryFn:ae.getPrinters});_.useEffect(()=>{N&&(i(N.spoolman_enabled==="true"),o(N.spoolman_url||""),c(N.spoolman_sync_mode||"auto"),d(N.spoolman_disable_weight_sync==="true"),p(N.spoolman_report_partial_usage!=="false"),x(!0))},[N]),_.useEffect(()=>{if(!y||!N)return;if(N.spoolman_enabled==="true"!==r||(N.spoolman_url||"")!==s||(N.spoolman_sync_mode||"auto")!==l||N.spoolman_disable_weight_sync==="true"!==u||N.spoolman_report_partial_usage!=="false"!==h){const Q=setTimeout(()=>{C.mutate()},500);return()=>clearTimeout(Q)}},[r,s,l,u,h,y]);const C=dt({mutationFn:()=>ae.updateSpoolmanSettings({spoolman_enabled:r?"true":"false",spoolman_url:s,spoolman_sync_mode:l,spoolman_disable_weight_sync:u?"true":"false",spoolman_report_partial_usage:h?"true":"false"}),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolman-settings"]}),e.invalidateQueries({queryKey:["spoolman-status"]}),n(t("settings.toast.settingsSaved"))}}),P=dt({mutationFn:ae.connectSpoolman,onSuccess:()=>{k()}}),U=dt({mutationFn:ae.disconnectSpoolman,onSuccess:()=>{k()}}),F=dt({mutationFn:ae.syncAllPrintersAms,onSuccess:K=>{K.success}}),H=dt({mutationFn:K=>ae.syncPrinterAms(K),onSuccess:K=>{K.success}}),D=()=>{m==="all"?F.mutate():H.mutate(m)},$=F.isPending||H.isPending,G=m==="all"?F.data:H.data,I=m==="all"?F.isSuccess:H.isSuccess;return T?a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Au,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Spoolman Integration"})]})}),a.jsx(Et,{children:a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Au,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Spoolman Integration"})]}),C.isPending&&a.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Connect to Spoolman for filament inventory tracking. AMS data will sync automatically."}),a.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(xo,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:"How Sync Works"}),a.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[a.jsx("li",{children:"Only official Bambu Lab spools with RFID are synced"}),a.jsx("li",{children:"New spools are auto-created in Spoolman on first sync"}),a.jsx("li",{children:"Non-Bambu Lab spools (third-party, refilled) are skipped"})]}),a.jsx("p",{className:"font-medium mt-2 mb-1",children:"Linking Existing Spools"}),a.jsx("p",{className:"text-blue-300/80",children:'To link existing Spoolman spools to your AMS, hover over an AMS slot and click "Link to Spoolman".'})]})]})}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:"Enable Spoolman"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Sync filament data with Spoolman server"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:K=>i(K.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Spoolman URL"}),a.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:K=>o(K.target.value),disabled:!r,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray/50 focus:border-bambu-green focus:outline-none disabled:opacity-50"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"URL of your Spoolman server (e.g., http://localhost:7912)"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Sync Mode"}),a.jsxs("select",{value:l,onChange:K=>c(K.target.value),disabled:!r,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 disabled:opacity-50",children:[a.jsx("option",{value:"auto",children:"Automatic"}),a.jsx("option",{value:"manual",children:"Manual Only"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:l==="auto"?"AMS data syncs automatically when changes are detected":"Only sync when manually triggered"})]}),l==="auto"&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:u,onChange:K=>d(K.target.checked),disabled:!r,className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),u&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:h,onChange:K=>p(K.target.checked),disabled:!r,className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),r&&a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:"Status:"}),A?a.jsx(ct,{className:"w-4 h-4 text-bambu-gray animate-spin"}):M?.connected?a.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[a.jsx($i,{className:"w-4 h-4"}),"Connected"]}):a.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[a.jsx(Lt,{className:"w-4 h-4"}),"Disconnected"]})]}),a.jsx("div",{className:"flex gap-2",children:M?.connected?a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>U.mutate(),disabled:U.isPending,children:[U.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Ide,{className:"w-4 h-4"}),"Disconnect"]}):a.jsxs(Ne,{size:"sm",onClick:()=>P.mutate(),disabled:P.isPending||!s,children:[P.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(dc,{className:"w-4 h-4"}),"Connect"]})})]}),P.isError&&a.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:P.error.message}),M?.connected&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Sync AMS Data"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Manually sync printer AMS data to Spoolman"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsxs("select",{value:m,onChange:K=>b(K.target.value==="all"?"all":Number(K.target.value)),className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"all",children:"All Printers"}),R?.map(K=>a.jsx("option",{value:K.id,children:K.name},K.id))]}),a.jsx(fr,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:D,disabled:$,children:[$?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Or,{className:"w-4 h-4"}),"Sync"]})]})]}),I&&G&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:`p-2 rounded text-sm ${G.success?"bg-green-500/20 border border-green-500/50 text-green-400":"bg-yellow-500/20 border border-yellow-500/50 text-yellow-400"}`,children:G.success?`Synced ${G.synced_count} spool${G.synced_count!==1?"s":""} successfully`:`Synced ${G.synced_count} spool${G.synced_count!==1?"s":""} with ${G.errors.length} error${G.errors.length!==1?"s":""}`}),G.skipped_count>0&&a.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[a.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(En,{className:"w-3.5 h-3.5"}),a.jsxs("span",{className:"font-medium",children:[G.skipped_count," spool",G.skipped_count!==1?"s":""," skipped"]})]}),G.skipped_count>5&&a.jsx("button",{onClick:()=>S(!v),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:v?"Show less":"Show all"})]}),a.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(v?G.skipped:G.skipped.slice(0,5)).map((K,Q)=>a.jsxs("li",{className:"flex items-center gap-2",children:[K.color&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:`#${K.color}`}}),a.jsx("span",{children:K.location}),a.jsxs("span",{className:"text-amber-300/60",children:["- ",K.reason]})]},Q)),!v&&G.skipped_count>5&&a.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",G.skipped_count-5," more"]})]})]}),G.errors.length>0&&a.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[a.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),a.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:G.errors.map((K,Q)=>a.jsx("li",{children:K},Q))})]})]})]})]})]})}function qKe({link:t,onClose:e}){const n=an(),r=!!t,i=_.useRef(null),[s,o]=_.useState(t?.name||""),[l,c]=_.useState(t?.url||""),[u,d]=_.useState(t?.icon||"link"),[h,p]=_.useState(!!t?.custom_icon),[m,b]=_.useState(t?.custom_icon?ae.getExternalLinkIconUrl(t.id):null),[y,x]=_.useState(null),[v,S]=_.useState(null);_.useEffect(()=>{const P=U=>{U.key==="Escape"&&e()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[e]);const N=dt({mutationFn:async P=>{const U=await ae.createExternalLink(P);return y?await ae.uploadExternalLinkIcon(U.id,y):U},onSuccess:()=>{n.invalidateQueries({queryKey:["external-links"]}),e()},onError:P=>{S(P.message)}}),T=dt({mutationFn:async P=>{let U=await ae.updateExternalLink(t.id,P);return y?U=await ae.uploadExternalLinkIcon(t.id,y):!h&&t?.custom_icon&&(U=await ae.deleteExternalLinkIcon(t.id)),U},onSuccess:()=>{n.invalidateQueries({queryKey:["external-links"]}),e()},onError:P=>{S(P.message)}}),M=P=>{const U=P.target.files?.[0];if(U){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(U.type)){S("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(U.size>1024*1024){S("Image file must be less than 1MB");return}x(U),p(!0);const H=new FileReader;H.onload=D=>{b(D.target?.result)},H.readAsDataURL(U)}},A=()=>{x(null),b(null),p(!1),i.current&&(i.current.value="")},k=P=>{if(P.preventDefault(),S(null),!s.trim()){S("Name is required");return}if(!l.trim()){S("URL is required");return}if(!l.startsWith("http://")&&!l.startsWith("https://")){S("URL must start with http:// or https://");return}const U={name:s.trim(),url:l.trim(),icon:u};r?T.mutate(U):N.mutate(U)},R=N.isPending||T.isPending,C=Tk(u);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:P=>P.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:h&&m?a.jsx("img",{src:m,alt:"",className:"w-5 h-5 rounded"}):a.jsx(C,{className:"w-5 h-5"})}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:r?"Edit Link":"Add External Link"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:k,className:"p-6 space-y-4",children:[v&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:v}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:s,onChange:P=>o(P.target.value),placeholder:"My Link",maxLength:50,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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),a.jsx("input",{type:"text",value:l,onChange:P=>c(P.target.value),placeholder:"https://example.com",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"})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),a.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),a.jsx("input",{ref:i,type:"file",accept:"image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon",className:"hidden",onChange:M}),h&&m?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("img",{src:m,alt:"Custom icon",className:"w-8 h-8 rounded border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:A,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:a.jsx(ln,{className:"w-4 h-4"})})]}):a.jsxs(Ne,{type:"button",variant:"secondary",size:"sm",onClick:()=>i.current?.click(),children:[a.jsx(Na,{className:"w-4 h-4"}),"Upload"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!h&&a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),a.jsx(Gfe,{value:u,onChange:d})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Ne,{type:"submit",disabled:R,className:"flex-1",children:[R?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function WKe(){const{t}=Yt(),e=an(),[n,r]=_.useState(!1),[i,s]=_.useState(null),[o,l]=_.useState(null),[c,u]=_.useState(null),{data:d,isLoading:h}=it({queryKey:["external-links"],queryFn:ae.getExternalLinks}),p=dt({mutationFn:N=>ae.deleteExternalLink(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),m=dt({mutationFn:N=>ae.reorderExternalLinks(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),b=(N,T)=>{u(T),N.dataTransfer.effectAllowed="move"},y=N=>{N.preventDefault(),N.dataTransfer.dropEffect="move"},x=(N,T)=>{if(N.preventDefault(),c===null||c===T||!d)return;const M=d.map(C=>C.id),A=M.indexOf(c),k=M.indexOf(T);if(A===-1||k===-1)return;const R=[...M];R.splice(A,1),R.splice(k,0,c),m.mutate(R),u(null)},v=N=>{l(N)},S=()=>{o&&(p.mutate(o.id),l(null))};return a.jsxs(a.Fragment,{children:[a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(dc,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),a.jsxs(Ne,{size:"sm",onClick:()=>r(!0),children:[a.jsx(cr,{className:"w-4 h-4"}),"Add Link"]})]})}),a.jsxs(Et,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),h?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):d&&d.length>0?a.jsx("div",{className:"space-y-2",children:d.map(N=>{const T=Tk(N.icon);return a.jsxs("div",{draggable:!0,onDragStart:M=>b(M,N.id),onDragOver:y,onDrop:M=>x(M,N.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${c===N.id?"opacity-50":""}`,children:[a.jsx(Vg,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(T,{className:"w-4 h-4"})}),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-white font-medium truncate",children:N.name}),a.jsx(Xr,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),a.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:N.url})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[a.jsx("button",{onClick:()=>s(N),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:t("common.edit"),children:a.jsx(Ji,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>v(N),disabled:p.isPending,className:"p-2 rounded-lg hover:bg-red-500/20 text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50",title:t("externalLinks.deleteLink"),children:a.jsx(ln,{className:"w-4 h-4"})})]})]},N.id)})}):a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(dc,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:t("externalLinks.noLinksConfigured")}),a.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(n||i)&&a.jsx(qKe,{link:i,onClose:()=>{r(!1),s(null)}}),o&&a.jsx(er,{title:"Delete Link",message:`Are you sure you want to delete "${o.name}"? This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger",onConfirm:S,onCancel:()=>l(null)})]})}function KKe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),[r,i]=_.useState(!1),[s,o]=_.useState(""),[l,c]=_.useState("immediate"),[u,d]=_.useState("3DPrinter-X1-Carbon"),[h,p]=_.useState(null),[m,b]=_.useState(""),[y,x]=_.useState(!1),[v,S]=_.useState(null),{data:N,isLoading:T}=it({queryKey:["virtual-printer-settings"],queryFn:S1.getSettings,refetchInterval:1e4}),{data:M}=it({queryKey:["virtual-printer-models"],queryFn:S1.getModels}),{data:A}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:k}=it({queryKey:["network-interfaces"],queryFn:()=>ae.getNetworkInterfaces().then(I=>I.interfaces),enabled:r});_.useEffect(()=>{if(N){i(N.enabled);let I=N.mode==="queue"?"review":N.mode;I!=="immediate"&&I!=="review"&&I!=="print_queue"&&I!=="proxy"&&(I="immediate"),c(I),d(N.model),p(N.target_printer_id),b(N.remote_interface_ip||"")}},[N]);const R=dt({mutationFn:I=>S1.updateSettings(I),onSuccess:()=>{e.invalidateQueries({queryKey:["virtual-printer-settings"]}),n(t("virtualPrinter.toast.updated")),S(null)},onError:I=>{if(n(I.message||t("virtualPrinter.toast.failedToUpdate"),"error"),N){i(N.enabled);const K=N.mode==="queue"?"review":N.mode;c(["immediate","review","print_queue","proxy"].includes(K)?K:"immediate"),d(N.model),p(N.target_printer_id)}S(null)}}),C=()=>{const I=!r;if(I){if(l==="proxy"){if(!h){n(t("virtualPrinter.toast.targetPrinterRequired"),"error");return}}else if(!s&&!N?.access_code_set){n(t("virtualPrinter.toast.accessCodeRequired"),"error");return}}i(I),S("toggle"),R.mutate({enabled:I,access_code:l!=="proxy"&&s||void 0,mode:l,target_printer_id:l==="proxy"?h??void 0:void 0})},P=()=>{if(!s){n(t("virtualPrinter.toast.accessCodeEmpty"),"error");return}if(s.length!==8){n(t("virtualPrinter.toast.accessCodeLength"),"error");return}S("accessCode"),R.mutate({access_code:s}),o("")},U=I=>{c(I),S("mode"),R.mutate({mode:I})},F=I=>{p(I),S("targetPrinter"),R.mutate({target_printer_id:I})},H=I=>{d(I),S("model"),R.mutate({model:I})},D=I=>{b(I),S("remoteInterface"),R.mutate({remote_interface_ip:I})};if(T)return a.jsx(St,{children:a.jsx(Et,{className:"py-8 flex justify-center",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const $=N?.status,G=$?.running||!1;return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[a.jsx("div",{className:"space-y-6 lg:w-[480px] lg:flex-shrink-0",children:a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(jr,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("virtualPrinter.title")})]}),$&&a.jsxs("div",{className:`flex items-center gap-2 text-sm ${G?"text-green-400":"text-bambu-gray"}`,children:[a.jsx("span",{className:`w-2 h-2 rounded-full ${G?"bg-green-400 animate-pulse":"bg-gray-500"}`}),t(G?"virtualPrinter.running":"virtualPrinter.stopped")]})]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t(l==="proxy"?"virtualPrinter.description.proxy":"virtualPrinter.description.default")}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-white font-medium",children:t("virtualPrinter.enable.title")}),a.jsx("div",{className:"text-sm text-bambu-gray",children:G?l==="proxy"?t("virtualPrinter.enable.proxyingTo",{name:A?.find(I=>I.id===h)?.name||"printer"}):t("virtualPrinter.enable.visibleInSlicer"):t("virtualPrinter.enable.notActive")})]}),a.jsx("button",{onClick:C,disabled:v==="toggle",className:`relative w-12 h-6 rounded-full transition-colors ${r?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${v==="toggle"?"opacity-50":""}`,children:a.jsx("span",{className:`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${r?"translate-x-6":""}`})})]}),l!=="proxy"&&a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.model.title")}),a.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:t("virtualPrinter.model.description")}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:u,onChange:I=>H(I.target.value),disabled:v==="model",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed pr-10",children:M?.models&&Object.entries(M.models).sort(([,I],[,K])=>I.localeCompare(K)).map(([I,K])=>a.jsx("option",{value:I,children:K},I))}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),r&&G&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[a.jsx(xo,{className:"w-3 h-3 inline mr-1"}),t("virtualPrinter.model.restartWarning")]})]}),l!=="proxy"&&a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.accessCode.title")}),a.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:N?.access_code_set?a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx($i,{className:"w-4 h-4"}),t("virtualPrinter.accessCode.isSet")]}):a.jsxs("span",{className:"flex items-center gap-1 text-yellow-400",children:[a.jsx(En,{className:"w-4 h-4"}),t("virtualPrinter.accessCode.notSet")]})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:y?"text":"password",value:s,onChange:I=>o(I.target.value),placeholder:N?.access_code_set?t("virtualPrinter.accessCode.placeholderChange"):t("virtualPrinter.accessCode.placeholder"),maxLength:8,className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white placeholder-bambu-gray pr-10 font-mono"}),a.jsx("button",{onClick:()=>x(!y),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:y?a.jsx(bk,{className:"w-4 h-4"}):a.jsx(gc,{className:"w-4 h-4"})})]}),a.jsx(Ne,{onClick:P,disabled:!s||v==="accessCode",variant:"primary",children:v==="accessCode"?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):t("common.save")})]}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[t("virtualPrinter.accessCode.hint"),s&&a.jsxs("span",{className:s.length===8?"text-green-400":"text-yellow-400",children:[" ",t("virtualPrinter.accessCode.charCount",{count:s.length})]})]})]}),l==="proxy"&&a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.targetPrinter.title")}),a.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:h?a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx($i,{className:"w-4 h-4"}),t("virtualPrinter.targetPrinter.configured")]}):a.jsxs("span",{className:"flex items-center gap-1 text-yellow-400",children:[a.jsx(En,{className:"w-4 h-4"}),t("virtualPrinter.targetPrinter.notConfigured")]})}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:h??"",onChange:I=>{const K=parseInt(I.target.value,10);isNaN(K)||F(K)},disabled:v==="targetPrinter",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed pr-10",children:[a.jsx("option",{value:"",children:t("virtualPrinter.targetPrinter.placeholder")}),A?.map(I=>a.jsxs("option",{value:I.id,children:[I.name," (",I.ip_address,")"]},I.id))]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:t("virtualPrinter.targetPrinter.hint")}),!A?.length&&a.jsxs("p",{className:"text-xs text-yellow-400 mt-2",children:[a.jsx(En,{className:"w-3 h-3 inline mr-1"}),t("virtualPrinter.targetPrinter.noPrinters")]})]}),r&&a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.remoteInterface.title")}),a.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:m?a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx($i,{className:"w-4 h-4"}),t("virtualPrinter.remoteInterface.configured")]}):a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(xo,{className:"w-4 h-4"}),t("virtualPrinter.remoteInterface.optional")]})}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:m,onChange:I=>D(I.target.value),disabled:v==="remoteInterface",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed pr-10",children:[a.jsx("option",{value:"",children:t("virtualPrinter.remoteInterface.placeholder")}),k?.map(I=>a.jsxs("option",{value:I.ip,children:[I.name," (",I.ip,") - ",I.subnet]},I.ip))]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:t("virtualPrinter.remoteInterface.hint")})]}),a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.mode.title")}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("button",{onClick:()=>U("immediate"),disabled:v==="mode",className:`p-3 rounded-lg border text-left transition-colors ${l==="immediate"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:"text-white font-medium",children:t("virtualPrinter.mode.archive")}),a.jsx("div",{className:"text-xs text-bambu-gray",children:t("virtualPrinter.mode.archiveDesc")})]}),a.jsxs("button",{onClick:()=>U("review"),disabled:v==="mode",className:`p-3 rounded-lg border text-left transition-colors ${l==="review"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:"text-white font-medium",children:t("virtualPrinter.mode.review")}),a.jsx("div",{className:"text-xs text-bambu-gray",children:t("virtualPrinter.mode.reviewDesc")})]}),a.jsxs("button",{onClick:()=>U("print_queue"),disabled:v==="mode",className:`p-3 rounded-lg border text-left transition-colors ${l==="print_queue"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:"text-white font-medium",children:t("virtualPrinter.mode.queue")}),a.jsx("div",{className:"text-xs text-bambu-gray",children:t("virtualPrinter.mode.queueDesc")})]}),a.jsxs("button",{onClick:()=>U("proxy"),disabled:v==="mode",className:`p-3 rounded-lg border text-left transition-colors ${l==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-white font-medium",children:[a.jsx(YU,{className:"w-4 h-4"}),t("virtualPrinter.mode.proxy")]}),a.jsx("div",{className:"text-xs text-bambu-gray",children:t("virtualPrinter.mode.proxyDesc")})]})]})]})]})]})}),a.jsxs("div",{className:"space-y-6 lg:w-[480px] lg:flex-shrink-0",children:[a.jsx(St,{className:"border-l-4 border-l-yellow-500",children:a.jsx(Et,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(En,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-sm",children:[a.jsx("p",{className:"text-white font-medium mb-2",children:t("virtualPrinter.setupRequired.title")}),a.jsx("p",{className:"text-bambu-gray mb-3",children:t("virtualPrinter.setupRequired.description")}),a.jsxs("a",{href:"https://wiki.bambuddy.cool/features/virtual-printer/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-4 py-2 bg-yellow-500/20 border border-yellow-500/50 rounded-md text-yellow-400 hover:bg-yellow-500/30 transition-colors",children:[a.jsx(Xr,{className:"w-4 h-4"}),t("virtualPrinter.setupRequired.readGuide")]})]})]})})}),a.jsx(St,{children:a.jsx(Et,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(xo,{className:"w-5 h-5 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-sm text-bambu-gray",children:[a.jsx("p",{className:"mb-2",children:a.jsxs("strong",{className:"text-white",children:[t(l==="proxy"?"virtualPrinter.howItWorks.titleProxy":"virtualPrinter.howItWorks.title"),":"]})}),l==="proxy"?a.jsxs("ol",{className:"list-decimal list-inside space-y-1",children:[a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep1")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep2")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep3")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep4")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep5")})]}):a.jsxs("ol",{className:"list-decimal list-inside space-y-1",children:[a.jsx("li",{children:t("virtualPrinter.howItWorks.step1")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step2")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step3")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step4")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step5")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step6")})]})]})]})})}),$&&G&&a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h3",{className:"text-md font-semibold text-white",children:t("virtualPrinter.status.title")})}),a.jsx(Et,{children:$.mode==="proxy"&&$.proxy?a.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.targetPrinter")}),a.jsx("div",{className:"text-white",children:A?.find(I=>I.id===h)?.name||$.proxy.target_host}),a.jsx("div",{className:"text-xs text-bambu-gray font-mono",children:$.proxy.target_host})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.mode")}),a.jsxs("div",{className:"text-white flex items-center gap-1.5",children:[a.jsx(YU,{className:"w-4 h-4"}),t("virtualPrinter.mode.proxy")]})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.ftpPort")}),a.jsx("div",{className:"text-white font-mono",children:$.proxy.ftp_port})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.mqttPort")}),a.jsx("div",{className:"text-white font-mono",children:$.proxy.mqtt_port})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.ftpConnections")}),a.jsx("div",{className:"text-white",children:$.proxy.ftp_connections??0})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.mqttConnections")}),a.jsx("div",{className:"text-white",children:$.proxy.mqtt_connections??0})]})]}):a.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.printerName")}),a.jsx("div",{className:"text-white",children:$.name})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.model")}),a.jsx("div",{className:"text-white",children:$.model_name||$.model})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.serialNumber")}),a.jsx("div",{className:"text-white font-mono",children:$.serial})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.mode")}),a.jsx("div",{className:"text-white capitalize",children:$.mode})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.pendingFiles")}),a.jsx("div",{className:"text-white",children:$.pending_files})]})]})})]})]})]})}function j9({status:t}){if(!t)return null;const e={success:"bg-green-500/20 text-green-400",failed:"bg-red-500/20 text-red-400",skipped:"bg-yellow-500/20 text-yellow-400",running:"bg-blue-500/20 text-blue-400"},n={success:a.jsx(mr,{className:"w-3 h-3"}),failed:a.jsx(Zi,{className:"w-3 h-3"}),skipped:a.jsx(qR,{className:"w-3 h-3"}),running:a.jsx(ct,{className:"w-3 h-3 animate-spin"})};return a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium ${e[t]||"bg-gray-500/20 text-gray-400"}`,children:[n[t],t.charAt(0).toUpperCase()+t.slice(1)]})}function XKe(t){return t?new Date(t).toLocaleString():"-"}function D9(t){if(!t)return"-";const e=new Date(t),n=new Date,r=e.getTime()-n.getTime(),i=Math.round(r/6e4);if(i<0){const s=Math.abs(i);if(s<60)return`${s}m ago`;const o=Math.floor(s/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}else{if(i<60)return`in ${i}m`;const s=Math.floor(i/60);return s<24?`in ${s}h`:`in ${Math.floor(s/24)}d`}}function YKe(){const t=an(),{showToast:e}=Tn(),{t:n}=Yt(),[r,i]=_.useState(""),[s,o]=_.useState(""),[l,c]=_.useState("main"),[u,d]=_.useState(!1),[h,p]=_.useState("daily"),[m,b]=_.useState(!0),[y,x]=_.useState(!0),[v,S]=_.useState(!1),[N,T]=_.useState(!0),[M,A]=_.useState(!1),[k,R]=_.useState(!1),[C,P]=_.useState(""),[U,F]=_.useState(!1),[H,D]=_.useState(null),[$,G]=_.useState(null),I=_.useRef(null);_.useEffect(()=>{if(M||k){const z=O=>(O.preventDefault(),O.returnValue="A backup operation is in progress. Are you sure you want to leave?",O.returnValue);return window.addEventListener("beforeunload",z),()=>window.removeEventListener("beforeunload",z)}},[M,k]);const[K,Q]=_.useState(!1),[oe,B]=_.useState(null),W=_.useRef(null),J=_.useRef(!1),{data:ne,isLoading:me}=it({queryKey:["github-backup-config"],queryFn:ae.getGitHubBackupConfig}),{data:fe}=it({queryKey:["github-backup-status"],queryFn:ae.getGitHubBackupStatus,refetchInterval:ee=>ee.state.data?.is_running?500:1e4}),{data:de}=it({queryKey:["github-backup-logs"],queryFn:()=>ae.getGitHubBackupLogs(20)}),{data:Re}=it({queryKey:["cloud-status"],queryFn:ae.getCloudStatus}),{data:se}=it({queryKey:["printers"],queryFn:ae.getPrinters}),ke=BR({queries:(se??[]).map(ee=>({queryKey:["printerStatus",ee.id],queryFn:()=>ae.getPrinterStatus(ee.id),staleTime:1e4,refetchInterval:3e4}))}),Fe=(se??[]).map((ee,z)=>({printer:ee,connected:ke[z]?.data?.connected??!1})),ce=Fe.length,Ve=Fe.filter(ee=>ee.connected).length,V=ce>0&&Ve===0,Y=Ve>0&&Ve{ne&&(i(ne.repository_url),c(ne.branch),d(ne.schedule_enabled),p(ne.schedule_type),b(ne.backup_kprofiles),x(ne.backup_cloud_profiles),S(ne.backup_settings),T(ne.enabled),o(""),setTimeout(()=>{J.current=!0},100))},[ne]);const ue=_.useCallback(async(ee=!1)=>{if(ne?.has_token)try{ee&&s?(await ae.saveGitHubBackupConfig({repository_url:r,access_token:s,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:m,backup_cloud_profiles:y,backup_settings:v,enabled:N}),o(""),e("Token updated")):(await ae.updateGitHubBackupConfig({repository_url:r,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:m,backup_cloud_profiles:y,backup_settings:v,enabled:N}),e("Settings saved")),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(z){e(`Failed to save: ${z.message}`,"error")}},[ne?.has_token,r,s,l,u,h,m,y,v,N,t,e]);_.useEffect(()=>{if(!(!J.current||!ne?.has_token))return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{ue(!1)},500),()=>{W.current&&clearTimeout(W.current)}},[r,l,u,h,m,y,v,N,ue,ne?.has_token]),_.useEffect(()=>{if(!(!J.current||!ne?.has_token||!s))return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{ue(!0)},1e3),()=>{W.current&&clearTimeout(W.current)}},[s,ue,ne?.has_token]);const q=dt({mutationFn:ee=>ae.saveGitHubBackupConfig(ee),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e("GitHub backup enabled"),o(""),J.current=!0},onError:ee=>{e(`Failed to save: ${ee.message}`,"error")}}),re=dt({mutationFn:ae.triggerGitHubBackup,onSuccess:ee=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),ee.success?ee.files_changed>0?e(`Backup complete - ${ee.files_changed} files updated`):e("Backup skipped - no changes"):e(`Backup failed: ${ee.message}`,"error")},onError:ee=>{e(`Backup failed: ${ee.message}`,"error")}}),X=dt({mutationFn:()=>ae.clearGitHubBackupLogs(0),onSuccess:ee=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(`Cleared ${ee.deleted} logs`)},onError:ee=>{e(`Failed to clear logs: ${ee.message}`,"error")}}),le=async()=>{Q(!0),B(null);try{let ee;if(s){if(!r){e("Enter repository URL","error"),Q(!1);return}ee=await ae.testGitHubConnection(r,s)}else if(ne?.has_token)ee=await ae.testGitHubStoredConnection();else{e("Enter repository URL and access token","error"),Q(!1);return}B({success:ee.success,message:ee.message})}catch(ee){B({success:!1,message:ee.message})}finally{Q(!1)}},pe=()=>{if(!r){e("Repository URL is required","error");return}if(!s){e("Access token is required","error");return}q.mutate({repository_url:r,access_token:s,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:m,backup_cloud_profiles:y,backup_settings:v,enabled:N})};return me?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})}):a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"space-y-6",children:[a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(kj,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"GitHub Backup"})]}),ne&&Re?.is_authenticated&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:"Enabled"}),a.jsx($n,{checked:N,onChange:T})]})]})}),a.jsx(Et,{className:"space-y-4",children:Re?.is_authenticated?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically sync your profiles to a private GitHub repository for backup and version history."}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Repository URL"}),a.jsx("input",{type:"text",value:r,onChange:ee=>{i(ee.target.value),B(null)},placeholder:"https://github.com/username/bambuddy-backup",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"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Personal Access Token ",ne?.has_token&&a.jsx("span",{className:"text-green-400",children:"(saved)"})]}),a.jsx("input",{type:"password",value:s,onChange:ee=>{o(ee.target.value),B(null)},placeholder:ne?.has_token?"Enter new token to update":"ghp_xxxxxxxxxxxx",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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Fine-grained token with Contents read/write permission"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Branch"}),a.jsx("input",{type:"text",value:l,onChange:ee=>c(ee.target.value),placeholder:"main",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Auto-backup"}),a.jsxs("select",{value:u?h:"disabled",onChange:ee=>{ee.target.value==="disabled"?d(!1):(d(!0),p(ee.target.value))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"disabled",children:"Manual only"}),a.jsx("option",{value:"hourly",children:"Hourly"}),a.jsx("option",{value:"daily",children:"Daily"}),a.jsx("option",{value:"weekly",children:"Weekly"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Include in backup"}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:`flex items-start gap-2 ${V?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[a.jsx("input",{type:"checkbox",checked:m,onChange:ee=>b(ee.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green",disabled:V}),a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`text-sm ${V?"text-bambu-gray":"text-white"}`,children:"K-Profiles"}),V&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[a.jsx(En,{className:"w-3 h-3"}),"No printers connected"]}),Y&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[a.jsx(En,{className:"w-3 h-3"}),Ve,"/",ce," connected"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Pressure advance calibration from connected printers"})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:y,onChange:ee=>x(ee.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green",disabled:!Re?.is_authenticated}),a.jsxs("div",{children:[a.jsx("span",{className:`text-sm ${Re?.is_authenticated?"text-white":"text-bambu-gray"}`,children:"Cloud Profiles"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Filament, printer, and process presets from Bambu Cloud"})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:v,onChange:ee=>S(ee.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white text-sm",children:"App Settings"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Bambuddy configuration (complete database)"})]})]})]})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[fe?.configured&&a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:fe.last_backup_at?a.jsxs(a.Fragment,{children:[a.jsxs("span",{children:["Last backup: ",D9(fe.last_backup_at)]}),a.jsx(j9,{status:fe.last_backup_status})]}):a.jsx("span",{children:"No backups yet"})}),fe.next_scheduled_run&&a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx(tr,{className:"w-3 h-3 inline mr-1"}),"Next: ",D9(fe.next_scheduled_run)]})]}),oe&&a.jsxs("div",{className:`text-sm flex items-center gap-1 ${oe.success?"text-green-400":"text-red-400"}`,children:[oe.success?a.jsx(mr,{className:"w-4 h-4"}):a.jsx(Zi,{className:"w-4 h-4"}),oe.message]}),a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:fe?.configured?a.jsx(a.Fragment,{children:re.isPending||fe.is_running?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{className:"text-sm",children:fe.progress||"Starting backup..."})]}):a.jsxs(a.Fragment,{children:[a.jsxs(Ne,{variant:"primary",size:"sm",onClick:()=>re.mutate(),disabled:!ne?.enabled,children:[a.jsx(Eo,{className:"w-4 h-4"}),"Backup Now"]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:le,disabled:K,children:[K?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Or,{className:"w-4 h-4"}),"Test"]})]})}):a.jsxs(a.Fragment,{children:[a.jsxs(Ne,{variant:"primary",size:"sm",onClick:pe,disabled:q.isPending||!r||!s,children:[q.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(mr,{className:"w-4 h-4"}),"Enable Backup"]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:le,disabled:K||!r||!s,children:[K?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Or,{className:"w-4 h-4"}),"Test Connection"]})]})})]})]}):a.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[a.jsx(En,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-sm text-yellow-400",children:"Bambu Cloud login required. Sign in under Profiles → Cloud Profiles to enable GitHub backup."})]})})]}),de&&de.length>0&&a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Y0,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"History"})]}),a.jsxs(Ne,{variant:"ghost",size:"sm",onClick:()=>X.mutate(),disabled:X.isPending,children:[a.jsx(ln,{className:"w-4 h-4"}),"Clear"]})]})}),a.jsx(Et,{children:a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left py-2 px-2",children:"Date"}),a.jsx("th",{className:"text-left py-2 px-2",children:"Status"}),a.jsx("th",{className:"text-left py-2 px-2",children:"Commit"})]})}),a.jsx("tbody",{children:de.slice(0,10).map(ee=>a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[a.jsx("td",{className:"py-2 px-2 text-white",children:XKe(ee.started_at)}),a.jsx("td",{className:"py-2 px-2",children:a.jsx(j9,{status:ee.status})}),a.jsx("td",{className:"py-2 px-2",children:ee.commit_sha?a.jsxs("a",{href:`${ne?.repository_url}/commit/${ee.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[ee.commit_sha.substring(0,7),a.jsx(Xr,{className:"w-3 h-3"})]}):a.jsx("span",{className:"text-bambu-gray",children:"-"})})]},ee.id))})]})})})]})]}),a.jsx("div",{className:"space-y-6",children:a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Au,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Local Backup"})]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Create a complete backup of your Bambuddy data including the database, archives, uploads, and all files."}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:"Download Backup"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Complete backup: database + all files (ZIP)"})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",disabled:M||k,onClick:async()=>{A(!0),P("Preparing backup...");try{P("Creating backup archive... This may take a while for large archives.");const{blob:ee,filename:z}=await ae.exportBackup();P("Downloading backup file...");const O=URL.createObjectURL(ee),Z=document.createElement("a");Z.href=O,Z.download=z,Z.click(),URL.revokeObjectURL(O),e("Backup downloaded successfully")}catch(ee){e(`Failed to create backup: ${ee instanceof Error?ee.message:"Unknown error"}`,"error")}finally{A(!1),P("")}},children:[a.jsx(wi,{className:"w-4 h-4"}),"Download"]})]}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:n("backup.restoreBackup")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.restoreDescription")}),a.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.restoreNote")})]}),a.jsx("input",{ref:I,type:"file",accept:".zip",className:"hidden",onChange:ee=>{const z=ee.target.files?.[0];z&&(D(z),F(!0)),ee.target.value=""}}),a.jsxs(Ne,{variant:"secondary",size:"sm",disabled:k||M,onClick:()=>I.current?.click(),children:[a.jsx(Na,{className:"w-4 h-4"}),"Restore"]})]}),$&&a.jsx("div",{className:`p-3 rounded-lg ${$.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[$.success?a.jsx(mr,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):a.jsx(Zi,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:$.success?"text-green-200":"text-red-200",children:[$.message,$.success&&a.jsx("div",{className:"mt-2",children:a.jsxs(Ne,{size:"sm",onClick:()=>window.location.reload(),children:[a.jsx(Bu,{className:"w-3 h-3"}),"Reload Now"]})})]})]})}),a.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[a.jsx(En,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"text-yellow-200",children:[a.jsx("span",{className:"font-medium",children:"Restore replaces all data."})," ",a.jsx("span",{className:"text-yellow-200/70",children:"Your current database and files will be completely replaced. A restart is required after restore."})]})]})})]})]})}),U&&H&&a.jsx(er,{title:"Restore Backup",message:`Are you sure you want to restore from "${H.name}"? This will completely replace your current database and all files. The application will need to be restarted after restore.`,confirmText:"Restore Backup",variant:"danger",onConfirm:async()=>{F(!1),R(!0),G(null);try{P("Uploading backup file...");const ee=await ae.importBackup(H);G(ee),ee.success?e("Backup restored. Please restart Bambuddy.","success"):e(ee.message,"error")}catch(ee){const z=ee instanceof Error?ee.message:"Failed to restore backup";G({success:!1,message:z}),e(z,"error")}finally{R(!1),P(""),D(null)}},onCancel:()=>{F(!1),D(null)}}),(M||k)&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-8 max-w-md w-full mx-4 text-center",children:[a.jsx("div",{className:"flex justify-center mb-4",children:a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),a.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),a.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:M?"Creating Backup":"Restoring Backup"}),a.jsx("p",{className:"text-bambu-gray mb-4",children:C||(M?"Preparing...":"Processing...")}),a.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[a.jsx(En,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-yellow-200 text-left",children:"Please do not close this page or navigate away. This operation may take several minutes for large backups."})]})})]})})]})}function QKe(){const{t}=Yt(),{showToast:e}=Tn(),n=an(),[r,i]=_.useState({smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",smtp_security:"starttls",smtp_auth_enabled:!0,smtp_from_email:"",smtp_from_name:"BamBuddy"}),[s,o]=_.useState(""),{data:l,isLoading:c}=it({queryKey:["smtpSettings"],queryFn:()=>ae.getSMTPSettings()}),{data:u}=it({queryKey:["advancedAuthStatus"],queryFn:()=>ae.getAdvancedAuthStatus()});_.useEffect(()=>{l&&i({...l,smtp_password:""})},[l]);const d=dt({mutationFn:x=>ae.saveSMTPSettings(x),onSuccess:()=>{n.invalidateQueries({queryKey:["smtpSettings"]}),n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(t("settings.email.success.settingsSaved"),"success")},onError:x=>{e(x.message,"error")}}),h=dt({mutationFn:x=>ae.testSMTP(x),onSuccess:x=>{e(x.message,x.success?"success":"error")},onError:x=>{e(x.message,"error")}}),p=dt({mutationFn:x=>x?ae.enableAdvancedAuth():ae.disableAdvancedAuth(),onSuccess:x=>{n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(x.message,"success")},onError:x=>{e(x.message,"error")}}),m=()=>{if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.requiredFields"),"error");return}if(r.smtp_auth_enabled&&!r.smtp_username){e(t("settings.email.errors.usernameRequired"),"error");return}d.mutate(r)},b=()=>{if(!s){e(t("settings.email.errors.enterTestEmail"),"error");return}if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.smtpServerAndEmail"),"error");return}if(r.smtp_auth_enabled&&(!r.smtp_username||!r.smtp_password)){e(t("settings.email.errors.usernamePasswordRequired"),"error");return}h.mutate({smtp_host:r.smtp_host,smtp_port:r.smtp_port,smtp_username:r.smtp_username,smtp_password:r.smtp_password,smtp_security:r.smtp_security,smtp_auth_enabled:r.smtp_auth_enabled,smtp_from_email:r.smtp_from_email,test_recipient:s})},y=()=>{if(!u?.advanced_auth_enabled&&!u?.smtp_configured){e(t("settings.email.errors.configureSmtpFirst"),"error");return}p.mutate(!u?.advanced_auth_enabled)};return c?a.jsx("div",{className:"flex items-center justify-center p-12",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})}):a.jsxs("div",{className:"space-y-6",children:[u?.smtp_configured&&a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Q0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.advancedAuth")||"Advanced Authentication"})]}),a.jsx(Ne,{onClick:y,disabled:p.isPending,variant:u?.advanced_auth_enabled?"danger":"primary",children:u?.advanced_auth_enabled?a.jsxs(a.Fragment,{children:[a.jsx(_1,{className:"w-4 h-4"}),t("settings.email.disable")||"Disable"]}):a.jsxs(a.Fragment,{children:[a.jsx(kf,{className:"w-4 h-4"}),t("settings.email.enable")||"Enable"]})})]})}),a.jsx(Et,{children:a.jsx("div",{className:"space-y-4",children:u?.advanced_auth_enabled?a.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(mr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthEnabled")||"Advanced Authentication is enabled"}),a.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[a.jsx("li",{children:t("settings.email.feature1")||"Passwords are auto-generated and emailed to new users"}),a.jsx("li",{children:t("settings.email.feature2")||"Users can login with username or email"}),a.jsx("li",{children:t("settings.email.feature3")||"Forgot password feature is available"}),a.jsx("li",{children:t("settings.email.feature4")||"Admins can reset user passwords via email"})]})]})]})}):a.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(En,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthDisabled")||"Advanced Authentication is disabled"}),a.jsx("p",{className:"text-sm text-yellow-300",children:t("settings.email.advancedAuthDisabledDesc")||"Enable advanced authentication to activate email-based features for user management."})]})]})})})})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.smtpSettings")||"SMTP Configuration"})}),a.jsx(Et,{children:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[t("settings.email.smtpHost")||"SMTP Server"," *"]}),a.jsx("input",{type:"text",value:r.smtp_host,onChange:x=>i({...r,smtp_host:x.target.value}),placeholder:"smtp.gmail.com",className:"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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.smtpPort")||"SMTP Port"}),a.jsx("input",{type:"number",value:r.smtp_port,onChange:x=>i({...r,smtp_port:parseInt(x.target.value)||587}),placeholder:"587",className:"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"})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.security")||"Security"}),a.jsxs("select",{value:r.smtp_security,onChange:x=>i({...r,smtp_security:x.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",children:[a.jsx("option",{value:"starttls",children:t("settings.email.securityOptions.starttls")}),a.jsx("option",{value:"ssl",children:t("settings.email.securityOptions.ssl")}),a.jsx("option",{value:"none",children:t("settings.email.securityOptions.none")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.authentication")||"Authentication"}),a.jsxs("select",{value:r.smtp_auth_enabled?"true":"false",onChange:x=>i({...r,smtp_auth_enabled:x.target.value==="true"}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",children:[a.jsx("option",{value:"true",children:t("settings.email.authOptions.enabled")}),a.jsx("option",{value:"false",children:t("settings.email.authOptions.disabled")})]})]})]}),r.smtp_auth_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.username")||"Username"}),a.jsx("input",{type:"text",value:r.smtp_username||"",onChange:x=>i({...r,smtp_username:x.target.value}),placeholder:"your.email@gmail.com",className:"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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.password")||"Password"}),a.jsx("input",{type:"password",value:r.smtp_password||"",onChange:x=>i({...r,smtp_password:x.target.value}),placeholder:l?"••••••••":"App password",className:"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"})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[t("settings.email.fromEmail")||"From Email"," *"]}),a.jsx("input",{type:"email",value:r.smtp_from_email,onChange:x=>i({...r,smtp_from_email:x.target.value}),placeholder:"your@email.com",className:"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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.fromName")||"From Name"}),a.jsx("input",{type:"text",value:r.smtp_from_name,onChange:x=>i({...r,smtp_from_name:x.target.value}),placeholder:"BamBuddy",className:"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"})]})]}),a.jsx("div",{className:"flex gap-2",children:a.jsx(Ne,{onClick:m,disabled:d.isPending,className:"flex-1",children:d.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),t("settings.email.saving")||"Saving..."]}):t("settings.email.save")||"Save Settings"})})]})})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.testConnection")||"Test SMTP Connection"})}),a.jsx(Et,{children:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.testRecipient")||"Test Recipient Email"}),a.jsx("input",{type:"email",value:s,onChange:x=>o(x.target.value),placeholder:"test@example.com",className:"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"})]}),a.jsx(Ne,{onClick:b,disabled:h.isPending,variant:"secondary",children:h.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),t("settings.email.sending")||"Sending..."]}):a.jsxs(a.Fragment,{children:[a.jsx(kk,{className:"w-4 h-4"}),t("settings.email.sendTest")||"Send Test Email"]})})]})})]})]})}const ZKe={get:"bg-blue-500/20 text-blue-400 border-blue-500/30",post:"bg-green-500/20 text-green-400 border-green-500/30",put:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",patch:"bg-orange-500/20 text-orange-400 border-orange-500/30",delete:"bg-red-500/20 text-red-400 border-red-500/30"};function JKe(t,e){const n=e.replace("#/","").split("/");let r=t;for(const i of n)r=r[i];return r}function y0(t,e,n=0){if(n>5)return"...";if(e.$ref)return y0(t,JKe(t,e.$ref),n+1);if(e.allOf){const r={};for(const i of e.allOf){const s=y0(t,i,n+1);typeof s=="object"&&s!==null&&Object.assign(r,s)}return r}if(e.example!==void 0)return e.example;if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:"string";case"integer":case"number":return 0;case"boolean":return!1;case"array":return e.items?[y0(t,e.items,n+1)]:[];case"object":if(e.properties){const r={};for(const[i,s]of Object.entries(e.properties))r[i]=y0(t,s,n+1);return r}return{};default:return null}}function eXe({path:t,method:e,spec:n,schema:r,apiKey:i}){const[s,o]=_.useState(!1),[l,c]=_.useState({}),[u,d]=_.useState(""),[h,p]=_.useState(null),[m,b]=_.useState(!1),[y,x]=_.useState(!1);_.useEffect(()=>{if(s&&n.parameters){const R={};for(const C of n.parameters)C.schema?.default!==void 0&&(R[C.name]=String(C.schema.default));c(C=>({...R,...C}))}},[s,n.parameters]),_.useEffect(()=>{if(s&&n.requestBody?.content?.["application/json"]?.schema&&!u){const R=n.requestBody.content["application/json"].schema,C=y0(r,R);d(JSON.stringify(C,null,2))}},[s,n.requestBody,r,u]);const S=(()=>{const R=[];for(const C of n.parameters||[])if(C.in==="path"||C.required){const P=l[C.name];(P===void 0||P==="")&&R.push(C.name)}return R})(),N=async()=>{if(S.length>0){p({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${S.join(", ")}`,duration:0});return}b(!0),p(null);try{let R=t;const C=new URLSearchParams;for(const oe of n.parameters||[]){const B=l[oe.name];B!==void 0&&B!==""&&(oe.in==="path"?R=R.replace(`{${oe.name}}`,encodeURIComponent(B)):oe.in==="query"&&C.append(oe.name,B))}const P=C.toString(),U=`${R}${P?`?${P}`:""}`,F={"Content-Type":"application/json"};i&&(F["X-API-Key"]=i);const H={method:e.toUpperCase(),headers:F};["post","put","patch"].includes(e)&&u&&(H.body=u);const D=performance.now(),$=await fetch(U,H),G=Math.round(performance.now()-D),I={};$.headers.forEach((oe,B)=>{I[B]=oe});let K;$.headers.get("content-type")?.includes("application/json")?K=await $.json():K=await $.text(),p({status:$.status,statusText:$.statusText,headers:I,body:K,duration:G})}catch(R){p({status:0,statusText:"Network Error",headers:{},body:R instanceof Error?R.message:"Unknown error",duration:0})}finally{b(!1)}},T=async()=>{if(h){const R=typeof h.body=="string"?h.body:JSON.stringify(h.body,null,2);try{await navigator.clipboard.writeText(R),x(!0),setTimeout(()=>x(!1),2e3)}catch{const C=document.createElement("textarea");C.value=R,C.style.position="fixed",C.style.left="-999999px",document.body.appendChild(C),C.select(),document.execCommand("copy"),document.body.removeChild(C),x(!0),setTimeout(()=>x(!1),2e3)}}},M=(n.parameters||[]).filter(R=>R.in==="path"),A=(n.parameters||[]).filter(R=>R.in==="query"),k=["post","put","patch"].includes(e)&&n.requestBody;return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center gap-3 p-3 hover:bg-bambu-dark-tertiary/50 transition-colors text-left",children:[s?a.jsx(fr,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):a.jsx(ks,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:`px-2 py-0.5 text-xs font-mono font-semibold uppercase rounded border ${ZKe[e]||"bg-gray-500/20 text-gray-400"}`,children:e}),a.jsx("code",{className:"text-sm text-white font-mono flex-1 truncate",children:t}),n.summary&&a.jsx("span",{className:"text-sm text-bambu-gray truncate max-w-[40%]",children:n.summary})]}),s&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary p-4 space-y-4 bg-bambu-dark/50",children:[n.description&&a.jsx("p",{className:"text-sm text-bambu-gray",children:n.description}),M.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Path Parameters"}),a.jsx("div",{className:"space-y-2",children:M.map(R=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[R.name,R.required&&a.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),a.jsx("input",{type:"text",value:l[R.name]||"",onChange:C=>c(P=>({...P,[R.name]:C.target.value})),placeholder:R.description||R.schema?.type||"value",className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none"})]},R.name))})]}),A.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Query Parameters"}),a.jsx("div",{className:"space-y-2",children:A.map(R=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[R.name,R.required&&a.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),R.schema?.enum?a.jsxs("select",{value:l[R.name]||"",onChange:C=>c(P=>({...P,[R.name]:C.target.value})),className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:"-- Select --"}),R.schema.enum.map(C=>a.jsx("option",{value:C,children:C},C))]}):a.jsx("input",{type:"text",value:l[R.name]||"",onChange:C=>c(P=>({...P,[R.name]:C.target.value})),placeholder:R.description||R.schema?.type||"value",className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none"})]},R.name))})]}),k&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Request Body"}),a.jsx("textarea",{value:u,onChange:R=>d(R.target.value),rows:8,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono focus:border-bambu-green focus:outline-none resize-y",placeholder:"JSON request body..."})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ne,{onClick:N,disabled:m,children:[m?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Eo,{className:"w-4 h-4"}),"Execute"]}),S.length>0&&a.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[a.jsx(Ti,{className:"w-3 h-3"}),"Fill in: ",S.join(", ")]})]}),h&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h4",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Response",a.jsxs("span",{className:`px-2 py-0.5 text-xs rounded ${h.status>=200&&h.status<300?"bg-green-500/20 text-green-400":h.status>=400?"bg-red-500/20 text-red-400":"bg-yellow-500/20 text-yellow-400"}`,children:[h.status," ",h.statusText]}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[h.duration,"ms"]})]}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:T,children:y?a.jsx(mr,{className:"w-3 h-3 text-green-400"}):a.jsx(zl,{className:"w-3 h-3"})})]}),a.jsx("pre",{className:"p-3 bg-bambu-dark rounded-lg text-sm font-mono text-white overflow-auto max-h-96 border border-bambu-dark-tertiary",children:typeof h.body=="string"?h.body:JSON.stringify(h.body,null,2)})]})]})]})}function tXe({apiKey:t=""}){const[e,n]=_.useState(null),[r,i]=_.useState(!0),[s,o]=_.useState(null),[l,c]=_.useState(new Set),[u,d]=_.useState("");if(_.useEffect(()=>{async function x(){try{const v=await fetch("/openapi.json");if(!v.ok)throw new Error("Failed to fetch OpenAPI schema");const S=await v.json();n(S)}catch(v){o(v instanceof Error?v.message:"Unknown error")}finally{i(!1)}}x()},[]),r)return a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(s||!e)return a.jsx(St,{children:a.jsx(Et,{className:"py-8",children:a.jsxs("div",{className:"text-center text-red-400",children:[a.jsx(Ti,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),a.jsx("p",{children:"Failed to load API schema"}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:s})]})})});const h={};for(const[x,v]of Object.entries(e.paths))for(const[S,N]of Object.entries(v)){if(S==="parameters")continue;const T=N.tags||["Other"];for(const M of T)h[M]||(h[M]=[]),h[M].push({path:x,method:S,spec:N})}const p=Object.entries(h).map(([x,v])=>{if(!u)return{tag:x,endpoints:v};const S=v.filter(({path:N,method:T,spec:M})=>{const A=u.toLowerCase();return N.toLowerCase().includes(A)||T.toLowerCase().includes(A)||(M.summary?.toLowerCase()||"").includes(A)||(M.description?.toLowerCase()||"").includes(A)});return{tag:x,endpoints:S}}).filter(({endpoints:x})=>x.length>0).sort((x,v)=>x.tag.localeCompare(v.tag)),m=x=>{c(v=>{const S=new Set(v);return S.has(x)?S.delete(x):S.add(x),S})},b=()=>{c(new Set(p.map(x=>x.tag)))},y=()=>{c(new Set)};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-4",children:[a.jsx("div",{className:"flex-1",children:a.jsx("input",{type:"text",value:u,onChange:x=>d(x.target.value),placeholder:"Search endpoints...",className:"w-full max-w-md px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ne,{variant:"secondary",size:"sm",onClick:b,children:"Expand All"}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:y,children:"Collapse All"}),a.jsxs("a",{href:"/docs",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-bambu-green hover:underline",children:[a.jsx(Xr,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[p.reduce((x,v)=>x+v.endpoints.length,0)," endpoints in ",p.length," categories"]}),a.jsx("div",{className:"space-y-3",children:p.map(({tag:x,endpoints:v})=>a.jsxs(St,{children:[a.jsx("button",{onClick:()=>m(x),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/30 transition-colors text-left",children:a.jsxs("div",{className:"flex items-center gap-2",children:[l.has(x)?a.jsx(fr,{className:"w-5 h-5 text-bambu-gray"}):a.jsx(ks,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:x.replace(/-/g," ")}),a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-2 py-0.5 rounded-full text-bambu-gray",children:v.length})]})}),l.has(x)&&a.jsx(Et,{className:"pt-0 space-y-2",children:v.map(({path:S,method:N,spec:T})=>a.jsx(eXe,{path:S,method:N,spec:T,schema:e,apiKey:t},`${N}-${S}`))})]},x))})]})}const nXe=["general","network","plugs","email","notifications","filament","apikeys","virtual-printer","users","backup"];function rXe(){const t=an(),e=Ec(),[n,r]=RR(),{t:i,i18n:s}=Yt(),{showToast:o}=Tn(),{authEnabled:l,user:c,refreshAuth:u}=Ir(),{mode:d,darkStyle:h,darkBackground:p,darkAccent:m,lightStyle:b,lightBackground:y,lightAccent:x,setDarkStyle:v,setDarkBackground:S,setDarkAccent:N,setLightStyle:T,setLightBackground:M,setLightAccent:A}=Dm(),[k,R]=_.useState(null),[C,P]=_.useState(!1),[U,F]=_.useState(null),[H,D]=_.useState(!1),[$,G]=_.useState(null),[I,K]=_.useState(null),[Q,oe]=_.useState(!1),[B,W]=_.useState(QW()),J=n.get("tab"),ne=J&&nXe.includes(J)?J:"general",[me,fe]=_.useState(ne),de=ie=>{fe(ie),ie==="general"?n.delete("tab"):n.set("tab",ie),r(n,{replace:!0})},[Re,se]=_.useState(!1),[ke,Fe]=_.useState(""),[ce,Ve]=_.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0}),[V,Y]=_.useState(null),[ue,q]=_.useState(null),[re,X]=_.useState(""),[le,pe]=_.useState(!1),[ee,z]=_.useState(!1),[O,Z]=_.useState(null),[ge,Ce]=_.useState(!1),[_e,Te]=_.useState(!1),[we,$e]=_.useState(!1),[Ge,ze]=_.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[be,Me]=_.useState(!1),[Be,Ae]=_.useState(!1),[qe,ve]=_.useState(!1),[et,Ee]=_.useState(null),[Ye,je]=_.useState(null),[Pe,ye]=_.useState(null),[Qe,yt]=_.useState(!1),[at,Ut]=_.useState({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),[zt,Ie]=_.useState(!1),[vt,Gt]=_.useState(null),[dn,fn]=_.useState(null),[vn,dr]=_.useState({name:"",description:"",permissions:[]}),[ar,kn]=_.useState(new Set),[Bn,Hr]=_.useState(null),[Ma,De]=_.useState(!1),[tt,ht]=_.useState({}),[mt,ut]=_.useState({}),Dt=ie=>{W(ie),Zfe(ie),o(i("settings.toast.settingsSaved"),"success")},he=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},{data:Le,isLoading:Ke}=it({queryKey:["settings"],queryFn:ae.getSettings}),{data:Ue,isLoading:Se}=it({queryKey:["smart-plugs"],queryFn:ae.getSmartPlugs}),{data:nt,isLoading:xt}=it({queryKey:["smart-plugs-energy",Ue?.map(ie=>ie.id)],queryFn:async()=>{if(!Ue||Ue.length===0)return null;const ie=await Promise.all(Ue.filter(Ca=>Ca.enabled).map(async Ca=>{try{const fs=await ae.getSmartPlugStatus(Ca.id);return{plug:Ca,status:fs}}catch{return{plug:Ca,status:null}}}));let kt=0,Hn=0,ir=0,jo=0,cd=0;for(const{plug:Ca,status:fs}of ie){const r2=Ca.plug_type==="mqtt"&&fs?.energy?.power!=null;(fs?.reachable||r2)&&fs?.energy&&(cd++,fs.energy?.power!=null&&(kt+=fs.energy.power),fs.energy?.today!=null&&(Hn+=fs.energy.today),fs.energy?.yesterday!=null&&(ir+=fs.energy.yesterday),fs.energy?.total!=null&&(jo+=fs.energy.total))}return{totalPower:kt,totalToday:Hn,totalYesterday:ir,totalLifetime:jo,reachableCount:cd,totalPlugs:Ue.filter(Ca=>Ca.enabled).length}},enabled:me==="plugs"&&!!Ue&&Ue.length>0,refetchInterval:me==="plugs"?1e4:!1}),{data:rt,isLoading:Ct}=it({queryKey:["notification-providers"],queryFn:ae.getNotificationProviders}),{data:It,isLoading:Rt}=it({queryKey:["api-keys"],queryFn:ae.getAPIKeys}),Tt=dt({mutationFn:ie=>ae.createAPIKey(ie),onSuccess:ie=>{Y(ie.key||null),se(!1),Fe(""),t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyCreated"))},onError:ie=>{o(`Failed to create API key: ${ie.message}`,"error")}}),mn=dt({mutationFn:ie=>ae.deleteAPIKey(ie),onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyDeleted"))},onError:ie=>{o(`Failed to delete API key: ${ie.message}`,"error")}}),{data:Bt}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:pn,isLoading:Mn}=it({queryKey:["notification-templates"],queryFn:ae.getNotificationTemplates}),{data:jn}=it({queryKey:["virtual-printer-settings"],queryFn:S1.getSettings,refetchInterval:1e4}),Kt=jn?.status?.running??!1,{data:Qt}=it({queryKey:["ffmpeg-status"],queryFn:ae.checkFfmpeg}),{data:Zt}=it({queryKey:["version"],queryFn:ae.getVersion}),{data:cn,refetch:$r,isRefetching:Qn}=it({queryKey:["updateCheck"],queryFn:ae.checkForUpdates,staleTime:300*1e3}),{data:ai,refetch:gt}=it({queryKey:["updateStatus"],queryFn:ae.getUpdateStatus,refetchInterval:ie=>{const kt=ie.state.data;return kt?.status==="downloading"||kt?.status==="installing"?1e3:!1}}),{data:jt}=it({queryKey:["mqtt-status"],queryFn:ae.getMQTTStatus,refetchInterval:me==="network"?5e3:!1}),{data:gn}=it({queryKey:["github-backup-status"],queryFn:ae.getGitHubBackupStatus}),{data:Nt}=it({queryKey:["cloud-status"],queryFn:ae.getCloudStatus}),{data:un={advanced_auth_enabled:!1,smtp_configured:!1}}=it({queryKey:["advancedAuthStatus"],queryFn:()=>ae.getAdvancedAuthStatus()}),{hasPermission:In}=Ir(),{data:rr=[],isLoading:ua}=it({queryKey:["users"],queryFn:()=>ae.getUsers(),enabled:l&&In("users:read")}),{data:Si=[],isLoading:Jt}=it({queryKey:["groups"],queryFn:()=>ae.getGroups(),enabled:l&&In("groups:read")}),{data:wn}=it({queryKey:["permissions"],queryFn:()=>ae.getPermissions(),enabled:l&&In("groups:read")}),Ea=dt({mutationFn:ie=>ae.createUser(ie),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Ae(!1),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userCreated"))},onError:ie=>{o(ie.message,"error")}}),Ta=dt({mutationFn:({id:ie,data:kt})=>ae.updateUser(ie,kt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),ve(!1),Ee(null),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userUpdated"))},onError:ie=>{o(ie.message,"error")}}),si=dt({mutationFn:({id:ie,deleteItems:kt})=>ae.deleteUser(ie,kt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),o(i("settings.toast.userDeleted")),je(null),ye(null)},onError:ie=>{o(ie.message,"error")}}),yl=dt({mutationFn:ie=>ae.resetUserPassword({user_id:ie}),onSuccess:ie=>{o(ie.message,"success")},onError:ie=>{o(ie.message,"error")}}),Pc=async ie=>{je(ie),yt(!0);try{const kt=await ae.getUserItemsCount(ie);ye(kt)}catch{ye({archives:0,queue_items:0,library_files:0})}finally{yt(!1)}},us=dt({mutationFn:ie=>ae.createGroup(ie),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),Ie(!1),da(),o(i("settings.toast.groupCreated"))},onError:ie=>{o(ie.message,"error")}}),ds=dt({mutationFn:({id:ie,data:kt})=>ae.updateGroup(ie,kt),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),Gt(null),da(),o(i("settings.toast.groupUpdated"))},onError:ie=>{o(ie.message,"error")}}),jc=dt({mutationFn:ie=>ae.deleteGroup(ie),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),o(i("settings.toast.groupDeleted"))},onError:ie=>{o(ie.message,"error")}}),hs=()=>{const ie=un?.advanced_auth_enabled||!1;if(!at.username){o(i("settings.toast.fillRequiredFields"),"error");return}if(ie&&!at.email){o("Email is required when advanced authentication is enabled","error");return}if(!ie){if(!at.password){o(i("settings.toast.fillRequiredFields"),"error");return}if(at.password!==at.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(at.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}}Ea.mutate({username:at.username,password:ie?void 0:at.password,email:at.email||void 0,role:at.role,group_ids:at.group_ids.length>0?at.group_ids:void 0})},Po=ie=>{if(at.password){if(at.password!==at.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(at.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}}const kt={username:at.username||void 0,password:at.password||void 0,role:at.role,group_ids:at.group_ids};kt.password||delete kt.password,Ta.mutate({id:ie,data:kt})},Aa=ie=>{Ee(ie.id),Ut({username:ie.username,password:"",email:ie.email||"",confirmPassword:"",role:ie.role,group_ids:ie.groups?.map(kt=>kt.id)||[]}),ve(!0)},_r=ie=>{Ut(kt=>({...kt,group_ids:kt.group_ids.includes(ie)?kt.group_ids.filter(Hn=>Hn!==ie):[...kt.group_ids,ie]}))},da=()=>{dr({name:"",description:"",permissions:[]}),kn(new Set)},eo=()=>{if(!vn.name.trim()){o(i("settings.toast.enterGroupName"),"error");return}us.mutate({name:vn.name,description:vn.description||void 0,permissions:vn.permissions})},Qr=()=>{if(vt){if(!vn.name.trim()){o(i("settings.toast.enterGroupName"),"error");return}ds.mutate({id:vt.id,data:{name:vn.name!==vt.name?vn.name:void 0,description:vn.description,permissions:vn.permissions}})}},Vb=ie=>{Gt(ie),dr({name:ie.name,description:ie.description||"",permissions:ie.permissions});const kt=new Set;wn?.categories.forEach(Hn=>{Hn.permissions.some(ir=>ie.permissions.includes(ir.value))&&kt.add(Hn.name)}),kn(kt)},Um=ie=>{kn(kt=>{const Hn=new Set(kt);return Hn.has(ie)?Hn.delete(ie):Hn.add(ie),Hn})},Av=ie=>{dr(kt=>{const Hn=kt.permissions.includes(ie)?kt.permissions.filter(ir=>ir!==ie):[...kt.permissions,ie];return{...kt,permissions:Hn}})},Bm=(ie,kt)=>{dr(Hn=>{const ir=ie.permissions.map(Ca=>Ca.value),jo=Hn.permissions.filter(Ca=>!ir.includes(Ca)),cd=kt?[...jo,...ir]:jo;return{...Hn,permissions:cd}})},ad=ie=>ie.permissions.every(kt=>vn.permissions.includes(kt.value)),Gb=ie=>{const kt=ie.permissions.filter(Hn=>vn.permissions.includes(Hn.value));return kt.length>0&&kt.length{ie.is_docker?o(ie.message,"error"):gt()}}),[js,sd]=_.useState(null),Dc=dt({mutationFn:ae.testAllNotificationProviders,onSuccess:ie=>{sd(ie),t.invalidateQueries({queryKey:["notification-providers"]}),ie.failed===0?o(`All ${ie.tested} providers tested successfully!`,"success"):o(`${ie.success}/${ie.tested} providers succeeded`,ie.failed>0?"error":"success")},onError:ie=>{o(`Failed to test providers: ${ie.message}`,"error")}}),Xh=dt({mutationFn:async ie=>{if(!Ue)return{success:0,failed:0};const kt=Ue.filter(ir=>ir.enabled),Hn=await Promise.all(kt.map(async ir=>{try{return await ae.controlSmartPlug(ir.id,ie),{success:!0}}catch{return{success:!1}}}));return{success:Hn.filter(ir=>ir.success).length,failed:Hn.filter(ir=>!ir.success).length}},onSuccess:(ie,kt)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),ie.failed===0?o(`All ${ie.success} plugs turned ${kt}`,"success"):o(`${ie.success} plugs turned ${kt}, ${ie.failed} failed`,"error")},onError:ie=>{o(`Failed: ${ie.message}`,"error")}}),Rc=_.useRef(null),od=_.useRef(!1),ld=_.useRef(!0);_.useEffect(()=>{if(Le&&!k){const ie={...Le,external_url:Le.external_url||window.location.origin};R(ie),setTimeout(()=>{ld.current=!1},100)}},[Le,k]);const Yh=dt({mutationFn:ae.updateSettings,onSuccess:ie=>{t.setQueryData(["settings"],ie),R(ie),t.invalidateQueries({queryKey:["archiveStats"]}),o(i("settings.toast.settingsSaved"),"success")},onError:ie=>{o(`Failed to save: ${ie.message}`,"error")},onSettled:()=>{od.current=!1}}),qb=dt({mutationFn:({id:ie,data:kt})=>ae.updatePrinter(ie,kt),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o(i("settings.toast.cameraSettingsSaved"),"success")},onError:ie=>{o(`Failed to update printer: ${ie.message}`,"error")}});_.useEffect(()=>{if(!(ld.current||!k||!Le||!(Le.auto_archive!==k.auto_archive||Le.save_thumbnails!==k.save_thumbnails||Le.capture_finish_photo!==k.capture_finish_photo||Le.default_filament_cost!==k.default_filament_cost||Le.currency!==k.currency||Le.energy_cost_per_kwh!==k.energy_cost_per_kwh||Le.energy_tracking_mode!==k.energy_tracking_mode||Le.check_updates!==k.check_updates||(Le.check_printer_firmware??!0)!==(k.check_printer_firmware??!0)||Le.notification_language!==k.notification_language||Le.ams_humidity_good!==k.ams_humidity_good||Le.ams_humidity_fair!==k.ams_humidity_fair||Le.ams_temp_good!==k.ams_temp_good||Le.ams_temp_fair!==k.ams_temp_fair||Le.ams_history_retention_days!==k.ams_history_retention_days||Le.per_printer_mapping_expanded!==k.per_printer_mapping_expanded||Le.date_format!==k.date_format||Le.time_format!==k.time_format||Le.default_printer_id!==k.default_printer_id||Le.ftp_retry_enabled!==k.ftp_retry_enabled||Le.ftp_retry_count!==k.ftp_retry_count||Le.ftp_retry_delay!==k.ftp_retry_delay||Le.ftp_timeout!==k.ftp_timeout||Le.mqtt_enabled!==k.mqtt_enabled||Le.mqtt_broker!==k.mqtt_broker||Le.mqtt_port!==k.mqtt_port||Le.mqtt_username!==k.mqtt_username||Le.mqtt_password!==k.mqtt_password||Le.mqtt_topic_prefix!==k.mqtt_topic_prefix||Le.mqtt_use_tls!==k.mqtt_use_tls||Le.external_url!==k.external_url||Le.ha_enabled!==k.ha_enabled||Le.ha_url!==k.ha_url||Le.ha_token!==k.ha_token||(Le.library_archive_mode??"ask")!==(k.library_archive_mode??"ask")||Number(Le.library_disk_warning_gb??5)!==Number(k.library_disk_warning_gb??5)||(Le.camera_view_mode??"window")!==(k.camera_view_mode??"window")||(Le.preferred_slicer??"bambu_studio")!==(k.preferred_slicer??"bambu_studio")||Le.prometheus_enabled!==k.prometheus_enabled||Le.prometheus_token!==k.prometheus_token))&&!od.current)return Rc.current&&clearTimeout(Rc.current),Rc.current=setTimeout(()=>{if(od.current)return;od.current=!0;const kt={auto_archive:k.auto_archive,save_thumbnails:k.save_thumbnails,capture_finish_photo:k.capture_finish_photo,default_filament_cost:k.default_filament_cost,currency:k.currency,energy_cost_per_kwh:k.energy_cost_per_kwh,energy_tracking_mode:k.energy_tracking_mode,check_updates:k.check_updates,check_printer_firmware:k.check_printer_firmware,notification_language:k.notification_language,ams_humidity_good:k.ams_humidity_good,ams_humidity_fair:k.ams_humidity_fair,ams_temp_good:k.ams_temp_good,ams_temp_fair:k.ams_temp_fair,ams_history_retention_days:k.ams_history_retention_days,per_printer_mapping_expanded:k.per_printer_mapping_expanded,date_format:k.date_format,time_format:k.time_format,default_printer_id:k.default_printer_id,ftp_retry_enabled:k.ftp_retry_enabled,ftp_retry_count:k.ftp_retry_count,ftp_retry_delay:k.ftp_retry_delay,ftp_timeout:k.ftp_timeout,mqtt_enabled:k.mqtt_enabled,mqtt_broker:k.mqtt_broker,mqtt_port:k.mqtt_port,mqtt_username:k.mqtt_username,mqtt_password:k.mqtt_password,mqtt_topic_prefix:k.mqtt_topic_prefix,mqtt_use_tls:k.mqtt_use_tls,external_url:k.external_url,ha_enabled:k.ha_enabled,ha_url:k.ha_url,ha_token:k.ha_token,library_archive_mode:k.library_archive_mode,library_disk_warning_gb:k.library_disk_warning_gb,camera_view_mode:k.camera_view_mode,preferred_slicer:k.preferred_slicer,prometheus_enabled:k.prometheus_enabled,prometheus_token:k.prometheus_token};Yh.mutate(kt)},500),()=>{Rc.current&&clearTimeout(Rc.current)}},[k,Le,Yh]);const Sn=_.useCallback((ie,kt)=>{R(Hn=>Hn?{...Hn,[ie]:kt}:null)},[]),t2=async(ie,kt,Hn)=>{if(!kt){o(i("settings.toast.enterCameraUrl"),"error");return}ut(ir=>({...ir,[ie]:!0})),ht(ir=>({...ir,[ie]:null}));try{const ir=await ae.testExternalCamera(ie,kt,Hn);ht(jo=>({...jo,[ie]:ir})),ir.success?o(i("settings.toast.cameraConnected",{resolution:ir.resolution||""}),"success"):o(ir.error||i("settings.toast.connectionFailed"),"error")}catch(ir){const jo=ir instanceof Error?ir.message:i("settings.toast.testFailed");ht(cd=>({...cd,[ie]:{success:!1,error:jo}})),o(jo,"error")}finally{ut(ir=>({...ir,[ie]:!1}))}},[Wb,Hm]=_.useState({}),Kb=_.useRef({}),Cv=_.useRef(new Set);_.useEffect(()=>{if(Bt){const ie={};Bt.forEach(kt=>{kt.external_camera_url&&!Cv.current.has(kt.id)&&(ie[kt.id]=kt.external_camera_url,Cv.current.add(kt.id))}),Object.keys(ie).length>0&&Hm(kt=>({...kt,...ie}))}},[Bt]);const n2=(ie,kt)=>{Hm(Hn=>({...Hn,[ie]:kt})),Kb.current[ie]&&clearTimeout(Kb.current[ie]),Kb.current[ie]=setTimeout(()=>{qb.mutate({id:ie,data:{external_camera_url:kt||null}})},800)},Pv=(ie,kt)=>{const Hn={};kt.type!==void 0&&(Hn.external_camera_type=kt.type||null),kt.enabled!==void 0&&(Hn.external_camera_enabled=kt.enabled),qb.mutate({id:ie,data:Hn})};return Ke||!k?a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"mb-8",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:i("settings.title")}),a.jsx("p",{className:"text-bambu-gray",children:i("settings.configureBambuddy")})]}),a.jsxs("div",{className:"flex flex-wrap gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>de("general"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${me==="general"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:i("settings.tabs.general")}),a.jsxs("button",{onClick:()=>de("plugs"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(sl,{className:"w-4 h-4"}),i("settings.tabs.smartPlugs"),Ue&&Ue.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Ue.length})]}),a.jsxs("button",{onClick:()=>de("email"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="email"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Q0,{className:"w-4 h-4"}),i("settings.tabs.globalEmail")||"Global Email",un?.advanced_auth_enabled&&a.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),a.jsxs("button",{onClick:()=>de("notifications"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(kg,{className:"w-4 h-4"}),i("settings.tabs.notifications"),rt&&rt.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:rt.length})]}),a.jsxs("button",{onClick:()=>de("filament"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Rue,{className:"w-4 h-4"}),i("settings.tabs.filament")]}),a.jsxs("button",{onClick:()=>de("network"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Eg,{className:"w-4 h-4"}),i("settings.tabs.network"),a.jsx("span",{className:`w-2 h-2 rounded-full ${jt?.enabled?"bg-green-400":"bg-gray-500"}`})]}),a.jsxs("button",{onClick:()=>de("apikeys"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Yo,{className:"w-4 h-4"}),i("settings.tabs.apiKeys"),It&&It.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:It.length})]}),a.jsxs("button",{onClick:()=>de("virtual-printer"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(jr,{className:"w-4 h-4"}),i("settings.tabs.virtualPrinter"),a.jsx("span",{className:`w-2 h-2 rounded-full ${Kt?"bg-green-400":"bg-gray-500"}`})]}),a.jsxs("button",{onClick:()=>de("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(zf,{className:"w-4 h-4"}),i("settings.tabs.users"),l&&a.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),a.jsxs("button",{onClick:()=>de("backup"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Au,{className:"w-4 h-4"}),i("settings.tabs.backup"),a.jsx("span",{className:`w-2 h-2 rounded-full ${Nt?.is_authenticated&&gn?.configured&&gn?.enabled?"bg-green-400":"bg-gray-500"}`})]})]}),me==="general"&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[a.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-xl",children:[a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.general")})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(gh,{className:"w-4 h-4 inline mr-1"}),i("settings.language")]}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:s.language,onChange:ie=>{s.changeLanguage(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:PU.map(ie=>a.jsxs("option",{value:ie.code,children:[ie.nativeName," (",ie.name,")"]},ie.code))}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.languageDescription")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultView")}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:B,onChange:ie=>Dt(ie.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:J0.map(ie=>a.jsx("option",{value:ie.to,children:i(ie.labelKey)},ie.id))}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.defaultViewDescription")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date Format"}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k.date_format||"system",onChange:ie=>Sn("date_format",ie.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"system",children:i("settings.systemDefault")}),a.jsx("option",{value:"us",children:"US (MM/DD/YYYY)"}),a.jsx("option",{value:"eu",children:"EU (DD/MM/YYYY)"}),a.jsx("option",{value:"iso",children:"ISO (YYYY-MM-DD)"})]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Time Format"}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k.time_format||"system",onChange:ie=>Sn("time_format",ie.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"system",children:i("settings.systemDefault")}),a.jsx("option",{value:"12h",children:"12-hour (3:30 PM)"}),a.jsx("option",{value:"24h",children:"24-hour (15:30)"})]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default Printer"}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k.default_printer_id??"",onChange:ie=>Sn("default_printer_id",ie.target.value?Number(ie.target.value):null),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"",children:i("settings.noDefaultPrinter")}),Bt?.map(ie=>a.jsx("option",{value:ie.id,children:ie.name},ie.id))]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Pre-select this printer for uploads, reprints, and other operations."})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.preferredSlicer")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k.preferred_slicer??"bambu_studio",onChange:ie=>Sn("preferred_slicer",ie.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"bambu_studio",children:"Bambu Studio"}),a.jsx("option",{value:"orcaslicer",children:"OrcaSlicer"})]}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.preferredSlicerDescription")})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.sidebarOrder")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Drag items in the sidebar to reorder. Reset to default order here."})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:he,children:[a.jsx(Bu,{className:"w-4 h-4"}),"Reset"]})]})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(zW,{className:"w-5 h-5"}),"Appearance"]})}),a.jsxs(Et,{className:"space-y-6",children:[a.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${d==="dark"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Dark Mode",d==="dark"&&a.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),a.jsxs("select",{value:p,onChange:ie=>{S(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"neutral",children:"Neutral"}),a.jsx("option",{value:"warm",children:"Warm"}),a.jsx("option",{value:"cool",children:"Cool"}),a.jsx("option",{value:"oled",children:"OLED Black"}),a.jsx("option",{value:"slate",children:"Slate Blue"}),a.jsx("option",{value:"forest",children:"Forest Green"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),a.jsxs("select",{value:m,onChange:ie=>{N(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"green",children:"Green"}),a.jsx("option",{value:"teal",children:"Teal"}),a.jsx("option",{value:"blue",children:"Blue"}),a.jsx("option",{value:"orange",children:"Orange"}),a.jsx("option",{value:"purple",children:"Purple"}),a.jsx("option",{value:"red",children:"Red"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),a.jsxs("select",{value:h,onChange:ie=>{v(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"classic",children:"Classic"}),a.jsx("option",{value:"glow",children:"Glow"}),a.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),a.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${d==="light"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Light Mode",d==="light"&&a.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),a.jsxs("select",{value:y,onChange:ie=>{M(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"neutral",children:"Neutral"}),a.jsx("option",{value:"warm",children:"Warm"}),a.jsx("option",{value:"cool",children:"Cool"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),a.jsxs("select",{value:x,onChange:ie=>{A(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"green",children:"Green"}),a.jsx("option",{value:"teal",children:"Teal"}),a.jsx("option",{value:"blue",children:"Blue"}),a.jsx("option",{value:"orange",children:"Orange"}),a.jsx("option",{value:"purple",children:"Purple"}),a.jsx("option",{value:"red",children:"Red"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),a.jsxs("select",{value:b,onChange:ie=>{T(ie.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"classic",children:"Classic"}),a.jsx("option",{value:"glow",children:"Glow"}),a.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Toggle between dark and light mode using the sun/moon icon in the sidebar."})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.archiveSettings")})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:"Auto-archive prints"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically save 3MF files when prints complete"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.auto_archive,onChange:ie=>Sn("auto_archive",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.saveThumbnails")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Extract and save preview images from 3MF files"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.save_thumbnails,onChange:ie=>Sn("save_thumbnails",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.captureFinishPhoto")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Take a photo from printer camera when print completes"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.capture_finish_photo,onChange:ie=>Sn("capture_finish_photo",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),k.capture_finish_photo&&Qt&&!Qt.installed&&a.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[a.jsx(En,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-sm",children:[a.jsx("p",{className:"text-yellow-500 font-medium",children:"ffmpeg not installed"}),a.jsxs("p",{className:"text-bambu-gray mt-1",children:["Camera capture requires ffmpeg. Install it via"," ",a.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"brew install ffmpeg"})," (macOS) or"," ",a.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"apt install ffmpeg"})," (Linux)."]})]})]})]})]})]}),a.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-md",children:[a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(KR,{className:"w-5 h-5 text-bambu-green"}),"Camera"]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Camera View Mode"}),a.jsxs("select",{value:k.camera_view_mode??"window",onChange:ie=>Sn("camera_view_mode",ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"window",children:i("settings.newWindow")}),a.jsx("option",{value:"embedded",children:i("settings.embeddedOverlay")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:k.camera_view_mode==="embedded"?"Camera opens in a resizable overlay on the main screen":"Camera opens in a separate browser window"})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:i("settings.externalCameras")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Configure external cameras to replace the built-in printer camera. Supports MJPEG streams, RTSP, HTTP snapshots, and USB cameras (V4L2). When enabled, the external camera is used for live view and finish photos."}),Bt&&Bt.length>0?a.jsx("div",{className:"space-y-3",children:Bt.map(ie=>a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-white font-medium text-sm",children:ie.name}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ie.external_camera_enabled,onChange:kt=>Pv(ie.id,{enabled:kt.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),ie.external_camera_enabled&&a.jsxs("div",{className:"space-y-2 mt-2",children:[a.jsx("input",{type:"text",placeholder:ie.external_camera_type==="usb"?"Device path (/dev/video0)":"Camera URL (rtsp://... or http://...)",value:Wb[ie.id]??ie.external_camera_url??"",onChange:kt=>n2(ie.id,kt.target.value),className:"w-full 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:"flex gap-2",children:[a.jsxs("select",{value:ie.external_camera_type||"mjpeg",onChange:kt=>Pv(ie.id,{type:kt.target.value}),className:"flex-1 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",children:[a.jsx("option",{value:"mjpeg",children:"MJPEG Stream"}),a.jsx("option",{value:"rtsp",children:"RTSP Stream"}),a.jsx("option",{value:"snapshot",children:"HTTP Snapshot"}),a.jsx("option",{value:"usb",children:"USB Camera (V4L2)"})]}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:()=>t2(ie.id,Wb[ie.id]??ie.external_camera_url??"",ie.external_camera_type||"mjpeg"),disabled:mt[ie.id]||!(Wb[ie.id]??ie.external_camera_url),children:mt[ie.id]?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):"Test"})]}),tt[ie.id]&&a.jsx("div",{className:`text-xs flex items-center gap-1 ${tt[ie.id]?.success?"text-green-500":"text-red-500"}`,children:tt[ie.id]?.success?a.jsxs(a.Fragment,{children:[a.jsx(mr,{className:"w-3 h-3"}),"Connected",tt[ie.id]?.resolution&&` (${tt[ie.id]?.resolution})`]}):a.jsxs(a.Fragment,{children:[a.jsx(Zi,{className:"w-3 h-3"}),tt[ie.id]?.error||i("settings.toast.connectionFailed")]})})]})]},ie.id))}):a.jsx("p",{className:"text-xs text-bambu-gray italic",children:i("settings.noPrintersConfigured")})]})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.costTracking")})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default filament cost (per kg)"}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:k.default_filament_cost,onChange:ie=>Sn("default_filament_cost",parseFloat(ie.target.value)||0),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Currency"}),a.jsxs("select",{value:k.currency,onChange:ie=>Sn("currency",ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"USD",children:"USD ($)"}),a.jsx("option",{value:"EUR",children:"EUR (€)"}),a.jsx("option",{value:"GBP",children:"GBP (£)"}),a.jsx("option",{value:"CHF",children:"CHF (Fr.)"}),a.jsx("option",{value:"JPY",children:"JPY (¥)"}),a.jsx("option",{value:"CNY",children:"CNY (¥)"}),a.jsx("option",{value:"CAD",children:"CAD ($)"}),a.jsx("option",{value:"AUD",children:"AUD ($)"}),a.jsx("option",{value:"HKD",children:"HKD ($)"}),a.jsx("option",{value:"INR",children:"INR (₹)"}),a.jsx("option",{value:"KRW",children:"KRW (₩)"}),a.jsx("option",{value:"SEK",children:"SEK (kr)"}),a.jsx("option",{value:"NOK",children:"NOK (kr)"}),a.jsx("option",{value:"DKK",children:"DKK (kr)"}),a.jsx("option",{value:"PLN",children:"PLN (zł)"}),a.jsx("option",{value:"BRL",children:"BRL (R$)"}),a.jsx("option",{value:"TWD",children:"TWD ($)"}),a.jsx("option",{value:"SGD",children:"SGD ($)"}),a.jsx("option",{value:"NZD",children:"NZD ($)"}),a.jsx("option",{value:"MXN",children:"MXN ($)"}),a.jsx("option",{value:"CZK",children:"CZK (Kč)"}),a.jsx("option",{value:"THB",children:"THB (฿)"}),a.jsx("option",{value:"ZAR",children:"ZAR (R)"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Electricity cost per kWh"}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:k.energy_cost_per_kwh,onChange:ie=>Sn("energy_cost_per_kwh",parseFloat(ie.target.value)||0),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy display mode"}),a.jsxs("select",{value:k.energy_tracking_mode||"total",onChange:ie=>Sn("energy_tracking_mode",ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"print",children:i("settings.printsOnly")}),a.jsx("option",{value:"total",children:i("settings.totalConsumption")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:k.energy_tracking_mode==="print"?"Dashboard shows sum of energy used during prints":"Dashboard shows lifetime energy from smart plugs"})]})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ys,{className:"w-5 h-5 text-bambu-green"}),"File Manager"]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Create Archive Entry When Printing"}),a.jsxs("select",{value:k.library_archive_mode??"ask",onChange:ie=>Sn("library_archive_mode",ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"always",children:i("settings.archiveMode.always")}),a.jsx("option",{value:"never",children:i("settings.archiveMode.never")}),a.jsx("option",{value:"ask",children:i("settings.archiveMode.ask")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"When printing from File Manager, optionally create an archive entry"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Low Disk Space Warning"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:k.library_disk_warning_gb??5,onChange:ie=>Sn("library_disk_warning_gb",parseFloat(ie.target.value)||5),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:"GB"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Show warning when free disk space falls below this threshold"})]})]})]})]}),a.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-sm",children:[a.jsx(WKe,{}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Updates"})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.checkForUpdatesLabel")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically check for new versions on startup"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.check_updates,onChange:ie=>Sn("check_updates",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.checkPrinterFirmware")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Check for printer firmware updates from Bambu Lab"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.check_printer_firmware??!0,onChange:ie=>Sn("check_printer_firmware",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.currentVersion")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",Zt?.version||"..."]})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>$r(),disabled:Qn,children:[Qn?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Or,{className:"w-4 h-4"}),"Check now"]})]}),cn?.update_available?a.jsxs("div",{className:"mt-4 p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:[a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{children:[a.jsxs("p",{className:"text-bambu-green font-medium",children:["Update available: v",cn.latest_version]}),cn.release_name&&cn.release_name!==cn.latest_version&&a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:cn.release_name})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[cn.release_notes&&a.jsx("button",{onClick:()=>Ce(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:"Release Notes"}),cn.release_url&&a.jsx("a",{href:cn.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:i("settings.viewReleaseOnGitHub"),children:a.jsx(Xr,{className:"w-4 h-4"})})]})]}),ai?.status==="downloading"||ai?.status==="installing"?a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{children:ai.message})]}),a.jsx("div",{className:"mt-2 w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${ai.progress}%`}})})]}):ai?.status==="complete"?a.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:ai.message}):ai?.status==="error"?a.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:ai.error||ai.message}):cn?.is_docker?a.jsxs("div",{className:"mt-3 p-3 bg-bambu-dark-tertiary rounded-lg",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:"Update via Docker Compose:"}),a.jsx("code",{className:"block text-xs bg-bambu-dark p-2 rounded text-bambu-green font-mono",children:"docker compose pull && docker compose up -d"})]}):a.jsxs(Ne,{className:"mt-3",onClick:()=>ha.mutate(),disabled:ha.isPending,children:[ha.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(wi,{className:"w-4 h-4"}),"Install Update"]})]}):cn?.error?a.jsxs("div",{className:"mt-2 p-2 bg-red-500/10 border border-red-500/30 rounded text-sm text-red-400",children:["Failed to check for updates: ",cn.error]}):cn&&!cn.update_available?a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:"You're running the latest version"}):null]})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.dataManagement")})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.clearNotificationLogs")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.clearNotificationLogsDescription")})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>pe(!0),children:[a.jsx(ln,{className:"w-4 h-4"}),i("common.clear")]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.resetUiPreferences")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.resetUiPreferencesDescription")})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>z(!0),children:[a.jsx(ln,{className:"w-4 h-4"}),"Reset"]})]}),a.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:"Backup & Restore"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Export/import settings and configure GitHub backup"})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>de("backup"),children:[a.jsx(Au,{className:"w-4 h-4"}),"Go to Backup"]})]})]})]})]})]}),me==="network"&&k&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(gh,{className:"w-5 h-5 text-blue-400"}),"External URL"]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"The external URL where Bambuddy is accessible. Used for notification images and external integrations."}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bambuddy URL"}),a.jsx("input",{type:"text",value:k.external_url??"",onChange:ie=>Sn("external_url",ie.target.value),placeholder:"http://192.168.1.100:8000",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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Include protocol and port (e.g., http://192.168.1.100:8000)"})]})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Or,{className:"w-5 h-5 text-blue-400"}),"FTP Retry"]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Retry FTP operations when printer WiFi is unreliable. Applies to 3MF downloads, print uploads, timelapse downloads, and firmware updates."}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableRetry")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically retry failed FTP operations"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.ftp_retry_enabled??!0,onChange:ie=>Sn("ftp_retry_enabled",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),k.ftp_retry_enabled&&a.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry attempts"}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:k.ftp_retry_count??3,onChange:ie=>Sn("ftp_retry_count",parseInt(ie.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[1,2,3,4,5,6,7,8,9,10].map(ie=>a.jsxs("option",{value:ie,children:[ie," ",ie===1?"time":"times"]},ie))}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry delay"}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:k.ftp_retry_delay??2,onChange:ie=>Sn("ftp_retry_delay",parseInt(ie.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[1,2,3,5,10,15,20,30].map(ie=>a.jsxs("option",{value:ie,children:[ie," ",ie===1?"second":"seconds"]},ie))}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Connection timeout"}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:k.ftp_timeout??30,onChange:ie=>Sn("ftp_timeout",parseInt(ie.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[10,15,20,30,45,60,90,120].map(ie=>a.jsxs("option",{value:ie,children:[ie," seconds"]},ie))}),a.jsx(fr,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Increase for printers with weak WiFi"})]})]})]})]})]}),a.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Hy,{className:"w-5 h-5 text-bambu-green"}),"Home Assistant"]}),k.ha_enabled&&Bn&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${Bn.success?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:`text-sm ${Bn.success?"text-green-400":"text-red-400"}`,children:Bn.success?"Connected":"Disconnected"})]})]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Connect to Home Assistant to control smart plugs via HA's REST API. Supports switch, light, input_boolean, and script entities."}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-white",children:i("settings.enableHomeAssistant")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.homeAssistantDescription")}),k.ha_env_managed&&a.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[a.jsx(kf,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:i("settings.autoEnabledViaEnv")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.ha_enabled??!1,onChange:ie=>Sn("ha_enabled",ie.target.checked),disabled:k.ha_env_managed,className:"sr-only peer"}),a.jsx("div",{className:`w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green ${k.ha_env_managed?"opacity-60 cursor-not-allowed":""}`})]})]}),k.ha_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Home Assistant URL",k.ha_url_from_env&&a.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:i("settings.environmentManagedLabel")})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",value:k.ha_url??"",onChange:ie=>Sn("ha_url",ie.target.value),placeholder:"http://192.168.1.100:8123",disabled:k.ha_url_from_env,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 ${k.ha_url_from_env?"opacity-60 cursor-not-allowed":""}`}),k.ha_url_from_env&&a.jsx(kf,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),k.ha_url_from_env&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.urlFromEnvReadOnly")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Long-Lived Access Token",k.ha_token_from_env&&a.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:i("settings.environmentManagedLabel")})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"password",value:k.ha_token??"",onChange:ie=>Sn("ha_token",ie.target.value),placeholder:"eyJ0eXAiOiJKV1QiLC...",disabled:k.ha_token_from_env,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 ${k.ha_token_from_env?"opacity-60 cursor-not-allowed":""}`}),k.ha_token_from_env&&a.jsx(kf,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),k.ha_token_from_env?a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.tokenFromEnvReadOnly")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Create a token in HA: Profile → Long-Lived Access Tokens → Create Token"})]}),k.ha_url&&k.ha_token&&a.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:a.jsxs(Ne,{variant:"secondary",size:"sm",disabled:Ma,onClick:async()=>{De(!0),Hr(null);try{const ie=await ae.testHAConnection(k.ha_url,k.ha_token);Hr(ie)}catch(ie){Hr({success:!1,message:null,error:ie instanceof Error?ie.message:i("common.unknownError")})}finally{De(!1)}},children:[Ma?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Eg,{className:"w-4 h-4"}),i("settings.testConnection")]})})]})]})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Eg,{className:"w-5 h-5 text-blue-400"}),"MQTT Publishing"]}),jt?.enabled&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${jt.connected?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:`text-sm ${jt.connected?"text-green-400":"text-red-400"}`,children:jt.connected?"Connected":"Disconnected"})]})]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish BamBuddy events to an external MQTT broker for integration with Node-RED, Home Assistant, and other automation systems."}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableMqtt")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish events to external MQTT broker"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.mqtt_enabled??!1,onChange:ie=>Sn("mqtt_enabled",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),k.mqtt_enabled&&a.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Broker hostname"}),a.jsx("input",{type:"text",value:k.mqtt_broker??"",onChange:ie=>Sn("mqtt_broker",ie.target.value),placeholder:"mqtt.example.com or 192.168.1.100",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"})]}),a.jsxs("div",{className:"flex items-end gap-4",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Port"}),a.jsx("input",{type:"number",min:"1",max:"65535",value:k.mqtt_port??1883,onChange:ie=>Sn("mqtt_port",Math.min(65535,Math.max(1,parseInt(ie.target.value)||1883))),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex items-center gap-3 pb-2",children:[a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.mqtt_use_tls??!1,onChange:ie=>{const kt=ie.target.checked;Sn("mqtt_use_tls",kt);const Hn=k.mqtt_port??1883;kt&&Hn===1883?Sn("mqtt_port",8883):!kt&&Hn===8883&&Sn("mqtt_port",1883)},className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]}),a.jsx("span",{className:"text-white text-sm",children:i("settings.useTls")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username (optional)"}),a.jsx("input",{type:"text",value:k.mqtt_username??"",onChange:ie=>Sn("mqtt_username",ie.target.value),placeholder:i("settings.leaveEmptyForAnonymous"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password (optional)"}),a.jsx("input",{type:"password",value:k.mqtt_password??"",onChange:ie=>Sn("mqtt_password",ie.target.value),placeholder:i("settings.leaveEmptyForAnonymous"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic prefix"}),a.jsx("input",{type:"text",value:k.mqtt_topic_prefix??"bambuddy",onChange:ie=>Sn("mqtt_topic_prefix",ie.target.value),placeholder:"bambuddy",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"}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["Topics will be: ",k.mqtt_topic_prefix||"bambuddy","/printers//status, etc."]})]}),jt&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:`w-2 h-2 rounded-full ${jt.connected?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:"text-bambu-gray",children:jt.connected?a.jsxs(a.Fragment,{children:[i("settings.mqttConnectedTo")," ",a.jsxs("span",{className:"text-white",children:[jt.broker,":",jt.port]})]}):i("settings.spoolmanDisconnected")})]})})]})]})]})]}),a.jsx("div",{className:"flex-1 lg:max-w-md space-y-4",children:a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Pj,{className:"w-5 h-5 text-orange-400"}),"Prometheus Metrics"]})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Expose printer metrics at ",a.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"/api/v1/metrics"})," for Prometheus/Grafana monitoring."]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableMetricsEndpoint")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.prometheusDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.prometheus_enabled??!1,onChange:ie=>Sn("prometheus_enabled",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),k.prometheus_enabled&&a.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bearer Token (optional)"}),a.jsx("input",{type:"password",value:k.prometheus_token??"",onChange:ie=>Sn("prometheus_token",ie.target.value),placeholder:i("settings.leaveEmptyForNoAuth"),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"}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["If set, requests must include ",a.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"Authorization: Bearer "})]})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-white mb-2",children:i("settings.availableMetrics")}),a.jsxs("div",{className:"text-xs text-bambu-gray space-y-1",children:[a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_connected"})," - Connection status"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_state"})," - Printer state (idle/printing/etc)"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_print_progress"})," - Print progress 0-100%"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_bed_temp_celsius"})," - Bed temperature"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_nozzle_temp_celsius"})," - Nozzle temperature"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_prints_total"})," - Total prints by result"]}),a.jsx("p",{className:"text-bambu-gray/70 italic",children:"...and more (layers, fans, queue, filament usage)"})]})]})]})]})]})})]}),Bn&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full mx-4",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[Bn.success?a.jsx(mr,{className:"w-8 h-8 text-green-400"}):a.jsx(Zi,{className:"w-8 h-8 text-red-400"}),a.jsx("h3",{className:"text-lg font-medium text-white",children:Bn.success?"Connection Successful":"Connection Failed"})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:Bn.success?Bn.message||"Successfully connected to Home Assistant.":Bn.error||"Failed to connect to Home Assistant."}),a.jsx("div",{className:"flex justify-end",children:a.jsx(Ne,{variant:"primary",onClick:()=>Hr(null),children:"OK"})})]})}),me==="plugs"&&a.jsxs("div",{className:"max-w-4xl",children:[a.jsxs("div",{className:"flex items-start justify-between mb-6",children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(sl,{className:"w-5 h-5 text-bambu-green"}),"Smart Plugs"]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Connect smart plugs (Tasmota or Home Assistant) to automate power control and track energy usage for your printers."})]}),a.jsxs("div",{className:"flex items-center gap-2 pt-1 shrink-0",children:[Ue&&Ue.filter(ie=>ie.enabled).length>1&&a.jsxs(a.Fragment,{children:[a.jsxs(Ne,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>Z("on"),disabled:Xh.isPending,title:i("settings.turnAllPlugsOn"),children:[Xh.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Ju,{className:"w-4 h-4 text-bambu-green"}),"All On"]}),a.jsxs(Ne,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>Z("off"),disabled:Xh.isPending,title:i("settings.turnAllPlugsOff"),children:[Xh.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Nk,{className:"w-4 h-4 text-red-400"}),"All Off"]})]}),a.jsxs(Ne,{className:"whitespace-nowrap",onClick:()=>{F(null),P(!0)},children:[a.jsx(cr,{className:"w-4 h-4"}),"Add Smart Plug"]})]})]}),Ue&&Ue.length>0&&a.jsxs(St,{className:"mb-6",children:[a.jsx(Pn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(Ah,{className:"w-4 h-4 text-yellow-400"}),"Energy Summary",xt&&a.jsx(ct,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),a.jsx(Et,{children:nt?a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(Ah,{className:"w-3 h-3"}),"Current Power"]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[nt.totalPower.toFixed(1),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"W"})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[nt.reachableCount,"/",nt.totalPlugs," plugs online"]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(ti,{className:"w-3 h-3"}),"Today"]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[nt.totalToday.toFixed(2),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(k?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(nt.totalToday*(k?.energy_cost_per_kwh??0)).toFixed(2)," ",k?.currency]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(Pj,{className:"w-3 h-3"}),"Yesterday"]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[nt.totalYesterday.toFixed(2),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(k?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(nt.totalYesterday*(k?.energy_cost_per_kwh??0)).toFixed(2)," ",k?.currency]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(Nj,{className:"w-3 h-3"}),"Total"]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[nt.totalLifetime.toFixed(1),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(k?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(nt.totalLifetime*(k?.energy_cost_per_kwh??0)).toFixed(2)," ",k?.currency]})]})]}):xt?null:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Enable plugs to see energy summary"})})]}),Se?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Ue&&Ue.length>0?a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ue.map(ie=>a.jsx(RKe,{plug:ie,onEdit:kt=>{F(kt),P(!0)}},ie.id))}):a.jsx(St,{children:a.jsx(Et,{className:"py-12",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(sl,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.noSmartPlugsTitle")}),a.jsx("p",{className:"text-sm mb-4",children:i("settings.noSmartPlugsDescription")}),a.jsxs(Ne,{onClick:()=>{F(null),P(!0)},children:[a.jsx(cr,{className:"w-4 h-4"}),i("settings.addFirstSmartPlug")]})]})})})]}),me==="notifications"&&a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[a.jsxs("div",{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(kg,{className:"w-5 h-5 text-bambu-green"}),i("settings.providers")]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Ne,{size:"sm",variant:"secondary",onClick:()=>oe(!0),children:[a.jsx(Y0,{className:"w-4 h-4"}),i("settings.log")]}),rt&&rt.length>0&&a.jsxs(Ne,{size:"sm",variant:"secondary",onClick:()=>{sd(null),Dc.mutate()},disabled:Dc.isPending,children:[Dc.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(kk,{className:"w-4 h-4"}),i("settings.testAll")]}),a.jsxs(Ne,{size:"sm",onClick:()=>{G(null),D(!0)},children:[a.jsx(cr,{className:"w-4 h-4"}),"Add"]})]})]}),a.jsx(St,{className:"mb-4",children:a.jsx(Et,{className:"py-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.notificationLanguage")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.notificationLanguageDescription")})]}),a.jsx("select",{value:k.notification_language||"en",onChange:ie=>Sn("notification_language",ie.target.value),className:"px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green",children:PU.map(ie=>a.jsx("option",{value:ie.code,children:ie.nativeName},ie.code))})]})})}),js&&a.jsx(St,{className:"mb-4",children:a.jsxs(Et,{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm font-medium text-white",children:i("settings.testResults")}),a.jsx("button",{onClick:()=>sd(null),className:"text-bambu-gray hover:text-white text-xs",children:i("common.dismiss")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm mb-2",children:[a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(mr,{className:"w-4 h-4"}),i("settings.testPassedCount",{count:js.success})]}),js.failed>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(Zi,{className:"w-4 h-4"}),i("settings.testFailedCount",{count:js.failed})]})]}),js.results.filter(ie=>!ie.success).length>0&&a.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:js.results.filter(ie=>!ie.success).map(ie=>a.jsxs("div",{className:"text-xs text-red-400",children:[a.jsxs("span",{className:"font-medium",children:[ie.provider_name,":"]})," ",ie.message]},ie.provider_id))})]})}),Ct?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):rt&&rt.length>0?a.jsx("div",{className:"space-y-3",children:rt.map(ie=>a.jsx(FKe,{provider:ie,onEdit:kt=>{G(kt),D(!0)}},ie.id))}):a.jsx(St,{children:a.jsx(Et,{className:"py-8",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(kg,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:i("settings.noProvidersTitle")}),a.jsx("p",{className:"text-xs mb-3",children:i("settings.noProvidersDescription")}),a.jsxs(Ne,{size:"sm",onClick:()=>{G(null),D(!0)},children:[a.jsx(cr,{className:"w-4 h-4"}),i("settings.addProvider")]})]})})})]}),a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-4",children:[a.jsx(ys,{className:"w-5 h-5 text-bambu-green"}),i("settings.messageTemplates")]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:i("settings.messageTemplatesDescription")}),Mn?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):pn&&pn.length>0?a.jsx("div",{className:"space-y-2",children:pn.map(ie=>a.jsx(St,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>K(ie),children:a.jsx(Et,{className:"py-2.5 px-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium text-sm truncate",children:ie.name}),a.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:ie.title_template})]}),a.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:kt=>{kt.stopPropagation(),K(ie)},children:a.jsx(bg,{className:"w-4 h-4 text-bambu-gray"})})]})})},ie.id))}):a.jsx(St,{children:a.jsx(Et,{className:"py-8",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(ys,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:i("settings.noTemplatesAvailable")})]})})})]})]}),me==="apikeys"&&a.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Yo,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiKeys")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiKeysDescription")})]}),a.jsxs(Ne,{size:"sm",onClick:()=>se(!0),className:"flex-shrink-0",children:[a.jsx(cr,{className:"w-4 h-4"}),i("settings.createKey")]})]}),V&&a.jsx(St,{className:"mb-6 border-bambu-green",children:a.jsx(Et,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(mr,{className:"w-5 h-5 text-bambu-green flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:i("settings.apiKeyCreated")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:i("settings.apiKeyCopyWarning")}),a.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark rounded-lg p-2",children:[a.jsx("code",{className:"flex-1 text-sm text-bambu-green font-mono break-all",children:V}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(V);else{const ie=document.createElement("textarea");ie.value=V,ie.style.position="fixed",ie.style.left="-999999px",document.body.appendChild(ie),ie.select(),document.execCommand("copy"),document.body.removeChild(ie)}o(i("settings.toast.keyCopied"))}catch{o(i("settings.toast.copyFailed"),"error")}},children:a.jsx(zl,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex gap-2 mt-3",children:[a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>{X(V),o(i("settings.toast.keyAddedToBrowser"))},children:i("settings.useInApiBrowser")}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>Y(null),children:i("common.dismiss")})]})]})]})})}),Re&&a.jsxs(St,{className:"mb-6",children:[a.jsx(Pn,{children:a.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.createNewApiKey")})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keyName")}),a.jsx("input",{type:"text",value:ke,onChange:ie=>Fe(ie.target.value),placeholder:i("settings.keyNamePlaceholder"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("common.permissions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ce.can_read_status,onChange:ie=>Ve(kt=>({...kt,can_read_status:ie.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.readStatus")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.readStatusDescription")})]})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ce.can_queue,onChange:ie=>Ve(kt=>({...kt,can_queue:ie.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.manageQueue")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.manageQueueDescription")})]})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ce.can_control_printer,onChange:ie=>Ve(kt=>({...kt,can_control_printer:ie.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.controlPrinter")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.controlPrinterDescription")})]})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[a.jsxs(Ne,{onClick:()=>Tt.mutate({name:ke||i("settings.unnamedKey"),...ce}),disabled:Tt.isPending,children:[Tt.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),i("settings.createKey")]}),a.jsx(Ne,{variant:"secondary",onClick:()=>se(!1),children:i("common.cancel")})]})]})]}),Rt?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):It&&It.length>0?a.jsx("div",{className:"space-y-3",children:It.map(ie=>a.jsx(St,{children:a.jsx(Et,{className:"py-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Yo,{className:`w-5 h-5 ${ie.enabled?"text-bambu-green":"text-bambu-gray"}`}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:ie.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[ie.key_prefix,"••••••••",ie.last_used&&` · ${i("settings.lastUsed")}: ${Gg(ie.last_used)}`]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex gap-1 text-xs",children:[ie.can_read_status&&a.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:i("settings.read")}),ie.can_queue&&a.jsx("span",{className:"px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded",children:i("queue.title")}),ie.can_control_printer&&a.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:i("settings.control")})]}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>q(ie.id),children:a.jsx(ln,{className:"w-4 h-4 text-red-400"})})]})]})})},ie.id))}):a.jsx(St,{children:a.jsx(Et,{className:"py-12",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(Yo,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.apiKeysEmptyTitle")}),a.jsx("p",{className:"text-sm mb-4",children:i("settings.apiKeysEmptyDescription")}),a.jsxs(Ne,{onClick:()=>se(!0),children:[a.jsx(cr,{className:"w-4 h-4"}),i("settings.createFirstKey")]})]})})}),a.jsxs(St,{className:"mt-6",children:[a.jsx(Pn,{children:a.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.webhookEndpoints")})}),a.jsxs(Et,{className:"space-y-3 text-sm",children:[a.jsx("p",{className:"text-bambu-gray",children:i("settings.webhookApiKeyHint")}),a.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-blue-400",children:"GET"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/status"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getAllStatus")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-blue-400",children:"GET"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/status/:id"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getSpecificStatus")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-green-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/queue"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.addToQueue")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-orange-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/pause"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.pausePrint")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-orange-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/resume"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.resumePrint")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-red-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/stop"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.stopPrint")]})]})]})]})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"mb-6",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(gh,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiBrowser")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiBrowserDescription")})]}),a.jsx(St,{className:"mb-4",children:a.jsxs(Et,{className:"py-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("settings.apiKeyForTesting")}),a.jsx("input",{type:"text",value:re,onChange:ie=>X(ie.target.value),placeholder:i("settings.apiKeyPlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("settings.apiKeyHint")})]})}),a.jsx(tXe,{apiKey:re})]})]}),me==="virtual-printer"&&a.jsx(KKe,{}),me==="filament"&&k&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[a.jsx("div",{className:"flex-1 lg:max-w-xl",children:a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.amsDisplayThresholds")})}),a.jsxs(Et,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.amsThresholdsDescription")}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(HR,{className:"w-4 h-4 text-blue-400"}),a.jsx("span",{className:"font-medium",children:i("settings.humidity")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodGreen")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0",max:"100",value:k.ams_humidity_good??40,onChange:ie=>Sn("ams_humidity_good",parseInt(ie.target.value)||40),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"}),a.jsx("span",{className:"text-bambu-gray",children:"%"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0",max:"100",value:k.ams_humidity_fair??60,onChange:ie=>Sn("ams_humidity_fair",parseInt(ie.target.value)||60),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"}),a.jsx("span",{className:"text-bambu-gray",children:"%"})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairBad")})]}),a.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(Ek,{className:"w-4 h-4 text-orange-400"}),a.jsx("span",{className:"font-medium",children:i("settings.temperature")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodBlue")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:k.ams_temp_good??28,onChange:ie=>Sn("ams_temp_good",parseFloat(ie.target.value)||28),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"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:k.ams_temp_fair??35,onChange:ie=>Sn("ams_temp_fair",parseFloat(ie.target.value)||35),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"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairHot")})]}),a.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(Au,{className:"w-4 h-4 text-purple-400"}),a.jsx("span",{className:"font-medium",children:i("settings.historyRetention")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keepSensorHistory")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"1",max:"365",value:k.ams_history_retention_days??30,onChange:ie=>Sn("ams_history_retention_days",parseInt(ie.target.value)||30),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:i("common.days")})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.historyRetentionDescription")})]}),a.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(jr,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"font-medium",children:i("settings.printModal")})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-white",children:i("settings.expandCustomMapping")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.expandCustomMappingDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.per_printer_mapping_expanded??!1,onChange:ie=>Sn("per_printer_mapping_expanded",ie.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})]})]})]})}),a.jsx("div",{className:"flex-1 lg:max-w-xl",children:a.jsx(GKe,{})})]}),ue!==null&&a.jsx(er,{title:i("settings.deleteApiKeyTitle"),message:i("settings.deleteApiKeyMessage"),confirmText:i("settings.deleteKey"),variant:"danger",onConfirm:()=>{mn.mutate(ue),q(null)},onCancel:()=>q(null)}),C&&a.jsx(OKe,{plug:U,onClose:()=>{P(!1),F(null)}}),H&&a.jsx(IKe,{provider:$,onClose:()=>{D(!1),G(null)}}),I&&a.jsx(zKe,{template:I,onClose:()=>K(null)}),Q&&a.jsx(HKe,{onClose:()=>oe(!1)}),le&&a.jsx(er,{title:i("settings.clearNotificationLogs"),message:i("settings.clearLogsMessage"),confirmText:i("settings.clearLogs"),variant:"warning",onConfirm:async()=>{pe(!1);try{const ie=await ae.clearNotificationLogs(30);o(ie.message,"success")}catch{o(i("settings.toast.clearLogsFailed"),"error")}},onCancel:()=>pe(!1)}),ee&&a.jsx(er,{title:i("settings.resetUiPreferences"),message:i("settings.resetUiPreferencesMessage"),confirmText:i("settings.resetPreferences"),variant:"default",onConfirm:()=>{z(!1),localStorage.clear(),o(i("settings.toast.uiPreferencesReset"),"success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>z(!1)}),O&&a.jsx(er,{title:`Turn All Plugs ${O==="on"?"On":"Off"}`,message:`This will turn ${O==="on"?"ON":"OFF"} all ${Ue?.filter(ie=>ie.enabled).length||0} enabled smart plugs. ${O==="off"?"Any running printers may be affected!":""}`,confirmText:`Turn All ${O==="on"?"On":"Off"}`,variant:O==="off"?"danger":"warning",onConfirm:()=>{const ie=O;Z(null),Xh.mutate(ie)},onCancel:()=>Z(null)}),ge&&cn?.release_notes&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Ce(!1),children:a.jsxs(St,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:ie=>ie.stopPropagation(),children:[a.jsxs(Pn,{className:"flex flex-row items-center justify-between shrink-0",children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Release Notes - v",cn.latest_version]}),cn.release_name&&cn.release_name!==cn.latest_version&&a.jsx("p",{className:"text-sm text-bambu-gray",children:cn.release_name})]}),a.jsx("button",{onClick:()=>Ce(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsx(Et,{className:"overflow-y-auto flex-1",children:a.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:cn.release_notes})}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[cn.release_url&&a.jsx("a",{href:cn.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:a.jsxs(Ne,{variant:"secondary",className:"w-full",children:[a.jsx(Xr,{className:"w-4 h-4"}),"View on GitHub"]})}),a.jsx(Ne,{onClick:()=>Ce(!1),className:"flex-1",children:"Close"})]})]})}),me==="users"&&a.jsxs("div",{className:"space-y-6",children:[a.jsx(St,{children:a.jsx(Et,{className:"py-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${l?"bg-green-500/20":"bg-gray-500/20"}`,children:l?a.jsx(kf,{className:"w-5 h-5 text-green-400"}):a.jsx(_1,{className:"w-5 h-5 text-gray-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-medium",children:i("settings.authentication")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i(l?"settings.authEnabledDescription":"settings.authDisabledDescription")})]})]}),l?c?.is_admin&&a.jsxs(Ne,{variant:"secondary",onClick:()=>Te(!0),children:[a.jsx(_1,{className:"w-4 h-4"}),i("common.disable")]}):a.jsxs(Ne,{onClick:()=>e("/setup"),children:[a.jsx(kf,{className:"w-4 h-4"}),i("common.enable")]})]})})}),un?.advanced_auth_enabled&&a.jsx(St,{className:"border-blue-500/30 bg-blue-500/5",children:a.jsx(Et,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:a.jsx(Q0,{className:"w-5 h-5 text-blue-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-medium",children:i("settings.email.advancedAuthEnabled")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.email.advancedAuthEnabledDesc")})]})]})})}),l&&a.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"space-y-6",children:[c&&a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(zf,{className:"w-5 h-5 text-bambu-green"}),i("settings.currentUser")]}),a.jsxs(Ne,{size:"sm",variant:"ghost",onClick:()=>$e(!0),children:[a.jsx(Yo,{className:"w-4 h-4"}),i("settings.changePassword")]})]})}),a.jsx(Et,{children:a.jsx("div",{className:"flex items-center justify-between",children:a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium text-lg",children:c.username}),a.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[c.is_admin&&a.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:i("settings.admin")}),c.groups?.map(ie=>a.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${ie.name==="Administrators"?"bg-purple-500/20 text-purple-300":ie.name==="Operators"?"bg-blue-500/20 text-blue-300":ie.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:ie.name},ie.id))]})]})})})]}),a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(zf,{className:"w-5 h-5 text-bambu-green"}),i("settings.users")]}),In("users:create")&&a.jsxs(Ne,{size:"sm",onClick:()=>{Ae(!0),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:[a.jsx(cr,{className:"w-4 h-4"}),i("settings.addUser")]})]})}),a.jsx(Et,{children:ua?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):rr.length===0?a.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noUsersFound")}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:rr.map(ie=>a.jsxs("div",{className:"py-3 flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-white font-medium truncate",children:ie.username}),a.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[ie.is_admin&&a.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:i("settings.admin")}),ie.groups?.map(kt=>a.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${kt.name==="Administrators"?"bg-purple-500/20 text-purple-300":kt.name==="Operators"?"bg-blue-500/20 text-blue-300":kt.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:kt.name},kt.id))]})]}),a.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[In("users:update")&&a.jsx(Ne,{size:"sm",variant:"ghost",onClick:()=>Aa(ie),children:a.jsx(bg,{className:"w-4 h-4"})}),In("users:delete")&&ie.id!==c?.id&&a.jsx(Ne,{size:"sm",variant:"ghost",onClick:()=>Pc(ie.id),children:a.jsx(ln,{className:"w-4 h-4"})})]})]},ie.id))})})]})]}),a.jsx("div",{children:a.jsxs(St,{children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(fT,{className:"w-5 h-5 text-bambu-green"}),i("settings.groups")]}),In("groups:create")&&a.jsxs(Ne,{size:"sm",onClick:()=>{Ie(!0),da()},children:[a.jsx(cr,{className:"w-4 h-4"}),i("settings.addGroup")]})]})}),a.jsx(Et,{children:Jt?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Si.length===0?a.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noGroupsFound")}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:Si.map(ie=>a.jsxs("div",{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(fT,{className:`w-4 h-4 ${ie.name==="Administrators"?"text-purple-400":ie.name==="Operators"?"text-blue-400":ie.name==="Viewers"?"text-green-400":"text-bambu-gray"}`}),a.jsx("span",{className:"text-white font-medium",children:ie.name}),ie.is_system&&a.jsx("span",{className:"px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:i("settings.system")})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[In("groups:update")&&a.jsx(Ne,{size:"sm",variant:"ghost",onClick:()=>Vb(ie),children:a.jsx(bg,{className:"w-4 h-4"})}),In("groups:delete")&&!ie.is_system&&a.jsx(Ne,{size:"sm",variant:"ghost",onClick:()=>fn(ie.id),children:a.jsx(ln,{className:"w-4 h-4"})})]})]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-6",children:ie.description||i("settings.noDescription")}),a.jsxs("div",{className:"flex items-center gap-4 mt-2 ml-6 text-xs text-bambu-gray",children:[a.jsx("span",{children:i("settings.userCount",{count:ie.user_count})}),a.jsx("span",{children:i("settings.permissionCount",{count:ie.permissions.length})})]})]},ie.id))})})]})})]}),!l&&a.jsx(St,{children:a.jsx(Et,{className:"py-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx(_1,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:i("settings.authDisabledTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4 max-w-md mx-auto",children:i("settings.authDisabledMessage")}),a.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-6 text-left max-w-xs mx-auto",children:[a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(mr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature1")})]}),a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(mr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature2")})]}),a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(mr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature3")})]})]}),a.jsxs(Ne,{onClick:()=>e("/setup"),children:[a.jsx(kf,{className:"w-4 h-4"}),i("settings.enableAuthentication")]})]})})})]}),Be&&!un?.advanced_auth_enabled&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Ae(!1),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsxs(St,{className:"w-full max-w-md",onClick:ie=>ie.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(zf,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.createUser")})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{Ae(!1),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsx(Lt,{className:"w-5 h-5"})})]})}),a.jsxs(Et,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.username")}),a.jsx("input",{type:"text",value:at.username,onChange:ie=>Ut({...at,username:ie.target.value}),className:"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:i("settings.enterUsername"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.password")}),a.jsx("input",{type:"password",value:at.password,onChange:ie=>Ut({...at,password:ie.target.value}),className:"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:i("settings.enterPassword"),autoComplete:"new-password",minLength:6})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),a.jsx("input",{type:"password",value:at.confirmPassword,onChange:ie=>Ut({...at,confirmPassword:ie.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${at.confirmPassword&&at.password!==at.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),at.confirmPassword&&at.password!==at.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Groups"}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[Si.map(ie=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:at.group_ids.includes(ie.id),onChange:()=>_r(ie.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:ie.name}),ie.is_system&&a.jsx("span",{className:"text-xs text-yellow-400",children:"(System)"})]},ie.id)),Si.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>{Ae(!1),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:"Cancel"}),a.jsx(Ne,{onClick:hs,disabled:Ea.isPending||!at.username||!at.password||at.password!==at.confirmPassword||at.password.length<6,children:Ea.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Creating..."]}):a.jsxs(a.Fragment,{children:[a.jsx(cr,{className:"w-4 h-4"}),"Create User"]})})]})]})]})}),Be&&un?.advanced_auth_enabled&&a.jsx(VKe,{formData:at,setFormData:Ut,groups:Si,onClose:()=>{Ae(!1),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},onCreate:hs,isCreating:Ea.isPending,isCreateButtonDisabled:Ea.isPending||!at.username||!at.email}),qe&&et!==null&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{ve(!1),Ee(null),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsxs(St,{className:"w-full max-w-md",onClick:ie=>ie.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(bg,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.editUser")})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{ve(!1),Ee(null),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsx(Lt,{className:"w-5 h-5"})})]})}),a.jsxs(Et,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("settings.username")," ",un?.advanced_auth_enabled&&a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:at.username,onChange:ie=>Ut({...at,username:ie.target.value}),className:"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:i("settings.enterUsername"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("users.form.email")||"Email"," ",un?.advanced_auth_enabled?a.jsx("span",{className:"text-red-400",children:"*"}):a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",i("users.form.optional")||"optional",")"]})]}),a.jsx("input",{type:"email",value:at.email,onChange:ie=>Ut({...at,email:ie.target.value}),className:"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:i("users.form.emailPlaceholder")||"user@example.com",required:un?.advanced_auth_enabled})]}),!un?.advanced_auth_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("users.form.password")||"Password"," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",i("users.form.leaveBlankToKeep")||"leave blank to keep current",")"]})]}),a.jsx("input",{type:"password",value:at.password,onChange:ie=>Ut({...at,password:ie.target.value,confirmPassword:""}),className:"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:i("settings.enterNewPassword"),autoComplete:"new-password",minLength:6})]}),at.password&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),a.jsx("input",{type:"password",value:at.confirmPassword,onChange:ie=>Ut({...at,confirmPassword:ie.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${at.confirmPassword&&at.password!==at.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),at.confirmPassword&&at.password!==at.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),un?.advanced_auth_enabled&&a.jsxs("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3 space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("users.form.passwordManagedByAdvancedAuth")||'Password is managed by Advanced Authentication. Use "Reset Password" to send a new password to the user via email.'}),a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>et&&yl.mutate(et),disabled:yl.isPending||!at.email,className:"w-full",children:yl.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),i("users.form.resettingPassword")||"Resetting Password..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Bu,{className:"w-4 h-4"}),i("users.form.resetPassword")||"Reset Password"]})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("users.form.groups")||"Groups"}),a.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:Si.map(ie=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:at.group_ids.includes(ie.id),onChange:()=>_r(ie.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:ie.name}),ie.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",i("users.system")||"System",")"]})]},ie.id))})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>{ve(!1),Ee(null),Ut({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i("users.modal.cancel")||"Cancel"}),a.jsx(Ne,{onClick:()=>Po(et),disabled:Ta.isPending||!at.username||un?.advanced_auth_enabled&&!at.email||!!(!un?.advanced_auth_enabled&&at.password&&(at.password!==at.confirmPassword||at.password.length<6)),children:Ta.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),i("users.modal.saving")||"Saving..."]}):a.jsxs(a.Fragment,{children:[a.jsx(vs,{className:"w-4 h-4"}),i("users.modal.saveChanges")||"Save Changes"]})})]})]})]})}),Ye!==null&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:()=>{je(null),ye(null)},children:a.jsxs(St,{className:"w-full max-w-md",onClick:ie=>ie.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center gap-2 text-red-400",children:[a.jsx(ln,{className:"w-5 h-5"}),a.jsx("h3",{className:"text-lg font-semibold",children:i("settings.deleteUserTitle")})]})}),a.jsx(Et,{className:"space-y-4",children:Qe?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-bambu-green border-t-transparent"})}):Pe&&Pe.archives+Pe.queue_items+Pe.library_files>0?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-white",children:i("settings.userHasCreated")}),a.jsxs("ul",{className:"list-disc list-inside text-bambu-gray space-y-1",children:[Pe.archives>0&&a.jsxs("li",{children:[Pe.archives," archive",Pe.archives!==1?"s":""]}),Pe.queue_items>0&&a.jsxs("li",{children:[Pe.queue_items," queue item",Pe.queue_items!==1?"s":""]}),Pe.library_files>0&&a.jsxs("li",{children:[Pe.library_files," library file",Pe.library_files!==1?"s":""]})]}),a.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.userItemsQuestion")}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(Ne,{variant:"danger",onClick:()=>si.mutate({id:Ye,deleteItems:!0}),disabled:si.isPending,className:"justify-center",children:"Delete user AND their items"}),a.jsx(Ne,{variant:"secondary",onClick:()=>si.mutate({id:Ye,deleteItems:!1}),disabled:si.isPending,className:"justify-center",children:"Delete user, keep items (become ownerless)"}),a.jsx(Ne,{variant:"ghost",onClick:()=>{je(null),ye(null)},disabled:si.isPending,className:"justify-center",children:"Cancel"})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-white",children:i("settings.deleteUserConfirm")}),a.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.actionCannotBeUndone")}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(Ne,{variant:"ghost",onClick:()=>{je(null),ye(null)},disabled:si.isPending,children:"Cancel"}),a.jsx(Ne,{variant:"danger",onClick:()=>si.mutate({id:Ye,deleteItems:!1}),disabled:si.isPending,children:"Delete User"})]})]})})]})}),(zt||vt)&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Ie(!1),Gt(null),da()},children:a.jsxs(St,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:ie=>ie.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(fT,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:vt?"Edit Group":"Create Group"})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{Ie(!1),Gt(null),da()},children:a.jsx(Lt,{className:"w-5 h-5"})})]})}),a.jsxs(Et,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.groupName")}),a.jsx("input",{type:"text",value:vn.name,onChange:ie=>dr({...vn,name:ie.target.value}),disabled:vt?.is_system,className:"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 disabled:opacity-50",placeholder:i("settings.enterGroupName")}),vt?.is_system&&a.jsx("p",{className:"text-xs text-yellow-400 mt-1",children:i("settings.systemGroupWarning")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Description"}),a.jsx("textarea",{value:vn.description,onChange:ie=>dr({...vn,description:ie.target.value}),rows:2,className:"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 resize-none",placeholder:i("settings.enterDescriptionOptional")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:["Permissions (",vn.permissions.length," selected)"]}),a.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:wn?.categories.map(ie=>a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary cursor-pointer hover:bg-bambu-dark-tertiary transition-colors",onClick:()=>Um(ie.name),children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("button",{type:"button",onClick:kt=>{kt.stopPropagation(),Bm(ie,!ad(ie))},className:`w-5 h-5 rounded border flex items-center justify-center transition-colors ${ad(ie)?"bg-bambu-green border-bambu-green":Gb(ie)?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:(ad(ie)||Gb(ie))&&a.jsx($i,{className:"w-3 h-3 text-white"})}),a.jsx("span",{className:"text-white font-medium",children:ie.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",ie.permissions.filter(kt=>vn.permissions.includes(kt.value)).length,"/",ie.permissions.length,")"]})]}),ar.has(ie.name)?a.jsx(fr,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(ks,{className:"w-4 h-4 text-bambu-gray"})]}),ar.has(ie.name)&&a.jsx("div",{className:"p-3 bg-bambu-dark space-y-2",children:ie.permissions.map(kt=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:vn.permissions.includes(kt.value),onChange:()=>Av(kt.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:kt.label})]},kt.value))})]},ie.name))})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>{Ie(!1),Gt(null),da()},children:"Cancel"}),a.jsx(Ne,{onClick:vt?Qr:eo,disabled:us.isPending||ds.isPending||!vn.name.trim(),children:us.isPending||ds.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),vt?"Saving...":"Creating..."]}):a.jsxs(a.Fragment,{children:[a.jsx(vs,{className:"w-4 h-4"}),vt?"Save Changes":"Create Group"]})})]})]})]})}),dn!==null&&a.jsx(er,{title:i("settings.deleteGroupTitle"),message:i("settings.deleteGroupMessage"),confirmText:i("settings.deleteGroup"),variant:"danger",onConfirm:()=>{jc.mutate(dn),fn(null)},onCancel:()=>fn(null)}),me==="email"&&a.jsx("div",{className:"max-w-2xl",children:a.jsx(QKe,{})}),me==="backup"&&a.jsx(YKe,{}),_e&&a.jsx(er,{title:i("settings.disableAuthenticationTitle"),message:i("settings.disableAuthenticationMessage"),confirmText:i("settings.disableAuthentication"),variant:"danger",onConfirm:async()=>{try{await ae.disableAuth(),o(i("settings.toast.authDisabled"),"success"),await u(),Te(!1),window.location.href="/"}catch(ie){const kt=ie instanceof Error?ie.message:i("settings.toast.authDisableFailed");o(kt,"error")}},onCancel:()=>Te(!1)}),we&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{$e(!1),ze({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsxs(St,{className:"w-full max-w-md",onClick:ie=>ie.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Yo,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.changePassword")})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{$e(!1),ze({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsx(Lt,{className:"w-5 h-5"})})]})}),a.jsxs(Et,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Current Password"}),a.jsx("input",{type:"password",value:Ge.currentPassword,onChange:ie=>ze({...Ge,currentPassword:ie.target.value}),className:"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:i("settings.enterCurrentPassword"),autoComplete:"current-password"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"New Password"}),a.jsx("input",{type:"password",value:Ge.newPassword,onChange:ie=>ze({...Ge,newPassword:ie.target.value}),className:"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:i("settings.enterNewPasswordMin6"),autoComplete:"new-password",minLength:6})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Confirm New Password"}),a.jsx("input",{type:"password",value:Ge.confirmPassword,onChange:ie=>ze({...Ge,confirmPassword:ie.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${Ge.confirmPassword&&Ge.newPassword!==Ge.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),Ge.confirmPassword&&Ge.newPassword!==Ge.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>{$e(!1),ze({currentPassword:"",newPassword:"",confirmPassword:""})},children:"Cancel"}),a.jsx(Ne,{onClick:async()=>{if(Ge.newPassword!==Ge.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(Ge.newPassword.length<6){o(i("settings.toast.passwordTooShort"),"error");return}Me(!0);try{await ae.changePassword(Ge.currentPassword,Ge.newPassword),o(i("settings.toast.passwordChanged"),"success"),$e(!1),ze({currentPassword:"",newPassword:"",confirmPassword:""})}catch(ie){const kt=ie instanceof Error?ie.message:"Failed to change password";o(kt,"error")}finally{Me(!1)}},disabled:be||!Ge.currentPassword||!Ge.newPassword||Ge.newPassword!==Ge.confirmPassword||Ge.newPassword.length<6,children:be?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),"Changing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Yo,{className:"w-4 h-4"}),"Change Password"]})})]})]})]})})]})}const iie=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},iXe=t=>t.startsWith("HH")?"HF":"S",aXe=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},SR=t=>{const e=["High Flow_","High Flow ","Standard_","Standard ","HF_","HF ","S_","S "];for(const r of e)if(t.startsWith(r))return t.slice(r.length);const n=t.indexOf("_");return n>0?t.slice(n+1):t};function ej({profile:t,onEdit:e,onCopy:n,selectionMode:r,isSelected:i,onToggleSelect:s,note:o}){const l=iXe(t.nozzle_id),c=t.nozzle_diameter,u=()=>{r&&s?s():e()};return a.jsxs("div",{className:"flex items-center gap-2",children:[r&&a.jsx("button",{onClick:s,className:"text-bambu-gray hover:text-white transition-colors p-1",children:i?a.jsx(Xs,{className:"w-4 h-4 text-bambu-green"}):a.jsx(ul,{className:"w-4 h-4"})}),a.jsxs("button",{onClick:u,className:`flex-1 text-left px-3 py-2 bg-bambu-dark rounded hover:bg-bambu-dark-tertiary transition-colors ${i?"ring-1 ring-bambu-green":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-green font-mono text-sm font-bold whitespace-nowrap",children:iie(t.k_value)}),a.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name||"Unnamed"}),o&&a.jsx("span",{title:"Has note",children:a.jsx(HW,{className:"w-3 h-3 text-yellow-500"})}),a.jsxs("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:[l," ",c]})]}),o&&a.jsxs("div",{className:"text-xs mt-0.5 truncate text-yellow-500/70",title:o,children:["Note: ",o.length>50?o.substring(0,50)+"...":o]})]}),!r&&n&&a.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"text-bambu-gray hover:text-white transition-colors p-1",title:"Copy profile",children:a.jsx(zl,{className:"w-4 h-4"})})]})}function tj({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:r=[],isDualNozzle:i=!1,initialNote:s="",initialNoteKey:o=null,onClose:l,onSave:c,onSaveNote:u,hasPermission:d}){const{t:h}=Yt(),{showToast:p}=Tn(),[m,b]=_.useState(t?.name||""),[y,x]=_.useState(t?.k_value?iie(t.k_value):"0.020"),[v,S]=_.useState(t?.filament_id||""),[N,T]=_.useState(t?.nozzle_id?aXe(t.nozzle_id):"HH00"),[M,A]=_.useState(t?.nozzle_diameter||n),[k,R]=_.useState(t?[t.extruder_id]:i?[0,1]:[0]),[C,P]=_.useState(!1),[U,F]=_.useState({current:0,total:0}),[H,D]=_.useState(s),$=ei.useMemo(()=>{const W=new Map;for(const J of r)if(J.filament_id&&!W.has(J.filament_id)){const ne=SR(J.name||"");W.set(J.filament_id,{id:J.filament_id,name:ne||J.filament_id})}return Array.from(W.values()).sort((J,ne)=>J.name.localeCompare(ne.name))},[r]),G=dt({mutationFn:W=>(console.log("[KProfile] Calling API..."),ae.setKProfile(e,W)),onSuccess:W=>{if(console.log("[KProfile] Save success:",W),p(h("kProfiles.toast.profileSaved")),u&&H!==s){let J;H===""&&o?J=o:t&&t.slot_id>0?J=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:J=`name_${m}_${v}`,u(J,H)}P(!0),setTimeout(()=>{P(!1),c()},2500)},onError:W=>{console.error("[KProfile] Save error:",W),p(W.message,"error"),P(!1)}}),I=dt({mutationFn:W=>(console.log("[KProfile] Deleting profile..."),ae.deleteKProfile(e,W)),onSuccess:W=>{console.log("[KProfile] Delete success:",W),p(h("kProfiles.toast.profileDeleted")),P(!0),setTimeout(()=>{P(!1),l()},4e3)},onError:W=>{console.error("[KProfile] Delete error:",W),p(W.message,"error"),P(!1)}}),[K,Q]=_.useState(!1),oe=()=>{t&&I.mutate({slot_id:t.slot_id,extruder_id:t.extruder_id,nozzle_id:t.nozzle_id,nozzle_diameter:t.nozzle_diameter,filament_id:t.filament_id,setting_id:t.setting_id})},B=async W=>{if(W.preventDefault(),i&&!t&&k.length===0){p(h("kProfiles.toast.selectAtLeastOneExtruder"),"error");return}const J=parseFloat(y).toFixed(6),ne=`${N}-${M}`;if(t||k.length===1){const fe={name:m,k_value:J,filament_id:v,nozzle_id:ne,nozzle_diameter:M,extruder_id:t?t.extruder_id:k[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",fe),G.mutate(fe);return}P(!0),F({current:1,total:k.length});const me=k.map(fe=>({name:m,k_value:J,filament_id:v,nozzle_id:ne,nozzle_diameter:M,extruder_id:fe,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${me.length} profiles in batch:`,me);try{if(await ae.setKProfilesBatch(e,me),p(h("kProfiles.toast.profilesSaved",{count:k.length})),u&&H){const fe=`name_${m}_${v}`;u(fe,H)}}catch(fe){console.error("[KProfile] Failed to save batch:",fe),p(h("kProfiles.toast.failedToSaveBatch"),"error"),P(!1),F({current:0,total:0});return}F({current:k.length,total:k.length}),setTimeout(()=>{P(!1),F({current:0,total:0}),c()},3e3)};return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:[a.jsxs(St,{className:"w-full max-w-md relative",children:[C&&a.jsxs("div",{className:"absolute inset-0 bg-bambu-dark-secondary/90 flex flex-col items-center justify-center z-10 rounded-lg",children:[a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),a.jsx("p",{className:"text-white font-medium",children:U.total>1?h("kProfiles.modal.savingExtruder",{current:U.current,total:U.total}):h("kProfiles.modal.syncing")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:h("kProfiles.modal.pleaseWait")})]}),a.jsxs(Et,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:h(t?"kProfiles.modal.editTitle":"kProfiles.modal.addTitle")}),a.jsx("button",{onClick:l,className:"text-bambu-gray hover:text-white transition-colors",disabled:C,children:a.jsx(Lt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:B,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h("kProfiles.modal.profileName")}),a.jsx("input",{type:"text",value:m,onChange:W=>b(W.target.value),disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,placeholder:h("kProfiles.modal.profileNamePlaceholder"),required:!t})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h("kProfiles.modal.kValue")}),a.jsx("input",{type:"text",inputMode:"decimal",value:y,onChange:W=>{const J=W.target.value;(J===""||/^\d*\.?\d*$/.test(J))&&x(J)},onBlur:W=>{const J=parseFloat(W.target.value);isNaN(J)||x((Math.trunc(J*1e3)/1e3).toFixed(3))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none font-mono",placeholder:h("kProfiles.modal.kValuePlaceholder"),required:!0}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:h("kProfiles.modal.kValueHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h("kProfiles.modal.filament")}),a.jsxs("select",{value:v,onChange:W=>{const J=W.target.value;if(S(J),!t&&J&&!m){const ne=$.find(me=>me.id===J);ne&&b(`${N==="HH00"?"HF":"S"} ${ne.name}`)}},disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,required:!t,children:[a.jsx("option",{value:"",children:h("kProfiles.modal.selectFilament")}),t?.filament_id&&a.jsx("option",{value:t.filament_id,children:$.find(W=>W.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&$.map(W=>a.jsx("option",{value:W.id,children:W.name},W.id))]}),!t&&$.length===0&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:h("kProfiles.modal.noFilamentsHelp")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h("kProfiles.modal.flowType")}),a.jsxs("select",{value:N,onChange:W=>{const J=W.target.value;if(T(J),!t&&v&&!m){const ne=$.find(me=>me.id===v);ne&&b(`${J==="HS00"?"HF":"S"} ${ne.name}`)}},disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,children:[a.jsx("option",{value:"HH00",children:h("kProfiles.modal.highFlow")}),a.jsx("option",{value:"HS00",children:h("kProfiles.modal.standard")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h("kProfiles.modal.nozzleSize")}),a.jsxs("select",{value:M,onChange:W=>A(W.target.value),disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,children:[a.jsx("option",{value:"0.2",children:"0.2mm"}),a.jsx("option",{value:"0.4",children:"0.4mm"}),a.jsx("option",{value:"0.6",children:"0.6mm"}),a.jsx("option",{value:"0.8",children:"0.8mm"})]})]})]}),i&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h(t?"kProfiles.modal.extruder":"kProfiles.modal.extruders")}),t?a.jsx("div",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white opacity-60",children:t.extruder_id===1?h("kProfiles.modal.left"):h("kProfiles.modal.right")}):a.jsxs("div",{className:"flex gap-4",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.includes(1),onChange:W=>{W.target.checked?R([...k,1]):R(k.filter(J=>J!==1))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),a.jsx("span",{className:"text-white",children:h("kProfiles.modal.left")})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.includes(0),onChange:W=>{W.target.checked?R([...k,0]):R(k.filter(J=>J!==0))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),a.jsx("span",{className:"text-white",children:h("kProfiles.modal.right")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:h("kProfiles.modal.notes")}),a.jsx("textarea",{value:H,onChange:W=>D(W.target.value),placeholder:h("kProfiles.modal.notesPlaceholder"),rows:2,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none resize-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:h("kProfiles.modal.notesHelp")})]}),a.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&a.jsx(Ne,{type:"button",variant:"secondary",onClick:()=>Q(!0),disabled:I.isPending||C||!d("kprofiles:delete"),title:d("kprofiles:delete")?void 0:h("kProfiles.permission.noDelete"),className:"text-red-500 hover:bg-red-500/10",children:I.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4"})}),a.jsx(Ne,{type:"button",variant:"secondary",onClick:l,disabled:C,className:"flex-1",children:h("common.cancel")}),a.jsxs(Ne,{type:"submit",disabled:G.isPending||C||!d(t?"kprofiles:update":"kprofiles:create"),title:d(t?"kprofiles:update":"kprofiles:create")?void 0:h(t?"kProfiles.permission.noUpdate":"kProfiles.permission.noCreate"),className:"flex-1",children:[G.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vk,{className:"w-4 h-4"}),h("common.save")]})]})]})]})]}),K&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:a.jsx(St,{className:"w-full max-w-sm",children:a.jsxs(Et,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:a.jsx(ln,{className:"w-5 h-5 text-red-500"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:h("kProfiles.deleteConfirm.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:h("kProfiles.deleteConfirm.cannotUndo")})]})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:h("kProfiles.deleteConfirm.message",{name:t?.name})}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>Q(!1),className:"flex-1",children:h("common.cancel")}),a.jsxs(Ne,{onClick:()=>{Q(!1),oe()},disabled:I.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[I.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4"}),h("common.delete")]})]})]})})})]})}const y1={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function sXe(){const{t}=Yt(),{showToast:e}=Tn(),{hasPermission:n}=Ir(),[r,i]=_.useState(null),[s,o]=_.useState(()=>localStorage.getItem(y1.NOZZLE_DIAMETER)||"0.4"),[l,c]=_.useState(null),[u,d]=_.useState(!1),[h,p]=_.useState(null),[m,b]=_.useState(""),[y,x]=_.useState("all"),[v,S]=_.useState("all"),[N,T]=_.useState(()=>localStorage.getItem(y1.SORT_OPTION)||"name"),[M,A]=_.useState(!1),[k,R]=_.useState(new Set),[C,P]=_.useState(!1),[U,F]=_.useState(!1),H=_.useCallback(X=>`${X.slot_id}_${X.extruder_id}`,[]);_.useEffect(()=>{localStorage.setItem(y1.NOZZLE_DIAMETER,s)},[s]),_.useEffect(()=>{localStorage.setItem(y1.SORT_OPTION,N)},[N]);const{data:D,isLoading:$}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:G,isLoading:I,isFetching:K,error:Q,refetch:oe}=it({queryKey:["kprofiles",r,s],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",r,"nozzle",s);const X=await ae.getKProfiles(r,s);return console.log("[KProfiles] Received profiles:",X?.profiles?.length||0,"profiles"),X},enabled:!!r,retry:!1,staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:B}=it({queryKey:["kprofiles",r,"0.4"],queryFn:()=>ae.getKProfiles(r,"0.4"),enabled:!!r,staleTime:6e4}),{data:W,refetch:J}=it({queryKey:["kprofile-notes",r],queryFn:()=>ae.getKProfileNotes(r),enabled:!!r,staleTime:3e4}),ne=Q?.message?.includes("not connected");_.useEffect(()=>{if(!r&&D&&D.length>0){const X=D.find(le=>le.is_active);X&&i(X.id)}},[r,D]),_.useEffect(()=>{if(r){const X=setTimeout(()=>{oe()},150);return()=>clearTimeout(X)}},[r,s]);const me=D?.filter(X=>X.is_active)||[],fe=ei.useMemo(()=>G?.profiles?G.profiles.filter(le=>{const pe=m.toLowerCase(),ee=!pe||le.name.toLowerCase().includes(pe)||le.filament_id.toLowerCase().includes(pe),z=y==="all"||y==="left"&&le.extruder_id===1||y==="right"&&le.extruder_id===0,O=v==="all"||v==="hf"&&le.nozzle_id.startsWith("HH")||v==="s"&&le.nozzle_id.startsWith("HS");return ee&&z&&O}).sort((le,pe)=>{switch(N){case"k_value":return parseFloat(le.k_value)-parseFloat(pe.k_value);case"filament":return SR(le.name).localeCompare(SR(pe.name));case"name":default:return le.name.localeCompare(pe.name)}}):[],[G?.profiles,m,y,v,N]),de=D?.find(X=>X.id===r),Re=de?.nozzle_count===2;_.useEffect(()=>{const X=le=>{le.target instanceof HTMLInputElement||le.target instanceof HTMLTextAreaElement||le.target instanceof HTMLSelectElement||l||u||h||(le.key==="r"||le.key==="R"?(le.preventDefault(),oe()):le.key==="n"||le.key==="N"?(le.preventDefault(),d(!0)):le.key==="Escape"&&M&&(le.preventDefault(),A(!1),R(new Set)))};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[l,u,h,M,oe]);const se=_.useCallback(()=>{if(!G?.profiles||G.profiles.length===0){e(t("kProfiles.toast.noProfilesToExport"),"error");return}const X={version:1,exported_at:new Date().toISOString(),printer:de?.name||"Unknown",nozzle_diameter:s,profiles:G.profiles.map(z=>({name:z.name,k_value:z.k_value,filament_id:z.filament_id,nozzle_id:z.nozzle_id,nozzle_diameter:z.nozzle_diameter,extruder_id:z.extruder_id}))},le=new Blob([JSON.stringify(X,null,2)],{type:"application/json"}),pe=URL.createObjectURL(le),ee=document.createElement("a");ee.href=pe,ee.download=`kprofiles_${de?.name||"printer"}_${s}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(ee),ee.click(),document.body.removeChild(ee),URL.revokeObjectURL(pe),e(t("kProfiles.toast.exportedProfiles",{count:G.profiles.length}))},[G?.profiles,de,s,e,t]),ke=_.useCallback(()=>{const X=document.createElement("input");X.type="file",X.accept=".json",X.onchange=async le=>{const pe=le.target.files?.[0];if(pe)try{const ee=await pe.text(),z=JSON.parse(ee);if(!z.profiles||!Array.isArray(z.profiles)){e(t("kProfiles.toast.invalidFileFormat"),"error");return}let O=0;for(const Z of z.profiles)if(!(!Z.name||!Z.k_value||!Z.filament_id))try{await ae.setKProfile(r,{name:Z.name,k_value:parseFloat(Z.k_value).toFixed(6),filament_id:Z.filament_id,nozzle_id:Z.nozzle_id||`HH00-${s}`,nozzle_diameter:Z.nozzle_diameter||s,extruder_id:Z.extruder_id??0,slot_id:0}),O++,await new Promise(ge=>setTimeout(ge,500))}catch(ge){console.error("Failed to import profile:",Z.name,ge)}e(t("kProfiles.toast.importedProfiles",{count:O,total:z.profiles.length})),oe()}catch(ee){console.error("Import error:",ee),e(t("kProfiles.toast.failedToParseImport"),"error")}},X.click()},[r,s,e,oe,t]),Fe=_.useCallback(X=>{R(le=>{const pe=new Set(le);return pe.has(X)?pe.delete(X):pe.add(X),pe})},[]),ce=_.useCallback(()=>{R(new Set(fe.map(X=>H(X))))},[fe,H]),Ve=_.useCallback(()=>{k.size!==0&&P(!0)},[k.size]),V=_.useCallback(async()=>{const X=fe.filter(pe=>k.has(H(pe)));F(!0);let le=0;for(const pe of X)try{await ae.deleteKProfile(r,{slot_id:pe.slot_id,extruder_id:pe.extruder_id,nozzle_id:pe.nozzle_id,nozzle_diameter:pe.nozzle_diameter,filament_id:pe.filament_id,setting_id:pe.setting_id}),le++,await new Promise(ee=>setTimeout(ee,300))}catch(ee){console.error("Failed to delete profile:",pe.name,ee)}e(t("kProfiles.toast.profilesDeleted",{count:le})),F(!1),P(!1),A(!1),R(new Set),oe()},[r,k,fe,e,oe,H,t]),Y=_.useCallback(X=>{const le=[];return X.setting_id&&le.push(X.setting_id),le.push(`slot_${X.slot_id}_${X.filament_id}_${X.extruder_id}`),le.push(`name_${X.name}_${X.filament_id}`),le},[]),ue=_.useCallback(async(X,le)=>{if(r)try{await ae.setKProfileNote(r,X,le),J()}catch(pe){console.error("Failed to save note:",pe),e(t("kProfiles.toast.failedToSaveNote"),"error")}},[r,J,e,t]),q=_.useCallback(X=>{if(!W?.notes)return{note:"",key:null};const le=Y(X);for(const pe of le)if(W.notes[pe])return{note:W.notes[pe],key:pe};return{note:"",key:null}},[W,Y]),re=_.useCallback(X=>q(X).note,[q]);return $?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!D||D.length===0?a.jsx(St,{children:a.jsxs(Et,{className:"py-12 text-center",children:[a.jsx(Ti,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noPrintersConfigured")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.addPrinterInSettings")})]})}):me.length===0?a.jsx(St,{children:a.jsxs(Et,{className:"py-12 text-center",children:[a.jsx(jr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noActivePrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.enablePrinterConnection")})]})}):a.jsxs(a.Fragment,{children:[K&&!I&&a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[a.jsx(ct,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),a.jsx("p",{className:"text-white font-medium",children:t("kProfiles.loadingProfiles")})]}),a.jsxs("div",{className:"flex flex-wrap gap-4 mb-6",children:[a.jsxs("div",{className:"flex-1 min-w-48",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.printer")}),a.jsx("select",{value:r||"",onChange:X=>i(parseInt(X.target.value)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:me.map(X=>a.jsx("option",{value:X.id,children:X.name},X.id))})]}),a.jsxs("div",{className:"w-32",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.nozzle")}),a.jsxs("select",{value:s,onChange:X=>o(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"0.2",children:"0.2mm"}),a.jsx("option",{value:"0.4",children:"0.4mm"}),a.jsx("option",{value:"0.6",children:"0.6mm"}),a.jsx("option",{value:"0.8",children:"0.8mm"})]})]}),a.jsxs("div",{className:"flex items-end gap-2",children:[a.jsxs(Ne,{variant:"secondary",onClick:()=>oe(),disabled:K||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noRead"),children:[a.jsx(Or,{className:`w-4 h-4 ${K?"animate-spin":""}`}),t("kProfiles.refresh")]}),a.jsxs(Ne,{onClick:()=>d(!0),disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noCreate"),children:[a.jsx(cr,{className:"w-4 h-4"}),t("kProfiles.addProfile")]})]})]}),a.jsxs("div",{className:"flex flex-wrap gap-4 mb-4",children:[a.jsxs("div",{className:"flex-1 min-w-48 relative",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:m,onChange:X=>b(X.target.value),placeholder:t("kProfiles.searchPlaceholder"),className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),Re&&a.jsx("div",{className:"w-36",children:a.jsxs("select",{value:y,onChange:X=>x(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("kProfiles.allExtruders")}),a.jsx("option",{value:"left",children:t("kProfiles.leftOnly")}),a.jsx("option",{value:"right",children:t("kProfiles.rightOnly")})]})}),a.jsx("div",{className:"w-32",children:a.jsxs("select",{value:v,onChange:X=>S(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("kProfiles.allFlow")}),a.jsx("option",{value:"hf",children:t("kProfiles.hfOnly")}),a.jsx("option",{value:"s",children:t("kProfiles.sOnly")})]})}),a.jsx("div",{className:"w-32",children:a.jsxs("select",{value:N,onChange:X=>T(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"name",children:t("kProfiles.sortName")}),a.jsx("option",{value:"k_value",children:t("kProfiles.sortKValue")}),a.jsx("option",{value:"filament",children:t("kProfiles.sortFilament")})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[a.jsxs(Ne,{variant:"secondary",onClick:se,disabled:!G?.profiles?.length||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noExport"),children:[a.jsx(wi,{className:"w-4 h-4"}),t("kProfiles.export")]}),a.jsxs(Ne,{variant:"secondary",onClick:ke,disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noImport"),children:[a.jsx(Na,{className:"w-4 h-4"}),t("kProfiles.import")]}),a.jsx("div",{className:"flex-1"}),M?a.jsxs(a.Fragment,{children:[a.jsxs(Ne,{variant:"secondary",onClick:ce,children:[a.jsx(Xs,{className:"w-4 h-4"}),t("kProfiles.selectAll")]}),a.jsxs(Ne,{variant:"secondary",onClick:Ve,disabled:k.size===0||!n("kprofiles:delete"),className:"text-red-500 hover:bg-red-500/10",title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[a.jsx(ln,{className:"w-4 h-4"}),t("kProfiles.delete")," (",k.size,")"]}),a.jsxs(Ne,{variant:"secondary",onClick:()=>{A(!1),R(new Set)},children:[a.jsx(Lt,{className:"w-4 h-4"}),t("common.cancel")]})]}):a.jsxs(Ne,{variant:"secondary",onClick:()=>A(!0),disabled:!fe.length||!n("kprofiles:delete"),title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[a.jsx(Xs,{className:"w-4 h-4"}),t("kProfiles.select")]})]}),I?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):ne?a.jsx(St,{children:a.jsxs(Et,{className:"py-12 text-center",children:[a.jsx(fm,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.printerOffline")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.printerOfflineDesc")}),a.jsxs(Ne,{variant:"secondary",onClick:()=>oe(),children:[a.jsx(Or,{className:"w-4 h-4"}),t("common.refresh")]})]})}):fe.length>0?Re?a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.leftExtruder")}),a.jsx("div",{className:"space-y-1",children:fe.filter(X=>X.extruder_id===1).map(X=>a.jsx(ej,{profile:X,onEdit:()=>c(X),onCopy:()=>p(X),selectionMode:M,isSelected:k.has(H(X)),onToggleSelect:()=>Fe(H(X)),note:re(X)},H(X)))})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.rightExtruder")}),a.jsx("div",{className:"space-y-1",children:fe.filter(X=>X.extruder_id===0).map(X=>a.jsx(ej,{profile:X,onEdit:()=>c(X),onCopy:()=>p(X),selectionMode:M,isSelected:k.has(H(X)),onToggleSelect:()=>Fe(H(X)),note:re(X)},H(X)))})]})]}):a.jsx("div",{className:"space-y-1",children:fe.map(X=>a.jsx(ej,{profile:X,onEdit:()=>c(X),onCopy:()=>p(X),selectionMode:M,isSelected:k.has(H(X)),onToggleSelect:()=>Fe(H(X)),note:re(X)},H(X)))}):m||y!=="all"||v!=="all"?a.jsx(St,{children:a.jsxs(Et,{className:"py-12 text-center",children:[a.jsx(Qi,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noMatchingProfiles")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.noMatchingProfilesDesc")})]})}):a.jsx(St,{children:a.jsxs(Et,{className:"py-12 text-center",children:[a.jsx(vk,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noKProfiles")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.noKProfilesDesc",{diameter:s})}),a.jsxs(Ne,{onClick:()=>d(!0),children:[a.jsx(cr,{className:"w-4 h-4"}),t("kProfiles.createFirstProfile")]})]})}),l&&r&&(()=>{const{note:X,key:le}=q(l);return a.jsx(tj,{profile:l,printerId:r,nozzleDiameter:s,existingProfiles:B?.profiles||G?.profiles,isDualNozzle:Re,initialNote:X,initialNoteKey:le,onSaveNote:ue,hasPermission:n,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),c(null),oe()},onSave:()=>{c(null),oe()}})})(),u&&r&&a.jsx(tj,{printerId:r,nozzleDiameter:s,existingProfiles:B?.profiles||G?.profiles,isDualNozzle:Re,onSaveNote:ue,hasPermission:n,onClose:()=>{d(!1),oe()},onSave:()=>{d(!1),oe()}}),h&&r&&a.jsx(tj,{printerId:r,nozzleDiameter:s,existingProfiles:B?.profiles||G?.profiles,isDualNozzle:Re,onSaveNote:ue,hasPermission:n,profile:{...h,slot_id:0,name:`${h.name} (Copy)`},onClose:()=>{p(null),oe()},onSave:()=>{p(null),oe()}}),C&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-sm",children:a.jsxs(Et,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:a.jsx(ln,{className:"w-5 h-5 text-red-500"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:t("kProfiles.bulkDelete.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("kProfiles.bulkDelete.cannotUndo")})]})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:t("kProfiles.bulkDelete.message",{count:k.size})}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>P(!1),disabled:U,className:"flex-1",children:t("common.cancel")}),a.jsxs(Ne,{onClick:V,disabled:U,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[U?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4"}),t("common.delete")]})]})]})})})]})}const aie=["PLA","PETG","ABS","ASA","TPU","PC","PA","PVA","HIPS","PP","PET","NYLON"],oXe={PLA:"E8E8E8",PETG:"4A90D9",ABS:"E67E22",ASA:"D35400",TPU:"9B59B6",PC:"BDC3C7",PA:"2ECC71",NYLON:"2ECC71",PVA:"F1C40F",HIPS:"95A5A6",PP:"ECF0F1",PET:"3498DB"};function lXe(t){const e=t.toUpperCase();for(const n of aie)if(new RegExp(`\\b${n}\\b`).test(e))return n;return null}function cXe(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const r of aie){const i=n.indexOf(r);if(i>0){const s=e.slice(0,i).trim();if(s&&s.length>1)return s}}return null}function nj({preset:t,onDelete:e,onExpand:n,isExpanded:r}){const{t:i}=Yt(),{hasPermission:s}=Ir(),o=t.filament_type||lXe(t.name),l=t.filament_vendor||cXe(t.name);let c=null,u=!1;if(t.default_filament_colour)try{const d=JSON.parse(t.default_filament_colour),h=Array.isArray(d)?d[0]:d;typeof h=="string"&&/^#?[0-9a-fA-F]{6,8}$/.test(h.replace("#",""))&&(c=h.replace("#","").slice(0,6),u=!0)}catch{const d=t.default_filament_colour;/^#?[0-9a-fA-F]{6,8}$/.test(d.replace("#",""))&&(c=d.replace("#","").slice(0,6),u=!0)}return!c&&o&&(c=oXe[o.toUpperCase()]||null),a.jsx(St,{className:"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80 transition-colors",children:a.jsxs(Et,{className:"p-3",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[t.preset_type==="filament"&&a.jsx("div",{className:`w-4 h-4 rounded-full border border-white/20 flex-shrink-0 ${!u&&!c?"opacity-25":u?"":"opacity-50"}`,style:{backgroundColor:c?`#${c}`:"#666"}}),a.jsx("span",{className:"text-sm font-medium text-white truncate",children:t.name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:o}),l&&a.jsx("span",{className:"text-xs text-bambu-gray",children:l}),a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400",children:i("profiles.localProfiles.badge")})]})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s("settings:update")&&a.jsx("button",{onClick:()=>e(t.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:i("profiles.localProfiles.delete"),children:a.jsx(ln,{className:"w-3.5 h-3.5"})}),a.jsx("button",{onClick:()=>n(r?null:t.id),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r?a.jsx(zu,{className:"w-3.5 h-3.5"}):a.jsx(fr,{className:"w-3.5 h-3.5"})})]})]}),r&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary text-xs space-y-1.5",children:[o&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.filamentType")}),a.jsx("span",{className:"text-white",children:o})]}),l&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.vendor")}),a.jsx("span",{className:"text-white",children:l})]}),t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.nozzleTemp")}),a.jsxs("span",{className:"text-white",children:[t.nozzle_temp_min,"–",t.nozzle_temp_max,"°C"]})]}),t.filament_cost&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.cost")}),a.jsx("span",{className:"text-white",children:t.filament_cost})]}),t.filament_density&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.density")}),a.jsxs("span",{className:"text-white",children:[t.filament_density," g/cm³"]})]}),t.pressure_advance&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.pressureAdvance")}),a.jsx("span",{className:"text-white",children:t.pressure_advance})]}),t.compatible_printers&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.compatiblePrinters")}),a.jsx("span",{className:"text-white truncate ml-2",children:(()=>{try{return JSON.parse(t.compatible_printers).join(", ")}catch{return t.compatible_printers}})()})]}),t.inherits&&t.inherits!==t.name&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.inheritsFrom")}),a.jsx("span",{className:"text-white truncate ml-2",children:t.inherits})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.source")}),a.jsx("span",{className:"text-white capitalize",children:t.source})]})]})]})})}function uXe(){const{t}=Yt(),{hasPermission:e}=Ir(),n=an(),{showToast:r}=Tn(),[i,s]=_.useState(""),[o,l]=_.useState(null),[c,u]=_.useState(!1),[d,h]=_.useState(null),{data:p,isLoading:m}=it({queryKey:["localPresets"],queryFn:()=>ae.getLocalPresets()}),b=dt({mutationFn:async k=>{const R=[];for(const C of Array.from(k)){const P=new FormData;P.append("file",C),R.push(await ae.importLocalPresets(P))}return R},onSuccess:k=>{n.invalidateQueries({queryKey:["localPresets"]});let R=0,C=0,P=0;for(const U of k)R+=U.imported,C+=U.skipped,P+=U.errors.length;R>0&&r(t("profiles.localProfiles.toast.importSuccess",{count:R})),C>0&&r(t("profiles.localProfiles.toast.importSkipped",{count:C}),"warning"),P>0&&r(t("profiles.localProfiles.toast.importError",{count:P}),"error")},onError:k=>{r(k.message,"error")}}),y=dt({mutationFn:k=>ae.deleteLocalPreset(k),onSuccess:()=>{n.invalidateQueries({queryKey:["localPresets"]}),h(null),r(t("profiles.localProfiles.toast.deleted"))}}),x=_.useCallback(k=>{!k||k.length===0||b.mutate(k)},[b]),v=_.useCallback(k=>{k.preventDefault(),u(!1),x(k.dataTransfer.files)},[x]),S=_.useCallback(k=>{if(!i)return k;const R=i.toLowerCase();return k.filter(C=>C.name.toLowerCase().includes(R)||C.filament_type?.toLowerCase().includes(R)||C.filament_vendor?.toLowerCase().includes(R))},[i]),N=_.useMemo(()=>S(p?.filament||[]),[p?.filament,S]),T=_.useMemo(()=>S(p?.printer||[]),[p?.printer,S]),M=_.useMemo(()=>S(p?.process||[]),[p?.process,S]),A=N.length+T.length+M.length;return m?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"space-y-6",children:[e("settings:update")&&a.jsxs("div",{onDragOver:k=>{k.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:v,className:`relative border-2 border-dashed rounded-lg p-6 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("input",{type:"file",accept:".json,.zip,.orca_filament,.bbscfg,.bbsflmt",multiple:!0,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer",onChange:k=>x(k.target.files)}),b.isPending?a.jsxs("div",{className:"flex items-center justify-center gap-2",children:[a.jsx(ct,{className:"w-5 h-5 text-bambu-green animate-spin"}),a.jsx("span",{className:"text-bambu-gray",children:t("profiles.localProfiles.importing")})]}):a.jsxs(a.Fragment,{children:[a.jsx(Na,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-white font-medium",children:t("profiles.localProfiles.import")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("profiles.localProfiles.importDesc")})]})]}),A>0&&a.jsxs("div",{className:"relative",children:[a.jsx(Qi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:i,onChange:k=>s(k.target.value),placeholder:t("profiles.localProfiles.search"),className:"w-full pl-9 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),A===0&&!m&&a.jsxs("div",{className:"text-center py-12",children:[a.jsx(Sb,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3 opacity-50"}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.localProfiles.noPresets")}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:t("profiles.localProfiles.importDesc")})]}),A>0&&a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[N.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(gk,{className:"w-4 h-4 text-bambu-green"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",N.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:N.map(k=>a.jsx(nj,{preset:k,onDelete:R=>h(R),onExpand:l,isExpanded:o===k.id},k.id))})]}),M.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(is,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",M.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:M.map(k=>a.jsx(nj,{preset:k,onDelete:R=>h(R),onExpand:l,isExpanded:o===k.id},k.id))})]}),T.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Hu,{className:"w-4 h-4 text-orange-400"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",T.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:T.map(k=>a.jsx(nj,{preset:k,onDelete:R=>h(R),onExpand:l,isExpanded:o===k.id},k.id))})]})]}),d!==null&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-6 max-w-sm mx-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Ti,{className:"w-5 h-5 text-red-400"}),a.jsx("h3",{className:"text-white font-medium",children:t("profiles.localProfiles.deleteConfirmTitle")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:t("profiles.localProfiles.deleteConfirm")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Ne,{variant:"secondary",size:"sm",onClick:()=>h(null),children:t("profiles.localProfiles.cancel")}),a.jsxs(Ne,{variant:"danger",size:"sm",onClick:()=>y.mutate(d),disabled:y.isPending,children:[y.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{className:"w-4 h-4"}),t("profiles.localProfiles.delete")]})]})]})})]})}function MF(t,e){const n=`${t} ${e||""}`,r=n.match(/@?\s*(?:BBL\s+)?(?:Bambu\s+Lab\s+)?([XPAH][1-9][A-Z]?(?:\s*(?:Carbon|mini))?|H2D)/i),i=r?r[1].trim():null,s=n.match(/(\d+\.?\d*)\s*(?:mm\s*)?nozzle|nozzle\s*(\d+\.?\d*)/i),o=s?(s[1]||s[2])+"mm":null,l=n.match(/(\d+\.?\d*)mm\s*(?:Standard|Fine|Extra Fine|Draft|Quality)?/i),c=l?l[1]+"mm":null,u=n.match(/\b(PLA|PETG|ABS|ASA|TPU|PC|PA|PVA|HIPS|PP|PET(?:-?CF)?|PA(?:-?CF)?|PLA(?:-?CF)?)\b/i),d=u?u[1].toUpperCase():null;return{printer:i,nozzle:o,layerHeight:c,filamentType:d}}function zy(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function dXe(t,e){const n=zi(t);if(!n)return"";const i=new Date().getTime()-n.getTime(),s=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return s<1?e("profiles.time.justNow"):s<60?e("profiles.time.minsAgo",{count:s}):o<24?e("profiles.time.hoursAgo",{count:o}):l<7?e("profiles.time.daysAgo",{count:l}):n.toLocaleDateString()}function hXe({onSuccess:t,t:e}){const{showToast:n}=Tn(),[r,i]=_.useState("email"),[s,o]=_.useState(""),[l,c]=_.useState(""),[u,d]=_.useState(""),[h,p]=_.useState(""),[m,b]=_.useState("global"),[y,x]=_.useState(null),[v,S]=_.useState(null),N=dt({mutationFn:()=>ae.cloudLogin(s,l,m),onSuccess:R=>{R.success?(n(e("profiles.login.toast.loggedIn")),t()):R.needs_verification?(x(R.verification_type||"email"),S(R.tfa_key||null),R.verification_type==="totp"?n(e("profiles.login.toast.enterTotp")):n(e("profiles.login.toast.codeSent")),i("code")):n(R.message,"error")},onError:R=>n(R.message,"error")}),T=dt({mutationFn:()=>ae.cloudVerify(s,u,v||void 0),onSuccess:R=>{R.success?(n(e("profiles.login.toast.loggedIn")),t()):n(R.message,"error")},onError:R=>n(R.message,"error")}),M=dt({mutationFn:()=>ae.cloudSetToken(h),onSuccess:()=>{n(e("profiles.login.toast.tokenSet")),t()},onError:R=>n(R.message,"error")}),A=R=>{R.preventDefault(),r==="email"?N.mutate():r==="code"?T.mutate():r==="token"&&M.mutate()},k=N.isPending||T.isPending||M.isPending;return a.jsx(St,{className:"max-w-md mx-auto",children:a.jsxs(Et,{children:[a.jsxs("div",{className:"text-center mb-6",children:[a.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-bambu-green/20 mb-3",children:a.jsx(pk,{className:"w-6 h-6 text-bambu-green"})}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:e("profiles.login.title")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:e("profiles.login.subtitle")})]}),a.jsxs("form",{onSubmit:A,className:"space-y-4",children:[r==="email"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.email")}),a.jsx("input",{type:"email",value:s,onChange:R=>o(R.target.value),className:"w-full px-3 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",placeholder:"your@email.com",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.password")}),a.jsx("input",{type:"password",value:l,onChange:R=>c(R.target.value),className:"w-full px-3 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",placeholder:"••••••••",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.region")}),a.jsxs("select",{value:m,onChange:R=>b(R.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"global",children:e("profiles.login.regionGlobal")}),a.jsx("option",{value:"china",children:e("profiles.login.regionChina")})]})]})]}),r==="code"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e(y==="totp"?"profiles.login.totpCode":"profiles.login.verificationCode")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:y==="totp"?e("profiles.login.enterTotpHint"):e("profiles.login.checkEmail",{email:s})}),a.jsx("input",{type:"text",value:u,onChange:R=>d(R.target.value.replace(/\D/g,"").slice(0,6)),className:"w-full px-3 py-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-center text-2xl tracking-widest font-mono focus:border-bambu-green focus:outline-none",placeholder:"000000",maxLength:6,required:!0})]}),r==="token"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.accessToken")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:e("profiles.login.accessTokenHint")}),a.jsx("textarea",{value:h,onChange:R=>p(R.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs font-mono placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none resize-none",placeholder:"eyJ...",rows:4,required:!0})]}),a.jsxs("div",{className:"flex gap-2",children:[r==="code"&&a.jsx(Ne,{type:"button",variant:"secondary",onClick:()=>i("email"),className:"flex-1",children:e("profiles.login.back")}),a.jsxs(Ne,{type:"submit",disabled:k,className:"flex-1",children:[k?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(QU,{className:"w-4 h-4"}),e(r==="email"?"profiles.login.loginButton":r==="code"?"profiles.login.verifyButton":"profiles.login.setTokenButton")]})]}),r==="email"&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("button",{type:"button",onClick:()=>i("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[a.jsx(Yo,{className:"w-4 h-4"}),e("profiles.login.useToken")]})}),r==="token"&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("button",{type:"button",onClick:()=>i("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[a.jsx(QU,{className:"w-4 h-4"}),e("profiles.login.useEmail")]})})]})]})})}function og({label:t,value:e,options:n,onChange:r}){const[i,s]=_.useState(!1),o=n.find(l=>l.value===e);return a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>s(!i),className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white hover:border-bambu-gray-dark transition-colors",children:[a.jsxs("span",{className:"text-bambu-gray",children:[t,":"]}),a.jsx("span",{children:o?.label||"All"}),a.jsx(fr,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"rotate-180":""}`})]}),i&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>s(!1)}),a.jsx("div",{className:"absolute top-full left-0 mt-1 min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 py-1 max-h-60 overflow-y-auto",children:n.map(l=>a.jsxs("button",{onClick:()=>{r(l.value),s(!1)},className:`w-full px-3 py-2 text-left text-sm flex items-center justify-between hover:bg-bambu-dark-tertiary transition-colors ${e===l.value?"text-bambu-green":"text-white"}`,children:[a.jsx("span",{children:l.label}),l.count!==void 0&&a.jsx("span",{className:"text-bambu-gray text-xs",children:l.count})]},l.value))})]})]})}function fXe(){const[t,e]=_.useState(!1);_.useEffect(()=>{const r=()=>{e(window.scrollY>300)};return window.addEventListener("scroll",r),()=>window.removeEventListener("scroll",r)},[]);const n=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?a.jsx("button",{onClick:n,className:"fixed bottom-6 right-6 p-3 bg-bambu-green hover:bg-bambu-green-light text-white rounded-full shadow-lg shadow-bambu-green/25 transition-all z-40","aria-label":"Scroll to top",children:a.jsx(Hg,{className:"w-5 h-5"})}):null}function rj({setting:t,onClick:e,onDuplicate:n,compareMode:r,isCompareSelected:i,compareIndex:s,compareDisabled:o,t:l}){const c=MF(t.name),u=zy(t.setting_id);return a.jsxs("div",{className:"flex items-center gap-2 group",children:[a.jsx("button",{onClick:e,disabled:o,className:`flex-1 text-left px-3 py-2 rounded transition-colors ${i?"bg-blue-500/20 border border-blue-500/50":o?"bg-bambu-dark/50 opacity-40 cursor-not-allowed":"bg-bambu-dark hover:bg-bambu-dark-tertiary"} ${r&&!o?"cursor-pointer":""}`,children:a.jsxs("div",{className:"flex items-center gap-2",children:[i&&s!==void 0&&a.jsx("span",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-blue-500 text-white text-xs flex items-center justify-center font-medium",children:s+1}),!i&&u&&a.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:l("profiles.presets.myPreset")}),a.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),c.filamentType&&t.type==="filament"&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.filamentType}),c.layerHeight&&t.type==="process"&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.layerHeight}),c.printer&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.printer})]})}),a.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"opacity-0 group-hover:opacity-100 text-bambu-gray hover:text-white transition-all p-1",title:l("profiles.presets.duplicate"),children:a.jsx(zl,{className:"w-4 h-4"})})]})}function NR(t,e=0){const n=" ".repeat(e);if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string"){if(t.includes("\\n")||t.includes(` `)){const i=t.replace(/\\n/g,` `).replace(/\\"/g,'"').replace(/\\t/g," ").split(` `);if(i.length>1)return`""" @@ -8678,6 +8678,6 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${s0(t. `+n+"]";if(typeof t=="object"){const r=Object.entries(t);return r.length===0?"{}":`{ `+r.map(([s,o])=>n+" "+JSON.stringify(s)+": "+NR(o,e+1)).join(`, `)+` -`+n+"}"}return String(t)}function fXe({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=Tn(),c=an(),[u,d]=_.useState(!1),{data:h,isLoading:p}=it({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ae.getCloudSettingDetail(t.setting_id)}),m=dt({mutationFn:()=>ae.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:x=>l(x.message,"error")}),b=zy(t.setting_id),y=MF(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(St,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:a.jsxs(Et,{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}),b&&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}`)}),y.printer&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"•"}),a.jsx("span",{children:y.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(Lt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{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:NR(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(En,{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(Ne,{variant:"secondary",onClick:()=>d(!1),disabled:m.isPending,className:"flex-1",children:o("common.cancel")}),a.jsxs(Ne,{variant:"danger",onClick:()=>m.mutate(),disabled:m.isPending,className:"flex-1",children:[m.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{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(Ne,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),a.jsxs(Ne,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[a.jsx(zl,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),b&&a.jsxs(a.Fragment,{children:[a.jsxs(Ne,{variant:"secondary",onClick:i,disabled:p||!h||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[a.jsx(Ji,{className:"w-4 h-4"}),o("common.edit")]}),a.jsx(Ne,{variant:"danger",onClick:()=>d(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:a.jsx(ln,{className:"w-4 h-4"})})]})]})})]})})})}function sie(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function oie(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function mXe({onClose:t,onApply:e,t:n}){const{showToast:r}=Tn(),[i,s]=_.useState(sie),[o,l]=_.useState("all"),[c,u]=_.useState(null),[d,h]=_.useState(""),[p,m]=_.useState(""),[b,y]=_.useState("{}"),[x,v]=_.useState(null),[S,N]=_.useState(null),T=o==="all"?i:i.filter(H=>H.type===o),M=H=>{s(H),oie(H)},A=H=>{const D=i.filter($=>$.id!==H);M(D),N(null),r(n("profiles.templates.toast.deleted"))},k=H=>{u(H.id),h(H.name),m(H.description),y(JSON.stringify(H.settings,null,2)),v(null)},R=()=>{if(!(!c||!d.trim()))try{const H=JSON.parse(b),D=i.map($=>$.id===c?{...$,name:d.trim(),description:p.trim(),settings:H}:$);M(D),u(null),r(n("profiles.templates.toast.updated"))}catch(H){v(H.message)}},C=()=>{u(null),h(""),m(""),y("{}"),v(null)},P=H=>{const D=i.map($=>$.id===H?{...$,showInModal:!$.showInModal}:$);M(D)},U={filament:{label:n("profiles.presets.types.filament"),icon:gk,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:Hu,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:jr,color:"text-purple-400"}},F=S?i.find(H=>H.id===S):null;return _.useEffect(()=>{const H=D=>{D.key==="Escape"&&(S?N(null):c?C():t())};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[S,c,t]),a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[F&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:a.jsx(St,{className:"w-full max-w-md",children:a.jsxs(Et,{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(En,{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:F.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),a.jsxs(Ne,{onClick:()=>A(S),className:"flex-1 bg-red-500 hover:bg-red-600",children:[a.jsx(ln,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),a.jsx(St,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:a.jsxs(Et,{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(Z0,{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(Lt,{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(H=>a.jsx("button",{onClick:()=>l(H),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===H?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:H==="all"?n("common.all"):U[H].label},H))]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:T.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(Z0,{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:T.map(H=>{const D=U[H.type],$=D.icon;return c===H.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:G=>h(G.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:p,onChange:G=>m(G.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:b,onChange:G=>{y(G.target.value),v(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 ${x?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),x&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:x})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ne,{size:"sm",onClick:R,disabled:!d.trim(),children:[a.jsx(vs,{className:"w-4 h-4"}),"Save"]}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:C,children:"Cancel"})]})]},H.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($,{className:`w-5 h-5 ${D.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:H.name}),a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:H.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(H.settings).length})}),a.jsx("button",{onClick:()=>P(H.id),className:`p-1 transition-colors ${H.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:H.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:H.showInModal?a.jsx(gc,{className:"w-4 h-4"}):a.jsx(bk,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>e(H),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(H),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:a.jsx(Ji,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>N(H.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:a.jsx(ln,{className:"w-4 h-4"})})]},H.id)})})})]})})]})}function lie({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:i,t:s}){const[o,l]=_.useState("changes"),[c,u]=_.useState(""),d=_.useMemo(()=>{const b=new Set([...Object.keys(e),...Object.keys(n)]),y=[];for(const x of b){if(x==="inherits"||x==="version")continue;const v=e[x],S=n[x],N=x in e,T=x in n;let M;!N&&T?M="added":N&&!T?M="removed":JSON.stringify(v)!==JSON.stringify(S)?M="changed":M="same",y.push({key:x,left:v,right:S,status:M})}return y.sort((x,v)=>{const S={changed:0,added:1,removed:2,same:3};return S[x.status]!==S[v.status]?S[x.status]-S[v.status]:x.key.localeCompare(v.key)})},[e,n]),h=_.useMemo(()=>{let b=[...d];if(o==="changes"&&(b=b.filter(y=>y.status!=="same")),c){const y=c.toLowerCase();b=b.filter(x=>x.key.toLowerCase().includes(y)||String(x.left).toLowerCase().includes(y)||String(x.right).toLowerCase().includes(y))}return b},[d,o,c]),p=_.useMemo(()=>({added:d.filter(b=>b.status==="added").length,removed:d.filter(b=>b.status==="removed").length,changed:d.filter(b=>b.status==="changed").length,same:d.filter(b=>b.status==="same").length}),[d]),m=b=>{if(b===void 0)return"—";if(b===null)return"null";if(Array.isArray(b))return b.length===0?"[]":b.length===1?String(b[0]):b.join(", ");if(typeof b=="object")return JSON.stringify(b);const y=String(b);if(y.includes("\\n")||y.length>100){const x=y.split("\\n").length;if(x>1)return`[${x} lines of G-code/script]`;if(y.length>100)return y.substring(0,100)+"…"}return y};return _.useEffect(()=>{const b=y=>{y.key==="Escape"&&t()};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:a.jsxs(Et,{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(Mg,{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(Lt,{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(cr,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(Aj,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[a.jsx(_j,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(hT,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"relative",children:[a.jsx(Qi,{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:b=>u(b.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"})]}),p.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(hT,{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(b=>{const y={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[b.status],x={added:a.jsx(cr,{className:"w-3.5 h-3.5 text-green-400"}),removed:a.jsx(Aj,{className:"w-3.5 h-3.5 text-red-400"}),changed:a.jsx(_j,{className:"w-3.5 h-3.5 text-amber-400"}),same:a.jsx(hT,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[b.status];return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${y}`,children:[a.jsx("td",{className:"p-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[x,a.jsx("span",{className:"text-sm text-white font-mono",children:b.key})]})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${b.status==="removed"?"text-red-300":b.status==="changed"?"text-white":"text-bambu-gray"}`,children:m(b.left)})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${b.status==="added"?"text-green-300":b.status==="changed"?"text-white":"text-bambu-gray"}`,children:m(b.right)})})]},b.key)})})]})})]})})})}function pXe({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:i}=Tn(),s=an(),o=!!e?.setting_id,[l,c]=_.useState("common"),[u,d]=_.useState(e?.type||"filament"),[h,p]=_.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[m,b]=_.useState(e?.base_id||""),[y,x]=_.useState(""),[v,S]=_.useState(e?.setting||{inherits:""}),[N,T]=_.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[M,A]=_.useState(null),[k,R]=_.useState(""),[C,P]=_.useState(!1),[U,F]=_.useState(""),[H,D]=_.useState(!1),[$,G]=_.useState(sie),[I,K]=_.useState(!1),[Q,oe]=_.useState(""),[B,W]=_.useState(""),[J,ne]=_.useState(!0),[me,fe]=_.useState(null),[de,Re]=_.useState(!1),se=_.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),ke=_.useMemo(()=>se.filter(Me=>zy(Me.setting_id)),[se]),{data:Fe}=it({queryKey:["cloudFields",u],queryFn:()=>ae.getCloudFields(u==="print"?"process":u),staleTime:1e3*60*60}),{data:ce}=it({queryKey:["allPresetDetails",u,ke.map(Me=>Me.setting_id).join(",")],queryFn:async()=>{const Me={};for(let Ae=0;Ae{try{const Ee=await ae.getCloudSettingDetail(et.setting_id);return{id:et.setting_id,detail:Ee}}catch{return null}}))).forEach(et=>{et&&(Me[et.id]=et.detail)})}return Me},enabled:ke.length>0,staleTime:1e3*60*10}),{data:Ve,isLoading:V}=it({queryKey:["cloudSettingDetail",m],queryFn:()=>ae.getCloudSettingDetail(m),enabled:!!m});_.useEffect(()=>{l!=="json"&&T(JSON.stringify(v,null,2))},[v,l]);const Y=_.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(Be=>!zy(Be.setting_id)).sort((Be,Ae)=>Be.name.localeCompare(Ae.name)),[n,u]);_.useEffect(()=>{if(!m)return;const Me=Y.find(Be=>Be.setting_id===m);Me&&(x(Me.name),o||(S({inherits:Me.name}),T(JSON.stringify({inherits:Me.name},null,2))))},[m,Y,o]);const ue=_.useMemo(()=>{const Me=Fe?.fields||[],Be=new Set(Me.map(et=>et.key)),Ae=new Set,qe=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);ce&&Object.values(ce).forEach(et=>{et?.setting&&Object.keys(et.setting).forEach(Ee=>{!Be.has(Ee)&&!qe.has(Ee)&&Ae.add(Ee)})}),Object.keys(v).forEach(et=>{!Be.has(et)&&!qe.has(et)&&Ae.add(et)});const ve=Array.from(Ae).sort().map(et=>({key:et,label:et.replace(/_/g," ").replace(/\b\w/g,Ee=>Ee.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Me,...ve]},[Fe,ce,v,r]),q=ue.filter(Me=>Me.label.toLowerCase().includes(k.toLowerCase())||Me.key.toLowerCase().includes(k.toLowerCase())),re=()=>{if(U.trim()){const Me=U.trim().toLowerCase().replace(/\s+/g,"_");X(Me,""),F(""),D(!1),i(r("profiles.presets.toast.fieldAdded",{key:Me}))}},X=(Me,Be)=>{S(Ae=>{const qe={...Ae};return Be===""||Be===void 0?delete qe[Me]:qe[Me]=Be,qe})},le=Me=>{S(Be=>({...Be,...Me.settings})),fe(Me.name),i(r("profiles.templates.toast.applied"))},pe=()=>{if(!Q.trim())return;const Me={...v};if(delete Me.inherits,Object.keys(Me).length===0){i(r("profiles.presets.noOverridesToSave"),"error");return}const Be={id:Date.now().toString(),name:Q.trim(),description:B.trim()||r("profiles.presets.customTemplate"),type:u,settings:Me,showInModal:J},Ae=[...$,Be];G(Ae),oie(Ae),K(!1),oe(""),W(""),ne(!0),i(r("profiles.templates.toast.created"))},ee=_.useMemo(()=>$.filter(Me=>Me.type===u&&Me.showInModal),[u,$]),z=Me=>{T(Me);try{const Be=JSON.parse(Me);S(Be),A(null)}catch(Be){A(Be.message)}},O=Me=>{Me.preventDefault(),P(!1);const Be=Me.dataTransfer.files[0];if(Be&&Be.name.endsWith(".json")){const Ae=new FileReader;Ae.onload=qe=>{try{const ve=qe.target?.result,et=JSON.parse(ve),Ee=et.setting||et;S(Ye=>({...Ye,...Ee})),T(JSON.stringify({...v,...Ee},null,2)),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJsonFile"),"error")}},Ae.readAsText(Be)}},Z=dt({mutationFn:()=>{const Me={...v},Be=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";Me[Be]=`"${h}"`;const Ae={type:u,name:h,base_id:m,setting:Me};return ae.createCloudSetting(Ae)},onSuccess:async()=>{i(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Me=>i(Me.message,"error")}),ge=dt({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return ae.updateCloudSetting(e.setting_id,{name:h,setting:v})},onSuccess:async()=>{i(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Me=>i(Me.message,"error")}),Ce=o?ge:Z,_e=Ve?.setting?.inherits,Te=_e?Y.find(Me=>Me.name===_e):void 0,{data:we}=it({queryKey:["cloudSettingDetail",Te?.setting_id],queryFn:()=>ae.getCloudSettingDetail(Te.setting_id),enabled:!!Te?.setting_id}),$e=_.useMemo(()=>{const Me=we?.setting||{},Be=Ve?.setting||{},Ae=m&&ce?.[m]?.setting?ce[m].setting:{};return{...Me,...Be,...Ae}},[m,Ve,we,ce]),Ge=Me=>{if(Me==null)return"";if(Array.isArray(Me)){const Be=[...new Set(Me.map(Ae=>String(Ae)))];return Be.length===1?Be[0]:Me.join(", ")}return String(Me)},ze=Me=>{const Be=v[Me.key],Ae=$e[Me.key],qe=Ge(Ae),ve=V?r("common.loading"):qe||"",et="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(Me.type==="boolean"){const Ee=Be==="1"||Be===void 0&&Ae==="1";return a.jsx("button",{type:"button",onClick:()=>X(Me.key,Be==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Ee?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Ee?"translate-x-3.5":"translate-x-0.5"}`})})}return Me.type==="select"?a.jsxs("select",{value:Be||"",onChange:Ee=>X(Me.key,Ee.target.value),className:et,children:[a.jsx("option",{value:"",children:ve}),Me.options?.map(Ee=>a.jsx("option",{value:Ee.value,children:Ee.label},Ee.value))]}):a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:Me.type==="number"?"number":"text",value:Be!==void 0?String(Be):"",onChange:Ee=>X(Me.key,Ee.target.value),step:Me.step,min:Me.min,max:Me.max,placeholder:ve,className:et}),Me.unit&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Me.unit})]})},be=_.useMemo(()=>Ve?.setting?Ve.setting:{},[Ve]);return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Me=>{Me.preventDefault(),P(!0)},onDragLeave:()=>P(!1),onDrop:O,children:[de&&m&&a.jsx(lie,{onClose:()=>Re(!1),leftPreset:be,rightPreset:v,leftLabel:r("profiles.presets.baseLabel",{name:y||m}),rightLabel:r("profiles.presets.currentLabel",{name:h||r("profiles.presets.newPreset")}),t:r}),a.jsx(St,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col",children:a.jsxs(Et,{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:[m&&a.jsxs("button",{onClick:()=>Re(!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(Mg,{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(Lt,{className:"w-5 h-5"})})]})]}),C&&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(Na,{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",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:Me=>{d(Me.target.value),b("")},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:m,onChange:Me=>b(Me.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")}),Y.map(Me=>a.jsx("option",{value:Me.setting_id,children:Me.name},Me.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:Me=>p(Me.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")})]})]}),y&&a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("p",{className:"flex items-center gap-1",children:[a.jsx($i,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",a.jsx("span",{className:"text-white",children:y}),V&&a.jsx(ct,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",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(ZU,{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(_k,{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(DW,{className:"w-4 h-4"}),"JSON",M&&a.jsx(Ti,{className:"w-3 h-3 text-red-400"})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("button",{onClick:()=>{const Me={name:h,type:u,base_id:m,setting:v},Be=new Blob([JSON.stringify(Me,null,2)],{type:"application/json"}),Ae=URL.createObjectURL(Be),qe=document.createElement("a");qe.href=Ae,qe.download=`${h||"preset"}.json`,document.body.appendChild(qe),qe.click(),document.body.removeChild(qe),URL.revokeObjectURL(Ae),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(wi,{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(Na,{className:"w-4 h-4"}),r("common.upload")]}),a.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Me=>{const Be=Me.target.files?.[0];if(Be){const Ae=new FileReader;Ae.onload=qe=>{try{const ve=JSON.parse(qe.target?.result),et=ve.setting||ve;S(Ee=>({...Ee,...et})),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJson"),"error")}},Ae.readAsText(Be)}}})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto 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(Z0,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(v).filter(Me=>Me!=="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(vs,{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:Q,onChange:Me=>oe(Me.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:B,onChange:Me=>W(Me.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(Ne,{size:"sm",onClick:pe,disabled:!Q.trim(),children:[a.jsx(vs,{className:"w-3 h-3"}),r("common.save")]}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:()=>K(!1),children:r("common.cancel")})]}),a.jsxs("button",{onClick:()=>ne(!J),className:`flex items-center gap-1.5 text-xs transition-colors ${J?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[J?a.jsx(gc,{className:"w-3.5 h-3.5"}):a.jsx(bk,{className:"w-3.5 h-3.5"}),r(J?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),me&&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($i,{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:me})]}),a.jsx("button",{onClick:()=>fe(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:a.jsx(Lt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[ee.map(Me=>a.jsxs("button",{onClick:()=>le(Me),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:Me.name}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Me.description})]},Me.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(Me=>a.jsxs("div",{className:"flex items-center justify-between gap-4",children:[a.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Me.label}),a.jsx("div",{className:"w-48",children:ze(Me)})]},Me.key))})]}),Object.keys(v).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(v).filter(([Me])=>Me!=="inherits").map(([Me,Be])=>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:[Me,": ",String(Be).slice(0,20),a.jsx("button",{onClick:()=>X(Me,void 0),className:"hover:text-white",children:a.jsx(Lt,{className:"w-3 h-3"})})]},Me))})]})]}),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:ce?r("profiles.templates.fieldsCount",{count:ue.length}):r("common.loading")})]}),a.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[a.jsx(Qi,{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:Me=>R(Me.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:[q.filter(Me=>!(Me.key in v)).map(Me=>{const Be=$e[Me.key],Ae=Ge(Be);return a.jsxs("div",{onClick:()=>{S(qe=>({...qe,[Me.key]:Ae||""}))},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:Me.label}),a.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Me.key})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Ae&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Ae,children:[Ae.slice(0,20),Ae.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(cr,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Me.key)}),q.filter(Me=>!(Me.key in v)).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:H?a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:U,onChange:Me=>F(Me.target.value),onKeyDown:Me=>Me.key==="Enter"&&re(),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(Ne,{size:"sm",onClick:re,disabled:!U.trim(),children:a.jsx(cr,{className:"w-4 h-4"})}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:()=>{D(!1),F("")},children:a.jsx(Lt,{className:"w-4 h-4"})})]}):a.jsxs("button",{onClick:()=>D(!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(cr,{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(v).filter(Me=>Me!=="inherits").length})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(v).filter(([Me])=>Me!=="inherits").map(([Me,Be])=>{const Ae=ue.find(qe=>qe.key===Me);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:Ae?.label||Me}),a.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Me})]}),a.jsx("button",{onClick:()=>X(Me,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:a.jsx(Lt,{className:"w-4 h-4"})})]}),Ae?ze(Ae):a.jsx("input",{type:"text",value:String(Be),onChange:qe=>X(Me,qe.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"})]},Me)}),Object.keys(v).filter(Me=>Me!=="inherits").length===0&&a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(ZU,{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(v).filter(Me=>Me!=="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(vs,{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(Ti,{className:"w-4 h-4"}),M]}),a.jsx("textarea",{value:N,onChange:Me=>z(Me.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(Ne,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsxs(Ne,{onClick:()=>Ce.mutate(),disabled:Ce.isPending||!h.trim()||!o&&!m||!!M,className:"flex-1",children:[Ce.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):o?a.jsx(vs,{className:"w-4 h-4"}):a.jsx(cr,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function gXe({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:i,hasPermission:s,t:o}){const[l,c]=_.useState(""),[u,d]=_.useState("all"),[h,p]=_.useState("all"),[m,b]=_.useState("all"),[y,x]=_.useState("all"),[v,S]=_.useState("all"),[N,T]=_.useState("all"),[M,A]=_.useState(null),[k,R]=_.useState(!1),[C,P]=_.useState(!1),[U,F]=_.useState(null),[H,D]=_.useState(null),[$,G]=_.useState(null),[I,K]=_.useState(!1),[Q,oe]=_.useState([null,null]),[B,W]=_.useState(!1),[J,ne]=_.useState(null),me=an(),fe=_.useMemo(()=>[...t.filament.map(re=>({...re,type:"filament"})),...t.printer.map(re=>({...re,type:"printer"})),...t.process.map(re=>({...re,type:"process"}))].map(re=>({...re,meta:MF(re.name)})),[t]),de=_.useMemo(()=>{const q=new Set,re=new Set,X=new Set;return fe.forEach(le=>{le.meta.nozzle&&q.add(le.meta.nozzle),le.meta.filamentType&&re.add(le.meta.filamentType),le.meta.layerHeight&&X.add(le.meta.layerHeight)}),{printers:i.map(le=>({id:le.id.toString(),name:le.name})),nozzles:Array.from(q).sort((le,pe)=>parseFloat(le)-parseFloat(pe)),filaments:Array.from(re).sort(),layerHeights:Array.from(X).sort((le,pe)=>parseFloat(le)-parseFloat(pe))}},[fe,i]),Re=_.useMemo(()=>m==="all"?null:i.find(re=>re.id.toString()===m)?.model||null,[m,i]),se=_.useMemo(()=>fe.filter(q=>u==="all"||q.type===u).filter(q=>{if(h==="all")return!0;const re=zy(q.setting_id);return h==="custom"?re:!re}).filter(q=>{if(m==="all"||!Re)return!0;const re=q.meta.printer?.toLowerCase()||"",X=Re.toLowerCase();return re.includes(X)||X.includes(re)}).filter(q=>y==="all"||q.meta.nozzle===y).filter(q=>v==="all"||q.meta.filamentType===v).filter(q=>N==="all"||q.meta.layerHeight===N).filter(q=>l===""||q.name.toLowerCase().includes(l.toLowerCase())).sort((q,re)=>q.name.localeCompare(re.name)),[fe,u,h,m,Re,y,v,N,l]),ke=q=>{if(I){const re=Q[0]?.setting_id===q.setting_id,X=Q[1]?.setting_id===q.setting_id;if(re)oe([Q[1],null]);else if(X)oe([Q[0],null]);else if(!Q[0])oe([q,null]);else if(Q[1]){if(Q[0].type!==q.type)return;oe([Q[0],q])}else{if(Q[0].type!==q.type)return;oe([Q[0],q])}}else A(q)},Fe=q=>{if(Q[0]?.setting_id===q.setting_id)return 0;if(Q[1]?.setting_id===q.setting_id)return 1},ce=async q=>{try{const re=await ae.getCloudSettingDetail(q.setting_id),X=q.type==="process"?"print":q.type;F({type:X,name:q.name,base_id:re.base_id||"GFSA00",setting:re.setting||{}}),A(null)}catch(re){console.error("Failed to fetch preset details for duplication:",re)}},Ve=async q=>{try{me.removeQueries({queryKey:["cloudSettingDetail",q.setting_id]});const re=await ae.getCloudSettingDetail(q.setting_id),X=q.type==="process"?"print":q.type;D({type:X,name:q.name,base_id:re.base_id||"GFSA00",setting:re.setting||{},setting_id:q.setting_id}),A(null)}catch(re){console.error("Failed to fetch preset details for editing:",re)}},V=()=>{d("all"),p("all"),b("all"),x("all"),S("all"),T("all"),c("")},Y=u!=="all"||h!=="all"||m!=="all"||y!=="all"||v!=="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(Qi,{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:q=>c(q.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",children:[a.jsxs(Ne,{variant:I?"primary":"secondary",onClick:()=>{I?(K(!1),oe([null,null])):K(!0)},children:[a.jsx(Mg,{className:"w-4 h-4"}),o(I?"common.cancel":"profiles.presets.compare")]}),a.jsxs(Ne,{variant:"secondary",onClick:()=>P(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[a.jsx(Z0,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),a.jsxs(Ne,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[a.jsx(Or,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),a.jsxs(Ne,{onClick:()=>R(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[a.jsx(cr,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(yk,{className:"w-4 h-4 text-bambu-gray"}),a.jsx(og,{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:q=>d(q)}),a.jsx(og,{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:q=>p(q)}),de.printers.length>0&&a.jsx(og,{label:o("profiles.cloudView.filters.printer"),value:m,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...de.printers.map(q=>({value:q.id,label:q.name}))],onChange:b}),de.nozzles.length>0&&a.jsx(og,{label:o("profiles.cloudView.filters.nozzle"),value:y,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...de.nozzles.map(q=>({value:q,label:q}))],onChange:x}),de.filaments.length>0&&(u==="all"||u==="filament")&&a.jsx(og,{label:o("profiles.cloudView.filters.filament"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...de.filaments.map(q=>({value:q,label:q}))],onChange:S}),de.layerHeights.length>0&&(u==="all"||u==="process")&&a.jsx(og,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...de.layerHeights.map(q=>({value:q,label:q}))],onChange:T}),Y&&a.jsx("button",{onClick:V,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(Mg,{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:Q[0]?o("profiles.cloudView.selectAnotherPreset",{type:Q[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] ${Q[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Q[0]?Q[0].name:o("profiles.cloudView.selectFirst")}),a.jsx(_j,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${Q[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Q[1]?Q[1].name:o("profiles.cloudView.selectSecond")})]}),Q[0]&&Q[1]&&a.jsxs(Ne,{size:"sm",onClick:async()=>{try{const[q,re]=await Promise.all([ae.getCloudSettingDetail(Q[0].setting_id),ae.getCloudSettingDetail(Q[1].setting_id)]);ne([q.setting||{},re.setting||{}]),W(!0)}catch{}},children:[a.jsx(Mg,{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(tr,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",uXe(e.toISOString(),o)]}),a.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:se.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")]})]})]}),se.length===0?a.jsxs("div",{className:"text-center py-16",children:[a.jsx(is,{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")}),Y&&a.jsx("button",{onClick:V,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(gk,{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:["(",se.filter(q=>q.type==="filament").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[se.filter(q=>q.type==="filament").map(q=>a.jsx(rj,{setting:q,onClick:()=>ke(q),onDuplicate:()=>ce(q),compareMode:I,isCompareSelected:Fe(q)!==void 0,compareIndex:Fe(q),compareDisabled:I&&!!Q[0]&&Q[0].type!==q.type,t:o},q.setting_id)),se.filter(q=>q.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(Hu,{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:["(",se.filter(q=>q.type==="process").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[se.filter(q=>q.type==="process").map(q=>a.jsx(rj,{setting:q,onClick:()=>ke(q),onDuplicate:()=>ce(q),compareMode:I,isCompareSelected:Fe(q)!==void 0,compareIndex:Fe(q),compareDisabled:I&&!!Q[0]&&Q[0].type!==q.type,t:o},q.setting_id)),se.filter(q=>q.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(jr,{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:["(",se.filter(q=>q.type==="printer").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[se.filter(q=>q.type==="printer").map(q=>a.jsx(rj,{setting:q,onClick:()=>ke(q),onDuplicate:()=>ce(q),compareMode:I,isCompareSelected:Fe(q)!==void 0,compareIndex:Fe(q),compareDisabled:I&&!!Q[0]&&Q[0].type!==q.type,t:o},q.setting_id)),se.filter(q=>q.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(fXe,{setting:M,onClose:()=>A(null),onDeleted:()=>A(null),onDuplicate:()=>ce(M),onEdit:()=>Ve(M),hasPermission:s,t:o}),(k||U||H||$)&&a.jsx(pXe,{onClose:()=>{R(!1),F(null),D(null),G(null)},initialData:H||U||($?{type:$.type,name:"",base_id:"",setting:$.setting}:void 0),allPresets:t,t:o}),C&&a.jsx(mXe,{onClose:()=>P(!1),onApply:q=>{G({type:q.type,setting:q.settings}),P(!1)},t:o}),B&&J&&Q[0]&&Q[1]&&a.jsx(lie,{onClose:()=>{W(!1),ne(null)},leftPreset:J[0],rightPreset:J[1],leftLabel:Q[0].name,rightLabel:Q[1].name,t:o})]})}function bXe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),{hasPermission:r}=Ir(),[i,s]=_.useState("cloud"),[o,l]=_.useState(),{data:c,isLoading:u}=it({queryKey:["cloudStatus"],queryFn:ae.getCloudStatus}),{data:d=[]}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:h,isLoading:p,refetch:m,dataUpdatedAt:b}=it({queryKey:["cloudSettings"],queryFn:()=>ae.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});_.useEffect(()=>{b&&l(new Date(b))},[b]);const y=dt({mutationFn:ae.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),x=()=>{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(ct,{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(pk,{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(Sb,{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(vk,{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(Ne,{variant:"secondary",size:"sm",onClick:()=>y.mutate(),disabled:y.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[a.jsx(Tj,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?a.jsx(gXe,{settings:h,lastSyncTime:o,onRefresh:()=>m(),isRefreshing:p,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(Ne,{onClick:()=>m(),children:t("profiles.retry")})]}):a.jsx(dXe,{onSuccess:x,t})]}),i==="local"&&a.jsx(cXe,{}),i==="kprofiles"&&a.jsx(aXe,{}),a.jsx(hXe,{})]})}const v0={Droplet:gk,Flame:tde,Ruler:Dhe,Sparkles:Z0,Square:ul,Cable:Yce,Wrench:mm,Calendar:ti,Timer:wu,Cog:Tue,Fan:RW,Zap:Ah,Wind:qW,Thermometer:Ek,Layers:is,Box:Ii,Target:$W,RefreshCw:Or,Settings:Mk,Filter:yk,CircleDot:pue};function V0(t){return t&&v0[t]||mm}function lg(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 ij(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 xXe(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 Linear Rails":return r?"https://wiki.bambulab.com/en/x1/maintenance/basic-maintenance":i?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":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":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/general/lead-screws-lubrication";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?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":s||o||d||h?null:"https://wiki.bambulab.com/en/general/carbon-rods-clearance";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 yXe({item:t,onPerform:e,onToggle:n,hasPermission:r,t:i}){const s=V0(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const m=t.days_since_maintenance??0;return Math.max(0,Math.min(100,m/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",p=()=>{if(!t.enabled)return i("common.disabled");if(o==="days"){const m=t.days_until_due??0;return t.is_due?i("maintenance.overdueBy",{duration:lg(Math.abs(m),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:lg(m,"days",i)}):i("maintenance.timeLeft",{duration:lg(m,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:lg(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:lg(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:lg(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",children:[a.jsxs("div",{className:`relative p-2.5 rounded-lg ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[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(ti,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const m=t.maintenance_type_wiki_url||xXe(t.maintenance_type_name,t.printer_model);return m?a.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:i("maintenance.viewDocumentation"),onClick:b=>b.stopPropagation(),children:a.jsx(Xr,{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(En,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&a.jsx(tr,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&a.jsx($i,{className:"w-3 h-3"}),p()]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[a.jsx("span",{title:r("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:a.jsx($n,{checked:t.enabled,onChange:m=>n(t.id,m),disabled:!r("maintenance:update")})}),a.jsxs(Ne,{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(Bu,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function vXe({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:i,t:s}){const[o,l]=_.useState(!0),[c,u]=_.useState(!1),[d,h]=_.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((y,x)=>y.is_due&&!x.is_due?-1:!y.is_due&&x.is_due?1:y.is_warning&&!x.is_warning?-1:!y.is_warning&&x.is_warning?1:y.maintenance_type_id-x.maintenance_type_id),m=p.find(y=>y.enabled&&(y.is_due||y.is_warning)),b=()=>{const y=parseFloat(d);!isNaN(y)&&y>=0&&(r(t.printer_id,y),u(!1))};return a.jsxs(St,{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(En,{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(tr,{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($i,{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(zu,{className:"w-4 h-4"}):a.jsx(fr,{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(wu,{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:y=>h(y.target.value),onKeyDown:y=>{y.key==="Enter"&&b(),y.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(Ne,{size:"sm",onClick:b,children:s("common.save")}),a.jsx(Ne,{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(dm,{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"}),m&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${m.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const y=V0(m.maintenance_type_icon);return a.jsx(y,{className:`w-4 h-4 ${m.is_due?"text-red-400":"text-amber-400"}`})})()}),a.jsxs("div",{children:[a.jsx("div",{className:`text-sm font-medium ${m.is_due?"text-red-400":"text-amber-400"}`,children:m.maintenance_type_name}),a.jsx("div",{className:`text-xs ${m.is_due?"text-red-400/70":"text-amber-400/70"}`,children:m.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&a.jsx(Et,{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:p.map(y=>a.jsx(yXe,{item:y,onPerform:e,onToggle:n,hasPermission:i,t:s},y.id))})})]})}function wXe({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:i,onDeleteType:s,onAssignType:o,onRemoveItem:l,hasPermission:c,t:u}){const[d,h]=_.useState(null),[p,m]=_.useState(""),[b,y]=_.useState("hours"),[x,v]=_.useState(!1),[S,N]=_.useState(""),[T,M]=_.useState("100"),[A,k]=_.useState("hours"),[R,C]=_.useState("Wrench"),[P,U]=_.useState(""),[F,H]=_.useState(new Set),[D,$]=_.useState(null),G=_.useMemo(()=>t?t.map(X=>({id:X.printer_id,name:X.printer_name})):[],[t]),I=X=>t?t.filter(le=>le.maintenance_items.some(pe=>pe.maintenance_type_id===X)).map(le=>({printerId:le.printer_id,printerName:le.printer_name,itemId:le.maintenance_items.find(pe=>pe.maintenance_type_id===X)?.id})):[],K=X=>{if(!t)return[];const le=new Set(I(X).map(pe=>pe.printerId));return G.filter(pe=>!le.has(pe.id))},[Q,oe]=_.useState(null),[B,W]=_.useState(""),[J,ne]=_.useState(""),[me,fe]=_.useState("hours"),[de,Re]=_.useState("Wrench"),[se,ke]=_.useState(""),Fe=X=>{oe(X),W(X.name),ne(X.default_interval_hours.toString()),fe(X.interval_type||"hours"),Re(X.icon||"Wrench"),ke(X.wiki_url||"")},ce=()=>{Q&&B.trim()&&parseFloat(J)>0&&(i(Q.id,{name:B.trim(),default_interval_hours:parseFloat(J),interval_type:me,icon:de,wiki_url:se.trim()||null}),oe(null))},Ve=(X,le,pe)=>{const ee=parseFloat(p);if(!isNaN(ee)&&ee>0){const z=Math.abs(ee-le)<.01?null:ee;n(X,{custom_interval_hours:z,custom_interval_type:b!==pe?b:null})}h(null)},V=X=>{X.preventDefault(),S.trim()&&parseFloat(T)>0&&F.size>0&&(r({name:S.trim(),default_interval_hours:parseFloat(T),interval_type:A,icon:R,wiki_url:P.trim()||null},Array.from(F)),N(""),M("100"),k("hours"),U(""),H(new Set),v(!1))},Y=X=>{H(le=>{const pe=new Set(le);return pe.has(X)?pe.delete(X):pe.add(X),pe})},ue=t?.map(X=>({printerId:X.printer_id,printerName:X.printer_name,items:X.maintenance_items.sort((le,pe)=>le.maintenance_type_id-pe.maintenance_type_id)})).sort((X,le)=>X.printerName.localeCompare(le.printerName))||[],q=e.filter(X=>X.is_system),re=e.filter(X=>!X.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:u("maintenance.maintenanceTypes")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:u("maintenance.maintenanceTypesDescription")})]}),a.jsxs(Ne,{onClick:()=>v(!x),disabled:!c("maintenance:create"),title:c("maintenance:create")?void 0:u("maintenance.noPermissionEditTypes"),children:[a.jsx(cr,{className:"w-4 h-4"}),u("maintenance.addCustomType")]})]}),x&&a.jsx(St,{className:"mb-6",children:a.jsx(Et,{className:"py-4",children:a.jsxs("form",{onSubmit:V,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:u("common.name")}),a.jsx("input",{type:"text",value:S,onChange:X=>N(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:u("maintenance.exampleName"),autoFocus:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:u("maintenance.intervalType")}),a.jsxs("select",{value:A,onChange:X=>{k(X.target.value),X.target.value==="days"?M("30"):M("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:u("maintenance.printHours")}),a.jsx("option",{value:"days",children:u("maintenance.calendarDays")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:u("maintenance.intervalValue",{type:A==="days"?u("maintenance.calendarDays").toLowerCase():u("common.hours")})}),a.jsx("input",{type:"number",value:T,onChange:X=>M(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),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:u("maintenance.icon")}),a.jsx("div",{className:"flex gap-1",children:Object.keys(v0).map(X=>{const le=v0[X];return a.jsx("button",{type:"button",onClick:()=>C(X),className:`p-2 rounded-lg transition-colors ${R===X?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:a.jsx(le,{className:"w-4 h-4"})},X)})})]})}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:u("maintenance.documentationLink")}),a.jsx("input",{type:"url",value:P,onChange:X=>U(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"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:u("maintenance.assignToPrinters")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:G.map(X=>a.jsx("button",{type:"button",onClick:()=>Y(X.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${F.has(X.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:X.name},X.id))}),F.size===0&&a.jsx("p",{className:"text-xs text-orange-400 mt-1",children:u("maintenance.selectAtLeastOnePrinter")})]}),a.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:()=>{v(!1),H(new Set)},children:u("common.cancel")}),a.jsx(Ne,{type:"submit",disabled:!S.trim()||F.size===0,children:u("maintenance.addType")})]})]})})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[q.map(X=>{const le=V0(X.icon),pe=X.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(le,{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:X.name}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[pe==="days"?a.jsx(ti,{className:"w-3 h-3"}):a.jsx(wu,{className:"w-3 h-3"}),ij(X.default_interval_hours,pe,u)]})]})]})},X.id)}),re.map(X=>{const le=V0(X.icon),pe=X.interval_type||"hours";if(Q?.id===X.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:B,onChange:ge=>W(ge.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:u("common.name"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:me,onChange:ge=>fe(ge.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:u("maintenance.printHours")}),a.jsx("option",{value:"days",children:u("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:J,onChange:ge=>ne(ge.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(v0).map(ge=>{const Ce=v0[ge];return a.jsx("button",{type:"button",onClick:()=>Re(ge),className:`p-1.5 rounded transition-colors ${de===ge?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a.jsx(Ce,{className:"w-3.5 h-3.5"})},ge)})}),a.jsx("input",{type:"url",value:se,onChange:ge=>ke(ge.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:u("maintenance.documentationLink")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ne,{size:"sm",onClick:ce,disabled:!B.trim(),children:u("common.save")}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:()=>oe(null),children:u("common.cancel")})]})]})},X.id);const z=I(X.id),O=K(X.id),Z=D===X.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(le,{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:X.name}),a.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:u("maintenance.custom")})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[pe==="days"?a.jsx(ti,{className:"w-3 h-3"}):a.jsx(wu,{className:"w-3 h-3"}),ij(X.default_interval_hours,pe,u)]})]}),a.jsxs("button",{onClick:()=>$(Z?null:X.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${z.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:u("maintenance.printersAssignedClick",{count:z.length}),children:[a.jsx(jr,{className:"w-3 h-3"}),a.jsx("span",{className:"text-xs font-medium",children:z.length}),a.jsx(fr,{className:`w-3 h-3 transition-transform ${Z?"rotate-180":""}`})]}),a.jsx("button",{onClick:()=>Fe(X),disabled:!c("maintenance:update"),title:c("maintenance:update")?void 0:u("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${c("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(dm,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{confirm(u("maintenance.deleteTypeConfirm",{name:X.name}))&&s(X.id)},disabled:!c("maintenance:delete"),title:c("maintenance:delete")?void 0:u("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${c("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(ln,{className:"w-4 h-4"})})]}),Z&&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:u("maintenance.assignedToPrinters")}),z.length===0?a.jsx("p",{className:"text-xs text-orange-400",children:u("maintenance.noPrintersAssigned")}):a.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:z.map(ge=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[ge.printerName,a.jsx("button",{onClick:()=>ge.itemId&&l(ge.itemId),disabled:!c("maintenance:delete"),title:c("maintenance:delete")?u("maintenance.removeFromPrinter"):u("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${c("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},ge.printerId))}),O.length>0&&a.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:u("maintenance.addPrinterShort")}),O.map(ge=>a.jsxs("button",{onClick:()=>o(ge.id,X.id),disabled:!c("maintenance:create"),title:c("maintenance:create")?void 0:u("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${c("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",ge.name]},ge.id))]})]})]},X.id)})]})]}),ue.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:u("maintenance.intervalOverrides")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:u("maintenance.intervalOverridesDescription")})]}),a.jsx("div",{className:"space-y-4",children:ue.map(X=>a.jsx(St,{children:a.jsxs(Et,{className:"py-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:X.printerName}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:X.items.map(le=>{const pe=V0(le.maintenance_type_icon),ee=e.find(Ce=>Ce.id===le.maintenance_type_id),z=ee?.default_interval_hours||le.interval_hours,O=ee?.interval_type||"hours",Z=le.interval_type||"hours",ge=d===le.id;return a.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[a.jsx(pe,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:le.maintenance_type_name}),ge?a.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?a.jsx(ti,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):a.jsx(wu,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),a.jsxs("select",{value:b,onChange:Ce=>y(Ce.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:u("maintenance.printHours")}),a.jsx("option",{value:"days",children:u("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:p,onChange:Ce=>m(Ce.target.value),onKeyDown:Ce=>{Ce.key==="Enter"&&Ve(le.id,z,O),Ce.key==="Escape"&&h(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(Ne,{size:"sm",onClick:()=>Ve(le.id,z,O),children:"OK"})]}):a.jsxs("button",{onClick:()=>{c("maintenance:update")&&(h(le.id),m(le.interval_hours.toString()),y(Z))},disabled:!c("maintenance:update"),title:c("maintenance:update")?void 0:u("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 ${c("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[Z==="days"?a.jsx(ti,{className:"w-3 h-3"}):a.jsx(wu,{className:"w-3 h-3"}),ij(le.interval_hours,Z,u),a.jsx(dm,{className:"w-3 h-3 text-bambu-gray"})]})]},le.id)})})]})},X.printerId))})]}),ue.length===0&&a.jsx(St,{children:a.jsxs(Et,{className:"text-center py-12",children:[a.jsx(tr,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-bambu-gray",children:u("common.noPrinters")}),a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:u("maintenance.intervalOverridesDescription")})]})})]})}function _Xe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),{hasPermission:r}=Ir(),[i,s]=_.useState("status"),{data:o,isLoading:l}=it({queryKey:["maintenanceOverview"],queryFn:ae.getMaintenanceOverview}),{data:c}=it({queryKey:["maintenanceTypes"],queryFn:ae.getMaintenanceTypes}),u=dt({mutationFn:({id:M,notes:A})=>ae.performMaintenance(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:M=>{n(M.message,"error")}}),d=dt({mutationFn:({id:M,data:A})=>ae.updateMaintenanceItem(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:M=>{n(M.message,"error")}}),h=dt({mutationFn:({id:M,data:A})=>ae.updateMaintenanceType(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:M=>{n(M.message,"error")}}),p=dt({mutationFn:ae.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:M=>{n(M.message,"error")}}),m=dt({mutationFn:({printerId:M,hours:A})=>ae.setPrinterHours(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:M=>{n(M.message,"error")}}),b=dt({mutationFn:({printerId:M,typeId:A})=>ae.assignMaintenanceType(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:M=>{n(M.message,"error")}}),y=dt({mutationFn:ae.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:M=>{n(M.message,"error")}}),x=M=>{u.mutate({id:M})},v=(M,A)=>{d.mutate({id:M,data:{enabled:A}})},S=(M,A)=>{m.mutate({printerId:M,hours:A})};if(l)return a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})});const N=o?.reduce((M,A)=>M+A.due_count,0)||0,T=o?.reduce((M,A)=>M+A.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:[N>0&&a.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:N})}),N>0&&T>0&&" · ",T>0&&a.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:T})}),N===0&&T===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((M,A)=>{const k=M.due_count*10+M.warning_count,R=A.due_count*10+A.warning_count;return k!==R?R-k:M.printer_name.localeCompare(A.printer_name)}).map(M=>a.jsx(vXe,{overview:M,onPerform:x,onToggle:v,onSetHours:S,hasPermission:r,t},M.printer_id)):a.jsx(St,{children:a.jsxs(Et,{className:"text-center py-16",children:[a.jsx(mm,{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(wXe,{overview:o,types:c||[],onUpdateInterval:(M,A)=>d.mutate({id:M,data:A}),onAddType:async(M,A)=>{const k=await ae.createMaintenanceType(M);for(const R of A)await ae.assignMaintenanceType(R,k.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(M,A)=>h.mutate({id:M,data:A}),onDeleteType:M=>p.mutate(M),onAssignType:(M,A)=>b.mutate({printerId:M,typeId:A}),onRemoveItem:M=>y.mutate(M),hasPermission:r,t})]})}const R9=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function cie({project:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=_.useState(t?.name||""),[l,c]=_.useState(t?.description||""),[u,d]=_.useState(t?.color||R9[0]),[h,p]=_.useState(t?.target_count?.toString()||""),[m,b]=_.useState(t?.target_parts_count?.toString()||""),[y,x]=_.useState(t?.status||"active"),[v,S]=_.useState(t?.tags||""),[N,T]=_.useState(t?.due_date?.split("T")[0]||""),[M,A]=_.useState(t?.priority||"normal"),k=R=>{R.preventDefault(),n({name:s.trim(),description:l.trim()||void 0,color:u,target_count:h?parseInt(h,10):void 0,target_parts_count:m?parseInt(m,10):void 0,tags:v.trim()||void 0,due_date:N||void 0,priority:M,...t&&{status:y}})};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:R=>o(R.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:R=>c(R.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:R9.map(R=>a.jsx("button",{type:"button",onClick:()=>d(R),className:`w-8 h-8 rounded-full transition-transform ${u===R?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:R}},R))})]}),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:R=>p(R.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:m,onChange:R=>b(R.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:v,onChange:R=>S(R.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:R=>T(R.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:R=>A(R.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:y,onChange:R=>x(R.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(Ne,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ne,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i(t?"common.save":"projects.create")})]})]})]})})}function SXe({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]=_.useState(!1),m=c?{icon:mk,color:"text-bambu-green",bg:"bg-bambu-green/10"}:u?{icon:vo,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:tr,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:rs,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 ${m.bg} flex-shrink-0`,children:a.jsx(m.icon,{className:`w-5 h-5 ${m.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 b=t.archives.map(S=>S.filament_type).filter(Boolean).flatMap(S=>S.split(",").map(N=>N.trim())).filter(Boolean),y=[...new Set(b)],x=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)),v=[...new Set(x)];return y.length===0&&v.length===0?null:a.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[y.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)),v.length>0&&a.jsxs("div",{className:"flex items-center gap-0.5",children:[v.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)),v.length>5&&a.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",v.length-5]})]})]})})()]})]}),a.jsxs("div",{className:"relative",onClick:b=>b.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(mh,{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(dm,{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(ln,{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(vo,{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(En,{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(tr,{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(b=>a.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:b.print_name||"Unknown",children:[b.thumbnail_path?a.jsx("img",{src:ae.getArchiveThumbnail(b.id),alt:b.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(bc,{className:"w-6 h-6"})}),b.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:a.jsx(En,{className:"w-4 h-4 text-white"})})]},b.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(is,{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(bc,{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(En,{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(Ej,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.queue_count})]})]}),a.jsx(ks,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function NXe(){const{t}=Yt(),e=Ec(),n=an(),{showToast:r}=Tn(),{hasPermission:i}=Ir(),[s,o]=_.useState(!1),[l,c]=_.useState(),[u,d]=_.useState("active"),[h,p]=_.useState(null),{data:m,isLoading:b}=it({queryKey:["projects",u==="all"?void 0:u],queryFn:()=>ae.getProjects(u==="all"?void 0:u)}),y=dt({mutationFn:H=>ae.createProject(H),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:H=>{r(H.message,"error")}}),x=dt({mutationFn:({id:H,data:D})=>ae.updateProject(H,D),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:H=>{r(H.message,"error")}}),v=dt({mutationFn:H=>ae.deleteProject(H),onSuccess:()=>{p(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:H=>{p(null),r(H.message,"error")}}),S=dt({mutationFn:H=>ae.importProject(H),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:H=>{r(H.message,"error")}}),N=_.useRef(null),T=async()=>{try{const H=await ae.getProjects(),D=await Promise.all(H.map(async K=>await ae.exportProjectJson(K.id))),$=new Blob([JSON.stringify(D,null,2)],{type:"application/json"}),G=URL.createObjectURL($),I=document.createElement("a");I.href=G,I.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,I.click(),URL.revokeObjectURL(G),r(t("projects.toast.exported"),"success")}catch(H){r(H.message,"error")}},M=()=>{N.current?.click()},A=async H=>{const D=H.target.files?.[0];if(D){try{if(D.name.toLowerCase().endsWith(".zip"))await ae.importProjectFile(D),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const G=await D.text(),I=JSON.parse(G),K=Array.isArray(I)?I:[I];for(const Q of K)await S.mutateAsync(Q);K.length>1&&r(t("projects.toast.multipleImported",{count:K.length}),"success")}}catch($){r(`${t("projects.toast.importFailed")}: ${$.message}`,"error")}H.target.value=""}},k=H=>{l?x.mutate({id:l.id,data:H}):y.mutate(H)},R=H=>{c(H),o(!0)},C=H=>{e(`/projects/${H.id}`)},P=H=>{p(H)},U=()=>{h!==null&&v.mutate(h)},F=m?.reduce((H,D)=>(H[D.status]=(H[D.status]||0)+1,H.all=(H.all||0)+1,H),{})||{};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:A,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(rs,{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(Ne,{variant:"secondary",onClick:M,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[a.jsx(Na,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),a.jsxs(Ne,{variant:"secondary",onClick:T,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[a.jsx(wi,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),a.jsxs(Ne,{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(cr,{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:tr},{key:"completed",label:t("projects.statusCompleted"),icon:mk},{key:"archived",label:t("projects.statusArchived"),icon:vo},{key:"all",label:t("common.all"),icon:rs}].map(({key:H,label:D,icon:$})=>a.jsxs("button",{onClick:()=>d(H),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===H?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[a.jsx($,{className:"w-4 h-4"}),a.jsx("span",{children:D}),F[H]>0&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===H?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:F[H]})]},H))}),b?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(ct,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):m?.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(rs,{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(Ne,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(cr,{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:m?.map(H=>a.jsx(SXe,{project:H,onClick:()=>C(H),onEdit:()=>R(H),onDelete:()=>P(H.id),hasPermission:i,t},H.id))}),h!==null&&a.jsx(er,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:U,onCancel:()=>p(null)}),s&&a.jsx(cie,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:k,isLoading:y.isPending||x.isPending,t})]})}function kXe(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 MXe(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function EXe({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 O9({icon:t,label:e,value:n,subValue:r,hint:i,color:s="text-bambu-gray"}){return a.jsx(St,{children:a.jsx(Et,{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 TXe({archives:t,t:e}){return t.length===0?a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(bc,{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(Bs,{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:ae.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(bc,{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(Zi,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&a.jsx("div",{className:"absolute top-1 right-1",children:a.jsx(mr,{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 AXe({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(En,{className:"w-3 h-3"}),i]})}function CXe(t){return t?Gg(t,{year:"numeric",month:"short",day:"numeric"}):""}function aj(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 PXe(){const{id:t}=dk(),e=Ec(),{t:n}=Yt(),r=an(),{showToast:i}=Tn(),{hasPermission:s}=Ir(),[o,l]=_.useState(!1),[c,u]=_.useState(!1),[d,h]=_.useState(""),p=parseInt(t||"0",10),{data:m,isLoading:b,error:y}=it({queryKey:["project",p],queryFn:()=>ae.getProject(p),enabled:p>0}),{data:x,isLoading:v}=it({queryKey:["project-archives",p],queryFn:()=>ae.getProjectArchives(p),enabled:p>0}),{data:S,isLoading:N}=it({queryKey:["project-bom",p],queryFn:()=>ae.getProjectBOM(p),enabled:p>0}),{data:T,isLoading:M}=it({queryKey:["project-timeline",p],queryFn:()=>ae.getProjectTimeline(p,20),enabled:p>0}),{data:A}=it({queryKey:["settings"],queryFn:ae.getSettings}),{data:k}=it({queryKey:["project-folders",p],queryFn:()=>ae.getLibraryFoldersByProject(p),enabled:p>0}),R=A?.currency||"$",C=A?.time_format||"system",P=dt({mutationFn:Ae=>ae.updateProject(p,Ae),onSuccess:()=>{r.invalidateQueries({queryKey:["project",p]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:Ae=>{i(Ae.message,"error")}}),U=()=>{h(m?.notes||""),u(!0)},F=()=>{P.mutate({notes:d})},H=()=>{u(!1),h("")},[D,$]=_.useState(""),[G,I]=_.useState(1),[K,Q]=_.useState(""),[oe,B]=_.useState(""),[W,J]=_.useState(""),[ne,me]=_.useState(!1),[fe,de]=_.useState(!1),[Re,se]=_.useState(null),[ke,Fe]=_.useState(""),[ce,Ve]=_.useState(1),[V,Y]=_.useState(""),[ue,q]=_.useState(""),[re,X]=_.useState(""),[le,pe]=_.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),ee=dt({mutationFn:Ae=>ae.createBOMItem(p,Ae),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),$(""),I(1),Q(""),B(""),J(""),me(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:Ae=>i(Ae.message,"error")}),z=dt({mutationFn:({itemId:Ae,data:qe})=>ae.updateBOMItem(p,Ae,qe),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),se(null)},onError:Ae=>i(Ae.message,"error")}),O=dt({mutationFn:Ae=>ae.deleteBOMItem(p,Ae),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:Ae=>i(Ae.message,"error")}),Z=Ae=>{Ae.preventDefault(),D.trim()&&ee.mutate({name:D.trim(),quantity_needed:G,unit_price:K?parseFloat(K):void 0,sourcing_url:oe.trim()||void 0,remarks:W.trim()||void 0})},ge=Ae=>{const qe=Ae.is_complete?0:Ae.quantity_needed;z.mutate({itemId:Ae.id,data:{quantity_acquired:qe}})},Ce=(Ae,qe)=>{pe({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:qe}),onConfirm:()=>{pe(ve=>({...ve,isOpen:!1})),O.mutate(Ae)}})},_e=Ae=>{se(Ae),Fe(Ae.name),Ve(Ae.quantity_needed),Y(Ae.unit_price?.toString()||""),q(Ae.sourcing_url||""),X(Ae.remarks||"")},Te=Ae=>{Ae.preventDefault(),!(!Re||!ke.trim())&&z.mutate({itemId:Re.id,data:{name:ke.trim(),quantity_needed:ce,unit_price:V?parseFloat(V):void 0,sourcing_url:ue.trim()||void 0,remarks:re.trim()||void 0}})},we=()=>{se(null)},$e=async()=>{try{const{blob:Ae,filename:qe}=await ae.exportProjectZip(Number(p)),ve=URL.createObjectURL(Ae),et=document.createElement("a");et.href=ve,et.download=qe||`${m?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,et.click(),URL.revokeObjectURL(ve),i(n("projectDetail.toast.projectExported"),"success")}catch(Ae){i(Ae.message,"error")}},Ge=dt({mutationFn:()=>ae.createTemplateFromProject(p),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:Ae=>i(Ae.message,"error")}),ze=Ae=>qg(Ae,C,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(b)return a.jsx("div",{className:"flex items-center justify-center py-24",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(y||!m)return a.jsxs("div",{className:"text-center py-24",children:[a.jsx("p",{className:"text-bambu-gray",children:y?`${n("common.error")}: ${y.message}`:n("projectDetail.notFound")}),a.jsx(Ne,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const be=m.stats,Me=be?.progress_percent??0,Be=be?.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(Bs,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),a.jsx(ks,{className:"w-4 h-4"}),a.jsx("span",{className:"text-white",children:m.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(jce,{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:m.color||"#6b7280"}}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:m.name}),m.description&&a.jsx("p",{className:"text-bambu-gray mt-1",children:m.description})]})]}),a.jsx(EXe,{status:m.status,t:n})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ne,{variant:"secondary",onClick:$e,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[a.jsx(wi,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),a.jsxs(Ne,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[a.jsx(dm,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(m.target_count||m.target_parts_count)&&a.jsx(St,{children:a.jsxs(Et,{className:"p-4 space-y-4",children:[m.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:[be?.total_archives||0," / ",m.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(Me,100)}%`,backgroundColor:Me>=100?"#22c55e":m.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:Me.toFixed(0)})}),be?.remaining_prints!=null&&be.remaining_prints>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:be.remaining_prints})})]})]}),m.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:[be?.completed_prints||0," / ",m.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(Be,100)}%`,backgroundColor:Be>=100?"#22c55e":m.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:Be.toFixed(0)})}),be?.remaining_parts!=null&&be.remaining_parts>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:be.remaining_parts})})]})]})]})}),be&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(St,{children:a.jsx(Et,{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(bc,{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:[be.total_archives," ",a.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),be.failed_prints>0&&a.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:be.failed_prints})}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:be.completed_prints})})]})]})})}),a.jsx(O9,{icon:tr,label:n("projectDetail.stats.printTime"),value:kXe(be.total_print_time_hours),color:"text-yellow-400"}),a.jsx(O9,{icon:jr,label:n("projectDetail.stats.filamentUsed"),value:MXe(be.total_filament_grams),color:"text-purple-400"})]}),be&&(be.estimated_cost>0||m.budget)&&a.jsx(St,{children:a.jsxs(Et,{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:[R,be.estimated_cost.toFixed(2)]})]}),be.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:[be.total_energy_kwh.toFixed(2)," kWh",be.total_energy_cost>0&&a.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",R,be.total_energy_cost.toFixed(2),")"]})]})]}),m.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:[R,m.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 ${m.budget-be.estimated_cost>=0?"text-bambu-green":"text-red-400"}`,children:[R,(m.budget-be.estimated_cost).toFixed(2)]})]})]})]})]})}),m.children&&m.children.length>0&&a.jsx(St,{children:a.jsxs(Et,{className:"p-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[a.jsx(ode,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:m.children.length})]}),a.jsx("div",{className:"space-y-2",children:m.children.map(Ae=>a.jsxs(Bs,{to:`/projects/${Ae.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:Ae.color||"#6b7280"}}),a.jsx("span",{className:"text-white",children:Ae.name}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${Ae.status==="completed"?"bg-status-ok/20 text-status-ok":Ae.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:Ae.status})]}),Ae.progress_percent!==null&&a.jsxs("span",{className:"text-sm text-bambu-gray",children:[Ae.progress_percent.toFixed(0),"%"]})]},Ae.id))})]})}),m.parent_id&&m.parent_name&&a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(is,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),a.jsx(Bs,{to:`/projects/${m.parent_id}`,className:"text-bambu-green hover:underline",children:m.parent_name})]}),(m.tags||m.due_date||m.priority!=="normal")&&a.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[m.priority&&m.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(AXe,{priority:m.priority,t:n})]}),m.due_date&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ti,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:CXe(m.due_date)}),aj(m.due_date,n)&&a.jsxs("span",{className:`text-xs ${aj(m.due_date,n).color}`,children:["(",aj(m.due_date,n).label,")"]})]}),m.tags&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Th,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:m.tags.split(",").map((Ae,qe)=>a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:Ae.trim()},qe))})]})]}),a.jsx(St,{children:a.jsxs(Et,{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(ys,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:H,disabled:P.isPending,children:[a.jsx(Lt,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),a.jsxs(Ne,{size:"sm",onClick:F,disabled:P.isPending,children:[P.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-1"}):a.jsx(vs,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:U,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[a.jsx(dm,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?a.jsx(bR,{content:d,onChange:h,placeholder:n("projectDetail.notes.placeholder")}):m.notes?a.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:m.notes}}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),a.jsx(St,{children:a.jsxs(Et,{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(Ul,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),a.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[a.jsx(Bs,{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(Ae=>a.jsxs(Bs,{to:`/files?folder=${Ae.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(Ul,{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:Ae.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:Ae.file_count})})]})]}),a.jsx(ks,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},Ae.id))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),a.jsx(St,{children:a.jsxs(Et,{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(BW,{className:"w-5 h-5"}),n("projectDetail.bom.title"),be&&be.bom_total_items>0&&a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:be.bom_completed_items,total:be.bom_total_items}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[S&&S.some(Ae=>Ae.is_complete)&&a.jsx("button",{onClick:()=>de(!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")}),!ne&&a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>me(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[a.jsx(cr,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),ne&&a.jsxs("form",{onSubmit:Z,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:D,onChange:Ae=>$(Ae.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:G,onChange:Ae=>I(parseInt(Ae.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:Ae=>Q(Ae.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:R})})]})]}),a.jsx("input",{type:"url",value:oe,onChange:Ae=>B(Ae.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:W,onChange:Ae=>J(Ae.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(Ne,{type:"button",variant:"secondary",size:"sm",onClick:()=>me(!1),children:n("common.cancel")}),a.jsx(Ne,{type:"submit",size:"sm",disabled:!D.trim()||ee.isPending,children:ee.isPending?a.jsx(ct,{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(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):S&&S.length>0?a.jsxs("div",{className:"space-y-2",children:[S.filter(Ae=>!fe||!Ae.is_complete).map(Ae=>a.jsx("div",{className:`p-3 rounded-lg transition-colors ${Ae.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:Re?.id===Ae.id?a.jsxs("form",{onSubmit:Te,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:ke,onChange:qe=>Fe(qe.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:ce,onChange:qe=>Ve(parseInt(qe.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:V,onChange:qe=>Y(qe.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:R})})]})]}),a.jsx("input",{type:"url",value:ue,onChange:qe=>q(qe.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:re,onChange:qe=>X(qe.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(Ne,{type:"button",variant:"secondary",size:"sm",onClick:we,children:n("common.cancel")}),a.jsx(Ne,{type:"submit",size:"sm",disabled:!ke.trim()||z.isPending,children:z.isPending?a.jsx(ct,{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")&&ge(Ae),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 ${Ae.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:Ae.is_complete&&a.jsx(mr,{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 ${Ae.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[Ae.name,a.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",Ae.quantity_needed]})]}),Ae.unit_price!==null&&a.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[R,(Ae.unit_price*Ae.quantity_needed).toFixed(2)]})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>s("projects:update")&&_e(Ae),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(Ji,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("projects:update")&&Ce(Ae.id,Ae.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(ln,{className:"w-4 h-4"})})]})]}),Ae.sourcing_url&&a.jsxs("a",{href:Ae.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:qe=>qe.stopPropagation(),children:[a.jsx(Xr,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"truncate",children:(()=>{try{return new URL(Ae.sourcing_url).hostname.replace("www.","")}catch{return Ae.sourcing_url}})()})]}),Ae.remarks&&a.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:Ae.remarks})]})]})},Ae.id)),S.some(Ae=>Ae.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:[R,S.reduce((Ae,qe)=>Ae+(qe.unit_price||0)*qe.quantity_needed,0).toFixed(2)]})]})]}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),a.jsx(St,{children:a.jsxs(Et,{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(Y0,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),M?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):T&&T.length>0?a.jsx("div",{className:"space-y-3",children:T.slice(0,10).map((Ae,qe)=>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 ${Ae.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":Ae.event_type==="print_failed"?"bg-status-error/20 text-status-error":Ae.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Ae.event_type==="print_completed"&&a.jsx(mr,{className:"w-4 h-4"}),Ae.event_type==="print_failed"&&a.jsx(Zi,{className:"w-4 h-4"}),Ae.event_type==="print_started"&&a.jsx(jr,{className:"w-4 h-4"}),Ae.event_type==="queued"&&a.jsx(Ej,{className:"w-4 h-4"}),Ae.event_type==="project_created"&&a.jsx(cr,{className:"w-4 h-4"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white",children:Ae.title}),Ae.description&&a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Ae.description}),a.jsx("p",{className:"text-xs text-bambu-gray/70",children:ze(Ae.timestamp)})]})]},qe))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!m.is_template&&a.jsx("div",{className:"flex justify-end",children:a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>Ge.mutate(),disabled:Ge.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[Ge.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(zl,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),be&&(be.queued_prints>0||be.in_progress_prints>0)&&a.jsx(St,{children:a.jsxs(Et,{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(Ej,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),a.jsx(Bs,{to:`/queue?project=${p}`,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:[be.in_progress_prints>0&&a.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:be.in_progress_prints})}),be.queued_prints>0&&a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:be.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(bc,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:x?.length||0})]})}),v?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):a.jsx(TXe,{archives:x||[],t:n})]}),o&&a.jsx(cie,{t:n,project:{...m,archive_count:be?.total_archives||0,total_items:be?.total_items||0,completed_count:be?.completed_prints||0,failed_count:be?.failed_prints||0,queue_count:be?.queued_prints||0,progress_percent:be?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:Ae=>P.mutate(Ae),isLoading:P.isPending}),le.isOpen&&a.jsx(er,{title:le.title,message:le.message,confirmText:n("common.delete"),variant:"danger",onConfirm:le.onConfirm,onCancel:()=>pe(Ae=>({...Ae,isOpen:!1}))})]})}function gg(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 jXe(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 DXe({parentId:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=_.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(Ne,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ne,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function RXe({type:t,currentName:e,onClose:n,onSave:r,isLoading:i,t:s}){const[o,l]=_.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(Ne,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),a.jsx(Ne,{type:"submit",disabled:!o.trim()||o.trim()===e||i,children:i?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function OXe({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:i,isLoading:s,t:o}){const[l,c]=_.useState(null),u=(h,p=0)=>{const m=[];for(const b of h)m.push({id:b.id,name:b.name,depth:p}),b.children.length>0&&m.push(...u(b.children,p+1));return m},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(Ul,{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(Ne,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),a.jsx(Ne,{onClick:()=>i(l),disabled:s,children:s?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function LXe({folder:t,onClose:e,onLink:n,isLoading:r,t:i}){const[s,o]=_.useState("project"),[l,c]=_.useState(t.project_id||t.archive_id||null);_.useState(()=>{t.archive_id&&o("archive")});const{data:u}=it({queryKey:["projects"],queryFn:()=>ae.getProjects()}),{data:d}=it({queryKey:["archives-for-link"],queryFn:()=>ae.getArchives(void 0,void 0,100)}),h=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},m=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(dc,{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(Lt,{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(jW,{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(vo,{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(b=>a.jsxs("button",{onClick:()=>c(b.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===b.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:b.color||"#00ae42"}}),a.jsx("span",{className:"truncate",children:b.name})]},b.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):d&&d.length>0?d.map(b=>a.jsxs("button",{onClick:()=>c(b.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===b.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx(Kf,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"truncate",children:b.print_name||b.filename})]},b.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:[m&&a.jsxs(Ne,{variant:"danger",onClick:p,disabled:r,children:[a.jsx(WR,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),a.jsxs("div",{className:`flex gap-2 ${m?"":"ml-auto"}`,children:[a.jsx(Ne,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ne,{onClick:h,disabled:!l||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function FXe({folderId:t,onClose:e,onUploadComplete:n,t:r}){const[i,s]=_.useState([]),[o,l]=_.useState(!1),[c,u]=_.useState(!1),[d,h]=_.useState(!0),[p,m]=_.useState(!1),[b,y]=_.useState(!0),x=_.useRef(null),v=$=>{$.preventDefault(),l(!0)},S=$=>{$.preventDefault(),l(!1)},N=$=>{$.preventDefault(),l(!1);const G=Array.from($.dataTransfer.files);M(G)},T=$=>{$.target.files&&M(Array.from($.target.files))},M=$=>{const G=$.map(I=>({file:I,status:"pending",isZip:I.name.toLowerCase().endsWith(".zip"),is3mf:I.name.toLowerCase().endsWith(".3mf")}));s(I=>[...I,...G])},A=$=>{s(G=>G.filter((I,K)=>K!==$))},k=i.some($=>$.isZip&&$.status==="pending"),R=i.some($=>$.file.name.toLowerCase().endsWith(".stl")&&$.status==="pending"),C=i.some($=>$.is3mf&&$.status==="pending"),P=async()=>{if(i.length!==0){u(!0);for(let $=0;$G.map((I,K)=>K===$?{...I,status:"uploading"}:I));try{if(i[$].isZip){const G=await ae.extractZipFile(i[$].file,t,d,p,b);s(I=>I.map((K,Q)=>Q===$?{...K,status:G.errors.length>0&&G.extracted===0?"error":"success",extractedCount:G.extracted,error:G.errors.length>0?`${G.errors.length} files failed`:void 0}:K))}else await ae.uploadLibraryFile(i[$].file,t,b),s(G=>G.map((I,K)=>K===$?{...I,status:"success"}:I))}catch(G){s(I=>I.map((K,Q)=>Q===$?{...K,status:"error",error:G instanceof Error?G.message:"Upload failed"}:K))}}u(!1),n(),e()}},U=i.filter($=>$.status==="pending").length,F=i.filter($=>$.status==="success").length,H=i.filter($=>$.status==="error").length,D=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(Lt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("div",{onDragOver:v,onDragLeave:S,onDrop:N,onClick:()=>x.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(Na,{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:x,type:"file",multiple:!0,className:"hidden",onChange:T}),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(vo,{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:$=>h($.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:p,onChange:$=>m($.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")})]})]})]})}),C&&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(jr,{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")})]})]})}),(R||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(Uu,{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&&!R?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:b,onChange:$=>y($.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(($,G)=>a.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[$.isZip?a.jsx(vo,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):a.jsx(xk,{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:$.file.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[($.file.size/1024/1024).toFixed(2)," MB",$.isZip&&$.status==="pending"&&a.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",r("fileManager.willBeExtracted")]}),$.extractedCount!==void 0&&a.jsxs("span",{className:"text-green-400 ml-2",children:["• ",r("fileManager.filesExtracted",{count:$.extractedCount})]})]})]}),$.status==="pending"&&a.jsx("button",{onClick:()=>A(G),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Lt,{className:"w-4 h-4 text-bambu-gray"})}),$.status==="uploading"&&a.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"}),$.status==="success"&&a.jsx(mr,{className:"w-4 h-4 text-green-500"}),$.status==="error"&&a.jsx("span",{title:$.error,children:a.jsx(Zi,{className:"w-4 h-4 text-red-500"})})]},G))}),D&&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:F}),H>0&&a.jsxs("span",{className:"text-red-400",children:[", ",r("fileManager.uploadFailed",{count:H})]})]})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[a.jsx(Ne,{variant:"secondary",onClick:e,children:r(D?"common.close":"common.cancel")}),!D&&a.jsx(Ne,{onClick:P,disabled:U===0||c,children:c?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}),r("fileManager.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Na,{className:"w-4 h-4 mr-2"}),r("common.upload")," ",U>0?`(${U})`:""]})})]})]})})}function uie({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]=_.useState(!0),[p,m]=_.useState(!1),b=t.children.length>0,y=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:[b?a.jsx("button",{onClick:x=>{x.stopPropagation(),h(!d)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(ks,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-90":""}`})}):a.jsx("div",{className:"w-4.5"}),a.jsx(Ul,{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}),y&&a.jsxs("button",{onClick:x=>{x.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(dc,{className:"w-3 h-3"}),t.project_name?a.jsx(jW,{className:"w-3 h-3"}):a.jsx(vo,{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}),!y&&a.jsx("button",{onClick:x=>{x.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:a.jsx(dc,{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:x=>x.stopPropagation(),children:a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:()=>m(!p),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:a.jsx(mh,{className:"w-3.5 h-3.5 text-bambu-gray"})}),p&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!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),m(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[a.jsx(Ji,{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),m(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[a.jsx(dc,{className:"w-3.5 h-3.5"}),u(y?"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),m(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[a.jsx(ln,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),b&&d&&a.jsx("div",{children:t.children.map(x=>a.jsx(uie,{folder:x,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},x.id))})]})}function kR(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function IXe({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:p,canModify:m,authEnabled:b,t:y}){const[x,v]=_.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:`${ae.getLibraryFileThumbnailUrl(t.id)}${h?`?v=${h}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):a.jsx(Kf,{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:gg(t.file_size)}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(tr,{className:"w-3 h-3"}),jXe(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(jr,{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:y("fileManager.printedCount",{count:t.print_count})}),b&&t.created_by_username&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx($u,{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:()=>v(!x),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:a.jsx(mh,{className:"w-4 h-4 text-bambu-gray"})}),x&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>v(!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&&kR(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("printers:control")&&(l(t),v(!1))},disabled:!p("printers:control"),title:p("printers:control")?void 0:y("fileManager.noPermissionPrint"),children:[a.jsx(jr,{className:"w-3.5 h-3.5"}),y("common.print")]}),o&&kR(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("queue:create")&&(o(t.id),v(!1))},disabled:!p("queue:create"),title:p("queue:create")?void 0:y("fileManager.noPermissionAddToQueue"),children:[a.jsx(tr,{className:"w-3.5 h-3.5"}),y("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 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(c(t),v(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:"You do not have permission to preview files",children:[a.jsx(Ii,{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 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(s(t.id),v(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:y("fileManager.noPermissionDownload"),children:[a.jsx(wi,{className:"w-3.5 h-3.5"}),y("common.download")]}),u&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${m("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{m("library","update",t.created_by_id)&&(u(t),v(!1))},disabled:!m("library","update",t.created_by_id),title:m("library","update",t.created_by_id)?void 0:y("fileManager.noPermissionRenameFile"),children:[a.jsx(Ji,{className:"w-3.5 h-3.5"}),y("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 ${m("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{m("library","update",t.created_by_id)&&(d(t),v(!1))},disabled:!m("library","update",t.created_by_id),title:m("library","update",t.created_by_id)?void 0:y("fileManager.noPermissionGenerateThumbnail"),children:[a.jsx(Uu,{className:"w-3.5 h-3.5"}),y("fileManager.generateThumbnail")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${m("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{m("library","delete",t.created_by_id)&&(i(t.id),v(!1))},disabled:!m("library","delete",t.created_by_id),title:m("library","delete",t.created_by_id)?void 0:y("fileManager.noPermissionDeleteFile"),children:[a.jsx(ln,{className:"w-3.5 h-3.5"}),y("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 zXe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),{hasPermission:r,hasAnyPermission:i,canModify:s,authEnabled:o}=Ir(),[l]=RR(),c=l.get("folder"),u=c?parseInt(c,10):null,[d,h]=_.useState(u),[p,m]=_.useState([]),[b,y]=_.useState(!1),[x,v]=_.useState(!1),[S,N]=_.useState(!1),[T,M]=_.useState(null),[A,k]=_.useState(null),[R,C]=_.useState(null),[P,U]=_.useState(null),[F,H]=_.useState(null),[D,$]=_.useState(null),[G,I]=_.useState({}),[K,Q]=_.useState(null),[oe,B]=_.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[W,J]=_.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[ne,me]=_.useState(()=>{const Ie=localStorage.getItem("library-sidebar-width");return Ie?parseInt(Ie,10):256}),[fe,de]=_.useState(!1),Re=_.useRef(null);_.useEffect(()=>{if(!fe)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ie=Gt=>{if(!Re.current)return;const dn=Re.current.parentElement?.getBoundingClientRect();if(!dn)return;const fn=Gt.clientX-dn.left,vn=Math.min(500,Math.max(200,fn));me(vn)},vt=()=>{de(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(ne))};return document.addEventListener("mousemove",Ie),document.addEventListener("mouseup",vt),()=>{document.removeEventListener("mousemove",Ie),document.removeEventListener("mouseup",vt),document.body.style.userSelect="",document.body.style.cursor=""}},[fe,ne]);const[se,ke]=_.useState(""),[Fe,ce]=_.useState("all"),[Ve,V]=_.useState(""),[Y,ue]=_.useState(()=>localStorage.getItem("library-sort-field")||"name"),[q,re]=_.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),X=QR();_.useEffect(()=>{const Ie=l.get("folder");if(Ie){const vt=parseInt(Ie,10);h(vt)}},[l]);const{data:le}=it({queryKey:["settings"],queryFn:()=>ae.getSettings()}),{data:pe,isLoading:ee}=it({queryKey:["library-folders"],queryFn:()=>ae.getLibraryFolders()}),{data:z,isLoading:O}=it({queryKey:["library-files",d],queryFn:()=>ae.getLibraryFiles(d,d===null)}),{data:Z}=it({queryKey:["library-stats"],queryFn:()=>ae.getLibraryStats()}),{data:ge}=it({queryKey:["users"],queryFn:()=>ae.getUsers()}),Ce=_.useMemo(()=>{if(!z)return[];const Ie=new Set(z.map(vt=>vt.file_type));return Array.from(Ie).sort()},[z]),_e=_.useMemo(()=>{if(!z)return[];let Ie=[...z];if(se.trim()){const vt=se.toLowerCase();Ie=Ie.filter(Gt=>Gt.filename.toLowerCase().includes(vt)||Gt.print_name&&Gt.print_name.toLowerCase().includes(vt))}if(Fe!=="all"&&(Ie=Ie.filter(vt=>vt.file_type===Fe)),Ve.trim()){const vt=Ve.toLowerCase();Ie=Ie.filter(Gt=>Gt.created_by_username&&Gt.created_by_username.toLowerCase().includes(vt))}return Ie.sort((vt,Gt)=>{let dn=0;switch(Y){case"name":dn=(vt.print_name||vt.filename).localeCompare(Gt.print_name||Gt.filename);break;case"date":dn=new Date(vt.created_at).getTime()-new Date(Gt.created_at).getTime();break;case"size":dn=vt.file_size-Gt.file_size;break;case"type":dn=vt.file_type.localeCompare(Gt.file_type);break;case"prints":dn=vt.print_count-Gt.print_count;break}return q==="asc"?dn:-dn}),Ie},[z,se,Fe,Ve,Y,q]),Te=_.useMemo(()=>{if(!Z||!le)return!1;const Ie=(le.library_disk_warning_gb||5)*1024*1024*1024;return Z.disk_free_bytesae.createLibraryFolder(Ie),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),y(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Ie=>n(Ie.message,"error")}),$e=dt({mutationFn:Ie=>ae.deleteLibraryFolder(Ie),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===A?.id&&h(null),k(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Ie=>{k(null),n(Ie.message,"error")}}),Ge=dt({mutationFn:Ie=>ae.deleteLibraryFile(Ie),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),m(Ie=>Ie.filter(vt=>vt!==A?.id)),k(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Ie=>{k(null),n(Ie.message,"error")}}),ze=dt({mutationFn:Ie=>ae.bulkDeleteLibrary(Ie,[]),onSuccess:(Ie,vt)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:vt.length}),"success"),m([]),k(null)},onError:Ie=>{k(null),n(Ie.message,"error")}}),be=dt({mutationFn:({fileIds:Ie,folderId:vt})=>ae.moveLibraryFiles(Ie,vt),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),m([]),v(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Ie=>n(Ie.message,"error")}),Me=dt({mutationFn:({id:Ie,data:vt})=>ae.updateLibraryFolder(Ie,vt),onSuccess:(Ie,vt)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),M(null);const Gt=vt.data.project_id===0&&vt.data.archive_id===0;n(t(Gt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ie=>n(Ie.message,"error")}),Be=dt({mutationFn:({id:Ie,filename:vt})=>ae.updateLibraryFile(Ie,{filename:vt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),$(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Ie=>{$(null),n(Ie.message,"error")}}),Ae=dt({mutationFn:({id:Ie,name:vt})=>ae.updateLibraryFolder(Ie,{name:vt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),$(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Ie=>{$(null),n(Ie.message,"error")}}),qe=dt({mutationFn:()=>ae.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ie=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ie.succeeded>0){const vt=Date.now(),Gt={};Ie.results.forEach(dn=>{dn.success&&(Gt[dn.file_id]=vt)}),I(dn=>({...dn,...Gt}))}Ie.succeeded>0&&Ie.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Ie.succeeded}),"success"):Ie.succeeded>0&&Ie.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ie.succeeded,failed:Ie.failed}),"success"):Ie.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Ie.results[0]?.error||"Unknown error"}),"error")},onError:Ie=>n(Ie.message,"error")}),ve=dt({mutationFn:Ie=>ae.batchGenerateStlThumbnails({file_ids:[Ie]}),onSuccess:Ie=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ie.succeeded>0){const vt=Ie.results[0]?.file_id;vt&&I(Gt=>({...Gt,[vt]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Ie.results[0]?.error||"Unknown error"}),"error")},onError:Ie=>n(Ie.message,"error")}),et=_.useCallback(Ie=>{const vt=Ie.toLowerCase();return vt.endsWith(".gcode")||vt.includes(".gcode.")},[]),Ee=_.useMemo(()=>z?z.filter(Ie=>p.includes(Ie.id)&&et(Ie.filename)):[],[z,p,et]),Ye=_.useCallback(Ie=>{m(vt=>vt.includes(Ie)?vt.filter(Gt=>Gt!==Ie):[...vt,Ie])},[]),je=_.useCallback(()=>{_e.length>0&&m(_e.map(Ie=>Ie.id))},[_e]),Pe=_.useCallback(()=>{m([])},[]),ye=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},Qe=Ie=>{ae.downloadLibraryFile(Ie).catch(vt=>{console.error("Library file download failed:",vt)})},yt=()=>{A&&(A.type==="file"?Ge.mutate(A.id):A.type==="folder"?$e.mutate(A.id):A.type==="bulk"&&ze.mutate(p))},at=$e.isPending||Ge.isPending||ze.isPending,Ut=Ie=>{B(Ie),localStorage.setItem("library-view-mode",Ie)},zt=ee||O;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(Ul,{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:()=>Ut("grid"),className:`p-1.5 rounded transition-colors ${oe==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:a.jsx(wk,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>Ut("list"),className:`p-1.5 rounded transition-colors ${oe==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:a.jsx(_k,{className:"w-4 h-4"})})]}),a.jsxs(Ne,{variant:"secondary",onClick:()=>qe.mutate(),disabled:qe.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[qe.isPending?a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(Uu,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),a.jsxs(Ne,{variant:"secondary",onClick:()=>y(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[a.jsx(ade,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a.jsxs(Ne,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(Na,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Te&&Z&&le&&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(En,{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:gg(Z.disk_free_bytes),total:gg(Z.disk_total_bytes),threshold:le.library_disk_warning_gb})})]})]}),Z&&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(xk,{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:Z.total_files})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Ul,{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:Z.total_folders})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Sb,{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:gg(Z.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 ${Te?"text-amber-500":"text-white"}`,children:gg(Z.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:Ie=>h(Ie.target.value?parseInt(Ie.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")]}),pe&&(()=>{const Ie=(vt,Gt=0)=>{const dn=[];for(const fn of vt)dn.push({id:fn.id,name:fn.name,fileCount:fn.file_count,depth:Gt}),fn.children.length>0&&dn.push(...Ie(fn.children,Gt+1));return dn};return Ie(pe).map(vt=>a.jsxs("option",{value:vt.id,children:["│ ".repeat(vt.depth),"📂 ",vt.name," ",vt.fileCount>0?`(${vt.fileCount})`:""]},vt.id))})()]})}),a.jsxs("div",{ref:Re,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:`${ne}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:Ie=>{Ie.preventDefault(),de(!0)},onDoubleClick:()=>{me(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 Ie=!W;J(Ie),localStorage.setItem("library-wrap-folders",String(Ie))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${W?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(W?"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(Kf,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),pe?.map(Ie=>a.jsx(uie,{folder:Ie,selectedFolderId:d,onSelect:h,onDelete:vt=>k({type:"folder",id:vt}),onLink:M,onRename:vt=>$({type:"folder",id:vt.id,name:vt.name}),wrapNames:W,hasPermission:r,t},Ie.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(Qi,{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:se,onChange:Ie=>ke(Ie.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(yk,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),a.jsxs("select",{value:Fe,onChange:Ie=>ce(Ie.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")}),Ce.map(Ie=>a.jsx("option",{value:Ie,children:Ie.toUpperCase()},Ie))]})]}),o&&a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:Ve,onChange:Ie=>V(Ie.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 ${Ve?"pr-7":""}`,style:Ve?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),Ve&&a.jsx("button",{onClick:()=>V(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:a.jsx(Lt,{className:"w-3 h-3"})}),a.jsx("datalist",{id:"usernames-list",children:ge?.map(Ie=>a.jsx("option",{value:Ie.username},Ie.id))})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{value:Y,onChange:Ie=>{const vt=Ie.target.value;ue(vt),localStorage.setItem("library-sort-field",vt)},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:()=>re(Ie=>{const vt=Ie==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",vt),vt}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(q==="asc"?"fileManager.ascending":"fileManager.descending"),children:q==="asc"?a.jsx(Fce,{className:"w-4 h-4 text-white"}):a.jsx(Ace,{className:"w-4 h-4 text-white"})})]}),(se||Fe!=="all"||Ve)&&a.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:_e.length,total:z.length})})]}),_e.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:[p.length===_e.length&&p.length>0?a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:Pe,children:[a.jsx(ul,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:je,children:[a.jsx(Xs,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),p.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:p.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:[Ee.length===1&&a.jsxs(Ne,{variant:"primary",size:"sm",onClick:()=>U(Ee[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[a.jsx(Eo,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Ee.length===1&&a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>H(Ee[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[a.jsx(tr,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>v(!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(hhe,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),a.jsxs(Ne,{variant:"danger",size:"sm",onClick:()=>{p.length===1?k({type:"file",id:p[0]}):k({type:"bulk",id:0,count:p.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(ln,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:Pe,children:[a.jsx(Lt,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),zt?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(ct,{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(Kf,{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(Ne,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(cr,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):_e.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(Qi,{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(Ne,{variant:"secondary",onClick:()=>{ke(""),ce("all")},children:t("fileManager.clearFilters")})]}):oe==="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:_e.map(Ie=>a.jsx(IXe,{file:Ie,isSelected:p.includes(Ie.id),isMobile:X,t,onSelect:Ye,onDelete:vt=>k({type:"file",id:vt}),onDownload:Qe,onAddToQueue:vt=>{const Gt=z?.find(dn=>dn.id===vt);Gt&&H(Gt)},onPrint:C,onPreview3d:Q,onRename:vt=>$({type:"file",id:vt.id,name:vt.filename}),onGenerateThumbnail:vt=>ve.mutate(vt.id),thumbnailVersion:G[Ie.id],hasPermission:r,canModify:s,authEnabled:o},Ie.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",{})]}),_e.map(Ie=>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 ${p.includes(Ie.id)?"bg-bambu-green/10":""}`,onClick:()=>Ye(Ie.id),children:[a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${p.includes(Ie.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:p.includes(Ie.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:Ie.thumbnail_path?a.jsx("img",{src:`${ae.getLibraryFileThumbnailUrl(Ie.id)}${G[Ie.id]?`?v=${G[Ie.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(Kf,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ie.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:`${ae.getLibraryFileThumbnailUrl(Ie.id)}${G[Ie.id]?`?v=${G[Ie.id]}`:""}`,alt:Ie.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:Ie.print_name||Ie.filename})})]}),o&&a.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ie.created_by_username?a.jsxs(a.Fragment,{children:[a.jsx($u,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate",children:Ie.created_by_username})]}):"-"}),a.jsx("div",{children:a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ie.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ie.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ie.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ie.file_type.toUpperCase()})}),a.jsx("div",{className:"text-sm text-bambu-gray",children:gg(Ie.file_size)}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Ie.print_count>0?`${Ie.print_count}x`:"-"}),a.jsxs("div",{className:"flex items-center gap-1",onClick:vt=>vt.stopPropagation(),children:[kR(Ie.filename)&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>r("printers:control")&&C(Ie),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(jr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{r("queue:create")&&H(Ie)},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(tr,{className:"w-4 h-4"})})]}),(Ie.file_type==="3mf"||Ie.file_type==="gcode"||Ie.file_type==="stl")&&a.jsx("button",{onClick:()=>r("library:read")&&Q(Ie),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(Ii,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>r("library:read")&&Qe(Ie.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(wi,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","update",Ie.created_by_id)&&$({type:"file",id:Ie.id,name:Ie.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ie.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ie.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ie.created_by_id),children:a.jsx(Ji,{className:"w-4 h-4"})}),Ie.file_type==="stl"&&a.jsx("button",{onClick:()=>s("library","update",Ie.created_by_id)&&ve.mutate(Ie.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ie.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",Ie.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:ve.isPending||!s("library","update",Ie.created_by_id),children:a.jsx(Uu,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","delete",Ie.created_by_id)&&k({type:"file",id:Ie.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ie.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",Ie.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ie.created_by_id),children:a.jsx(ln,{className:"w-4 h-4"})})]})]},Ie.id))]})})]})]}),b&&a.jsx(DXe,{parentId:d,onClose:()=>y(!1),onSave:Ie=>we.mutate(Ie),isLoading:we.isPending,t}),x&&pe&&a.jsx(OXe,{folders:pe,selectedFiles:p,currentFolderId:d,onClose:()=>v(!1),onMove:Ie=>be.mutate({fileIds:p,folderId:Ie}),isLoading:be.isPending,t}),S&&a.jsx(FXe,{folderId:d,onClose:()=>N(!1),onUploadComplete:ye,t}),T&&a.jsx(LXe,{folder:T,onClose:()=>M(null),onLink:Ie=>Me.mutate({id:T.id,data:Ie}),isLoading:Me.isPending,t}),A&&a.jsx(er,{title:A.type==="folder"?t("fileManager.deleteFolder"):A.type==="bulk"?t("fileManager.deleteFilesCount",{count:A.count}):t("fileManager.deleteFile"),message:A.type==="folder"?t("fileManager.deleteFolderConfirm"):A.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:A.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:at,loadingText:t("fileManager.deleting"),onConfirm:yt,onCancel:()=>k(null)}),R&&a.jsx(Ou,{mode:"reprint",libraryFileId:R.id,archiveName:R.print_name||R.filename,onClose:()=>C(null),onSuccess:()=>{C(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),P&&a.jsx(Ou,{mode:"reprint",libraryFileId:P.id,archiveName:P.print_name||P.filename,onClose:()=>U(null),onSuccess:()=>{U(null),m([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),F&&a.jsx(Ou,{mode:"add-to-queue",libraryFileId:F.id,archiveName:F.print_name||F.filename,onClose:()=>H(null),onSuccess:()=>{H(null),m([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),K&&a.jsx(C4,{libraryFileId:K.id,title:K.print_name||K.filename,fileType:K.file_type,onClose:()=>Q(null)}),D&&a.jsx(RXe,{type:D.type,currentName:D.name,onClose:()=>$(null),onSave:Ie=>{D.type==="file"?Be.mutate({id:D.id,filename:Ie}):Ae.mutate({id:D.id,name:Ie})},isLoading:Be.isPending||Ae.isPending,t})]})}const sj=5,UXe=2e3,BXe=3e4,HXe=5e3;function $Xe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),{hasPermission:r}=Ir(),{printerId:i}=dk(),s=parseInt(i||"0",10),[o,l]=_.useState("stream"),[c,u]=_.useState(!1),[d,h]=_.useState(!1),[p,m]=_.useState(!0),[b,y]=_.useState(Date.now()),[x,v]=_.useState(!1),[S,N]=_.useState(!1),[T,M]=_.useState(0),[A,k]=_.useState(!1),[R,C]=_.useState(0),[P,U]=_.useState(1),[F,H]=_.useState({x:0,y:0}),[D,$]=_.useState(!1),[G,I]=_.useState({x:0,y:0}),[K,Q]=_.useState(null),[oe,B]=_.useState(null),W=_.useRef(null),J=_.useRef(null),ne=_.useRef(null),me=_.useRef(null),fe=_.useRef(null),{data:de}=it({queryKey:["printer",s],queryFn:()=>ae.getPrinter(s),enabled:s>0}),{data:Re}=it({queryKey:["printerStatus",s],queryFn:()=>ae.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),se=dt({mutationFn:be=>ae.setChamberLight(s,be),onMutate:async be=>{await e.cancelQueries({queryKey:["printerStatus",s]});const Me=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],Be=>({...Be,chamber_light:be})),{previousStatus:Me}},onSuccess:(be,Me)=>{n(`Chamber light ${Me?"on":"off"}`)},onError:(be,Me,Be)=>{Be?.previousStatus&&e.setQueryData(["printerStatus",s],Be.previousStatus),n(be.message||t("printers.toast.failedToControlChamberLight"),"error")}}),ke=(Re?.state==="RUNNING"||Re?.state==="PAUSE"||Re?.state==="PAUSED")&&(Re?.printable_objects_count??0)>=2;_.useEffect(()=>(de&&(document.title=`${de.name} - Camera`),()=>{document.title="Bambuddy"}),[de]);const Fe=_.useRef(!1);_.useEffect(()=>{const be=`/api/v1/printers/${s}/camera/stop`;Fe.current=!1;const Me=()=>{if(s>0&&!Fe.current){Fe.current=!0;const qe={},ve=Ch();ve&&(qe.Authorization=`Bearer ${ve}`),fetch(be,{method:"POST",keepalive:!0,headers:qe}).catch(()=>{})}},Be=()=>{Me()};window.addEventListener("beforeunload",Be);const Ae=W.current;return()=>{window.removeEventListener("beforeunload",Be),Ae&&(Ae.src=""),Me()}},[s]),_.useEffect(()=>{if(p&&!x){const Me=setTimeout(()=>{m(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(Me)}},[o,p,b,x]),_.useEffect(()=>{const be=()=>{const Me=!!document.fullscreenElement;N(Me),U(1),H({x:0,y:0}),o==="stream"&&!x&&(W.current&&(W.current.src=""),setTimeout(()=>{m(!0),y(Date.now())},200))};return document.addEventListener("fullscreenchange",be),()=>document.removeEventListener("fullscreenchange",be)},[o,x]),_.useEffect(()=>{let be;const Me=()=>{clearTimeout(be),be=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Me),()=>{clearTimeout(be),window.removeEventListener("resize",Me)}},[]),_.useEffect(()=>()=>{ne.current&&clearTimeout(ne.current),me.current&&clearInterval(me.current),fe.current&&clearInterval(fe.current)},[]);const ce=_.useCallback(()=>{if(T>=sj){k(!1),h(!0);return}const be=Math.min(UXe*Math.pow(2,T),BXe);k(!0),C(Math.ceil(be/1e3)),me.current=setInterval(()=>{C(Me=>Me<=1?(me.current&&clearInterval(me.current),0):Me-1)},1e3),ne.current=setTimeout(()=>{M(Me=>Me+1),k(!1),m(!0),h(!1),W.current&&(W.current.src=""),y(Date.now())},be)},[T]);_.useEffect(()=>{if(o!=="stream"||p||A||x){fe.current&&(clearInterval(fe.current),fe.current=null);return}return fe.current=setInterval(async()=>{try{const be=await ae.getCameraStatus(s);(be.stalled||!be.active&&!d)&&(console.log(`Stream issue detected: stalled=${be.stalled}, active=${be.active}, reconnecting...`),fe.current&&(clearInterval(fe.current),fe.current=null),m(!1),ce())}catch{}},HXe),()=>{fe.current&&(clearInterval(fe.current),fe.current=null)}},[o,p,d,A,x,s,ce]);const Ve=()=>{m(!1),o==="stream"&&T{if(m(!1),h(!1),M(0),k(!1),ne.current&&clearTimeout(ne.current),me.current&&clearInterval(me.current),W.current&&!localStorage.getItem("cameraWindowState")){const be=W.current,Me=be.naturalWidth,Be=be.naturalHeight;if(Me>0&&Be>0){const ve=window.outerWidth-window.innerWidth,et=window.outerHeight-window.innerHeight,Ee=Me+16+ve,Ye=Be+45+16+et;try{window.resizeTo(Ee,Ye)}catch{}}}},Y=()=>{if(s>0){const be={},Me=Ch();Me&&(be.Authorization=`Bearer ${Me}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:be}).catch(()=>{})}},ue=be=>{o===be||x||(v(!0),m(!0),h(!1),M(0),k(!1),U(1),H({x:0,y:0}),ne.current&&clearTimeout(ne.current),me.current&&clearInterval(me.current),W.current&&(W.current.src=""),o==="stream"&&Y(),setTimeout(()=>{l(be),y(Date.now()),v(!1)},100))},q=()=>{x||(v(!0),m(!0),h(!1),M(0),k(!1),ne.current&&clearTimeout(ne.current),me.current&&clearInterval(me.current),W.current&&(W.current.src=""),o==="stream"&&Y(),setTimeout(()=>{y(Date.now()),v(!1)},100))},re=()=>{J.current&&(document.fullscreenElement?document.exitFullscreen():J.current.requestFullscreen())},X=()=>{U(be=>Math.min(be+.5,4))},le=()=>{U(be=>{const Me=Math.max(be-.5,1);return Me===1&&H({x:0,y:0}),Me})},pe=be=>{be.preventDefault(),be.deltaY<0?X():le()},ee=be=>{P>1&&(be.preventDefault(),$(!0),I({x:be.clientX-F.x,y:be.clientY-F.y}))},z=_.useCallback(()=>{if(!J.current)return{x:300,y:200};const be=J.current.getBoundingClientRect(),Me=be.width*(P-1)/2,Be=be.height*(P-1)/2;return{x:Math.max(50,Me),y:Math.max(50,Be)}},[P]),O=be=>{if(D&&P>1){const Me=be.clientX-G.x,Be=be.clientY-G.y,Ae=z();H({x:Math.max(-Ae.x,Math.min(Ae.x,Me)),y:Math.max(-Ae.y,Math.min(Ae.y,Be))})}},Z=()=>{$(!1)},ge=be=>{if(be.length<2)return 0;const Me=be[0].clientX-be[1].clientX,Be=be[0].clientY-be[1].clientY;return Math.sqrt(Me*Me+Be*Be)},Ce=be=>be.length<2?{x:be[0].clientX,y:be[0].clientY}:{x:(be[0].clientX+be[1].clientX)/2,y:(be[0].clientY+be[1].clientY)/2},_e=be=>{be.touches.length===2?(be.preventDefault(),Q(ge(be.touches)),B(Ce(be.touches))):be.touches.length===1&&P>1&&(be.preventDefault(),$(!0),I({x:be.touches[0].clientX-F.x,y:be.touches[0].clientY-F.y}))},Te=be=>{if(be.touches.length===2&&K!==null){be.preventDefault();const Me=ge(be.touches),Be=Me/K;U(qe=>{const ve=Math.max(1,Math.min(4,qe*Be));return ve===1&&H({x:0,y:0}),ve}),Q(Me);const Ae=Ce(be.touches);if(oe){const qe=z();H(ve=>({x:Math.max(-qe.x,Math.min(qe.x,ve.x+(Ae.x-oe.x))),y:Math.max(-qe.y,Math.min(qe.y,ve.y+(Ae.y-oe.y)))}))}B(Ae)}else if(be.touches.length===1&&D&&P>1){be.preventDefault();const Me=be.touches[0].clientX-G.x,Be=be.touches[0].clientY-G.y,Ae=z();H({x:Math.max(-Ae.x,Math.min(Ae.x,Me)),y:Math.max(-Ae.y,Math.min(Ae.y,Be))})}},we=be=>{be.touches.length<2&&(Q(null),B(null)),be.touches.length===0&&$(!1)},$e=()=>{U(1),H({x:0,y:0})},Ge=x?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${b}`:`/api/v1/printers/${s}/camera/snapshot?t=${b}`,ze=p||x||A;return s?a.jsxs("div",{ref:J,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($g,{className:"w-4 h-4"}),de?.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:ze,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:ze,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:()=>se.mutate(!Re?.chamber_light),disabled:!Re?.connected||se.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${Re?.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(MO,{on:Re?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>u(!0),disabled:!ke||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${ke&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(ke?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:a.jsx(zk,{className:"w-4 h-4 text-bambu-gray"})}),a.jsx("button",{onClick:q,disabled:ze,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:a.jsx(Or,{className:`w-4 h-4 text-bambu-gray ${ze?"animate-spin":""}`})}),a.jsx("button",{onClick:re,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(S?"camera.exitFullscreen":"camera.fullscreen"),children:S?a.jsx(IW,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(ehe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:pe,onMouseMove:O,onMouseUp:Z,onMouseLeave:Z,onTouchStart:_e,onTouchMove:Te,onTouchEnd:we,style:{touchAction:"none"},children:a.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(p||x)&&!A&&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(Or,{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")})]})}),A&&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(fm,{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:R,attempt:T+1,max:sj})}),a.jsx("button",{onClick:q,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&&!A&&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(En,{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:q,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:W,src:Ge,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${P}) translate(${F.x/P}px, ${F.y/P}px)`,cursor:P>1?D?"grabbing":"grab":"default"},onError:Ge?Ve:void 0,onLoad:Ge?V:void 0,onMouseDown:ee,draggable:!1},b),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:le,disabled:P<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:a.jsx(YR,{className:"w-4 h-4 text-white"})}),a.jsxs("button",{onClick:$e,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:X,disabled:P>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:a.jsx(XR,{className:"w-4 h-4 text-white"})})]})]})}),a.jsx(EO,{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 VXe(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 GXe(t){const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function qXe(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 WXe(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 KXe(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"};case"medium":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 XXe(){const{printerId:t}=dk(),[e]=RR(),{t:n}=Yt(),r=an(),i=parseInt(t||"0",10),[s,o]=_.useState(Date.now()),l=_.useMemo(()=>VXe(e),[e]),c=KXe(l.size),{data:u}=it({queryKey:["printer",i],queryFn:()=>ae.getPrinter(i),enabled:i>0}),{data:d}=it({queryKey:["printerStatus",i],queryFn:()=>ae.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3});_.useEffect(()=>{if(!i)return;const x=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,v=new WebSocket(x);return v.onmessage=S=>{try{const N=JSON.parse(S.data);N.type==="printer_status"&&N.printer_id===i&&r.setQueryData(["printerStatus",i],N.status)}catch{}},v.onerror=()=>{},()=>{v.close()}},[i,r]),_.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 p=d.state==="RUNNING"||d.state==="PAUSE",m=d.progress||0,b=`/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:b,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(jr,{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:WXe(d,n)}),l.showProgress&&p&&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(m),"%"]})]}),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:`${m}%`}})})]}),p&&(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(is,{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(wu,{className:c.icon}),a.jsx("span",{className:`${c.text} text-white`,children:GXe(d.remaining_time*60)})]}),a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(tr,{className:c.icon}),a.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",qXe(d.remaining_time,n)]})]})]})]}),!p&&a.jsx("div",{className:`${c.text} text-white/70 py-2`,children:d.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function YXe(){const{t}=Yt(),{id:e}=dk(),{mode:n}=Dm(),{data:r,isLoading:i,error:s}=it({queryKey:["external-link",e],queryFn:()=>ae.getExternalLink(Number(e)),enabled:!!e});return i?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(ct,{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(En,{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 L9=["DEBUG","INFO","WARNING","ERROR"],oj={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},QXe={DEBUG:fk,INFO:xo,WARNING:En,ERROR:Ti};function ZXe(){const t=an(),[e,n]=_.useState(!0),[r,i]=_.useState(new Set),[s,o]=_.useState(""),[l,c]=_.useState("ALL"),[u,d]=_.useState(!1),[h,p]=_.useState(!1),m=_.useRef(null),{data:b,isLoading:y,refetch:x}=it({queryKey:["application-logs",l,s],queryFn:()=>Tg.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:h?2e3:!1,enabled:u});_.useEffect(()=>{u||p(!1)},[u]);const v=dt({mutationFn:()=>Tg.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});_.useEffect(()=>{e&&m.current&&b?.entries&&(m.current.scrollTop=m.current.scrollHeight)},[b?.entries,e]);const S=k=>{i(R=>{const C=new Set(R);return C.has(k)?C.delete(k):C.add(k),C})},N=k=>{const R=k.split(" ");return R.length>=2?R[1]:k},T=_.useMemo(()=>b?.entries??[],[b?.entries]),M=_.useMemo(()=>[...T].reverse(),[T]),A=({level:k})=>{const R=QXe[k]||xo;return a.jsx(R,{className:`w-3.5 h-3.5 ${oj[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(fk,{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 - ${b?.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(zu,{className:"w-5 h-5 text-bambu-gray"}):a.jsx(fr,{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(),p(!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(ul,{className:"w-4 h-4"}),"Stop"]}):a.jsxs("button",{onClick:k=>{k.stopPropagation(),p(!0),x()},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(Eo,{className:"w-4 h-4"}),"Start"]}),a.jsxs("button",{onClick:()=>v.mutate(),disabled:v.isPending||T.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(ln,{className:"w-4 h-4"}),"Clear"]}),a.jsx("button",{onClick:()=>x(),disabled:y,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(Or,{className:`w-4 h-4 ${y?"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:[b?.filtered_count??0,"/",b?.total_in_file??0]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Qi,{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(Lt,{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"}),L9.map((k,R)=>a.jsx("button",{onClick:()=>c(k),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${R===L9.length-1?"rounded-r":""} ${l===k?`${oj[k]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:k},k))]})]})]}),a.jsx("div",{ref:m,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:T.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,R)=>{const C=r.has(R),P=k.message.includes(` +`+n+"}"}return String(t)}function mXe({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=Tn(),c=an(),[u,d]=_.useState(!1),{data:h,isLoading:p}=it({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ae.getCloudSettingDetail(t.setting_id)}),m=dt({mutationFn:()=>ae.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:x=>l(x.message,"error")}),b=zy(t.setting_id),y=MF(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(St,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:a.jsxs(Et,{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}),b&&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}`)}),y.printer&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"•"}),a.jsx("span",{children:y.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(Lt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{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:NR(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(En,{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(Ne,{variant:"secondary",onClick:()=>d(!1),disabled:m.isPending,className:"flex-1",children:o("common.cancel")}),a.jsxs(Ne,{variant:"danger",onClick:()=>m.mutate(),disabled:m.isPending,className:"flex-1",children:[m.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(ln,{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(Ne,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),a.jsxs(Ne,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[a.jsx(zl,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),b&&a.jsxs(a.Fragment,{children:[a.jsxs(Ne,{variant:"secondary",onClick:i,disabled:p||!h||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[a.jsx(Ji,{className:"w-4 h-4"}),o("common.edit")]}),a.jsx(Ne,{variant:"danger",onClick:()=>d(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:a.jsx(ln,{className:"w-4 h-4"})})]})]})})]})})})}function sie(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function oie(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function pXe({onClose:t,onApply:e,t:n}){const{showToast:r}=Tn(),[i,s]=_.useState(sie),[o,l]=_.useState("all"),[c,u]=_.useState(null),[d,h]=_.useState(""),[p,m]=_.useState(""),[b,y]=_.useState("{}"),[x,v]=_.useState(null),[S,N]=_.useState(null),T=o==="all"?i:i.filter(H=>H.type===o),M=H=>{s(H),oie(H)},A=H=>{const D=i.filter($=>$.id!==H);M(D),N(null),r(n("profiles.templates.toast.deleted"))},k=H=>{u(H.id),h(H.name),m(H.description),y(JSON.stringify(H.settings,null,2)),v(null)},R=()=>{if(!(!c||!d.trim()))try{const H=JSON.parse(b),D=i.map($=>$.id===c?{...$,name:d.trim(),description:p.trim(),settings:H}:$);M(D),u(null),r(n("profiles.templates.toast.updated"))}catch(H){v(H.message)}},C=()=>{u(null),h(""),m(""),y("{}"),v(null)},P=H=>{const D=i.map($=>$.id===H?{...$,showInModal:!$.showInModal}:$);M(D)},U={filament:{label:n("profiles.presets.types.filament"),icon:gk,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:Hu,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:jr,color:"text-purple-400"}},F=S?i.find(H=>H.id===S):null;return _.useEffect(()=>{const H=D=>{D.key==="Escape"&&(S?N(null):c?C():t())};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[S,c,t]),a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[F&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:a.jsx(St,{className:"w-full max-w-md",children:a.jsxs(Et,{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(En,{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:F.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ne,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),a.jsxs(Ne,{onClick:()=>A(S),className:"flex-1 bg-red-500 hover:bg-red-600",children:[a.jsx(ln,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),a.jsx(St,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:a.jsxs(Et,{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(Z0,{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(Lt,{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(H=>a.jsx("button",{onClick:()=>l(H),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===H?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:H==="all"?n("common.all"):U[H].label},H))]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:T.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(Z0,{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:T.map(H=>{const D=U[H.type],$=D.icon;return c===H.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:G=>h(G.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:p,onChange:G=>m(G.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:b,onChange:G=>{y(G.target.value),v(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 ${x?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),x&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:x})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ne,{size:"sm",onClick:R,disabled:!d.trim(),children:[a.jsx(vs,{className:"w-4 h-4"}),"Save"]}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:C,children:"Cancel"})]})]},H.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($,{className:`w-5 h-5 ${D.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:H.name}),a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:H.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(H.settings).length})}),a.jsx("button",{onClick:()=>P(H.id),className:`p-1 transition-colors ${H.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:H.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:H.showInModal?a.jsx(gc,{className:"w-4 h-4"}):a.jsx(bk,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>e(H),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(H),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:a.jsx(Ji,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>N(H.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:a.jsx(ln,{className:"w-4 h-4"})})]},H.id)})})})]})})]})}function lie({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:i,t:s}){const[o,l]=_.useState("changes"),[c,u]=_.useState(""),d=_.useMemo(()=>{const b=new Set([...Object.keys(e),...Object.keys(n)]),y=[];for(const x of b){if(x==="inherits"||x==="version")continue;const v=e[x],S=n[x],N=x in e,T=x in n;let M;!N&&T?M="added":N&&!T?M="removed":JSON.stringify(v)!==JSON.stringify(S)?M="changed":M="same",y.push({key:x,left:v,right:S,status:M})}return y.sort((x,v)=>{const S={changed:0,added:1,removed:2,same:3};return S[x.status]!==S[v.status]?S[x.status]-S[v.status]:x.key.localeCompare(v.key)})},[e,n]),h=_.useMemo(()=>{let b=[...d];if(o==="changes"&&(b=b.filter(y=>y.status!=="same")),c){const y=c.toLowerCase();b=b.filter(x=>x.key.toLowerCase().includes(y)||String(x.left).toLowerCase().includes(y)||String(x.right).toLowerCase().includes(y))}return b},[d,o,c]),p=_.useMemo(()=>({added:d.filter(b=>b.status==="added").length,removed:d.filter(b=>b.status==="removed").length,changed:d.filter(b=>b.status==="changed").length,same:d.filter(b=>b.status==="same").length}),[d]),m=b=>{if(b===void 0)return"—";if(b===null)return"null";if(Array.isArray(b))return b.length===0?"[]":b.length===1?String(b[0]):b.join(", ");if(typeof b=="object")return JSON.stringify(b);const y=String(b);if(y.includes("\\n")||y.length>100){const x=y.split("\\n").length;if(x>1)return`[${x} lines of G-code/script]`;if(y.length>100)return y.substring(0,100)+"…"}return y};return _.useEffect(()=>{const b=y=>{y.key==="Escape"&&t()};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:a.jsxs(Et,{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(Mg,{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(Lt,{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(cr,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(Aj,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[a.jsx(_j,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(hT,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"relative",children:[a.jsx(Qi,{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:b=>u(b.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"})]}),p.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(hT,{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(b=>{const y={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[b.status],x={added:a.jsx(cr,{className:"w-3.5 h-3.5 text-green-400"}),removed:a.jsx(Aj,{className:"w-3.5 h-3.5 text-red-400"}),changed:a.jsx(_j,{className:"w-3.5 h-3.5 text-amber-400"}),same:a.jsx(hT,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[b.status];return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${y}`,children:[a.jsx("td",{className:"p-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[x,a.jsx("span",{className:"text-sm text-white font-mono",children:b.key})]})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${b.status==="removed"?"text-red-300":b.status==="changed"?"text-white":"text-bambu-gray"}`,children:m(b.left)})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${b.status==="added"?"text-green-300":b.status==="changed"?"text-white":"text-bambu-gray"}`,children:m(b.right)})})]},b.key)})})]})})]})})})}function gXe({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:i}=Tn(),s=an(),o=!!e?.setting_id,[l,c]=_.useState("common"),[u,d]=_.useState(e?.type||"filament"),[h,p]=_.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[m,b]=_.useState(e?.base_id||""),[y,x]=_.useState(""),[v,S]=_.useState(e?.setting||{inherits:""}),[N,T]=_.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[M,A]=_.useState(null),[k,R]=_.useState(""),[C,P]=_.useState(!1),[U,F]=_.useState(""),[H,D]=_.useState(!1),[$,G]=_.useState(sie),[I,K]=_.useState(!1),[Q,oe]=_.useState(""),[B,W]=_.useState(""),[J,ne]=_.useState(!0),[me,fe]=_.useState(null),[de,Re]=_.useState(!1),se=_.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),ke=_.useMemo(()=>se.filter(Me=>zy(Me.setting_id)),[se]),{data:Fe}=it({queryKey:["cloudFields",u],queryFn:()=>ae.getCloudFields(u==="print"?"process":u),staleTime:1e3*60*60}),{data:ce}=it({queryKey:["allPresetDetails",u,ke.map(Me=>Me.setting_id).join(",")],queryFn:async()=>{const Me={};for(let Ae=0;Ae{try{const Ee=await ae.getCloudSettingDetail(et.setting_id);return{id:et.setting_id,detail:Ee}}catch{return null}}))).forEach(et=>{et&&(Me[et.id]=et.detail)})}return Me},enabled:ke.length>0,staleTime:1e3*60*10}),{data:Ve,isLoading:V}=it({queryKey:["cloudSettingDetail",m],queryFn:()=>ae.getCloudSettingDetail(m),enabled:!!m});_.useEffect(()=>{l!=="json"&&T(JSON.stringify(v,null,2))},[v,l]);const Y=_.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(Be=>!zy(Be.setting_id)).sort((Be,Ae)=>Be.name.localeCompare(Ae.name)),[n,u]);_.useEffect(()=>{if(!m)return;const Me=Y.find(Be=>Be.setting_id===m);Me&&(x(Me.name),o||(S({inherits:Me.name}),T(JSON.stringify({inherits:Me.name},null,2))))},[m,Y,o]);const ue=_.useMemo(()=>{const Me=Fe?.fields||[],Be=new Set(Me.map(et=>et.key)),Ae=new Set,qe=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);ce&&Object.values(ce).forEach(et=>{et?.setting&&Object.keys(et.setting).forEach(Ee=>{!Be.has(Ee)&&!qe.has(Ee)&&Ae.add(Ee)})}),Object.keys(v).forEach(et=>{!Be.has(et)&&!qe.has(et)&&Ae.add(et)});const ve=Array.from(Ae).sort().map(et=>({key:et,label:et.replace(/_/g," ").replace(/\b\w/g,Ee=>Ee.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Me,...ve]},[Fe,ce,v,r]),q=ue.filter(Me=>Me.label.toLowerCase().includes(k.toLowerCase())||Me.key.toLowerCase().includes(k.toLowerCase())),re=()=>{if(U.trim()){const Me=U.trim().toLowerCase().replace(/\s+/g,"_");X(Me,""),F(""),D(!1),i(r("profiles.presets.toast.fieldAdded",{key:Me}))}},X=(Me,Be)=>{S(Ae=>{const qe={...Ae};return Be===""||Be===void 0?delete qe[Me]:qe[Me]=Be,qe})},le=Me=>{S(Be=>({...Be,...Me.settings})),fe(Me.name),i(r("profiles.templates.toast.applied"))},pe=()=>{if(!Q.trim())return;const Me={...v};if(delete Me.inherits,Object.keys(Me).length===0){i(r("profiles.presets.noOverridesToSave"),"error");return}const Be={id:Date.now().toString(),name:Q.trim(),description:B.trim()||r("profiles.presets.customTemplate"),type:u,settings:Me,showInModal:J},Ae=[...$,Be];G(Ae),oie(Ae),K(!1),oe(""),W(""),ne(!0),i(r("profiles.templates.toast.created"))},ee=_.useMemo(()=>$.filter(Me=>Me.type===u&&Me.showInModal),[u,$]),z=Me=>{T(Me);try{const Be=JSON.parse(Me);S(Be),A(null)}catch(Be){A(Be.message)}},O=Me=>{Me.preventDefault(),P(!1);const Be=Me.dataTransfer.files[0];if(Be&&Be.name.endsWith(".json")){const Ae=new FileReader;Ae.onload=qe=>{try{const ve=qe.target?.result,et=JSON.parse(ve),Ee=et.setting||et;S(Ye=>({...Ye,...Ee})),T(JSON.stringify({...v,...Ee},null,2)),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJsonFile"),"error")}},Ae.readAsText(Be)}},Z=dt({mutationFn:()=>{const Me={...v},Be=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";Me[Be]=`"${h}"`;const Ae={type:u,name:h,base_id:m,setting:Me};return ae.createCloudSetting(Ae)},onSuccess:async()=>{i(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Me=>i(Me.message,"error")}),ge=dt({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return ae.updateCloudSetting(e.setting_id,{name:h,setting:v})},onSuccess:async()=>{i(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Me=>i(Me.message,"error")}),Ce=o?ge:Z,_e=Ve?.setting?.inherits,Te=_e?Y.find(Me=>Me.name===_e):void 0,{data:we}=it({queryKey:["cloudSettingDetail",Te?.setting_id],queryFn:()=>ae.getCloudSettingDetail(Te.setting_id),enabled:!!Te?.setting_id}),$e=_.useMemo(()=>{const Me=we?.setting||{},Be=Ve?.setting||{},Ae=m&&ce?.[m]?.setting?ce[m].setting:{};return{...Me,...Be,...Ae}},[m,Ve,we,ce]),Ge=Me=>{if(Me==null)return"";if(Array.isArray(Me)){const Be=[...new Set(Me.map(Ae=>String(Ae)))];return Be.length===1?Be[0]:Me.join(", ")}return String(Me)},ze=Me=>{const Be=v[Me.key],Ae=$e[Me.key],qe=Ge(Ae),ve=V?r("common.loading"):qe||"",et="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(Me.type==="boolean"){const Ee=Be==="1"||Be===void 0&&Ae==="1";return a.jsx("button",{type:"button",onClick:()=>X(Me.key,Be==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Ee?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Ee?"translate-x-3.5":"translate-x-0.5"}`})})}return Me.type==="select"?a.jsxs("select",{value:Be||"",onChange:Ee=>X(Me.key,Ee.target.value),className:et,children:[a.jsx("option",{value:"",children:ve}),Me.options?.map(Ee=>a.jsx("option",{value:Ee.value,children:Ee.label},Ee.value))]}):a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:Me.type==="number"?"number":"text",value:Be!==void 0?String(Be):"",onChange:Ee=>X(Me.key,Ee.target.value),step:Me.step,min:Me.min,max:Me.max,placeholder:ve,className:et}),Me.unit&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Me.unit})]})},be=_.useMemo(()=>Ve?.setting?Ve.setting:{},[Ve]);return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Me=>{Me.preventDefault(),P(!0)},onDragLeave:()=>P(!1),onDrop:O,children:[de&&m&&a.jsx(lie,{onClose:()=>Re(!1),leftPreset:be,rightPreset:v,leftLabel:r("profiles.presets.baseLabel",{name:y||m}),rightLabel:r("profiles.presets.currentLabel",{name:h||r("profiles.presets.newPreset")}),t:r}),a.jsx(St,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col",children:a.jsxs(Et,{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:[m&&a.jsxs("button",{onClick:()=>Re(!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(Mg,{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(Lt,{className:"w-5 h-5"})})]})]}),C&&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(Na,{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",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:Me=>{d(Me.target.value),b("")},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:m,onChange:Me=>b(Me.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")}),Y.map(Me=>a.jsx("option",{value:Me.setting_id,children:Me.name},Me.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:Me=>p(Me.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")})]})]}),y&&a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("p",{className:"flex items-center gap-1",children:[a.jsx($i,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",a.jsx("span",{className:"text-white",children:y}),V&&a.jsx(ct,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",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(ZU,{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(_k,{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(DW,{className:"w-4 h-4"}),"JSON",M&&a.jsx(Ti,{className:"w-3 h-3 text-red-400"})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("button",{onClick:()=>{const Me={name:h,type:u,base_id:m,setting:v},Be=new Blob([JSON.stringify(Me,null,2)],{type:"application/json"}),Ae=URL.createObjectURL(Be),qe=document.createElement("a");qe.href=Ae,qe.download=`${h||"preset"}.json`,document.body.appendChild(qe),qe.click(),document.body.removeChild(qe),URL.revokeObjectURL(Ae),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(wi,{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(Na,{className:"w-4 h-4"}),r("common.upload")]}),a.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Me=>{const Be=Me.target.files?.[0];if(Be){const Ae=new FileReader;Ae.onload=qe=>{try{const ve=JSON.parse(qe.target?.result),et=ve.setting||ve;S(Ee=>({...Ee,...et})),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJson"),"error")}},Ae.readAsText(Be)}}})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto 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(Z0,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(v).filter(Me=>Me!=="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(vs,{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:Q,onChange:Me=>oe(Me.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:B,onChange:Me=>W(Me.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(Ne,{size:"sm",onClick:pe,disabled:!Q.trim(),children:[a.jsx(vs,{className:"w-3 h-3"}),r("common.save")]}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:()=>K(!1),children:r("common.cancel")})]}),a.jsxs("button",{onClick:()=>ne(!J),className:`flex items-center gap-1.5 text-xs transition-colors ${J?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[J?a.jsx(gc,{className:"w-3.5 h-3.5"}):a.jsx(bk,{className:"w-3.5 h-3.5"}),r(J?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),me&&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($i,{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:me})]}),a.jsx("button",{onClick:()=>fe(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:a.jsx(Lt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[ee.map(Me=>a.jsxs("button",{onClick:()=>le(Me),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:Me.name}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Me.description})]},Me.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(Me=>a.jsxs("div",{className:"flex items-center justify-between gap-4",children:[a.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Me.label}),a.jsx("div",{className:"w-48",children:ze(Me)})]},Me.key))})]}),Object.keys(v).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(v).filter(([Me])=>Me!=="inherits").map(([Me,Be])=>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:[Me,": ",String(Be).slice(0,20),a.jsx("button",{onClick:()=>X(Me,void 0),className:"hover:text-white",children:a.jsx(Lt,{className:"w-3 h-3"})})]},Me))})]})]}),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:ce?r("profiles.templates.fieldsCount",{count:ue.length}):r("common.loading")})]}),a.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[a.jsx(Qi,{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:Me=>R(Me.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:[q.filter(Me=>!(Me.key in v)).map(Me=>{const Be=$e[Me.key],Ae=Ge(Be);return a.jsxs("div",{onClick:()=>{S(qe=>({...qe,[Me.key]:Ae||""}))},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:Me.label}),a.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Me.key})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Ae&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Ae,children:[Ae.slice(0,20),Ae.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(cr,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Me.key)}),q.filter(Me=>!(Me.key in v)).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:H?a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:U,onChange:Me=>F(Me.target.value),onKeyDown:Me=>Me.key==="Enter"&&re(),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(Ne,{size:"sm",onClick:re,disabled:!U.trim(),children:a.jsx(cr,{className:"w-4 h-4"})}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:()=>{D(!1),F("")},children:a.jsx(Lt,{className:"w-4 h-4"})})]}):a.jsxs("button",{onClick:()=>D(!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(cr,{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(v).filter(Me=>Me!=="inherits").length})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(v).filter(([Me])=>Me!=="inherits").map(([Me,Be])=>{const Ae=ue.find(qe=>qe.key===Me);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:Ae?.label||Me}),a.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Me})]}),a.jsx("button",{onClick:()=>X(Me,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:a.jsx(Lt,{className:"w-4 h-4"})})]}),Ae?ze(Ae):a.jsx("input",{type:"text",value:String(Be),onChange:qe=>X(Me,qe.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"})]},Me)}),Object.keys(v).filter(Me=>Me!=="inherits").length===0&&a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(ZU,{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(v).filter(Me=>Me!=="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(vs,{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(Ti,{className:"w-4 h-4"}),M]}),a.jsx("textarea",{value:N,onChange:Me=>z(Me.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(Ne,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsxs(Ne,{onClick:()=>Ce.mutate(),disabled:Ce.isPending||!h.trim()||!o&&!m||!!M,className:"flex-1",children:[Ce.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):o?a.jsx(vs,{className:"w-4 h-4"}):a.jsx(cr,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function bXe({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:i,hasPermission:s,t:o}){const[l,c]=_.useState(""),[u,d]=_.useState("all"),[h,p]=_.useState("all"),[m,b]=_.useState("all"),[y,x]=_.useState("all"),[v,S]=_.useState("all"),[N,T]=_.useState("all"),[M,A]=_.useState(null),[k,R]=_.useState(!1),[C,P]=_.useState(!1),[U,F]=_.useState(null),[H,D]=_.useState(null),[$,G]=_.useState(null),[I,K]=_.useState(!1),[Q,oe]=_.useState([null,null]),[B,W]=_.useState(!1),[J,ne]=_.useState(null),me=an(),fe=_.useMemo(()=>[...t.filament.map(re=>({...re,type:"filament"})),...t.printer.map(re=>({...re,type:"printer"})),...t.process.map(re=>({...re,type:"process"}))].map(re=>({...re,meta:MF(re.name)})),[t]),de=_.useMemo(()=>{const q=new Set,re=new Set,X=new Set;return fe.forEach(le=>{le.meta.nozzle&&q.add(le.meta.nozzle),le.meta.filamentType&&re.add(le.meta.filamentType),le.meta.layerHeight&&X.add(le.meta.layerHeight)}),{printers:i.map(le=>({id:le.id.toString(),name:le.name})),nozzles:Array.from(q).sort((le,pe)=>parseFloat(le)-parseFloat(pe)),filaments:Array.from(re).sort(),layerHeights:Array.from(X).sort((le,pe)=>parseFloat(le)-parseFloat(pe))}},[fe,i]),Re=_.useMemo(()=>m==="all"?null:i.find(re=>re.id.toString()===m)?.model||null,[m,i]),se=_.useMemo(()=>fe.filter(q=>u==="all"||q.type===u).filter(q=>{if(h==="all")return!0;const re=zy(q.setting_id);return h==="custom"?re:!re}).filter(q=>{if(m==="all"||!Re)return!0;const re=q.meta.printer?.toLowerCase()||"",X=Re.toLowerCase();return re.includes(X)||X.includes(re)}).filter(q=>y==="all"||q.meta.nozzle===y).filter(q=>v==="all"||q.meta.filamentType===v).filter(q=>N==="all"||q.meta.layerHeight===N).filter(q=>l===""||q.name.toLowerCase().includes(l.toLowerCase())).sort((q,re)=>q.name.localeCompare(re.name)),[fe,u,h,m,Re,y,v,N,l]),ke=q=>{if(I){const re=Q[0]?.setting_id===q.setting_id,X=Q[1]?.setting_id===q.setting_id;if(re)oe([Q[1],null]);else if(X)oe([Q[0],null]);else if(!Q[0])oe([q,null]);else if(Q[1]){if(Q[0].type!==q.type)return;oe([Q[0],q])}else{if(Q[0].type!==q.type)return;oe([Q[0],q])}}else A(q)},Fe=q=>{if(Q[0]?.setting_id===q.setting_id)return 0;if(Q[1]?.setting_id===q.setting_id)return 1},ce=async q=>{try{const re=await ae.getCloudSettingDetail(q.setting_id),X=q.type==="process"?"print":q.type;F({type:X,name:q.name,base_id:re.base_id||"GFSA00",setting:re.setting||{}}),A(null)}catch(re){console.error("Failed to fetch preset details for duplication:",re)}},Ve=async q=>{try{me.removeQueries({queryKey:["cloudSettingDetail",q.setting_id]});const re=await ae.getCloudSettingDetail(q.setting_id),X=q.type==="process"?"print":q.type;D({type:X,name:q.name,base_id:re.base_id||"GFSA00",setting:re.setting||{},setting_id:q.setting_id}),A(null)}catch(re){console.error("Failed to fetch preset details for editing:",re)}},V=()=>{d("all"),p("all"),b("all"),x("all"),S("all"),T("all"),c("")},Y=u!=="all"||h!=="all"||m!=="all"||y!=="all"||v!=="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(Qi,{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:q=>c(q.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",children:[a.jsxs(Ne,{variant:I?"primary":"secondary",onClick:()=>{I?(K(!1),oe([null,null])):K(!0)},children:[a.jsx(Mg,{className:"w-4 h-4"}),o(I?"common.cancel":"profiles.presets.compare")]}),a.jsxs(Ne,{variant:"secondary",onClick:()=>P(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[a.jsx(Z0,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),a.jsxs(Ne,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[a.jsx(Or,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),a.jsxs(Ne,{onClick:()=>R(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[a.jsx(cr,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(yk,{className:"w-4 h-4 text-bambu-gray"}),a.jsx(og,{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:q=>d(q)}),a.jsx(og,{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:q=>p(q)}),de.printers.length>0&&a.jsx(og,{label:o("profiles.cloudView.filters.printer"),value:m,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...de.printers.map(q=>({value:q.id,label:q.name}))],onChange:b}),de.nozzles.length>0&&a.jsx(og,{label:o("profiles.cloudView.filters.nozzle"),value:y,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...de.nozzles.map(q=>({value:q,label:q}))],onChange:x}),de.filaments.length>0&&(u==="all"||u==="filament")&&a.jsx(og,{label:o("profiles.cloudView.filters.filament"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...de.filaments.map(q=>({value:q,label:q}))],onChange:S}),de.layerHeights.length>0&&(u==="all"||u==="process")&&a.jsx(og,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...de.layerHeights.map(q=>({value:q,label:q}))],onChange:T}),Y&&a.jsx("button",{onClick:V,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(Mg,{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:Q[0]?o("profiles.cloudView.selectAnotherPreset",{type:Q[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] ${Q[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Q[0]?Q[0].name:o("profiles.cloudView.selectFirst")}),a.jsx(_j,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${Q[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Q[1]?Q[1].name:o("profiles.cloudView.selectSecond")})]}),Q[0]&&Q[1]&&a.jsxs(Ne,{size:"sm",onClick:async()=>{try{const[q,re]=await Promise.all([ae.getCloudSettingDetail(Q[0].setting_id),ae.getCloudSettingDetail(Q[1].setting_id)]);ne([q.setting||{},re.setting||{}]),W(!0)}catch{}},children:[a.jsx(Mg,{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(tr,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",dXe(e.toISOString(),o)]}),a.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:se.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")]})]})]}),se.length===0?a.jsxs("div",{className:"text-center py-16",children:[a.jsx(is,{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")}),Y&&a.jsx("button",{onClick:V,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(gk,{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:["(",se.filter(q=>q.type==="filament").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[se.filter(q=>q.type==="filament").map(q=>a.jsx(rj,{setting:q,onClick:()=>ke(q),onDuplicate:()=>ce(q),compareMode:I,isCompareSelected:Fe(q)!==void 0,compareIndex:Fe(q),compareDisabled:I&&!!Q[0]&&Q[0].type!==q.type,t:o},q.setting_id)),se.filter(q=>q.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(Hu,{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:["(",se.filter(q=>q.type==="process").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[se.filter(q=>q.type==="process").map(q=>a.jsx(rj,{setting:q,onClick:()=>ke(q),onDuplicate:()=>ce(q),compareMode:I,isCompareSelected:Fe(q)!==void 0,compareIndex:Fe(q),compareDisabled:I&&!!Q[0]&&Q[0].type!==q.type,t:o},q.setting_id)),se.filter(q=>q.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(jr,{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:["(",se.filter(q=>q.type==="printer").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[se.filter(q=>q.type==="printer").map(q=>a.jsx(rj,{setting:q,onClick:()=>ke(q),onDuplicate:()=>ce(q),compareMode:I,isCompareSelected:Fe(q)!==void 0,compareIndex:Fe(q),compareDisabled:I&&!!Q[0]&&Q[0].type!==q.type,t:o},q.setting_id)),se.filter(q=>q.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(mXe,{setting:M,onClose:()=>A(null),onDeleted:()=>A(null),onDuplicate:()=>ce(M),onEdit:()=>Ve(M),hasPermission:s,t:o}),(k||U||H||$)&&a.jsx(gXe,{onClose:()=>{R(!1),F(null),D(null),G(null)},initialData:H||U||($?{type:$.type,name:"",base_id:"",setting:$.setting}:void 0),allPresets:t,t:o}),C&&a.jsx(pXe,{onClose:()=>P(!1),onApply:q=>{G({type:q.type,setting:q.settings}),P(!1)},t:o}),B&&J&&Q[0]&&Q[1]&&a.jsx(lie,{onClose:()=>{W(!1),ne(null)},leftPreset:J[0],rightPreset:J[1],leftLabel:Q[0].name,rightLabel:Q[1].name,t:o})]})}function xXe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),{hasPermission:r}=Ir(),[i,s]=_.useState("cloud"),[o,l]=_.useState(),{data:c,isLoading:u}=it({queryKey:["cloudStatus"],queryFn:ae.getCloudStatus}),{data:d=[]}=it({queryKey:["printers"],queryFn:ae.getPrinters}),{data:h,isLoading:p,refetch:m,dataUpdatedAt:b}=it({queryKey:["cloudSettings"],queryFn:()=>ae.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});_.useEffect(()=>{b&&l(new Date(b))},[b]);const y=dt({mutationFn:ae.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),x=()=>{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(ct,{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(pk,{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(Sb,{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(vk,{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(Ne,{variant:"secondary",size:"sm",onClick:()=>y.mutate(),disabled:y.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[a.jsx(Tj,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?a.jsx(bXe,{settings:h,lastSyncTime:o,onRefresh:()=>m(),isRefreshing:p,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(Ne,{onClick:()=>m(),children:t("profiles.retry")})]}):a.jsx(hXe,{onSuccess:x,t})]}),i==="local"&&a.jsx(uXe,{}),i==="kprofiles"&&a.jsx(sXe,{}),a.jsx(fXe,{})]})}const v0={Droplet:gk,Flame:tde,Ruler:Dhe,Sparkles:Z0,Square:ul,Cable:Yce,Wrench:mm,Calendar:ti,Timer:wu,Cog:Tue,Fan:RW,Zap:Ah,Wind:qW,Thermometer:Ek,Layers:is,Box:Ii,Target:$W,RefreshCw:Or,Settings:Mk,Filter:yk,CircleDot:pue};function V0(t){return t&&v0[t]||mm}function lg(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 ij(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 yXe(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 Linear Rails":return r?"https://wiki.bambulab.com/en/x1/maintenance/basic-maintenance":i?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":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":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/general/lead-screws-lubrication";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?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":s||o||d||h?null:"https://wiki.bambulab.com/en/general/carbon-rods-clearance";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 vXe({item:t,onPerform:e,onToggle:n,hasPermission:r,t:i}){const s=V0(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const m=t.days_since_maintenance??0;return Math.max(0,Math.min(100,m/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",p=()=>{if(!t.enabled)return i("common.disabled");if(o==="days"){const m=t.days_until_due??0;return t.is_due?i("maintenance.overdueBy",{duration:lg(Math.abs(m),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:lg(m,"days",i)}):i("maintenance.timeLeft",{duration:lg(m,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:lg(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:lg(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:lg(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",children:[a.jsxs("div",{className:`relative p-2.5 rounded-lg ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[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(ti,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const m=t.maintenance_type_wiki_url||yXe(t.maintenance_type_name,t.printer_model);return m?a.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:i("maintenance.viewDocumentation"),onClick:b=>b.stopPropagation(),children:a.jsx(Xr,{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(En,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&a.jsx(tr,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&a.jsx($i,{className:"w-3 h-3"}),p()]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[a.jsx("span",{title:r("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:a.jsx($n,{checked:t.enabled,onChange:m=>n(t.id,m),disabled:!r("maintenance:update")})}),a.jsxs(Ne,{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(Bu,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function wXe({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:i,t:s}){const[o,l]=_.useState(!0),[c,u]=_.useState(!1),[d,h]=_.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((y,x)=>y.is_due&&!x.is_due?-1:!y.is_due&&x.is_due?1:y.is_warning&&!x.is_warning?-1:!y.is_warning&&x.is_warning?1:y.maintenance_type_id-x.maintenance_type_id),m=p.find(y=>y.enabled&&(y.is_due||y.is_warning)),b=()=>{const y=parseFloat(d);!isNaN(y)&&y>=0&&(r(t.printer_id,y),u(!1))};return a.jsxs(St,{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(En,{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(tr,{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($i,{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(zu,{className:"w-4 h-4"}):a.jsx(fr,{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(wu,{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:y=>h(y.target.value),onKeyDown:y=>{y.key==="Enter"&&b(),y.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(Ne,{size:"sm",onClick:b,children:s("common.save")}),a.jsx(Ne,{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(dm,{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"}),m&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${m.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const y=V0(m.maintenance_type_icon);return a.jsx(y,{className:`w-4 h-4 ${m.is_due?"text-red-400":"text-amber-400"}`})})()}),a.jsxs("div",{children:[a.jsx("div",{className:`text-sm font-medium ${m.is_due?"text-red-400":"text-amber-400"}`,children:m.maintenance_type_name}),a.jsx("div",{className:`text-xs ${m.is_due?"text-red-400/70":"text-amber-400/70"}`,children:m.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&a.jsx(Et,{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:p.map(y=>a.jsx(vXe,{item:y,onPerform:e,onToggle:n,hasPermission:i,t:s},y.id))})})]})}function _Xe({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:i,onDeleteType:s,onAssignType:o,onRemoveItem:l,hasPermission:c,t:u}){const[d,h]=_.useState(null),[p,m]=_.useState(""),[b,y]=_.useState("hours"),[x,v]=_.useState(!1),[S,N]=_.useState(""),[T,M]=_.useState("100"),[A,k]=_.useState("hours"),[R,C]=_.useState("Wrench"),[P,U]=_.useState(""),[F,H]=_.useState(new Set),[D,$]=_.useState(null),G=_.useMemo(()=>t?t.map(X=>({id:X.printer_id,name:X.printer_name})):[],[t]),I=X=>t?t.filter(le=>le.maintenance_items.some(pe=>pe.maintenance_type_id===X)).map(le=>({printerId:le.printer_id,printerName:le.printer_name,itemId:le.maintenance_items.find(pe=>pe.maintenance_type_id===X)?.id})):[],K=X=>{if(!t)return[];const le=new Set(I(X).map(pe=>pe.printerId));return G.filter(pe=>!le.has(pe.id))},[Q,oe]=_.useState(null),[B,W]=_.useState(""),[J,ne]=_.useState(""),[me,fe]=_.useState("hours"),[de,Re]=_.useState("Wrench"),[se,ke]=_.useState(""),Fe=X=>{oe(X),W(X.name),ne(X.default_interval_hours.toString()),fe(X.interval_type||"hours"),Re(X.icon||"Wrench"),ke(X.wiki_url||"")},ce=()=>{Q&&B.trim()&&parseFloat(J)>0&&(i(Q.id,{name:B.trim(),default_interval_hours:parseFloat(J),interval_type:me,icon:de,wiki_url:se.trim()||null}),oe(null))},Ve=(X,le,pe)=>{const ee=parseFloat(p);if(!isNaN(ee)&&ee>0){const z=Math.abs(ee-le)<.01?null:ee;n(X,{custom_interval_hours:z,custom_interval_type:b!==pe?b:null})}h(null)},V=X=>{X.preventDefault(),S.trim()&&parseFloat(T)>0&&F.size>0&&(r({name:S.trim(),default_interval_hours:parseFloat(T),interval_type:A,icon:R,wiki_url:P.trim()||null},Array.from(F)),N(""),M("100"),k("hours"),U(""),H(new Set),v(!1))},Y=X=>{H(le=>{const pe=new Set(le);return pe.has(X)?pe.delete(X):pe.add(X),pe})},ue=t?.map(X=>({printerId:X.printer_id,printerName:X.printer_name,items:X.maintenance_items.sort((le,pe)=>le.maintenance_type_id-pe.maintenance_type_id)})).sort((X,le)=>X.printerName.localeCompare(le.printerName))||[],q=e.filter(X=>X.is_system),re=e.filter(X=>!X.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:u("maintenance.maintenanceTypes")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:u("maintenance.maintenanceTypesDescription")})]}),a.jsxs(Ne,{onClick:()=>v(!x),disabled:!c("maintenance:create"),title:c("maintenance:create")?void 0:u("maintenance.noPermissionEditTypes"),children:[a.jsx(cr,{className:"w-4 h-4"}),u("maintenance.addCustomType")]})]}),x&&a.jsx(St,{className:"mb-6",children:a.jsx(Et,{className:"py-4",children:a.jsxs("form",{onSubmit:V,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:u("common.name")}),a.jsx("input",{type:"text",value:S,onChange:X=>N(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:u("maintenance.exampleName"),autoFocus:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:u("maintenance.intervalType")}),a.jsxs("select",{value:A,onChange:X=>{k(X.target.value),X.target.value==="days"?M("30"):M("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:u("maintenance.printHours")}),a.jsx("option",{value:"days",children:u("maintenance.calendarDays")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:u("maintenance.intervalValue",{type:A==="days"?u("maintenance.calendarDays").toLowerCase():u("common.hours")})}),a.jsx("input",{type:"number",value:T,onChange:X=>M(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),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:u("maintenance.icon")}),a.jsx("div",{className:"flex gap-1",children:Object.keys(v0).map(X=>{const le=v0[X];return a.jsx("button",{type:"button",onClick:()=>C(X),className:`p-2 rounded-lg transition-colors ${R===X?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:a.jsx(le,{className:"w-4 h-4"})},X)})})]})}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:u("maintenance.documentationLink")}),a.jsx("input",{type:"url",value:P,onChange:X=>U(X.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"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:u("maintenance.assignToPrinters")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:G.map(X=>a.jsx("button",{type:"button",onClick:()=>Y(X.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${F.has(X.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:X.name},X.id))}),F.size===0&&a.jsx("p",{className:"text-xs text-orange-400 mt-1",children:u("maintenance.selectAtLeastOnePrinter")})]}),a.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[a.jsx(Ne,{type:"button",variant:"secondary",onClick:()=>{v(!1),H(new Set)},children:u("common.cancel")}),a.jsx(Ne,{type:"submit",disabled:!S.trim()||F.size===0,children:u("maintenance.addType")})]})]})})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[q.map(X=>{const le=V0(X.icon),pe=X.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(le,{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:X.name}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[pe==="days"?a.jsx(ti,{className:"w-3 h-3"}):a.jsx(wu,{className:"w-3 h-3"}),ij(X.default_interval_hours,pe,u)]})]})]})},X.id)}),re.map(X=>{const le=V0(X.icon),pe=X.interval_type||"hours";if(Q?.id===X.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:B,onChange:ge=>W(ge.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:u("common.name"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:me,onChange:ge=>fe(ge.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:u("maintenance.printHours")}),a.jsx("option",{value:"days",children:u("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:J,onChange:ge=>ne(ge.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(v0).map(ge=>{const Ce=v0[ge];return a.jsx("button",{type:"button",onClick:()=>Re(ge),className:`p-1.5 rounded transition-colors ${de===ge?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a.jsx(Ce,{className:"w-3.5 h-3.5"})},ge)})}),a.jsx("input",{type:"url",value:se,onChange:ge=>ke(ge.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:u("maintenance.documentationLink")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ne,{size:"sm",onClick:ce,disabled:!B.trim(),children:u("common.save")}),a.jsx(Ne,{size:"sm",variant:"secondary",onClick:()=>oe(null),children:u("common.cancel")})]})]})},X.id);const z=I(X.id),O=K(X.id),Z=D===X.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(le,{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:X.name}),a.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:u("maintenance.custom")})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[pe==="days"?a.jsx(ti,{className:"w-3 h-3"}):a.jsx(wu,{className:"w-3 h-3"}),ij(X.default_interval_hours,pe,u)]})]}),a.jsxs("button",{onClick:()=>$(Z?null:X.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${z.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:u("maintenance.printersAssignedClick",{count:z.length}),children:[a.jsx(jr,{className:"w-3 h-3"}),a.jsx("span",{className:"text-xs font-medium",children:z.length}),a.jsx(fr,{className:`w-3 h-3 transition-transform ${Z?"rotate-180":""}`})]}),a.jsx("button",{onClick:()=>Fe(X),disabled:!c("maintenance:update"),title:c("maintenance:update")?void 0:u("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${c("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(dm,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{confirm(u("maintenance.deleteTypeConfirm",{name:X.name}))&&s(X.id)},disabled:!c("maintenance:delete"),title:c("maintenance:delete")?void 0:u("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${c("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(ln,{className:"w-4 h-4"})})]}),Z&&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:u("maintenance.assignedToPrinters")}),z.length===0?a.jsx("p",{className:"text-xs text-orange-400",children:u("maintenance.noPrintersAssigned")}):a.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:z.map(ge=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[ge.printerName,a.jsx("button",{onClick:()=>ge.itemId&&l(ge.itemId),disabled:!c("maintenance:delete"),title:c("maintenance:delete")?u("maintenance.removeFromPrinter"):u("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${c("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},ge.printerId))}),O.length>0&&a.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:u("maintenance.addPrinterShort")}),O.map(ge=>a.jsxs("button",{onClick:()=>o(ge.id,X.id),disabled:!c("maintenance:create"),title:c("maintenance:create")?void 0:u("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${c("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",ge.name]},ge.id))]})]})]},X.id)})]})]}),ue.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:u("maintenance.intervalOverrides")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:u("maintenance.intervalOverridesDescription")})]}),a.jsx("div",{className:"space-y-4",children:ue.map(X=>a.jsx(St,{children:a.jsxs(Et,{className:"py-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:X.printerName}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:X.items.map(le=>{const pe=V0(le.maintenance_type_icon),ee=e.find(Ce=>Ce.id===le.maintenance_type_id),z=ee?.default_interval_hours||le.interval_hours,O=ee?.interval_type||"hours",Z=le.interval_type||"hours",ge=d===le.id;return a.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[a.jsx(pe,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:le.maintenance_type_name}),ge?a.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?a.jsx(ti,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):a.jsx(wu,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),a.jsxs("select",{value:b,onChange:Ce=>y(Ce.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:u("maintenance.printHours")}),a.jsx("option",{value:"days",children:u("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:p,onChange:Ce=>m(Ce.target.value),onKeyDown:Ce=>{Ce.key==="Enter"&&Ve(le.id,z,O),Ce.key==="Escape"&&h(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(Ne,{size:"sm",onClick:()=>Ve(le.id,z,O),children:"OK"})]}):a.jsxs("button",{onClick:()=>{c("maintenance:update")&&(h(le.id),m(le.interval_hours.toString()),y(Z))},disabled:!c("maintenance:update"),title:c("maintenance:update")?void 0:u("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 ${c("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[Z==="days"?a.jsx(ti,{className:"w-3 h-3"}):a.jsx(wu,{className:"w-3 h-3"}),ij(le.interval_hours,Z,u),a.jsx(dm,{className:"w-3 h-3 text-bambu-gray"})]})]},le.id)})})]})},X.printerId))})]}),ue.length===0&&a.jsx(St,{children:a.jsxs(Et,{className:"text-center py-12",children:[a.jsx(tr,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-bambu-gray",children:u("common.noPrinters")}),a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:u("maintenance.intervalOverridesDescription")})]})})]})}function SXe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),{hasPermission:r}=Ir(),[i,s]=_.useState("status"),{data:o,isLoading:l}=it({queryKey:["maintenanceOverview"],queryFn:ae.getMaintenanceOverview}),{data:c}=it({queryKey:["maintenanceTypes"],queryFn:ae.getMaintenanceTypes}),u=dt({mutationFn:({id:M,notes:A})=>ae.performMaintenance(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:M=>{n(M.message,"error")}}),d=dt({mutationFn:({id:M,data:A})=>ae.updateMaintenanceItem(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:M=>{n(M.message,"error")}}),h=dt({mutationFn:({id:M,data:A})=>ae.updateMaintenanceType(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:M=>{n(M.message,"error")}}),p=dt({mutationFn:ae.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:M=>{n(M.message,"error")}}),m=dt({mutationFn:({printerId:M,hours:A})=>ae.setPrinterHours(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:M=>{n(M.message,"error")}}),b=dt({mutationFn:({printerId:M,typeId:A})=>ae.assignMaintenanceType(M,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:M=>{n(M.message,"error")}}),y=dt({mutationFn:ae.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:M=>{n(M.message,"error")}}),x=M=>{u.mutate({id:M})},v=(M,A)=>{d.mutate({id:M,data:{enabled:A}})},S=(M,A)=>{m.mutate({printerId:M,hours:A})};if(l)return a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})});const N=o?.reduce((M,A)=>M+A.due_count,0)||0,T=o?.reduce((M,A)=>M+A.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:[N>0&&a.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:N})}),N>0&&T>0&&" · ",T>0&&a.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:T})}),N===0&&T===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((M,A)=>{const k=M.due_count*10+M.warning_count,R=A.due_count*10+A.warning_count;return k!==R?R-k:M.printer_name.localeCompare(A.printer_name)}).map(M=>a.jsx(wXe,{overview:M,onPerform:x,onToggle:v,onSetHours:S,hasPermission:r,t},M.printer_id)):a.jsx(St,{children:a.jsxs(Et,{className:"text-center py-16",children:[a.jsx(mm,{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(_Xe,{overview:o,types:c||[],onUpdateInterval:(M,A)=>d.mutate({id:M,data:A}),onAddType:async(M,A)=>{const k=await ae.createMaintenanceType(M);for(const R of A)await ae.assignMaintenanceType(R,k.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(M,A)=>h.mutate({id:M,data:A}),onDeleteType:M=>p.mutate(M),onAssignType:(M,A)=>b.mutate({printerId:M,typeId:A}),onRemoveItem:M=>y.mutate(M),hasPermission:r,t})]})}const R9=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function cie({project:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=_.useState(t?.name||""),[l,c]=_.useState(t?.description||""),[u,d]=_.useState(t?.color||R9[0]),[h,p]=_.useState(t?.target_count?.toString()||""),[m,b]=_.useState(t?.target_parts_count?.toString()||""),[y,x]=_.useState(t?.status||"active"),[v,S]=_.useState(t?.tags||""),[N,T]=_.useState(t?.due_date?.split("T")[0]||""),[M,A]=_.useState(t?.priority||"normal"),k=R=>{R.preventDefault(),n({name:s.trim(),description:l.trim()||void 0,color:u,target_count:h?parseInt(h,10):void 0,target_parts_count:m?parseInt(m,10):void 0,tags:v.trim()||void 0,due_date:N||void 0,priority:M,...t&&{status:y}})};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:R=>o(R.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:R=>c(R.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:R9.map(R=>a.jsx("button",{type:"button",onClick:()=>d(R),className:`w-8 h-8 rounded-full transition-transform ${u===R?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:R}},R))})]}),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:R=>p(R.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:m,onChange:R=>b(R.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:v,onChange:R=>S(R.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:R=>T(R.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:R=>A(R.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:y,onChange:R=>x(R.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(Ne,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ne,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i(t?"common.save":"projects.create")})]})]})]})})}function NXe({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]=_.useState(!1),m=c?{icon:mk,color:"text-bambu-green",bg:"bg-bambu-green/10"}:u?{icon:vo,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:tr,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:rs,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 ${m.bg} flex-shrink-0`,children:a.jsx(m.icon,{className:`w-5 h-5 ${m.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 b=t.archives.map(S=>S.filament_type).filter(Boolean).flatMap(S=>S.split(",").map(N=>N.trim())).filter(Boolean),y=[...new Set(b)],x=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)),v=[...new Set(x)];return y.length===0&&v.length===0?null:a.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[y.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)),v.length>0&&a.jsxs("div",{className:"flex items-center gap-0.5",children:[v.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)),v.length>5&&a.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",v.length-5]})]})]})})()]})]}),a.jsxs("div",{className:"relative",onClick:b=>b.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(mh,{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(dm,{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(ln,{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(vo,{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(En,{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(tr,{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(b=>a.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:b.print_name||"Unknown",children:[b.thumbnail_path?a.jsx("img",{src:ae.getArchiveThumbnail(b.id),alt:b.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(bc,{className:"w-6 h-6"})}),b.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:a.jsx(En,{className:"w-4 h-4 text-white"})})]},b.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(is,{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(bc,{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(En,{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(Ej,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.queue_count})]})]}),a.jsx(ks,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function kXe(){const{t}=Yt(),e=Ec(),n=an(),{showToast:r}=Tn(),{hasPermission:i}=Ir(),[s,o]=_.useState(!1),[l,c]=_.useState(),[u,d]=_.useState("active"),[h,p]=_.useState(null),{data:m,isLoading:b}=it({queryKey:["projects",u==="all"?void 0:u],queryFn:()=>ae.getProjects(u==="all"?void 0:u)}),y=dt({mutationFn:H=>ae.createProject(H),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:H=>{r(H.message,"error")}}),x=dt({mutationFn:({id:H,data:D})=>ae.updateProject(H,D),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:H=>{r(H.message,"error")}}),v=dt({mutationFn:H=>ae.deleteProject(H),onSuccess:()=>{p(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:H=>{p(null),r(H.message,"error")}}),S=dt({mutationFn:H=>ae.importProject(H),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:H=>{r(H.message,"error")}}),N=_.useRef(null),T=async()=>{try{const H=await ae.getProjects(),D=await Promise.all(H.map(async K=>await ae.exportProjectJson(K.id))),$=new Blob([JSON.stringify(D,null,2)],{type:"application/json"}),G=URL.createObjectURL($),I=document.createElement("a");I.href=G,I.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,I.click(),URL.revokeObjectURL(G),r(t("projects.toast.exported"),"success")}catch(H){r(H.message,"error")}},M=()=>{N.current?.click()},A=async H=>{const D=H.target.files?.[0];if(D){try{if(D.name.toLowerCase().endsWith(".zip"))await ae.importProjectFile(D),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const G=await D.text(),I=JSON.parse(G),K=Array.isArray(I)?I:[I];for(const Q of K)await S.mutateAsync(Q);K.length>1&&r(t("projects.toast.multipleImported",{count:K.length}),"success")}}catch($){r(`${t("projects.toast.importFailed")}: ${$.message}`,"error")}H.target.value=""}},k=H=>{l?x.mutate({id:l.id,data:H}):y.mutate(H)},R=H=>{c(H),o(!0)},C=H=>{e(`/projects/${H.id}`)},P=H=>{p(H)},U=()=>{h!==null&&v.mutate(h)},F=m?.reduce((H,D)=>(H[D.status]=(H[D.status]||0)+1,H.all=(H.all||0)+1,H),{})||{};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:A,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(rs,{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(Ne,{variant:"secondary",onClick:M,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[a.jsx(Na,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),a.jsxs(Ne,{variant:"secondary",onClick:T,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[a.jsx(wi,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),a.jsxs(Ne,{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(cr,{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:tr},{key:"completed",label:t("projects.statusCompleted"),icon:mk},{key:"archived",label:t("projects.statusArchived"),icon:vo},{key:"all",label:t("common.all"),icon:rs}].map(({key:H,label:D,icon:$})=>a.jsxs("button",{onClick:()=>d(H),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===H?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[a.jsx($,{className:"w-4 h-4"}),a.jsx("span",{children:D}),F[H]>0&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===H?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:F[H]})]},H))}),b?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(ct,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):m?.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(rs,{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(Ne,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(cr,{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:m?.map(H=>a.jsx(NXe,{project:H,onClick:()=>C(H),onEdit:()=>R(H),onDelete:()=>P(H.id),hasPermission:i,t},H.id))}),h!==null&&a.jsx(er,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:U,onCancel:()=>p(null)}),s&&a.jsx(cie,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:k,isLoading:y.isPending||x.isPending,t})]})}function MXe(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 EXe(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function TXe({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 O9({icon:t,label:e,value:n,subValue:r,hint:i,color:s="text-bambu-gray"}){return a.jsx(St,{children:a.jsx(Et,{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 AXe({archives:t,t:e}){return t.length===0?a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(bc,{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(Bs,{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:ae.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(bc,{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(Zi,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&a.jsx("div",{className:"absolute top-1 right-1",children:a.jsx(mr,{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 CXe({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(En,{className:"w-3 h-3"}),i]})}function PXe(t){return t?Gg(t,{year:"numeric",month:"short",day:"numeric"}):""}function aj(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 jXe(){const{id:t}=dk(),e=Ec(),{t:n}=Yt(),r=an(),{showToast:i}=Tn(),{hasPermission:s}=Ir(),[o,l]=_.useState(!1),[c,u]=_.useState(!1),[d,h]=_.useState(""),p=parseInt(t||"0",10),{data:m,isLoading:b,error:y}=it({queryKey:["project",p],queryFn:()=>ae.getProject(p),enabled:p>0}),{data:x,isLoading:v}=it({queryKey:["project-archives",p],queryFn:()=>ae.getProjectArchives(p),enabled:p>0}),{data:S,isLoading:N}=it({queryKey:["project-bom",p],queryFn:()=>ae.getProjectBOM(p),enabled:p>0}),{data:T,isLoading:M}=it({queryKey:["project-timeline",p],queryFn:()=>ae.getProjectTimeline(p,20),enabled:p>0}),{data:A}=it({queryKey:["settings"],queryFn:ae.getSettings}),{data:k}=it({queryKey:["project-folders",p],queryFn:()=>ae.getLibraryFoldersByProject(p),enabled:p>0}),R=A?.currency||"$",C=A?.time_format||"system",P=dt({mutationFn:Ae=>ae.updateProject(p,Ae),onSuccess:()=>{r.invalidateQueries({queryKey:["project",p]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:Ae=>{i(Ae.message,"error")}}),U=()=>{h(m?.notes||""),u(!0)},F=()=>{P.mutate({notes:d})},H=()=>{u(!1),h("")},[D,$]=_.useState(""),[G,I]=_.useState(1),[K,Q]=_.useState(""),[oe,B]=_.useState(""),[W,J]=_.useState(""),[ne,me]=_.useState(!1),[fe,de]=_.useState(!1),[Re,se]=_.useState(null),[ke,Fe]=_.useState(""),[ce,Ve]=_.useState(1),[V,Y]=_.useState(""),[ue,q]=_.useState(""),[re,X]=_.useState(""),[le,pe]=_.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),ee=dt({mutationFn:Ae=>ae.createBOMItem(p,Ae),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),$(""),I(1),Q(""),B(""),J(""),me(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:Ae=>i(Ae.message,"error")}),z=dt({mutationFn:({itemId:Ae,data:qe})=>ae.updateBOMItem(p,Ae,qe),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),se(null)},onError:Ae=>i(Ae.message,"error")}),O=dt({mutationFn:Ae=>ae.deleteBOMItem(p,Ae),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:Ae=>i(Ae.message,"error")}),Z=Ae=>{Ae.preventDefault(),D.trim()&&ee.mutate({name:D.trim(),quantity_needed:G,unit_price:K?parseFloat(K):void 0,sourcing_url:oe.trim()||void 0,remarks:W.trim()||void 0})},ge=Ae=>{const qe=Ae.is_complete?0:Ae.quantity_needed;z.mutate({itemId:Ae.id,data:{quantity_acquired:qe}})},Ce=(Ae,qe)=>{pe({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:qe}),onConfirm:()=>{pe(ve=>({...ve,isOpen:!1})),O.mutate(Ae)}})},_e=Ae=>{se(Ae),Fe(Ae.name),Ve(Ae.quantity_needed),Y(Ae.unit_price?.toString()||""),q(Ae.sourcing_url||""),X(Ae.remarks||"")},Te=Ae=>{Ae.preventDefault(),!(!Re||!ke.trim())&&z.mutate({itemId:Re.id,data:{name:ke.trim(),quantity_needed:ce,unit_price:V?parseFloat(V):void 0,sourcing_url:ue.trim()||void 0,remarks:re.trim()||void 0}})},we=()=>{se(null)},$e=async()=>{try{const{blob:Ae,filename:qe}=await ae.exportProjectZip(Number(p)),ve=URL.createObjectURL(Ae),et=document.createElement("a");et.href=ve,et.download=qe||`${m?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,et.click(),URL.revokeObjectURL(ve),i(n("projectDetail.toast.projectExported"),"success")}catch(Ae){i(Ae.message,"error")}},Ge=dt({mutationFn:()=>ae.createTemplateFromProject(p),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:Ae=>i(Ae.message,"error")}),ze=Ae=>qg(Ae,C,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(b)return a.jsx("div",{className:"flex items-center justify-center py-24",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(y||!m)return a.jsxs("div",{className:"text-center py-24",children:[a.jsx("p",{className:"text-bambu-gray",children:y?`${n("common.error")}: ${y.message}`:n("projectDetail.notFound")}),a.jsx(Ne,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const be=m.stats,Me=be?.progress_percent??0,Be=be?.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(Bs,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),a.jsx(ks,{className:"w-4 h-4"}),a.jsx("span",{className:"text-white",children:m.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(jce,{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:m.color||"#6b7280"}}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:m.name}),m.description&&a.jsx("p",{className:"text-bambu-gray mt-1",children:m.description})]})]}),a.jsx(TXe,{status:m.status,t:n})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ne,{variant:"secondary",onClick:$e,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[a.jsx(wi,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),a.jsxs(Ne,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[a.jsx(dm,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(m.target_count||m.target_parts_count)&&a.jsx(St,{children:a.jsxs(Et,{className:"p-4 space-y-4",children:[m.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:[be?.total_archives||0," / ",m.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(Me,100)}%`,backgroundColor:Me>=100?"#22c55e":m.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:Me.toFixed(0)})}),be?.remaining_prints!=null&&be.remaining_prints>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:be.remaining_prints})})]})]}),m.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:[be?.completed_prints||0," / ",m.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(Be,100)}%`,backgroundColor:Be>=100?"#22c55e":m.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:Be.toFixed(0)})}),be?.remaining_parts!=null&&be.remaining_parts>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:be.remaining_parts})})]})]})]})}),be&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(St,{children:a.jsx(Et,{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(bc,{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:[be.total_archives," ",a.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),be.failed_prints>0&&a.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:be.failed_prints})}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:be.completed_prints})})]})]})})}),a.jsx(O9,{icon:tr,label:n("projectDetail.stats.printTime"),value:MXe(be.total_print_time_hours),color:"text-yellow-400"}),a.jsx(O9,{icon:jr,label:n("projectDetail.stats.filamentUsed"),value:EXe(be.total_filament_grams),color:"text-purple-400"})]}),be&&(be.estimated_cost>0||m.budget)&&a.jsx(St,{children:a.jsxs(Et,{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:[R,be.estimated_cost.toFixed(2)]})]}),be.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:[be.total_energy_kwh.toFixed(2)," kWh",be.total_energy_cost>0&&a.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",R,be.total_energy_cost.toFixed(2),")"]})]})]}),m.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:[R,m.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 ${m.budget-be.estimated_cost>=0?"text-bambu-green":"text-red-400"}`,children:[R,(m.budget-be.estimated_cost).toFixed(2)]})]})]})]})]})}),m.children&&m.children.length>0&&a.jsx(St,{children:a.jsxs(Et,{className:"p-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[a.jsx(ode,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:m.children.length})]}),a.jsx("div",{className:"space-y-2",children:m.children.map(Ae=>a.jsxs(Bs,{to:`/projects/${Ae.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:Ae.color||"#6b7280"}}),a.jsx("span",{className:"text-white",children:Ae.name}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${Ae.status==="completed"?"bg-status-ok/20 text-status-ok":Ae.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:Ae.status})]}),Ae.progress_percent!==null&&a.jsxs("span",{className:"text-sm text-bambu-gray",children:[Ae.progress_percent.toFixed(0),"%"]})]},Ae.id))})]})}),m.parent_id&&m.parent_name&&a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(is,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),a.jsx(Bs,{to:`/projects/${m.parent_id}`,className:"text-bambu-green hover:underline",children:m.parent_name})]}),(m.tags||m.due_date||m.priority!=="normal")&&a.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[m.priority&&m.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(CXe,{priority:m.priority,t:n})]}),m.due_date&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ti,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:PXe(m.due_date)}),aj(m.due_date,n)&&a.jsxs("span",{className:`text-xs ${aj(m.due_date,n).color}`,children:["(",aj(m.due_date,n).label,")"]})]}),m.tags&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Th,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:m.tags.split(",").map((Ae,qe)=>a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:Ae.trim()},qe))})]})]}),a.jsx(St,{children:a.jsxs(Et,{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(ys,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:H,disabled:P.isPending,children:[a.jsx(Lt,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),a.jsxs(Ne,{size:"sm",onClick:F,disabled:P.isPending,children:[P.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-1"}):a.jsx(vs,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:U,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[a.jsx(dm,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?a.jsx(bR,{content:d,onChange:h,placeholder:n("projectDetail.notes.placeholder")}):m.notes?a.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:m.notes}}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),a.jsx(St,{children:a.jsxs(Et,{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(Ul,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),a.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[a.jsx(Bs,{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(Ae=>a.jsxs(Bs,{to:`/files?folder=${Ae.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(Ul,{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:Ae.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:Ae.file_count})})]})]}),a.jsx(ks,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},Ae.id))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),a.jsx(St,{children:a.jsxs(Et,{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(BW,{className:"w-5 h-5"}),n("projectDetail.bom.title"),be&&be.bom_total_items>0&&a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:be.bom_completed_items,total:be.bom_total_items}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[S&&S.some(Ae=>Ae.is_complete)&&a.jsx("button",{onClick:()=>de(!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")}),!ne&&a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>me(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[a.jsx(cr,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),ne&&a.jsxs("form",{onSubmit:Z,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:D,onChange:Ae=>$(Ae.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:G,onChange:Ae=>I(parseInt(Ae.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:Ae=>Q(Ae.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:R})})]})]}),a.jsx("input",{type:"url",value:oe,onChange:Ae=>B(Ae.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:W,onChange:Ae=>J(Ae.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(Ne,{type:"button",variant:"secondary",size:"sm",onClick:()=>me(!1),children:n("common.cancel")}),a.jsx(Ne,{type:"submit",size:"sm",disabled:!D.trim()||ee.isPending,children:ee.isPending?a.jsx(ct,{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(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):S&&S.length>0?a.jsxs("div",{className:"space-y-2",children:[S.filter(Ae=>!fe||!Ae.is_complete).map(Ae=>a.jsx("div",{className:`p-3 rounded-lg transition-colors ${Ae.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:Re?.id===Ae.id?a.jsxs("form",{onSubmit:Te,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:ke,onChange:qe=>Fe(qe.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:ce,onChange:qe=>Ve(parseInt(qe.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:V,onChange:qe=>Y(qe.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:R})})]})]}),a.jsx("input",{type:"url",value:ue,onChange:qe=>q(qe.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:re,onChange:qe=>X(qe.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(Ne,{type:"button",variant:"secondary",size:"sm",onClick:we,children:n("common.cancel")}),a.jsx(Ne,{type:"submit",size:"sm",disabled:!ke.trim()||z.isPending,children:z.isPending?a.jsx(ct,{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")&&ge(Ae),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 ${Ae.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:Ae.is_complete&&a.jsx(mr,{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 ${Ae.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[Ae.name,a.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",Ae.quantity_needed]})]}),Ae.unit_price!==null&&a.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[R,(Ae.unit_price*Ae.quantity_needed).toFixed(2)]})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>s("projects:update")&&_e(Ae),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(Ji,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("projects:update")&&Ce(Ae.id,Ae.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(ln,{className:"w-4 h-4"})})]})]}),Ae.sourcing_url&&a.jsxs("a",{href:Ae.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:qe=>qe.stopPropagation(),children:[a.jsx(Xr,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"truncate",children:(()=>{try{return new URL(Ae.sourcing_url).hostname.replace("www.","")}catch{return Ae.sourcing_url}})()})]}),Ae.remarks&&a.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:Ae.remarks})]})]})},Ae.id)),S.some(Ae=>Ae.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:[R,S.reduce((Ae,qe)=>Ae+(qe.unit_price||0)*qe.quantity_needed,0).toFixed(2)]})]})]}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),a.jsx(St,{children:a.jsxs(Et,{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(Y0,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),M?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):T&&T.length>0?a.jsx("div",{className:"space-y-3",children:T.slice(0,10).map((Ae,qe)=>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 ${Ae.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":Ae.event_type==="print_failed"?"bg-status-error/20 text-status-error":Ae.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Ae.event_type==="print_completed"&&a.jsx(mr,{className:"w-4 h-4"}),Ae.event_type==="print_failed"&&a.jsx(Zi,{className:"w-4 h-4"}),Ae.event_type==="print_started"&&a.jsx(jr,{className:"w-4 h-4"}),Ae.event_type==="queued"&&a.jsx(Ej,{className:"w-4 h-4"}),Ae.event_type==="project_created"&&a.jsx(cr,{className:"w-4 h-4"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white",children:Ae.title}),Ae.description&&a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Ae.description}),a.jsx("p",{className:"text-xs text-bambu-gray/70",children:ze(Ae.timestamp)})]})]},qe))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!m.is_template&&a.jsx("div",{className:"flex justify-end",children:a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>Ge.mutate(),disabled:Ge.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[Ge.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(zl,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),be&&(be.queued_prints>0||be.in_progress_prints>0)&&a.jsx(St,{children:a.jsxs(Et,{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(Ej,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),a.jsx(Bs,{to:`/queue?project=${p}`,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:[be.in_progress_prints>0&&a.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:be.in_progress_prints})}),be.queued_prints>0&&a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:be.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(bc,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:x?.length||0})]})}),v?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):a.jsx(AXe,{archives:x||[],t:n})]}),o&&a.jsx(cie,{t:n,project:{...m,archive_count:be?.total_archives||0,total_items:be?.total_items||0,completed_count:be?.completed_prints||0,failed_count:be?.failed_prints||0,queue_count:be?.queued_prints||0,progress_percent:be?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:Ae=>P.mutate(Ae),isLoading:P.isPending}),le.isOpen&&a.jsx(er,{title:le.title,message:le.message,confirmText:n("common.delete"),variant:"danger",onConfirm:le.onConfirm,onCancel:()=>pe(Ae=>({...Ae,isOpen:!1}))})]})}function gg(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 DXe(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 RXe({parentId:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=_.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(Ne,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ne,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function OXe({type:t,currentName:e,onClose:n,onSave:r,isLoading:i,t:s}){const[o,l]=_.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(Ne,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),a.jsx(Ne,{type:"submit",disabled:!o.trim()||o.trim()===e||i,children:i?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function LXe({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:i,isLoading:s,t:o}){const[l,c]=_.useState(null),u=(h,p=0)=>{const m=[];for(const b of h)m.push({id:b.id,name:b.name,depth:p}),b.children.length>0&&m.push(...u(b.children,p+1));return m},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(Ul,{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(Ne,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),a.jsx(Ne,{onClick:()=>i(l),disabled:s,children:s?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function FXe({folder:t,onClose:e,onLink:n,isLoading:r,t:i}){const[s,o]=_.useState("project"),[l,c]=_.useState(t.project_id||t.archive_id||null);_.useState(()=>{t.archive_id&&o("archive")});const{data:u}=it({queryKey:["projects"],queryFn:()=>ae.getProjects()}),{data:d}=it({queryKey:["archives-for-link"],queryFn:()=>ae.getArchives(void 0,void 0,100)}),h=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},m=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(dc,{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(Lt,{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(jW,{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(vo,{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(b=>a.jsxs("button",{onClick:()=>c(b.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===b.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:b.color||"#00ae42"}}),a.jsx("span",{className:"truncate",children:b.name})]},b.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):d&&d.length>0?d.map(b=>a.jsxs("button",{onClick:()=>c(b.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===b.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx(Kf,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"truncate",children:b.print_name||b.filename})]},b.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:[m&&a.jsxs(Ne,{variant:"danger",onClick:p,disabled:r,children:[a.jsx(WR,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),a.jsxs("div",{className:`flex gap-2 ${m?"":"ml-auto"}`,children:[a.jsx(Ne,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ne,{onClick:h,disabled:!l||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function IXe({folderId:t,onClose:e,onUploadComplete:n,t:r}){const[i,s]=_.useState([]),[o,l]=_.useState(!1),[c,u]=_.useState(!1),[d,h]=_.useState(!0),[p,m]=_.useState(!1),[b,y]=_.useState(!0),x=_.useRef(null),v=$=>{$.preventDefault(),l(!0)},S=$=>{$.preventDefault(),l(!1)},N=$=>{$.preventDefault(),l(!1);const G=Array.from($.dataTransfer.files);M(G)},T=$=>{$.target.files&&M(Array.from($.target.files))},M=$=>{const G=$.map(I=>({file:I,status:"pending",isZip:I.name.toLowerCase().endsWith(".zip"),is3mf:I.name.toLowerCase().endsWith(".3mf")}));s(I=>[...I,...G])},A=$=>{s(G=>G.filter((I,K)=>K!==$))},k=i.some($=>$.isZip&&$.status==="pending"),R=i.some($=>$.file.name.toLowerCase().endsWith(".stl")&&$.status==="pending"),C=i.some($=>$.is3mf&&$.status==="pending"),P=async()=>{if(i.length!==0){u(!0);for(let $=0;$G.map((I,K)=>K===$?{...I,status:"uploading"}:I));try{if(i[$].isZip){const G=await ae.extractZipFile(i[$].file,t,d,p,b);s(I=>I.map((K,Q)=>Q===$?{...K,status:G.errors.length>0&&G.extracted===0?"error":"success",extractedCount:G.extracted,error:G.errors.length>0?`${G.errors.length} files failed`:void 0}:K))}else await ae.uploadLibraryFile(i[$].file,t,b),s(G=>G.map((I,K)=>K===$?{...I,status:"success"}:I))}catch(G){s(I=>I.map((K,Q)=>Q===$?{...K,status:"error",error:G instanceof Error?G.message:"Upload failed"}:K))}}u(!1),n(),e()}},U=i.filter($=>$.status==="pending").length,F=i.filter($=>$.status==="success").length,H=i.filter($=>$.status==="error").length,D=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(Lt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("div",{onDragOver:v,onDragLeave:S,onDrop:N,onClick:()=>x.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(Na,{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:x,type:"file",multiple:!0,className:"hidden",onChange:T}),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(vo,{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:$=>h($.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:p,onChange:$=>m($.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")})]})]})]})}),C&&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(jr,{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")})]})]})}),(R||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(Uu,{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&&!R?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:b,onChange:$=>y($.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(($,G)=>a.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[$.isZip?a.jsx(vo,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):a.jsx(xk,{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:$.file.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[($.file.size/1024/1024).toFixed(2)," MB",$.isZip&&$.status==="pending"&&a.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",r("fileManager.willBeExtracted")]}),$.extractedCount!==void 0&&a.jsxs("span",{className:"text-green-400 ml-2",children:["• ",r("fileManager.filesExtracted",{count:$.extractedCount})]})]})]}),$.status==="pending"&&a.jsx("button",{onClick:()=>A(G),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Lt,{className:"w-4 h-4 text-bambu-gray"})}),$.status==="uploading"&&a.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"}),$.status==="success"&&a.jsx(mr,{className:"w-4 h-4 text-green-500"}),$.status==="error"&&a.jsx("span",{title:$.error,children:a.jsx(Zi,{className:"w-4 h-4 text-red-500"})})]},G))}),D&&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:F}),H>0&&a.jsxs("span",{className:"text-red-400",children:[", ",r("fileManager.uploadFailed",{count:H})]})]})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[a.jsx(Ne,{variant:"secondary",onClick:e,children:r(D?"common.close":"common.cancel")}),!D&&a.jsx(Ne,{onClick:P,disabled:U===0||c,children:c?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}),r("fileManager.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Na,{className:"w-4 h-4 mr-2"}),r("common.upload")," ",U>0?`(${U})`:""]})})]})]})})}function uie({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]=_.useState(!0),[p,m]=_.useState(!1),b=t.children.length>0,y=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:[b?a.jsx("button",{onClick:x=>{x.stopPropagation(),h(!d)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(ks,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-90":""}`})}):a.jsx("div",{className:"w-4.5"}),a.jsx(Ul,{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}),y&&a.jsxs("button",{onClick:x=>{x.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(dc,{className:"w-3 h-3"}),t.project_name?a.jsx(jW,{className:"w-3 h-3"}):a.jsx(vo,{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}),!y&&a.jsx("button",{onClick:x=>{x.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:a.jsx(dc,{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:x=>x.stopPropagation(),children:a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:()=>m(!p),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:a.jsx(mh,{className:"w-3.5 h-3.5 text-bambu-gray"})}),p&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!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),m(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[a.jsx(Ji,{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),m(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[a.jsx(dc,{className:"w-3.5 h-3.5"}),u(y?"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),m(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[a.jsx(ln,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),b&&d&&a.jsx("div",{children:t.children.map(x=>a.jsx(uie,{folder:x,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},x.id))})]})}function kR(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function zXe({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:p,canModify:m,authEnabled:b,t:y}){const[x,v]=_.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:`${ae.getLibraryFileThumbnailUrl(t.id)}${h?`?v=${h}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):a.jsx(Kf,{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:gg(t.file_size)}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(tr,{className:"w-3 h-3"}),DXe(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(jr,{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:y("fileManager.printedCount",{count:t.print_count})}),b&&t.created_by_username&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx($u,{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:()=>v(!x),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:a.jsx(mh,{className:"w-4 h-4 text-bambu-gray"})}),x&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>v(!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&&kR(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("printers:control")&&(l(t),v(!1))},disabled:!p("printers:control"),title:p("printers:control")?void 0:y("fileManager.noPermissionPrint"),children:[a.jsx(jr,{className:"w-3.5 h-3.5"}),y("common.print")]}),o&&kR(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("queue:create")&&(o(t.id),v(!1))},disabled:!p("queue:create"),title:p("queue:create")?void 0:y("fileManager.noPermissionAddToQueue"),children:[a.jsx(tr,{className:"w-3.5 h-3.5"}),y("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 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(c(t),v(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:"You do not have permission to preview files",children:[a.jsx(Ii,{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 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(s(t.id),v(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:y("fileManager.noPermissionDownload"),children:[a.jsx(wi,{className:"w-3.5 h-3.5"}),y("common.download")]}),u&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${m("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{m("library","update",t.created_by_id)&&(u(t),v(!1))},disabled:!m("library","update",t.created_by_id),title:m("library","update",t.created_by_id)?void 0:y("fileManager.noPermissionRenameFile"),children:[a.jsx(Ji,{className:"w-3.5 h-3.5"}),y("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 ${m("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{m("library","update",t.created_by_id)&&(d(t),v(!1))},disabled:!m("library","update",t.created_by_id),title:m("library","update",t.created_by_id)?void 0:y("fileManager.noPermissionGenerateThumbnail"),children:[a.jsx(Uu,{className:"w-3.5 h-3.5"}),y("fileManager.generateThumbnail")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${m("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{m("library","delete",t.created_by_id)&&(i(t.id),v(!1))},disabled:!m("library","delete",t.created_by_id),title:m("library","delete",t.created_by_id)?void 0:y("fileManager.noPermissionDeleteFile"),children:[a.jsx(ln,{className:"w-3.5 h-3.5"}),y("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 UXe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),{hasPermission:r,hasAnyPermission:i,canModify:s,authEnabled:o}=Ir(),[l]=RR(),c=l.get("folder"),u=c?parseInt(c,10):null,[d,h]=_.useState(u),[p,m]=_.useState([]),[b,y]=_.useState(!1),[x,v]=_.useState(!1),[S,N]=_.useState(!1),[T,M]=_.useState(null),[A,k]=_.useState(null),[R,C]=_.useState(null),[P,U]=_.useState(null),[F,H]=_.useState(null),[D,$]=_.useState(null),[G,I]=_.useState({}),[K,Q]=_.useState(null),[oe,B]=_.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[W,J]=_.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[ne,me]=_.useState(()=>{const Ie=localStorage.getItem("library-sidebar-width");return Ie?parseInt(Ie,10):256}),[fe,de]=_.useState(!1),Re=_.useRef(null);_.useEffect(()=>{if(!fe)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ie=Gt=>{if(!Re.current)return;const dn=Re.current.parentElement?.getBoundingClientRect();if(!dn)return;const fn=Gt.clientX-dn.left,vn=Math.min(500,Math.max(200,fn));me(vn)},vt=()=>{de(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(ne))};return document.addEventListener("mousemove",Ie),document.addEventListener("mouseup",vt),()=>{document.removeEventListener("mousemove",Ie),document.removeEventListener("mouseup",vt),document.body.style.userSelect="",document.body.style.cursor=""}},[fe,ne]);const[se,ke]=_.useState(""),[Fe,ce]=_.useState("all"),[Ve,V]=_.useState(""),[Y,ue]=_.useState(()=>localStorage.getItem("library-sort-field")||"name"),[q,re]=_.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),X=QR();_.useEffect(()=>{const Ie=l.get("folder");if(Ie){const vt=parseInt(Ie,10);h(vt)}},[l]);const{data:le}=it({queryKey:["settings"],queryFn:()=>ae.getSettings()}),{data:pe,isLoading:ee}=it({queryKey:["library-folders"],queryFn:()=>ae.getLibraryFolders()}),{data:z,isLoading:O}=it({queryKey:["library-files",d],queryFn:()=>ae.getLibraryFiles(d,d===null)}),{data:Z}=it({queryKey:["library-stats"],queryFn:()=>ae.getLibraryStats()}),{data:ge}=it({queryKey:["users"],queryFn:()=>ae.getUsers()}),Ce=_.useMemo(()=>{if(!z)return[];const Ie=new Set(z.map(vt=>vt.file_type));return Array.from(Ie).sort()},[z]),_e=_.useMemo(()=>{if(!z)return[];let Ie=[...z];if(se.trim()){const vt=se.toLowerCase();Ie=Ie.filter(Gt=>Gt.filename.toLowerCase().includes(vt)||Gt.print_name&&Gt.print_name.toLowerCase().includes(vt))}if(Fe!=="all"&&(Ie=Ie.filter(vt=>vt.file_type===Fe)),Ve.trim()){const vt=Ve.toLowerCase();Ie=Ie.filter(Gt=>Gt.created_by_username&&Gt.created_by_username.toLowerCase().includes(vt))}return Ie.sort((vt,Gt)=>{let dn=0;switch(Y){case"name":dn=(vt.print_name||vt.filename).localeCompare(Gt.print_name||Gt.filename);break;case"date":dn=new Date(vt.created_at).getTime()-new Date(Gt.created_at).getTime();break;case"size":dn=vt.file_size-Gt.file_size;break;case"type":dn=vt.file_type.localeCompare(Gt.file_type);break;case"prints":dn=vt.print_count-Gt.print_count;break}return q==="asc"?dn:-dn}),Ie},[z,se,Fe,Ve,Y,q]),Te=_.useMemo(()=>{if(!Z||!le)return!1;const Ie=(le.library_disk_warning_gb||5)*1024*1024*1024;return Z.disk_free_bytesae.createLibraryFolder(Ie),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),y(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Ie=>n(Ie.message,"error")}),$e=dt({mutationFn:Ie=>ae.deleteLibraryFolder(Ie),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===A?.id&&h(null),k(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Ie=>{k(null),n(Ie.message,"error")}}),Ge=dt({mutationFn:Ie=>ae.deleteLibraryFile(Ie),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),m(Ie=>Ie.filter(vt=>vt!==A?.id)),k(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Ie=>{k(null),n(Ie.message,"error")}}),ze=dt({mutationFn:Ie=>ae.bulkDeleteLibrary(Ie,[]),onSuccess:(Ie,vt)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:vt.length}),"success"),m([]),k(null)},onError:Ie=>{k(null),n(Ie.message,"error")}}),be=dt({mutationFn:({fileIds:Ie,folderId:vt})=>ae.moveLibraryFiles(Ie,vt),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),m([]),v(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Ie=>n(Ie.message,"error")}),Me=dt({mutationFn:({id:Ie,data:vt})=>ae.updateLibraryFolder(Ie,vt),onSuccess:(Ie,vt)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),M(null);const Gt=vt.data.project_id===0&&vt.data.archive_id===0;n(t(Gt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ie=>n(Ie.message,"error")}),Be=dt({mutationFn:({id:Ie,filename:vt})=>ae.updateLibraryFile(Ie,{filename:vt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),$(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Ie=>{$(null),n(Ie.message,"error")}}),Ae=dt({mutationFn:({id:Ie,name:vt})=>ae.updateLibraryFolder(Ie,{name:vt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),$(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Ie=>{$(null),n(Ie.message,"error")}}),qe=dt({mutationFn:()=>ae.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ie=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ie.succeeded>0){const vt=Date.now(),Gt={};Ie.results.forEach(dn=>{dn.success&&(Gt[dn.file_id]=vt)}),I(dn=>({...dn,...Gt}))}Ie.succeeded>0&&Ie.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Ie.succeeded}),"success"):Ie.succeeded>0&&Ie.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ie.succeeded,failed:Ie.failed}),"success"):Ie.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Ie.results[0]?.error||"Unknown error"}),"error")},onError:Ie=>n(Ie.message,"error")}),ve=dt({mutationFn:Ie=>ae.batchGenerateStlThumbnails({file_ids:[Ie]}),onSuccess:Ie=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ie.succeeded>0){const vt=Ie.results[0]?.file_id;vt&&I(Gt=>({...Gt,[vt]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Ie.results[0]?.error||"Unknown error"}),"error")},onError:Ie=>n(Ie.message,"error")}),et=_.useCallback(Ie=>{const vt=Ie.toLowerCase();return vt.endsWith(".gcode")||vt.includes(".gcode.")},[]),Ee=_.useMemo(()=>z?z.filter(Ie=>p.includes(Ie.id)&&et(Ie.filename)):[],[z,p,et]),Ye=_.useCallback(Ie=>{m(vt=>vt.includes(Ie)?vt.filter(Gt=>Gt!==Ie):[...vt,Ie])},[]),je=_.useCallback(()=>{_e.length>0&&m(_e.map(Ie=>Ie.id))},[_e]),Pe=_.useCallback(()=>{m([])},[]),ye=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},Qe=Ie=>{ae.downloadLibraryFile(Ie).catch(vt=>{console.error("Library file download failed:",vt)})},yt=()=>{A&&(A.type==="file"?Ge.mutate(A.id):A.type==="folder"?$e.mutate(A.id):A.type==="bulk"&&ze.mutate(p))},at=$e.isPending||Ge.isPending||ze.isPending,Ut=Ie=>{B(Ie),localStorage.setItem("library-view-mode",Ie)},zt=ee||O;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(Ul,{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:()=>Ut("grid"),className:`p-1.5 rounded transition-colors ${oe==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:a.jsx(wk,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>Ut("list"),className:`p-1.5 rounded transition-colors ${oe==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:a.jsx(_k,{className:"w-4 h-4"})})]}),a.jsxs(Ne,{variant:"secondary",onClick:()=>qe.mutate(),disabled:qe.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[qe.isPending?a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(Uu,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),a.jsxs(Ne,{variant:"secondary",onClick:()=>y(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[a.jsx(ade,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a.jsxs(Ne,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(Na,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Te&&Z&&le&&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(En,{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:gg(Z.disk_free_bytes),total:gg(Z.disk_total_bytes),threshold:le.library_disk_warning_gb})})]})]}),Z&&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(xk,{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:Z.total_files})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Ul,{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:Z.total_folders})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Sb,{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:gg(Z.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 ${Te?"text-amber-500":"text-white"}`,children:gg(Z.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:Ie=>h(Ie.target.value?parseInt(Ie.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")]}),pe&&(()=>{const Ie=(vt,Gt=0)=>{const dn=[];for(const fn of vt)dn.push({id:fn.id,name:fn.name,fileCount:fn.file_count,depth:Gt}),fn.children.length>0&&dn.push(...Ie(fn.children,Gt+1));return dn};return Ie(pe).map(vt=>a.jsxs("option",{value:vt.id,children:["│ ".repeat(vt.depth),"📂 ",vt.name," ",vt.fileCount>0?`(${vt.fileCount})`:""]},vt.id))})()]})}),a.jsxs("div",{ref:Re,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:`${ne}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:Ie=>{Ie.preventDefault(),de(!0)},onDoubleClick:()=>{me(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 Ie=!W;J(Ie),localStorage.setItem("library-wrap-folders",String(Ie))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${W?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(W?"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(Kf,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),pe?.map(Ie=>a.jsx(uie,{folder:Ie,selectedFolderId:d,onSelect:h,onDelete:vt=>k({type:"folder",id:vt}),onLink:M,onRename:vt=>$({type:"folder",id:vt.id,name:vt.name}),wrapNames:W,hasPermission:r,t},Ie.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(Qi,{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:se,onChange:Ie=>ke(Ie.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(yk,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),a.jsxs("select",{value:Fe,onChange:Ie=>ce(Ie.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")}),Ce.map(Ie=>a.jsx("option",{value:Ie,children:Ie.toUpperCase()},Ie))]})]}),o&&a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:Ve,onChange:Ie=>V(Ie.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 ${Ve?"pr-7":""}`,style:Ve?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),Ve&&a.jsx("button",{onClick:()=>V(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:a.jsx(Lt,{className:"w-3 h-3"})}),a.jsx("datalist",{id:"usernames-list",children:ge?.map(Ie=>a.jsx("option",{value:Ie.username},Ie.id))})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{value:Y,onChange:Ie=>{const vt=Ie.target.value;ue(vt),localStorage.setItem("library-sort-field",vt)},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:()=>re(Ie=>{const vt=Ie==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",vt),vt}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(q==="asc"?"fileManager.ascending":"fileManager.descending"),children:q==="asc"?a.jsx(Fce,{className:"w-4 h-4 text-white"}):a.jsx(Ace,{className:"w-4 h-4 text-white"})})]}),(se||Fe!=="all"||Ve)&&a.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:_e.length,total:z.length})})]}),_e.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:[p.length===_e.length&&p.length>0?a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:Pe,children:[a.jsx(ul,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:je,children:[a.jsx(Xs,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),p.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:p.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:[Ee.length===1&&a.jsxs(Ne,{variant:"primary",size:"sm",onClick:()=>U(Ee[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[a.jsx(Eo,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Ee.length===1&&a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>H(Ee[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[a.jsx(tr,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:()=>v(!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(hhe,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),a.jsxs(Ne,{variant:"danger",size:"sm",onClick:()=>{p.length===1?k({type:"file",id:p[0]}):k({type:"bulk",id:0,count:p.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(ln,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),a.jsxs(Ne,{variant:"secondary",size:"sm",onClick:Pe,children:[a.jsx(Lt,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),zt?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(ct,{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(Kf,{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(Ne,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(cr,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):_e.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(Qi,{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(Ne,{variant:"secondary",onClick:()=>{ke(""),ce("all")},children:t("fileManager.clearFilters")})]}):oe==="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:_e.map(Ie=>a.jsx(zXe,{file:Ie,isSelected:p.includes(Ie.id),isMobile:X,t,onSelect:Ye,onDelete:vt=>k({type:"file",id:vt}),onDownload:Qe,onAddToQueue:vt=>{const Gt=z?.find(dn=>dn.id===vt);Gt&&H(Gt)},onPrint:C,onPreview3d:Q,onRename:vt=>$({type:"file",id:vt.id,name:vt.filename}),onGenerateThumbnail:vt=>ve.mutate(vt.id),thumbnailVersion:G[Ie.id],hasPermission:r,canModify:s,authEnabled:o},Ie.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",{})]}),_e.map(Ie=>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 ${p.includes(Ie.id)?"bg-bambu-green/10":""}`,onClick:()=>Ye(Ie.id),children:[a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${p.includes(Ie.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:p.includes(Ie.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:Ie.thumbnail_path?a.jsx("img",{src:`${ae.getLibraryFileThumbnailUrl(Ie.id)}${G[Ie.id]?`?v=${G[Ie.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(Kf,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ie.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:`${ae.getLibraryFileThumbnailUrl(Ie.id)}${G[Ie.id]?`?v=${G[Ie.id]}`:""}`,alt:Ie.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:Ie.print_name||Ie.filename})})]}),o&&a.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ie.created_by_username?a.jsxs(a.Fragment,{children:[a.jsx($u,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate",children:Ie.created_by_username})]}):"-"}),a.jsx("div",{children:a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ie.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ie.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ie.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ie.file_type.toUpperCase()})}),a.jsx("div",{className:"text-sm text-bambu-gray",children:gg(Ie.file_size)}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Ie.print_count>0?`${Ie.print_count}x`:"-"}),a.jsxs("div",{className:"flex items-center gap-1",onClick:vt=>vt.stopPropagation(),children:[kR(Ie.filename)&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>r("printers:control")&&C(Ie),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(jr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{r("queue:create")&&H(Ie)},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(tr,{className:"w-4 h-4"})})]}),(Ie.file_type==="3mf"||Ie.file_type==="gcode"||Ie.file_type==="stl")&&a.jsx("button",{onClick:()=>r("library:read")&&Q(Ie),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(Ii,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>r("library:read")&&Qe(Ie.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(wi,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","update",Ie.created_by_id)&&$({type:"file",id:Ie.id,name:Ie.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ie.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ie.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ie.created_by_id),children:a.jsx(Ji,{className:"w-4 h-4"})}),Ie.file_type==="stl"&&a.jsx("button",{onClick:()=>s("library","update",Ie.created_by_id)&&ve.mutate(Ie.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ie.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",Ie.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:ve.isPending||!s("library","update",Ie.created_by_id),children:a.jsx(Uu,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","delete",Ie.created_by_id)&&k({type:"file",id:Ie.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ie.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",Ie.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ie.created_by_id),children:a.jsx(ln,{className:"w-4 h-4"})})]})]},Ie.id))]})})]})]}),b&&a.jsx(RXe,{parentId:d,onClose:()=>y(!1),onSave:Ie=>we.mutate(Ie),isLoading:we.isPending,t}),x&&pe&&a.jsx(LXe,{folders:pe,selectedFiles:p,currentFolderId:d,onClose:()=>v(!1),onMove:Ie=>be.mutate({fileIds:p,folderId:Ie}),isLoading:be.isPending,t}),S&&a.jsx(IXe,{folderId:d,onClose:()=>N(!1),onUploadComplete:ye,t}),T&&a.jsx(FXe,{folder:T,onClose:()=>M(null),onLink:Ie=>Me.mutate({id:T.id,data:Ie}),isLoading:Me.isPending,t}),A&&a.jsx(er,{title:A.type==="folder"?t("fileManager.deleteFolder"):A.type==="bulk"?t("fileManager.deleteFilesCount",{count:A.count}):t("fileManager.deleteFile"),message:A.type==="folder"?t("fileManager.deleteFolderConfirm"):A.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:A.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:at,loadingText:t("fileManager.deleting"),onConfirm:yt,onCancel:()=>k(null)}),R&&a.jsx(Ou,{mode:"reprint",libraryFileId:R.id,archiveName:R.print_name||R.filename,onClose:()=>C(null),onSuccess:()=>{C(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),P&&a.jsx(Ou,{mode:"reprint",libraryFileId:P.id,archiveName:P.print_name||P.filename,onClose:()=>U(null),onSuccess:()=>{U(null),m([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),F&&a.jsx(Ou,{mode:"add-to-queue",libraryFileId:F.id,archiveName:F.print_name||F.filename,onClose:()=>H(null),onSuccess:()=>{H(null),m([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),K&&a.jsx(C4,{libraryFileId:K.id,title:K.print_name||K.filename,fileType:K.file_type,onClose:()=>Q(null)}),D&&a.jsx(OXe,{type:D.type,currentName:D.name,onClose:()=>$(null),onSave:Ie=>{D.type==="file"?Be.mutate({id:D.id,filename:Ie}):Ae.mutate({id:D.id,name:Ie})},isLoading:Be.isPending||Ae.isPending,t})]})}const sj=5,BXe=2e3,HXe=3e4,$Xe=5e3;function VXe(){const{t}=Yt(),e=an(),{showToast:n}=Tn(),{hasPermission:r}=Ir(),{printerId:i}=dk(),s=parseInt(i||"0",10),[o,l]=_.useState("stream"),[c,u]=_.useState(!1),[d,h]=_.useState(!1),[p,m]=_.useState(!0),[b,y]=_.useState(Date.now()),[x,v]=_.useState(!1),[S,N]=_.useState(!1),[T,M]=_.useState(0),[A,k]=_.useState(!1),[R,C]=_.useState(0),[P,U]=_.useState(1),[F,H]=_.useState({x:0,y:0}),[D,$]=_.useState(!1),[G,I]=_.useState({x:0,y:0}),[K,Q]=_.useState(null),[oe,B]=_.useState(null),W=_.useRef(null),J=_.useRef(null),ne=_.useRef(null),me=_.useRef(null),fe=_.useRef(null),{data:de}=it({queryKey:["printer",s],queryFn:()=>ae.getPrinter(s),enabled:s>0}),{data:Re}=it({queryKey:["printerStatus",s],queryFn:()=>ae.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),se=dt({mutationFn:be=>ae.setChamberLight(s,be),onMutate:async be=>{await e.cancelQueries({queryKey:["printerStatus",s]});const Me=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],Be=>({...Be,chamber_light:be})),{previousStatus:Me}},onSuccess:(be,Me)=>{n(`Chamber light ${Me?"on":"off"}`)},onError:(be,Me,Be)=>{Be?.previousStatus&&e.setQueryData(["printerStatus",s],Be.previousStatus),n(be.message||t("printers.toast.failedToControlChamberLight"),"error")}}),ke=(Re?.state==="RUNNING"||Re?.state==="PAUSE"||Re?.state==="PAUSED")&&(Re?.printable_objects_count??0)>=2;_.useEffect(()=>(de&&(document.title=`${de.name} - Camera`),()=>{document.title="Bambuddy"}),[de]);const Fe=_.useRef(!1);_.useEffect(()=>{const be=`/api/v1/printers/${s}/camera/stop`;Fe.current=!1;const Me=()=>{if(s>0&&!Fe.current){Fe.current=!0;const qe={},ve=Ch();ve&&(qe.Authorization=`Bearer ${ve}`),fetch(be,{method:"POST",keepalive:!0,headers:qe}).catch(()=>{})}},Be=()=>{Me()};window.addEventListener("beforeunload",Be);const Ae=W.current;return()=>{window.removeEventListener("beforeunload",Be),Ae&&(Ae.src=""),Me()}},[s]),_.useEffect(()=>{if(p&&!x){const Me=setTimeout(()=>{m(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(Me)}},[o,p,b,x]),_.useEffect(()=>{const be=()=>{const Me=!!document.fullscreenElement;N(Me),U(1),H({x:0,y:0}),o==="stream"&&!x&&(W.current&&(W.current.src=""),setTimeout(()=>{m(!0),y(Date.now())},200))};return document.addEventListener("fullscreenchange",be),()=>document.removeEventListener("fullscreenchange",be)},[o,x]),_.useEffect(()=>{let be;const Me=()=>{clearTimeout(be),be=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Me),()=>{clearTimeout(be),window.removeEventListener("resize",Me)}},[]),_.useEffect(()=>()=>{ne.current&&clearTimeout(ne.current),me.current&&clearInterval(me.current),fe.current&&clearInterval(fe.current)},[]);const ce=_.useCallback(()=>{if(T>=sj){k(!1),h(!0);return}const be=Math.min(BXe*Math.pow(2,T),HXe);k(!0),C(Math.ceil(be/1e3)),me.current=setInterval(()=>{C(Me=>Me<=1?(me.current&&clearInterval(me.current),0):Me-1)},1e3),ne.current=setTimeout(()=>{M(Me=>Me+1),k(!1),m(!0),h(!1),W.current&&(W.current.src=""),y(Date.now())},be)},[T]);_.useEffect(()=>{if(o!=="stream"||p||A||x){fe.current&&(clearInterval(fe.current),fe.current=null);return}return fe.current=setInterval(async()=>{try{const be=await ae.getCameraStatus(s);(be.stalled||!be.active&&!d)&&(console.log(`Stream issue detected: stalled=${be.stalled}, active=${be.active}, reconnecting...`),fe.current&&(clearInterval(fe.current),fe.current=null),m(!1),ce())}catch{}},$Xe),()=>{fe.current&&(clearInterval(fe.current),fe.current=null)}},[o,p,d,A,x,s,ce]);const Ve=()=>{m(!1),o==="stream"&&T{if(m(!1),h(!1),M(0),k(!1),ne.current&&clearTimeout(ne.current),me.current&&clearInterval(me.current),W.current&&!localStorage.getItem("cameraWindowState")){const be=W.current,Me=be.naturalWidth,Be=be.naturalHeight;if(Me>0&&Be>0){const ve=window.outerWidth-window.innerWidth,et=window.outerHeight-window.innerHeight,Ee=Me+16+ve,Ye=Be+45+16+et;try{window.resizeTo(Ee,Ye)}catch{}}}},Y=()=>{if(s>0){const be={},Me=Ch();Me&&(be.Authorization=`Bearer ${Me}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:be}).catch(()=>{})}},ue=be=>{o===be||x||(v(!0),m(!0),h(!1),M(0),k(!1),U(1),H({x:0,y:0}),ne.current&&clearTimeout(ne.current),me.current&&clearInterval(me.current),W.current&&(W.current.src=""),o==="stream"&&Y(),setTimeout(()=>{l(be),y(Date.now()),v(!1)},100))},q=()=>{x||(v(!0),m(!0),h(!1),M(0),k(!1),ne.current&&clearTimeout(ne.current),me.current&&clearInterval(me.current),W.current&&(W.current.src=""),o==="stream"&&Y(),setTimeout(()=>{y(Date.now()),v(!1)},100))},re=()=>{J.current&&(document.fullscreenElement?document.exitFullscreen():J.current.requestFullscreen())},X=()=>{U(be=>Math.min(be+.5,4))},le=()=>{U(be=>{const Me=Math.max(be-.5,1);return Me===1&&H({x:0,y:0}),Me})},pe=be=>{be.preventDefault(),be.deltaY<0?X():le()},ee=be=>{P>1&&(be.preventDefault(),$(!0),I({x:be.clientX-F.x,y:be.clientY-F.y}))},z=_.useCallback(()=>{if(!J.current)return{x:300,y:200};const be=J.current.getBoundingClientRect(),Me=be.width*(P-1)/2,Be=be.height*(P-1)/2;return{x:Math.max(50,Me),y:Math.max(50,Be)}},[P]),O=be=>{if(D&&P>1){const Me=be.clientX-G.x,Be=be.clientY-G.y,Ae=z();H({x:Math.max(-Ae.x,Math.min(Ae.x,Me)),y:Math.max(-Ae.y,Math.min(Ae.y,Be))})}},Z=()=>{$(!1)},ge=be=>{if(be.length<2)return 0;const Me=be[0].clientX-be[1].clientX,Be=be[0].clientY-be[1].clientY;return Math.sqrt(Me*Me+Be*Be)},Ce=be=>be.length<2?{x:be[0].clientX,y:be[0].clientY}:{x:(be[0].clientX+be[1].clientX)/2,y:(be[0].clientY+be[1].clientY)/2},_e=be=>{be.touches.length===2?(be.preventDefault(),Q(ge(be.touches)),B(Ce(be.touches))):be.touches.length===1&&P>1&&(be.preventDefault(),$(!0),I({x:be.touches[0].clientX-F.x,y:be.touches[0].clientY-F.y}))},Te=be=>{if(be.touches.length===2&&K!==null){be.preventDefault();const Me=ge(be.touches),Be=Me/K;U(qe=>{const ve=Math.max(1,Math.min(4,qe*Be));return ve===1&&H({x:0,y:0}),ve}),Q(Me);const Ae=Ce(be.touches);if(oe){const qe=z();H(ve=>({x:Math.max(-qe.x,Math.min(qe.x,ve.x+(Ae.x-oe.x))),y:Math.max(-qe.y,Math.min(qe.y,ve.y+(Ae.y-oe.y)))}))}B(Ae)}else if(be.touches.length===1&&D&&P>1){be.preventDefault();const Me=be.touches[0].clientX-G.x,Be=be.touches[0].clientY-G.y,Ae=z();H({x:Math.max(-Ae.x,Math.min(Ae.x,Me)),y:Math.max(-Ae.y,Math.min(Ae.y,Be))})}},we=be=>{be.touches.length<2&&(Q(null),B(null)),be.touches.length===0&&$(!1)},$e=()=>{U(1),H({x:0,y:0})},Ge=x?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${b}`:`/api/v1/printers/${s}/camera/snapshot?t=${b}`,ze=p||x||A;return s?a.jsxs("div",{ref:J,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($g,{className:"w-4 h-4"}),de?.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:ze,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:ze,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:()=>se.mutate(!Re?.chamber_light),disabled:!Re?.connected||se.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${Re?.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(MO,{on:Re?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>u(!0),disabled:!ke||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${ke&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(ke?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:a.jsx(zk,{className:"w-4 h-4 text-bambu-gray"})}),a.jsx("button",{onClick:q,disabled:ze,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:a.jsx(Or,{className:`w-4 h-4 text-bambu-gray ${ze?"animate-spin":""}`})}),a.jsx("button",{onClick:re,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(S?"camera.exitFullscreen":"camera.fullscreen"),children:S?a.jsx(IW,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(ehe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:pe,onMouseMove:O,onMouseUp:Z,onMouseLeave:Z,onTouchStart:_e,onTouchMove:Te,onTouchEnd:we,style:{touchAction:"none"},children:a.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(p||x)&&!A&&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(Or,{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")})]})}),A&&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(fm,{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:R,attempt:T+1,max:sj})}),a.jsx("button",{onClick:q,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&&!A&&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(En,{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:q,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:W,src:Ge,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${P}) translate(${F.x/P}px, ${F.y/P}px)`,cursor:P>1?D?"grabbing":"grab":"default"},onError:Ge?Ve:void 0,onLoad:Ge?V:void 0,onMouseDown:ee,draggable:!1},b),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:le,disabled:P<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:a.jsx(YR,{className:"w-4 h-4 text-white"})}),a.jsxs("button",{onClick:$e,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:X,disabled:P>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:a.jsx(XR,{className:"w-4 h-4 text-white"})})]})]})}),a.jsx(EO,{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 GXe(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 qXe(t){const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function WXe(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 KXe(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 XXe(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"};case"medium":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 YXe(){const{printerId:t}=dk(),[e]=RR(),{t:n}=Yt(),r=an(),i=parseInt(t||"0",10),[s,o]=_.useState(Date.now()),l=_.useMemo(()=>GXe(e),[e]),c=XXe(l.size),{data:u}=it({queryKey:["printer",i],queryFn:()=>ae.getPrinter(i),enabled:i>0}),{data:d}=it({queryKey:["printerStatus",i],queryFn:()=>ae.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3});_.useEffect(()=>{if(!i)return;const x=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,v=new WebSocket(x);return v.onmessage=S=>{try{const N=JSON.parse(S.data);N.type==="printer_status"&&N.printer_id===i&&r.setQueryData(["printerStatus",i],N.status)}catch{}},v.onerror=()=>{},()=>{v.close()}},[i,r]),_.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 p=d.state==="RUNNING"||d.state==="PAUSE",m=d.progress||0,b=`/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:b,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(jr,{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:KXe(d,n)}),l.showProgress&&p&&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(m),"%"]})]}),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:`${m}%`}})})]}),p&&(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(is,{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(wu,{className:c.icon}),a.jsx("span",{className:`${c.text} text-white`,children:qXe(d.remaining_time*60)})]}),a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(tr,{className:c.icon}),a.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",WXe(d.remaining_time,n)]})]})]})]}),!p&&a.jsx("div",{className:`${c.text} text-white/70 py-2`,children:d.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function QXe(){const{t}=Yt(),{id:e}=dk(),{mode:n}=Dm(),{data:r,isLoading:i,error:s}=it({queryKey:["external-link",e],queryFn:()=>ae.getExternalLink(Number(e)),enabled:!!e});return i?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(ct,{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(En,{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 L9=["DEBUG","INFO","WARNING","ERROR"],oj={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},ZXe={DEBUG:fk,INFO:xo,WARNING:En,ERROR:Ti};function JXe(){const t=an(),[e,n]=_.useState(!0),[r,i]=_.useState(new Set),[s,o]=_.useState(""),[l,c]=_.useState("ALL"),[u,d]=_.useState(!1),[h,p]=_.useState(!1),m=_.useRef(null),{data:b,isLoading:y,refetch:x}=it({queryKey:["application-logs",l,s],queryFn:()=>Tg.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:h?2e3:!1,enabled:u});_.useEffect(()=>{u||p(!1)},[u]);const v=dt({mutationFn:()=>Tg.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});_.useEffect(()=>{e&&m.current&&b?.entries&&(m.current.scrollTop=m.current.scrollHeight)},[b?.entries,e]);const S=k=>{i(R=>{const C=new Set(R);return C.has(k)?C.delete(k):C.add(k),C})},N=k=>{const R=k.split(" ");return R.length>=2?R[1]:k},T=_.useMemo(()=>b?.entries??[],[b?.entries]),M=_.useMemo(()=>[...T].reverse(),[T]),A=({level:k})=>{const R=ZXe[k]||xo;return a.jsx(R,{className:`w-3.5 h-3.5 ${oj[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(fk,{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 - ${b?.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(zu,{className:"w-5 h-5 text-bambu-gray"}):a.jsx(fr,{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(),p(!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(ul,{className:"w-4 h-4"}),"Stop"]}):a.jsxs("button",{onClick:k=>{k.stopPropagation(),p(!0),x()},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(Eo,{className:"w-4 h-4"}),"Start"]}),a.jsxs("button",{onClick:()=>v.mutate(),disabled:v.isPending||T.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(ln,{className:"w-4 h-4"}),"Clear"]}),a.jsx("button",{onClick:()=>x(),disabled:y,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(Or,{className:`w-4 h-4 ${y?"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:[b?.filtered_count??0,"/",b?.total_in_file??0]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Qi,{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(Lt,{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"}),L9.map((k,R)=>a.jsx("button",{onClick:()=>c(k),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${R===L9.length-1?"rounded-r":""} ${l===k?`${oj[k]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:k},k))]})]})]}),a.jsx("div",{ref:m,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:T.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,R)=>{const C=r.has(R),P=k.message.includes(` `);return a.jsx("div",{className:`p-2 cursor-pointer hover:bg-bambu-dark-secondary/50 transition-colors ${C?"bg-bambu-dark-secondary/30":""}`,onClick:()=>P&&S(R),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(A,{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 ${oj[k.level]||"text-white/80"} ${!C&&P?"truncate":""}`,children:C?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:C?a.jsx(zu,{className:"w-3.5 h-3.5"}):a.jsx(fr,{className:"w-3.5 h-3.5"})})]})},R)})})}),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 JXe(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 pi({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 F9({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 Wd({title:t,icon:e,children:n}){return a.jsxs(St,{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 eYe(){const{t}=Yt(),e=an(),[n,r]=_.useState(null),[i,s]=_.useState(!1),[o,l]=_.useState(!1),{data:c,isLoading:u,refetch:d,isFetching:h}=it({queryKey:["systemInfo"],queryFn:ae.getSystemInfo,refetchInterval:3e4}),{data:p}=it({queryKey:["debugLogging"],queryFn:Tg.getDebugLoggingState,staleTime:10*1e3,refetchInterval:10*1e3}),{data:m}=it({queryKey:["settings"],queryFn:ae.getSettings}),{data:b}=it({queryKey:["library-stats"],queryFn:ae.getLibraryStats}),y=m?.time_format||"system",x=async()=>{l(!0);try{const T=await Tg.setDebugLogging(!p?.enabled);e.setQueryData(["debugLogging"],T)}catch(T){console.error("Failed to toggle debug logging:",T)}finally{l(!1)}},v=async()=>{r(null),s(!0);try{await Tg.downloadSupportBundle()}catch(T){r(T instanceof Error?T.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(ct,{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(Or,{className:`w-4 h-4 ${h?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),a.jsx(Wd,{title:t("system.application","Application"),icon:Mf,children:a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[a.jsx(pi,{icon:Mf,label:t("system.version","Version"),value:`v${c.app.version}`}),a.jsx(pi,{icon:tr,label:t("system.uptime","System Uptime"),value:c.system.uptime_formatted}),a.jsx(pi,{icon:Mf,label:t("system.hostname","Hostname"),value:c.system.hostname})]})}),a.jsx(Wd,{title:t("support.title","Support & Troubleshooting"),icon:Nde,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 ${p?.enabled?"bg-amber-500/20 text-amber-500":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:a.jsx(fk,{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:[p?.enabled?t("support.debugLoggingEnabled","Capturing detailed logs"):t("support.debugLoggingDisabled","Normal logging level"),p?.enabled&&p.duration_seconds!==null&&a.jsxs("span",{className:"text-amber-400 ml-2",children:["(",Math.floor(p.duration_seconds/60),"m ",p.duration_seconds%60,"s)"]})]})]})]}),a.jsxs("button",{onClick:x,disabled:o,className:`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${p?.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(ct,{className:"w-4 h-4 animate-spin"}),p?.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(wi,{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:v,disabled:i||!p?.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:p?.enabled?void 0:t("support.enableDebugFirst","Enable debug logging first"),children:[i&&a.jsx(ct,{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}),!p?.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(ZXe,{})]})}),a.jsxs(Wd,{title:t("system.database","Database"),icon:Au,children:[a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[a.jsx(pi,{icon:vo,label:t("system.totalArchives","Total Archives"),value:c.database.archives}),a.jsx(pi,{icon:mk,label:t("system.completed","Completed"),value:c.database.archives_completed,color:"text-green-500"}),a.jsx(pi,{icon:Zi,label:t("system.failed","Failed"),value:c.database.archives_failed,color:"text-red-500"}),a.jsx(pi,{icon:ct,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(pi,{icon:jr,label:t("system.printers","Printers"),value:c.database.printers}),a.jsx(pi,{icon:zW,label:t("system.filaments","Filaments"),value:c.database.filaments}),a.jsx(pi,{icon:rs,label:t("system.projects","Projects"),value:c.database.projects}),a.jsx(pi,{icon:sl,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(pi,{icon:tr,label:t("system.totalPrintTime","Total Print Time"),value:c.database.total_print_time_formatted}),a.jsx(pi,{icon:vo,label:t("system.totalFilament","Total Filament Used"),value:`${c.database.total_filament_kg} kg`,subValue:`${c.database.total_filament_grams.toLocaleString()} g`})]})]}),a.jsxs(Wd,{title:t("system.connectedPrinters","Connected Printers"),icon:jr,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(T=>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:T.name})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[a.jsx("span",{children:T.model}),a.jsx("span",{className:`px-2 py-0.5 rounded ${T.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":T.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:T.state})]})]},T.id))}):a.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),a.jsx(Wd,{title:t("system.storage","Storage"),icon:Sb,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(F9,{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(pi,{icon:vo,label:t("system.archiveStorage","Archive Storage"),value:c.storage.archive_size_formatted}),a.jsx(pi,{icon:Au,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),b&&a.jsx(pi,{icon:Ul,label:t("system.fileManagerStorage","File Manager"),value:JXe(b.total_size_bytes),subValue:`${b.total_files} files, ${b.total_folders} folders`})]})]})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[a.jsx(Wd,{title:t("system.memory","Memory"),icon:nhe,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(F9,{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(Wd,{title:t("system.cpu","CPU"),icon:zw,children:a.jsx("div",{className:"space-y-4",children:a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsx(pi,{icon:zw,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),a.jsx(pi,{icon:zw,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),a.jsx(Wd,{title:t("system.systemDetails","System Details"),icon:Mf,children:a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(pi,{icon:Mf,label:t("system.os","Operating System"),value:c.system.platform,subValue:c.system.platform_release}),a.jsx(pi,{icon:zw,label:t("system.architecture","Architecture"),value:c.system.architecture}),a.jsx(pi,{icon:Mf,label:t("system.python","Python"),value:c.system.python_version}),a.jsx(pi,{icon:tr,label:t("system.bootTime","Boot Time"),value:qg(c.system.boot_time,y)})]})})]})}function tYe(){const t=Ec(),{t:e}=Yt(),{login:n}=Ir(),{showToast:r}=Tn(),{mode:i}=Dm(),[s,o]=_.useState(""),[l,c]=_.useState(""),[u,d]=_.useState(!1),[h,p]=_.useState(""),{data:m}=it({queryKey:["advancedAuthStatus"],queryFn:()=>ae.getAdvancedAuthStatus()}),b=dt({mutationFn:()=>n(s,l),onSuccess:()=>{r(e("login.loginSuccess")),t("/")},onError:S=>{r(S.message||e("login.loginFailed"),"error")}}),y=dt({mutationFn:S=>ae.forgotPassword({email:S}),onSuccess:S=>{r(S.message,"success"),d(!1),p("")},onError:S=>{r(S.message,"error")}}),x=S=>{if(S.preventDefault(),!s||!l){r(e("login.enterCredentials"),"error");return}b.mutate()},v=S=>{if(S.preventDefault(),!h){r("Please enter your email address","error");return}y.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:x,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:m?.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:m?.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:b.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:b.isPending?e("login.signingIn"):e("login.signIn")})}),m?.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(St,{className:"w-full max-w-md",onClick:S=>S.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Q0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:e("login.forgotPasswordTitle")})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{d(!1),p("")},children:a.jsx(Lt,{className:"w-5 h-5"})})]})}),a.jsx(Et,{children:m?.advanced_auth_enabled?a.jsxs("form",{onSubmit:v,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=>p(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(Ne,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{d(!1),p("")},children:e("login.cancel")||"Cancel"}),a.jsx(Ne,{type:"submit",className:"flex-1",disabled:y.isPending,children:y.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(Ne,{variant:"secondary",className:"w-full",onClick:()=>d(!1),children:e("login.gotIt")})]})})]})})]})}function nYe(){const t=Ec(),{t:e}=Yt(),{showToast:n}=Tn(),{mode:r}=Dm(),{refreshAuth:i}=Ir(),[s,o]=_.useState(!1),[l,c]=_.useState(""),[u,d]=_.useState(""),[h,p]=_.useState(""),m=dt({mutationFn:()=>ae.setupAuth({auth_enabled:s,admin_username:s?l:void 0,admin_password:s?u:void 0}),onSuccess:async y=>{await i(),y.auth_enabled?y.admin_created?(n(e("setup.toast.authEnabledAdminCreated")),t("/login")):(n(e("setup.toast.authEnabledExistingAdmins")),t("/login")):(n(e("setup.toast.setupCompleted")),t("/"))},onError:y=>{n(y.message,"error")}}),b=y=>{if(y.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}}m.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:b,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:y=>o(y.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(xo,{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:y=>c(y.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:y=>d(y.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:y=>p(y.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:m.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:m.isPending?e("setup.settingUp"):e("setup.completeSetup")})})]})]})})}function rYe(){const t=_.useRef(null),e=_.useRef(null),n=an(),[r,i]=_.useState(!1),s=_.useRef(new Set),o=_.useRef(null),l=_.useRef(new Map),c=_.useRef(null),u=_.useRef([]),d=_.useRef(!1),h=_.useRef(()=>{}),p=_.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()},[]),m=_.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const N=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,T=new WebSocket(N);let M=null;T.onopen=()=>{console.log("[WebSocket] Connected"),i(!0),M=window.setInterval(()=>{T.readyState===WebSocket.OPEN&&T.send(JSON.stringify({type:"ping"}))},3e4)},T.onmessage=A=>{try{const k=JSON.parse(A.data);k.type==="printer_status"&&k.printer_id!==void 0&&k.data?h.current(k):(u.current.push(k),p())}catch{}},T.onclose=A=>{console.log("[WebSocket] Closed",A.code,A.reason),M&&(clearInterval(M),M=null),i(!1),t.current=null,e.current=window.setTimeout(()=>{m()},3e3)},T.onerror=A=>{console.error("[WebSocket] Error",A),T.close()},t.current=T},[p]),b=_.useCallback((S,N)=>{const T=l.current.get(S)||{};l.current.set(S,{...T,...N}),c.current||(c.current=window.setTimeout(()=>{const M=new Map(l.current);l.current.clear(),c.current=null,requestAnimationFrame(()=>{M.forEach((A,k)=>{n.setQueryData(["printerStatus",k],R=>{const C={...R,...A};return C.wifi_signal==null&&R?.wifi_signal!=null&&(C.wifi_signal=R.wifi_signal),C})})})},100))},[n]),y=_.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 T=0;N.forEach(M=>{setTimeout(()=>{requestAnimationFrame(()=>{n.invalidateQueries({queryKey:[M]})})},T),T+=500})},3e3)},[n]),x=_.useCallback(S=>{switch(S.type){case"printer_status":S.printer_id!==void 0&&S.data&&b(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":y("archives"),y("archiveStats");break;case"archive_created":y("archives"),y("archiveStats");break;case"archive_updated":y("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}},[n,y,b]);_.useEffect(()=>{h.current=x},[x]),_.useEffect(()=>(m(),()=>{e.current&&clearTimeout(e.current),o.current&&clearTimeout(o.current),c.current&&clearTimeout(c.current),t.current&&t.current.close()}),[m]);const v=_.useCallback(S=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(S))},[]);return{isConnected:r,sendMessage:v}}const iYe=new pce({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function aYe({children:t}){return rYe(),a.jsx(a.Fragment,{children:t})}function sYe({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(Bg,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function oYe({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(Bg,{to:"/",replace:!0}):a.jsx(Bg,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function lYe({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(Bg,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function cYe(){return a.jsx(Bfe,{children:a.jsx(Xfe,{children:a.jsx(gce,{client:iYe,children:a.jsx(qfe,{children:a.jsx(Lle,{children:a.jsxs(dle,{children:[a.jsx(Li,{path:"/setup",element:a.jsx(lYe,{children:a.jsx(nYe,{})})}),a.jsx(Li,{path:"/login",element:a.jsx(tYe,{})}),a.jsx(Li,{path:"/camera/:printerId",element:a.jsx($Xe,{})}),a.jsx(Li,{path:"/overlay/:printerId",element:a.jsx(XXe,{})}),a.jsxs(Li,{element:a.jsx(sYe,{children:a.jsx(aYe,{children:a.jsx(Jfe,{})})}),children:[a.jsx(Li,{index:!0,element:a.jsx(R8e,{})}),a.jsx(Li,{path:"archives",element:a.jsx(D9e,{})}),a.jsx(Li,{path:"queue",element:a.jsx(xKe,{})}),a.jsx(Li,{path:"stats",element:a.jsx(jKe,{})}),a.jsx(Li,{path:"profiles",element:a.jsx(bXe,{})}),a.jsx(Li,{path:"maintenance",element:a.jsx(_Xe,{})}),a.jsx(Li,{path:"projects",element:a.jsx(NXe,{})}),a.jsx(Li,{path:"projects/:id",element:a.jsx(PXe,{})}),a.jsx(Li,{path:"files",element:a.jsx(zXe,{})}),a.jsx(Li,{path:"settings",element:a.jsx(oYe,{children:a.jsx(nXe,{})})}),a.jsx(Li,{path:"users",element:a.jsx(Bg,{to:"/settings?tab=users",replace:!0})}),a.jsx(Li,{path:"groups",element:a.jsx(Bg,{to:"/settings?tab=users",replace:!0})}),a.jsx(Li,{path:"system",element:a.jsx(eYe,{})}),a.jsx(Li,{path:"external/:id",element:a.jsx(YXe,{})})]})]})})})})})})}ose.createRoot(document.getElementById("root")).render(a.jsx(_.StrictMode,{children:a.jsx(cYe,{})})); +`)[0]}),P&&a.jsx("span",{className:"text-bambu-gray/50 shrink-0",children:C?a.jsx(zu,{className:"w-3.5 h-3.5"}):a.jsx(fr,{className:"w-3.5 h-3.5"})})]})},R)})})}),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 eYe(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 pi({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 F9({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 Wd({title:t,icon:e,children:n}){return a.jsxs(St,{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 tYe(){const{t}=Yt(),e=an(),[n,r]=_.useState(null),[i,s]=_.useState(!1),[o,l]=_.useState(!1),{data:c,isLoading:u,refetch:d,isFetching:h}=it({queryKey:["systemInfo"],queryFn:ae.getSystemInfo,refetchInterval:3e4}),{data:p}=it({queryKey:["debugLogging"],queryFn:Tg.getDebugLoggingState,staleTime:10*1e3,refetchInterval:10*1e3}),{data:m}=it({queryKey:["settings"],queryFn:ae.getSettings}),{data:b}=it({queryKey:["library-stats"],queryFn:ae.getLibraryStats}),y=m?.time_format||"system",x=async()=>{l(!0);try{const T=await Tg.setDebugLogging(!p?.enabled);e.setQueryData(["debugLogging"],T)}catch(T){console.error("Failed to toggle debug logging:",T)}finally{l(!1)}},v=async()=>{r(null),s(!0);try{await Tg.downloadSupportBundle()}catch(T){r(T instanceof Error?T.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(ct,{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(Or,{className:`w-4 h-4 ${h?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),a.jsx(Wd,{title:t("system.application","Application"),icon:Mf,children:a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[a.jsx(pi,{icon:Mf,label:t("system.version","Version"),value:`v${c.app.version}`}),a.jsx(pi,{icon:tr,label:t("system.uptime","System Uptime"),value:c.system.uptime_formatted}),a.jsx(pi,{icon:Mf,label:t("system.hostname","Hostname"),value:c.system.hostname})]})}),a.jsx(Wd,{title:t("support.title","Support & Troubleshooting"),icon:Nde,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 ${p?.enabled?"bg-amber-500/20 text-amber-500":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:a.jsx(fk,{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:[p?.enabled?t("support.debugLoggingEnabled","Capturing detailed logs"):t("support.debugLoggingDisabled","Normal logging level"),p?.enabled&&p.duration_seconds!==null&&a.jsxs("span",{className:"text-amber-400 ml-2",children:["(",Math.floor(p.duration_seconds/60),"m ",p.duration_seconds%60,"s)"]})]})]})]}),a.jsxs("button",{onClick:x,disabled:o,className:`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${p?.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(ct,{className:"w-4 h-4 animate-spin"}),p?.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(wi,{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:v,disabled:i||!p?.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:p?.enabled?void 0:t("support.enableDebugFirst","Enable debug logging first"),children:[i&&a.jsx(ct,{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}),!p?.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(JXe,{})]})}),a.jsxs(Wd,{title:t("system.database","Database"),icon:Au,children:[a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[a.jsx(pi,{icon:vo,label:t("system.totalArchives","Total Archives"),value:c.database.archives}),a.jsx(pi,{icon:mk,label:t("system.completed","Completed"),value:c.database.archives_completed,color:"text-green-500"}),a.jsx(pi,{icon:Zi,label:t("system.failed","Failed"),value:c.database.archives_failed,color:"text-red-500"}),a.jsx(pi,{icon:ct,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(pi,{icon:jr,label:t("system.printers","Printers"),value:c.database.printers}),a.jsx(pi,{icon:zW,label:t("system.filaments","Filaments"),value:c.database.filaments}),a.jsx(pi,{icon:rs,label:t("system.projects","Projects"),value:c.database.projects}),a.jsx(pi,{icon:sl,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(pi,{icon:tr,label:t("system.totalPrintTime","Total Print Time"),value:c.database.total_print_time_formatted}),a.jsx(pi,{icon:vo,label:t("system.totalFilament","Total Filament Used"),value:`${c.database.total_filament_kg} kg`,subValue:`${c.database.total_filament_grams.toLocaleString()} g`})]})]}),a.jsxs(Wd,{title:t("system.connectedPrinters","Connected Printers"),icon:jr,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(T=>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:T.name})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[a.jsx("span",{children:T.model}),a.jsx("span",{className:`px-2 py-0.5 rounded ${T.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":T.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:T.state})]})]},T.id))}):a.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),a.jsx(Wd,{title:t("system.storage","Storage"),icon:Sb,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(F9,{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(pi,{icon:vo,label:t("system.archiveStorage","Archive Storage"),value:c.storage.archive_size_formatted}),a.jsx(pi,{icon:Au,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),b&&a.jsx(pi,{icon:Ul,label:t("system.fileManagerStorage","File Manager"),value:eYe(b.total_size_bytes),subValue:`${b.total_files} files, ${b.total_folders} folders`})]})]})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[a.jsx(Wd,{title:t("system.memory","Memory"),icon:nhe,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(F9,{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(Wd,{title:t("system.cpu","CPU"),icon:zw,children:a.jsx("div",{className:"space-y-4",children:a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsx(pi,{icon:zw,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),a.jsx(pi,{icon:zw,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),a.jsx(Wd,{title:t("system.systemDetails","System Details"),icon:Mf,children:a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(pi,{icon:Mf,label:t("system.os","Operating System"),value:c.system.platform,subValue:c.system.platform_release}),a.jsx(pi,{icon:zw,label:t("system.architecture","Architecture"),value:c.system.architecture}),a.jsx(pi,{icon:Mf,label:t("system.python","Python"),value:c.system.python_version}),a.jsx(pi,{icon:tr,label:t("system.bootTime","Boot Time"),value:qg(c.system.boot_time,y)})]})})]})}function nYe(){const t=Ec(),{t:e}=Yt(),{login:n}=Ir(),{showToast:r}=Tn(),{mode:i}=Dm(),[s,o]=_.useState(""),[l,c]=_.useState(""),[u,d]=_.useState(!1),[h,p]=_.useState(""),{data:m}=it({queryKey:["advancedAuthStatus"],queryFn:()=>ae.getAdvancedAuthStatus()}),b=dt({mutationFn:()=>n(s,l),onSuccess:()=>{r(e("login.loginSuccess")),t("/")},onError:S=>{r(S.message||e("login.loginFailed"),"error")}}),y=dt({mutationFn:S=>ae.forgotPassword({email:S}),onSuccess:S=>{r(S.message,"success"),d(!1),p("")},onError:S=>{r(S.message,"error")}}),x=S=>{if(S.preventDefault(),!s||!l){r(e("login.enterCredentials"),"error");return}b.mutate()},v=S=>{if(S.preventDefault(),!h){r("Please enter your email address","error");return}y.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:x,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:m?.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:m?.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:b.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:b.isPending?e("login.signingIn"):e("login.signIn")})}),m?.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(St,{className:"w-full max-w-md",onClick:S=>S.stopPropagation(),children:[a.jsx(Pn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Q0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:e("login.forgotPasswordTitle")})]}),a.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>{d(!1),p("")},children:a.jsx(Lt,{className:"w-5 h-5"})})]})}),a.jsx(Et,{children:m?.advanced_auth_enabled?a.jsxs("form",{onSubmit:v,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=>p(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(Ne,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{d(!1),p("")},children:e("login.cancel")||"Cancel"}),a.jsx(Ne,{type:"submit",className:"flex-1",disabled:y.isPending,children:y.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(Ne,{variant:"secondary",className:"w-full",onClick:()=>d(!1),children:e("login.gotIt")})]})})]})})]})}function rYe(){const t=Ec(),{t:e}=Yt(),{showToast:n}=Tn(),{mode:r}=Dm(),{refreshAuth:i}=Ir(),[s,o]=_.useState(!1),[l,c]=_.useState(""),[u,d]=_.useState(""),[h,p]=_.useState(""),m=dt({mutationFn:()=>ae.setupAuth({auth_enabled:s,admin_username:s?l:void 0,admin_password:s?u:void 0}),onSuccess:async y=>{await i(),y.auth_enabled?y.admin_created?(n(e("setup.toast.authEnabledAdminCreated")),t("/login")):(n(e("setup.toast.authEnabledExistingAdmins")),t("/login")):(n(e("setup.toast.setupCompleted")),t("/"))},onError:y=>{n(y.message,"error")}}),b=y=>{if(y.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}}m.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:b,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:y=>o(y.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(xo,{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:y=>c(y.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:y=>d(y.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:y=>p(y.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:m.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:m.isPending?e("setup.settingUp"):e("setup.completeSetup")})})]})]})})}function iYe(){const t=_.useRef(null),e=_.useRef(null),n=an(),[r,i]=_.useState(!1),s=_.useRef(new Set),o=_.useRef(null),l=_.useRef(new Map),c=_.useRef(null),u=_.useRef([]),d=_.useRef(!1),h=_.useRef(()=>{}),p=_.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()},[]),m=_.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const N=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,T=new WebSocket(N);let M=null;T.onopen=()=>{console.log("[WebSocket] Connected"),i(!0),M=window.setInterval(()=>{T.readyState===WebSocket.OPEN&&T.send(JSON.stringify({type:"ping"}))},3e4)},T.onmessage=A=>{try{const k=JSON.parse(A.data);k.type==="printer_status"&&k.printer_id!==void 0&&k.data?h.current(k):(u.current.push(k),p())}catch{}},T.onclose=A=>{console.log("[WebSocket] Closed",A.code,A.reason),M&&(clearInterval(M),M=null),i(!1),t.current=null,e.current=window.setTimeout(()=>{m()},3e3)},T.onerror=A=>{console.error("[WebSocket] Error",A),T.close()},t.current=T},[p]),b=_.useCallback((S,N)=>{const T=l.current.get(S)||{};l.current.set(S,{...T,...N}),c.current||(c.current=window.setTimeout(()=>{const M=new Map(l.current);l.current.clear(),c.current=null,requestAnimationFrame(()=>{M.forEach((A,k)=>{n.setQueryData(["printerStatus",k],R=>{const C={...R,...A};return C.wifi_signal==null&&R?.wifi_signal!=null&&(C.wifi_signal=R.wifi_signal),C})})})},100))},[n]),y=_.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 T=0;N.forEach(M=>{setTimeout(()=>{requestAnimationFrame(()=>{n.invalidateQueries({queryKey:[M]})})},T),T+=500})},3e3)},[n]),x=_.useCallback(S=>{switch(S.type){case"printer_status":S.printer_id!==void 0&&S.data&&b(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":y("archives"),y("archiveStats");break;case"archive_created":y("archives"),y("archiveStats");break;case"archive_updated":y("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}},[n,y,b]);_.useEffect(()=>{h.current=x},[x]),_.useEffect(()=>(m(),()=>{e.current&&clearTimeout(e.current),o.current&&clearTimeout(o.current),c.current&&clearTimeout(c.current),t.current&&t.current.close()}),[m]);const v=_.useCallback(S=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(S))},[]);return{isConnected:r,sendMessage:v}}const aYe=new pce({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function sYe({children:t}){return iYe(),a.jsx(a.Fragment,{children:t})}function oYe({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(Bg,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function lYe({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(Bg,{to:"/",replace:!0}):a.jsx(Bg,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function cYe({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(Bg,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function uYe(){return a.jsx(Bfe,{children:a.jsx(Xfe,{children:a.jsx(gce,{client:aYe,children:a.jsx(qfe,{children:a.jsx(Lle,{children:a.jsxs(dle,{children:[a.jsx(Li,{path:"/setup",element:a.jsx(cYe,{children:a.jsx(rYe,{})})}),a.jsx(Li,{path:"/login",element:a.jsx(nYe,{})}),a.jsx(Li,{path:"/camera/:printerId",element:a.jsx(VXe,{})}),a.jsx(Li,{path:"/overlay/:printerId",element:a.jsx(YXe,{})}),a.jsxs(Li,{element:a.jsx(oYe,{children:a.jsx(sYe,{children:a.jsx(Jfe,{})})}),children:[a.jsx(Li,{index:!0,element:a.jsx(O8e,{})}),a.jsx(Li,{path:"archives",element:a.jsx(R9e,{})}),a.jsx(Li,{path:"queue",element:a.jsx(yKe,{})}),a.jsx(Li,{path:"stats",element:a.jsx(DKe,{})}),a.jsx(Li,{path:"profiles",element:a.jsx(xXe,{})}),a.jsx(Li,{path:"maintenance",element:a.jsx(SXe,{})}),a.jsx(Li,{path:"projects",element:a.jsx(kXe,{})}),a.jsx(Li,{path:"projects/:id",element:a.jsx(jXe,{})}),a.jsx(Li,{path:"files",element:a.jsx(UXe,{})}),a.jsx(Li,{path:"settings",element:a.jsx(lYe,{children:a.jsx(rXe,{})})}),a.jsx(Li,{path:"users",element:a.jsx(Bg,{to:"/settings?tab=users",replace:!0})}),a.jsx(Li,{path:"groups",element:a.jsx(Bg,{to:"/settings?tab=users",replace:!0})}),a.jsx(Li,{path:"system",element:a.jsx(tYe,{})}),a.jsx(Li,{path:"external/:id",element:a.jsx(QXe,{})})]})]})})})})})})}ose.createRoot(document.getElementById("root")).render(a.jsx(_.StrictMode,{children:a.jsx(uYe,{})})); diff --git a/static/index.html b/static/index.html index bf1cc68f0..6c0af756e 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +