diff --git a/frontend/src/components/spoolbuddy/SpoolBuddyLayout.tsx b/frontend/src/components/spoolbuddy/SpoolBuddyLayout.tsx index d531ceed7..a369f0130 100644 --- a/frontend/src/components/spoolbuddy/SpoolBuddyLayout.tsx +++ b/frontend/src/components/spoolbuddy/SpoolBuddyLayout.tsx @@ -64,7 +64,7 @@ export function SpoolBuddyLayout() { queryFn: () => device ? spoolbuddyApi.checkDaemonUpdate(device.device_id) : Promise.resolve(null), enabled: !!device, refetchInterval: 5 * 60 * 1000, // re-check every 5 minutes - staleTime: 30 * 1000, + staleTime: 0, }); // Update alert based on device state and available updates diff --git a/frontend/src/pages/spoolbuddy/SpoolBuddySettingsPage.tsx b/frontend/src/pages/spoolbuddy/SpoolBuddySettingsPage.tsx index 0bfbd790c..e4f0769f0 100644 --- a/frontend/src/pages/spoolbuddy/SpoolBuddySettingsPage.tsx +++ b/frontend/src/pages/spoolbuddy/SpoolBuddySettingsPage.tsx @@ -502,30 +502,36 @@ function ScaleTab({ device, weight, weightStable, rawAdc }: { function UpdatesTab({ device }: { device: SpoolBuddyDevice }) { const { t } = useTranslation(); - const [applying, setApplying] = useState(false); + const [busy, setBusy] = useState<'checking' | 'applying' | null>(null); const [error, setError] = useState(null); const [sshExpanded, setSSHExpanded] = useState(false); const [copied, setCopied] = useState(false); - const [manualChecking, setManualChecking] = useState(false); - const wasUpdatingRef = useRef(false); const isUpdating = device.update_status === 'pending' || device.update_status === 'updating'; - // Track when an update was in progress so we can reload when device comes back + // When applying succeeds and device picks up the update, keep showing busy useEffect(() => { - if (isUpdating) { - wasUpdatingRef.current = true; - } else if (wasUpdatingRef.current && device.update_status == null) { - // Status cleared = daemon re-registered after update. Reload for fresh state. - wasUpdatingRef.current = false; - window.location.reload(); + if (isUpdating && busy === 'applying') { + setBusy(null); // device has picked it up, isUpdating takes over the UI } - }, [isUpdating, device.update_status]); + }, [isUpdating, busy]); + + // Reload the page when daemon comes back online after an update + useEffect(() => { + const handleOnline = () => { + if (isUpdating) { + // Daemon re-registered — reload to get fresh version + state + setTimeout(() => window.location.reload(), 1000); + } + }; + window.addEventListener('spoolbuddy-online', handleOnline); + return () => window.removeEventListener('spoolbuddy-online', handleOnline); + }, [isUpdating]); const { data: updateResult, refetch } = useQuery({ queryKey: ['spoolbuddy-update-check', device.device_id], queryFn: () => spoolbuddyApi.checkDaemonUpdate(device.device_id), - staleTime: 30 * 1000, + staleTime: 0, }); const { data: sshKeyData } = useQuery({ @@ -536,26 +542,29 @@ function UpdatesTab({ device }: { device: SpoolBuddyDevice }) { }); const checkForUpdates = async () => { - setManualChecking(true); + setBusy('checking'); + setError(null); try { await refetch(); } finally { - setManualChecking(false); + setBusy(null); } }; const applyUpdate = async () => { - setApplying(true); + setBusy('applying'); setError(null); try { await spoolbuddyApi.triggerUpdate(device.device_id); + // Don't clear busy — keep showing spinner until isUpdating takes over or timeout } catch (e) { setError(e instanceof Error ? e.message : 'Failed to trigger update'); - } finally { - setApplying(false); + setBusy(null); } }; + const showSpinner = busy != null || isUpdating; + const copyKey = () => { if (sshKeyData?.public_key) { navigator.clipboard.writeText(sshKeyData.public_key); @@ -581,95 +590,58 @@ function UpdatesTab({ device }: { device: SpoolBuddyDevice }) { - {/* Update progress */} - {isUpdating && ( -
+ {/* Status / progress row */} + {showSpinner ? ( +
- {device.update_message || t('spoolbuddy.settings.updateWaiting', 'Updating...')} + {busy === 'checking' ? t('spoolbuddy.settings.checking', 'Checking for updates...') + : device.update_message || t('spoolbuddy.settings.updateWaiting', 'Updating...')}
- )} - - {/* Update error */} - {device.update_status === 'error' && ( + ) : device.update_status === 'error' ? (

{device.update_message || t('spoolbuddy.settings.updateFailed', 'Update failed')}

- )} + ) : error ? ( +

{error}

+ ) : updateResult?.update_available ? ( +

+ {t('spoolbuddy.settings.updateAvailable', 'Update available')}: {displayVersion} → {updateResult.latest_version} +

+ ) : null} - {/* Error from trigger */} - {error &&

{error}

} - - {/* Update available → Apply button */} - {updateResult?.update_available ? ( - <> -

- {t('spoolbuddy.settings.updateAvailable', 'Update available')}: {displayVersion} → {updateResult.latest_version} -

+ {/* Action buttons */} + {!showSpinner && ( + updateResult?.update_available ? ( - - ) : updateResult && !isUpdating ? ( - /* Up to date → Check + Force buttons side by side */ -
- - -
- ) : !isUpdating ? ( - /* No result yet → Check button */ - - ) : null} + ) : ( +
+ + +
+ ) + )}
{/* SSH Setup — collapsible */} diff --git a/static/assets/index-B8Ecu_qy.js b/static/assets/index-aq4iRnuK.js similarity index 97% rename from static/assets/index-B8Ecu_qy.js rename to static/assets/index-aq4iRnuK.js index 6d86c5dda..35635317c 100644 --- a/static/assets/index-B8Ecu_qy.js +++ b/static/assets/index-aq4iRnuK.js @@ -4015,7 +4015,7 @@ void main() { gl_FragColor = texture2D( tEquirect, sampleUV ); } - `},a=new kw(5,5,5),s=new $h({name:"CubemapFromEquirect",uniforms:Sx(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:So,blending:Eh});s.uniforms.tEquirect.value=n;const o=new Sc(a,s),l=n.minFilter;return n.minFilter===j0&&(n.minFilter=Rl),new LNe(1,10,this).update(e,o),n.minFilter=l,o.geometry.dispose(),o.material.dispose(),this}clear(e,n,r,a){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(n,r,a);e.setRenderTarget(s)}}const e2=new at,INe=new at,zNe=new tr;class Qm{constructor(e=new at(1,0,0),n=0){this.isPlane=!0,this.normal=e,this.constant=n}set(e,n){return this.normal.copy(e),this.constant=n,this}setComponents(e,n,r,a){return this.normal.set(e,n,r),this.constant=a,this}setFromNormalAndCoplanarPoint(e,n){return this.normal.copy(e),this.constant=-n.dot(this.normal),this}setFromCoplanarPoints(e,n,r){const a=e2.subVectors(r,n).cross(INe.subVectors(e,n)).normalize();return this.setFromNormalAndCoplanarPoint(a,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,n){return n.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,n){const r=e.delta(e2),a=this.normal.dot(r);if(a===0)return this.distanceToPoint(e.start)===0?n.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/a;return s<0||s>1?null:n.copy(e.start).addScaledVector(r,s)}intersectsLine(e){const n=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return n<0&&r>0||r<0&&n>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,n){const r=n||zNe.getNormalMatrix(e),a=this.coplanarPoint(e2).applyMatrix4(e),s=this.normal.applyMatrix3(r).normalize();return this.constant=-a.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const jp=new pu,r1=new at;class wT{constructor(e=new Qm,n=new Qm,r=new Qm,a=new Qm,s=new Qm,o=new Qm){this.planes=[e,n,r,a,s,o]}set(e,n,r,a,s,o){const l=this.planes;return l[0].copy(e),l[1].copy(n),l[2].copy(r),l[3].copy(a),l[4].copy(s),l[5].copy(o),this}copy(e){const n=this.planes;for(let r=0;r<6;r++)n[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e,n=cu){const r=this.planes,a=e.elements,s=a[0],o=a[1],l=a[2],c=a[3],u=a[4],d=a[5],m=a[6],p=a[7],f=a[8],y=a[9],v=a[10],b=a[11],g=a[12],_=a[13],N=a[14],C=a[15];if(r[0].setComponents(c-s,p-u,b-f,C-g).normalize(),r[1].setComponents(c+s,p+u,b+f,C+g).normalize(),r[2].setComponents(c+o,p+d,b+y,C+_).normalize(),r[3].setComponents(c-o,p-d,b-y,C-_).normalize(),r[4].setComponents(c-l,p-m,b-v,C-N).normalize(),n===cu)r[5].setComponents(c+l,p+m,b+v,C+N).normalize();else if(n===R0)r[5].setComponents(l,m,v,N).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+n);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),jp.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),jp.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(jp)}intersectsSprite(e){return jp.center.set(0,0,0),jp.radius=.7071067811865476,jp.applyMatrix4(e.matrixWorld),this.intersectsSphere(jp)}intersectsSphere(e){const n=this.planes,r=e.center,a=-e.radius;for(let s=0;s<6;s++)if(n[s].distanceToPoint(r)0?e.max.x:e.min.x,r1.y=a.normal.y>0?e.max.y:e.min.y,r1.z=a.normal.z>0?e.max.z:e.min.z,a.distanceToPoint(r1)<0)return!1}return!0}containsPoint(e){const n=this.planes;for(let r=0;r<6;r++)if(n[r].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function TZ(){let t=null,e=!1,n=null,r=null;function a(s,o){n(s,o),r=t.requestAnimationFrame(a)}return{start:function(){e!==!0&&n!==null&&(r=t.requestAnimationFrame(a),e=!0)},stop:function(){t.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(s){n=s},setContext:function(s){t=s}}}function UNe(t,e){const n=e.isWebGL2,r=new WeakMap;function a(u,d){const m=u.array,p=u.usage,f=m.byteLength,y=t.createBuffer();t.bindBuffer(d,y),t.bufferData(d,m,p),u.onUploadCallback();let v;if(m instanceof Float32Array)v=t.FLOAT;else if(m instanceof Uint16Array)if(u.isFloat16BufferAttribute)if(n)v=t.HALF_FLOAT;else throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.");else v=t.UNSIGNED_SHORT;else if(m instanceof Int16Array)v=t.SHORT;else if(m instanceof Uint32Array)v=t.UNSIGNED_INT;else if(m instanceof Int32Array)v=t.INT;else if(m instanceof Int8Array)v=t.BYTE;else if(m instanceof Uint8Array)v=t.UNSIGNED_BYTE;else if(m instanceof Uint8ClampedArray)v=t.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+m);return{buffer:y,type:v,bytesPerElement:m.BYTES_PER_ELEMENT,version:u.version,size:f}}function s(u,d,m){const p=d.array,f=d._updateRange,y=d.updateRanges;if(t.bindBuffer(m,u),f.count===-1&&y.length===0&&t.bufferSubData(m,0,p),y.length!==0){for(let v=0,b=y.length;v1?null:n.copy(e.start).addScaledVector(r,s)}intersectsLine(e){const n=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return n<0&&r>0||r<0&&n>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,n){const r=n||zNe.getNormalMatrix(e),a=this.coplanarPoint(ej).applyMatrix4(e),s=this.normal.applyMatrix3(r).normalize();return this.constant=-a.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const jp=new pu,r1=new at;class wT{constructor(e=new Qm,n=new Qm,r=new Qm,a=new Qm,s=new Qm,o=new Qm){this.planes=[e,n,r,a,s,o]}set(e,n,r,a,s,o){const l=this.planes;return l[0].copy(e),l[1].copy(n),l[2].copy(r),l[3].copy(a),l[4].copy(s),l[5].copy(o),this}copy(e){const n=this.planes;for(let r=0;r<6;r++)n[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e,n=cu){const r=this.planes,a=e.elements,s=a[0],o=a[1],l=a[2],c=a[3],u=a[4],d=a[5],m=a[6],p=a[7],f=a[8],y=a[9],v=a[10],b=a[11],g=a[12],_=a[13],N=a[14],C=a[15];if(r[0].setComponents(c-s,p-u,b-f,C-g).normalize(),r[1].setComponents(c+s,p+u,b+f,C+g).normalize(),r[2].setComponents(c+o,p+d,b+y,C+_).normalize(),r[3].setComponents(c-o,p-d,b-y,C-_).normalize(),r[4].setComponents(c-l,p-m,b-v,C-N).normalize(),n===cu)r[5].setComponents(c+l,p+m,b+v,C+N).normalize();else if(n===R0)r[5].setComponents(l,m,v,N).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+n);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),jp.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),jp.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(jp)}intersectsSprite(e){return jp.center.set(0,0,0),jp.radius=.7071067811865476,jp.applyMatrix4(e.matrixWorld),this.intersectsSphere(jp)}intersectsSphere(e){const n=this.planes,r=e.center,a=-e.radius;for(let s=0;s<6;s++)if(n[s].distanceToPoint(r)0?e.max.x:e.min.x,r1.y=a.normal.y>0?e.max.y:e.min.y,r1.z=a.normal.z>0?e.max.z:e.min.z,a.distanceToPoint(r1)<0)return!1}return!0}containsPoint(e){const n=this.planes;for(let r=0;r<6;r++)if(n[r].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function TZ(){let t=null,e=!1,n=null,r=null;function a(s,o){n(s,o),r=t.requestAnimationFrame(a)}return{start:function(){e!==!0&&n!==null&&(r=t.requestAnimationFrame(a),e=!0)},stop:function(){t.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(s){n=s},setContext:function(s){t=s}}}function UNe(t,e){const n=e.isWebGL2,r=new WeakMap;function a(u,d){const m=u.array,p=u.usage,f=m.byteLength,y=t.createBuffer();t.bindBuffer(d,y),t.bufferData(d,m,p),u.onUploadCallback();let v;if(m instanceof Float32Array)v=t.FLOAT;else if(m instanceof Uint16Array)if(u.isFloat16BufferAttribute)if(n)v=t.HALF_FLOAT;else throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.");else v=t.UNSIGNED_SHORT;else if(m instanceof Int16Array)v=t.SHORT;else if(m instanceof Uint32Array)v=t.UNSIGNED_INT;else if(m instanceof Int32Array)v=t.INT;else if(m instanceof Int8Array)v=t.BYTE;else if(m instanceof Uint8Array)v=t.UNSIGNED_BYTE;else if(m instanceof Uint8ClampedArray)v=t.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+m);return{buffer:y,type:v,bytesPerElement:m.BYTES_PER_ELEMENT,version:u.version,size:f}}function s(u,d,m){const p=d.array,f=d._updateRange,y=d.updateRanges;if(t.bindBuffer(m,u),f.count===-1&&y.length===0&&t.bufferSubData(m,0,p),y.length!==0){for(let v=0,b=y.length;v #include #include -}`,Gn={alphahash_fragment:BNe,alphahash_pars_fragment:HNe,alphamap_fragment:$Ne,alphamap_pars_fragment:qNe,alphatest_fragment:VNe,alphatest_pars_fragment:GNe,aomap_fragment:WNe,aomap_pars_fragment:KNe,batching_pars_vertex:YNe,batching_vertex:XNe,begin_vertex:QNe,beginnormal_vertex:ZNe,bsdfs:JNe,iridescence_fragment:eke,bumpmap_pars_fragment:tke,clipping_planes_fragment:nke,clipping_planes_pars_fragment:rke,clipping_planes_pars_vertex:ike,clipping_planes_vertex:ake,color_fragment:ske,color_pars_fragment:oke,color_pars_vertex:lke,color_vertex:cke,common:uke,cube_uv_reflection_fragment:dke,defaultnormal_vertex:mke,displacementmap_pars_vertex:hke,displacementmap_vertex:pke,emissivemap_fragment:fke,emissivemap_pars_fragment:gke,colorspace_fragment:bke,colorspace_pars_fragment:xke,envmap_fragment:yke,envmap_common_pars_fragment:vke,envmap_pars_fragment:wke,envmap_pars_vertex:Ske,envmap_physical_pars_fragment:Rke,envmap_vertex:_ke,fog_vertex:Nke,fog_pars_vertex:kke,fog_fragment:Cke,fog_pars_fragment:Tke,gradientmap_pars_fragment:Ake,lightmap_fragment:Pke,lightmap_pars_fragment:Mke,lights_lambert_fragment:Eke,lights_lambert_pars_fragment:jke,lights_pars_begin:Dke,lights_toon_fragment:Fke,lights_toon_pars_fragment:Lke,lights_phong_fragment:Oke,lights_phong_pars_fragment:Ike,lights_physical_fragment:zke,lights_physical_pars_fragment:Uke,lights_fragment_begin:Bke,lights_fragment_maps:Hke,lights_fragment_end:$ke,logdepthbuf_fragment:qke,logdepthbuf_pars_fragment:Vke,logdepthbuf_pars_vertex:Gke,logdepthbuf_vertex:Wke,map_fragment:Kke,map_pars_fragment:Yke,map_particle_fragment:Xke,map_particle_pars_fragment:Qke,metalnessmap_fragment:Zke,metalnessmap_pars_fragment:Jke,morphcolor_vertex:eCe,morphnormal_vertex:tCe,morphtarget_pars_vertex:nCe,morphtarget_vertex:rCe,normal_fragment_begin:iCe,normal_fragment_maps:aCe,normal_pars_fragment:sCe,normal_pars_vertex:oCe,normal_vertex:lCe,normalmap_pars_fragment:cCe,clearcoat_normal_fragment_begin:uCe,clearcoat_normal_fragment_maps:dCe,clearcoat_pars_fragment:mCe,iridescence_pars_fragment:hCe,opaque_fragment:pCe,packing:fCe,premultiplied_alpha_fragment:gCe,project_vertex:bCe,dithering_fragment:xCe,dithering_pars_fragment:yCe,roughnessmap_fragment:vCe,roughnessmap_pars_fragment:wCe,shadowmap_pars_fragment:SCe,shadowmap_pars_vertex:_Ce,shadowmap_vertex:NCe,shadowmask_pars_fragment:kCe,skinbase_vertex:CCe,skinning_pars_vertex:TCe,skinning_vertex:ACe,skinnormal_vertex:PCe,specularmap_fragment:MCe,specularmap_pars_fragment:ECe,tonemapping_fragment:jCe,tonemapping_pars_fragment:DCe,transmission_fragment:RCe,transmission_pars_fragment:FCe,uv_pars_fragment:LCe,uv_pars_vertex:OCe,uv_vertex:ICe,worldpos_vertex:zCe,background_vert:UCe,background_frag:BCe,backgroundCube_vert:HCe,backgroundCube_frag:$Ce,cube_vert:qCe,cube_frag:VCe,depth_vert:GCe,depth_frag:WCe,distanceRGBA_vert:KCe,distanceRGBA_frag:YCe,equirect_vert:XCe,equirect_frag:QCe,linedashed_vert:ZCe,linedashed_frag:JCe,meshbasic_vert:eTe,meshbasic_frag:tTe,meshlambert_vert:nTe,meshlambert_frag:rTe,meshmatcap_vert:iTe,meshmatcap_frag:aTe,meshnormal_vert:sTe,meshnormal_frag:oTe,meshphong_vert:lTe,meshphong_frag:cTe,meshphysical_vert:uTe,meshphysical_frag:dTe,meshtoon_vert:mTe,meshtoon_frag:hTe,points_vert:pTe,points_frag:fTe,shadow_vert:gTe,shadow_frag:bTe,sprite_vert:xTe,sprite_frag:yTe},Vt={common:{diffuse:{value:new vn(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new tr},alphaMap:{value:null},alphaMapTransform:{value:new tr},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new tr}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new tr}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new tr}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new tr},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new tr},normalScale:{value:new Fn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new tr},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new tr}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new tr}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new tr}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new vn(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new vn(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new tr},alphaTest:{value:0},uvTransform:{value:new tr}},sprite:{diffuse:{value:new vn(16777215)},opacity:{value:1},center:{value:new Fn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new tr},alphaMap:{value:null},alphaMapTransform:{value:new tr},alphaTest:{value:0}}},go={basic:{uniforms:Is([Vt.common,Vt.specularmap,Vt.envmap,Vt.aomap,Vt.lightmap,Vt.fog]),vertexShader:Gn.meshbasic_vert,fragmentShader:Gn.meshbasic_frag},lambert:{uniforms:Is([Vt.common,Vt.specularmap,Vt.envmap,Vt.aomap,Vt.lightmap,Vt.emissivemap,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.fog,Vt.lights,{emissive:{value:new vn(0)}}]),vertexShader:Gn.meshlambert_vert,fragmentShader:Gn.meshlambert_frag},phong:{uniforms:Is([Vt.common,Vt.specularmap,Vt.envmap,Vt.aomap,Vt.lightmap,Vt.emissivemap,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.fog,Vt.lights,{emissive:{value:new vn(0)},specular:{value:new vn(1118481)},shininess:{value:30}}]),vertexShader:Gn.meshphong_vert,fragmentShader:Gn.meshphong_frag},standard:{uniforms:Is([Vt.common,Vt.envmap,Vt.aomap,Vt.lightmap,Vt.emissivemap,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.roughnessmap,Vt.metalnessmap,Vt.fog,Vt.lights,{emissive:{value:new vn(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Gn.meshphysical_vert,fragmentShader:Gn.meshphysical_frag},toon:{uniforms:Is([Vt.common,Vt.aomap,Vt.lightmap,Vt.emissivemap,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.gradientmap,Vt.fog,Vt.lights,{emissive:{value:new vn(0)}}]),vertexShader:Gn.meshtoon_vert,fragmentShader:Gn.meshtoon_frag},matcap:{uniforms:Is([Vt.common,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.fog,{matcap:{value:null}}]),vertexShader:Gn.meshmatcap_vert,fragmentShader:Gn.meshmatcap_frag},points:{uniforms:Is([Vt.points,Vt.fog]),vertexShader:Gn.points_vert,fragmentShader:Gn.points_frag},dashed:{uniforms:Is([Vt.common,Vt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Gn.linedashed_vert,fragmentShader:Gn.linedashed_frag},depth:{uniforms:Is([Vt.common,Vt.displacementmap]),vertexShader:Gn.depth_vert,fragmentShader:Gn.depth_frag},normal:{uniforms:Is([Vt.common,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,{opacity:{value:1}}]),vertexShader:Gn.meshnormal_vert,fragmentShader:Gn.meshnormal_frag},sprite:{uniforms:Is([Vt.sprite,Vt.fog]),vertexShader:Gn.sprite_vert,fragmentShader:Gn.sprite_frag},background:{uniforms:{uvTransform:{value:new tr},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Gn.background_vert,fragmentShader:Gn.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:Gn.backgroundCube_vert,fragmentShader:Gn.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Gn.cube_vert,fragmentShader:Gn.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Gn.equirect_vert,fragmentShader:Gn.equirect_frag},distanceRGBA:{uniforms:Is([Vt.common,Vt.displacementmap,{referencePosition:{value:new at},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Gn.distanceRGBA_vert,fragmentShader:Gn.distanceRGBA_frag},shadow:{uniforms:Is([Vt.lights,Vt.fog,{color:{value:new vn(0)},opacity:{value:1}}]),vertexShader:Gn.shadow_vert,fragmentShader:Gn.shadow_frag}};go.physical={uniforms:Is([go.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new tr},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new tr},clearcoatNormalScale:{value:new Fn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new tr},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new tr},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new tr},sheen:{value:0},sheenColor:{value:new vn(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new tr},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new tr},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new tr},transmissionSamplerSize:{value:new Fn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new tr},attenuationDistance:{value:0},attenuationColor:{value:new vn(0)},specularColor:{value:new vn(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new tr},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new tr},anisotropyVector:{value:new Fn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new tr}}]),vertexShader:Gn.meshphysical_vert,fragmentShader:Gn.meshphysical_frag};const i1={r:0,b:0,g:0};function vTe(t,e,n,r,a,s,o){const l=new vn(0);let c=s===!0?0:1,u,d,m=null,p=0,f=null;function y(b,g){let _=!1,N=g.isScene===!0?g.background:null;N&&N.isTexture&&(N=(g.backgroundBlurriness>0?n:e).get(N)),N===null?v(l,c):N&&N.isColor&&(v(N,1),_=!0);const C=t.xr.getEnvironmentBlendMode();C==="additive"?r.buffers.color.setClear(0,0,0,1,o):C==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,o),(t.autoClear||_)&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),N&&(N.isCubeTexture||N.mapping===yT)?(d===void 0&&(d=new Sc(new kw(1,1,1),new $h({name:"BackgroundCubeMaterial",uniforms:Sx(go.backgroundCube.uniforms),vertexShader:go.backgroundCube.vertexShader,fragmentShader:go.backgroundCube.fragmentShader,side:So,depthTest:!1,depthWrite:!1,fog:!1})),d.geometry.deleteAttribute("normal"),d.geometry.deleteAttribute("uv"),d.onBeforeRender=function(k,P,T){this.matrixWorld.copyPosition(T.matrixWorld)},Object.defineProperty(d.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),a.update(d)),d.material.uniforms.envMap.value=N,d.material.uniforms.flipEnvMap.value=N.isCubeTexture&&N.isRenderTargetTexture===!1?-1:1,d.material.uniforms.backgroundBlurriness.value=g.backgroundBlurriness,d.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,d.material.toneMapped=Hr.getTransfer(N.colorSpace)!==oi,(m!==N||p!==N.version||f!==t.toneMapping)&&(d.material.needsUpdate=!0,m=N,p=N.version,f=t.toneMapping),d.layers.enableAll(),b.unshift(d,d.geometry,d.material,0,0,null)):N&&N.isTexture&&(u===void 0&&(u=new Sc(new NO(2,2),new $h({name:"BackgroundMaterial",uniforms:Sx(go.background.uniforms),vertexShader:go.background.vertexShader,fragmentShader:go.background.fragmentShader,side:Hh,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),Object.defineProperty(u.material,"map",{get:function(){return this.uniforms.t2D.value}}),a.update(u)),u.material.uniforms.t2D.value=N,u.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,u.material.toneMapped=Hr.getTransfer(N.colorSpace)!==oi,N.matrixAutoUpdate===!0&&N.updateMatrix(),u.material.uniforms.uvTransform.value.copy(N.matrix),(m!==N||p!==N.version||f!==t.toneMapping)&&(u.material.needsUpdate=!0,m=N,p=N.version,f=t.toneMapping),u.layers.enableAll(),b.unshift(u,u.geometry,u.material,0,0,null))}function v(b,g){b.getRGB(i1,NZ(t)),r.buffers.color.setClear(i1.r,i1.g,i1.b,g,o)}return{getClearColor:function(){return l},setClearColor:function(b,g=1){l.set(b),c=g,v(l,c)},getClearAlpha:function(){return c},setClearAlpha:function(b){c=b,v(l,c)},render:y}}function wTe(t,e,n,r){const a=t.getParameter(t.MAX_VERTEX_ATTRIBS),s=r.isWebGL2?null:e.get("OES_vertex_array_object"),o=r.isWebGL2||s!==null,l={},c=b(null);let u=c,d=!1;function m(I,J,ae,Y,ue){let de=!1;if(o){const he=v(Y,ae,J);u!==he&&(u=he,f(u.object)),de=g(I,Y,ae,ue),de&&_(I,Y,ae,ue)}else{const he=J.wireframe===!0;(u.geometry!==Y.id||u.program!==ae.id||u.wireframe!==he)&&(u.geometry=Y.id,u.program=ae.id,u.wireframe=he,de=!0)}ue!==null&&n.update(ue,t.ELEMENT_ARRAY_BUFFER),(de||d)&&(d=!1,D(I,J,ae,Y),ue!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.get(ue).buffer))}function p(){return r.isWebGL2?t.createVertexArray():s.createVertexArrayOES()}function f(I){return r.isWebGL2?t.bindVertexArray(I):s.bindVertexArrayOES(I)}function y(I){return r.isWebGL2?t.deleteVertexArray(I):s.deleteVertexArrayOES(I)}function v(I,J,ae){const Y=ae.wireframe===!0;let ue=l[I.id];ue===void 0&&(ue={},l[I.id]=ue);let de=ue[J.id];de===void 0&&(de={},ue[J.id]=de);let he=de[Y];return he===void 0&&(he=b(p()),de[Y]=he),he}function b(I){const J=[],ae=[],Y=[];for(let ue=0;ue=0){const pe=ue[ne];let Te=de[ne];if(Te===void 0&&(ne==="instanceMatrix"&&I.instanceMatrix&&(Te=I.instanceMatrix),ne==="instanceColor"&&I.instanceColor&&(Te=I.instanceColor)),pe===void 0||pe.attribute!==Te||Te&&pe.data!==Te.data)return!0;he++}return u.attributesNum!==he||u.index!==Y}function _(I,J,ae,Y){const ue={},de=J.attributes;let he=0;const V=ae.getAttributes();for(const ne in V)if(V[ne].location>=0){let pe=de[ne];pe===void 0&&(ne==="instanceMatrix"&&I.instanceMatrix&&(pe=I.instanceMatrix),ne==="instanceColor"&&I.instanceColor&&(pe=I.instanceColor));const Te={};Te.attribute=pe,pe&&pe.data&&(Te.data=pe.data),ue[ne]=Te,he++}u.attributes=ue,u.attributesNum=he,u.index=Y}function N(){const I=u.newAttributes;for(let J=0,ae=I.length;J=0){let se=ue[V];if(se===void 0&&(V==="instanceMatrix"&&I.instanceMatrix&&(se=I.instanceMatrix),V==="instanceColor"&&I.instanceColor&&(se=I.instanceColor)),se!==void 0){const pe=se.normalized,Te=se.itemSize,q=n.get(se);if(q===void 0)continue;const X=q.buffer,j=q.type,E=q.bytesPerElement,U=r.isWebGL2===!0&&(j===t.INT||j===t.UNSIGNED_INT||se.gpuType===iZ);if(se.isInterleavedBufferAttribute){const K=se.data,H=K.stride,re=se.offset;if(K.isInstancedInterleavedBuffer){for(let O=0;O0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";T="mediump"}return T==="mediump"&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const o=typeof WebGL2RenderingContext<"u"&&t.constructor.name==="WebGL2RenderingContext";let l=n.precision!==void 0?n.precision:"highp";const c=s(l);c!==l&&(console.warn("THREE.WebGLRenderer:",l,"not supported, using",c,"instead."),l=c);const u=o||e.has("WEBGL_draw_buffers"),d=n.logarithmicDepthBuffer===!0,m=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),p=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),f=t.getParameter(t.MAX_TEXTURE_SIZE),y=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),v=t.getParameter(t.MAX_VERTEX_ATTRIBS),b=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),g=t.getParameter(t.MAX_VARYING_VECTORS),_=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),N=p>0,C=o||e.has("OES_texture_float"),k=N&&C,P=o?t.getParameter(t.MAX_SAMPLES):0;return{isWebGL2:o,drawBuffers:u,getMaxAnisotropy:a,getMaxPrecision:s,precision:l,logarithmicDepthBuffer:d,maxTextures:m,maxVertexTextures:p,maxTextureSize:f,maxCubemapSize:y,maxAttributes:v,maxVertexUniforms:b,maxVaryings:g,maxFragmentUniforms:_,vertexTextures:N,floatFragmentTextures:C,floatVertexTextures:k,maxSamples:P}}function NTe(t){const e=this;let n=null,r=0,a=!1,s=!1;const o=new Qm,l=new tr,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(m,p){const f=m.length!==0||p||r!==0||a;return a=p,r=m.length,f},this.beginShadows=function(){s=!0,d(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(m,p){n=d(m,p,0)},this.setState=function(m,p,f){const y=m.clippingPlanes,v=m.clipIntersection,b=m.clipShadows,g=t.get(m);if(!a||y===null||y.length===0||s&&!b)s?d(null):u();else{const _=s?0:r,N=_*4;let C=g.clippingState||null;c.value=C,C=d(y,p,N,f);for(let k=0;k!==N;++k)C[k]=n[k];g.clippingState=C,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=_}};function u(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function d(m,p,f,y){const v=m!==null?m.length:0;let b=null;if(v!==0){if(b=c.value,y!==!0||b===null){const g=f+v*4,_=p.matrixWorldInverse;l.getNormalMatrix(_),(b===null||b.length0){const u=new ONe(c.height/2);return u.fromEquirectangularTexture(t,o),e.set(o,u),o.addEventListener("dispose",a),n(u.texture,o.mapping)}else return null}}return o}function a(o){const l=o.target;l.removeEventListener("dispose",a);const c=e.get(l);c!==void 0&&(e.delete(l),c.dispose())}function s(){e=new WeakMap}return{get:r,dispose:s}}class CTe extends kZ{constructor(e=-1,n=1,r=1,a=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=n,this.top=r,this.bottom=a,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,n,r,a,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=a,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),n=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,a=(this.top+this.bottom)/2;let s=r-e,o=r+e,l=a+n,c=a-n;if(this.view!==null&&this.view.enabled){const u=(this.right-this.left)/this.view.fullWidth/this.zoom,d=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=u*this.view.offsetX,o=s+u*this.view.width,l-=d*this.view.offsetY,c=l-d*this.view.height}this.projectionMatrix.makeOrthographic(s,o,l,c,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.zoom=this.zoom,n.object.left=this.left,n.object.right=this.right,n.object.top=this.top,n.object.bottom=this.bottom,n.object.near=this.near,n.object.far=this.far,this.view!==null&&(n.object.view=Object.assign({},this.view)),n}}const Bb=4,h$=[.125,.215,.35,.446,.526,.582],Kp=20,t2=new CTe,p$=new vn;let n2=null,r2=0,i2=0;const zp=(1+Math.sqrt(5))/2,xb=1/zp,f$=[new at(1,1,1),new at(-1,1,1),new at(1,1,-1),new at(-1,1,-1),new at(0,zp,xb),new at(0,zp,-xb),new at(xb,0,zp),new at(-xb,0,zp),new at(zp,xb,0),new at(-zp,xb,0)];class g${constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,n=0,r=.1,a=100){n2=this._renderer.getRenderTarget(),r2=this._renderer.getActiveCubeFace(),i2=this._renderer.getActiveMipmapLevel(),this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,r,a,s),n>0&&this._blur(s,0,0,n),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,n=null){return this._fromTexture(e,n)}fromCubemap(e,n=null){return this._fromTexture(e,n)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=y$(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=x$(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?N:0,N,N),d.setRenderTarget(a),v&&d.render(y,l),d.render(e,l)}y.geometry.dispose(),y.material.dispose(),d.toneMapping=p,d.autoClear=m,e.background=b}_textureToCubeUV(e,n){const r=this._renderer,a=e.mapping===yx||e.mapping===vx;a?(this._cubemapMaterial===null&&(this._cubemapMaterial=y$()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=x$());const s=a?this._cubemapMaterial:this._equirectMaterial,o=new Sc(this._lodPlanes[0],s),l=s.uniforms;l.envMap.value=e;const c=this._cubeSize;a1(n,0,0,3*c,2*c),r.setRenderTarget(n),r.render(o,t2)}_applyPMREM(e){const n=this._renderer,r=n.autoClear;n.autoClear=!1;for(let a=1;aKp&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${b} samples when the maximum is set to ${Kp}`);const g=[];let _=0;for(let T=0;TN-Bb?a-N+Bb:0),P=4*(this._cubeSize-C);a1(n,k,P,3*C,2*C),c.setRenderTarget(n),c.render(m,t2)}}function TTe(t){const e=[],n=[],r=[];let a=t;const s=t-Bb+1+h$.length;for(let o=0;ot-Bb?c=h$[o-t+Bb-1]:o===0&&(c=0),r.push(c);const u=1/(l-2),d=-u,m=1+u,p=[d,d,m,d,m,m,d,d,m,m,d,m],f=6,y=6,v=3,b=2,g=1,_=new Float32Array(v*y*f),N=new Float32Array(b*y*f),C=new Float32Array(g*y*f);for(let P=0;P2?0:-1,A=[T,D,0,T+2/3,D,0,T+2/3,D+1,0,T,D,0,T+2/3,D+1,0,T,D+1,0];_.set(A,v*y*P),N.set(p,b*y*P);const R=[P,P,P,P,P,P];C.set(R,g*y*P)}const k=new _s;k.setAttribute("position",new el(_,v)),k.setAttribute("uv",new el(N,b)),k.setAttribute("faceIndex",new el(C,g)),e.push(k),a>Bb&&a--}return{lodPlanes:e,sizeLods:n,sigmas:r}}function b$(t,e,n){const r=new Of(t,e,n);return r.texture.mapping=yT,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function a1(t,e,n,r,a){t.viewport.set(e,n,r,a),t.scissor.set(e,n,r,a)}function ATe(t,e,n){const r=new Float32Array(Kp),a=new at(0,1,0);return new $h({name:"SphericalGaussianBlur",defines:{n:Kp,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:a}},vertexShader:kO(),fragmentShader:` +}`,Gn={alphahash_fragment:BNe,alphahash_pars_fragment:HNe,alphamap_fragment:$Ne,alphamap_pars_fragment:qNe,alphatest_fragment:VNe,alphatest_pars_fragment:GNe,aomap_fragment:WNe,aomap_pars_fragment:KNe,batching_pars_vertex:YNe,batching_vertex:XNe,begin_vertex:QNe,beginnormal_vertex:ZNe,bsdfs:JNe,iridescence_fragment:eke,bumpmap_pars_fragment:tke,clipping_planes_fragment:nke,clipping_planes_pars_fragment:rke,clipping_planes_pars_vertex:ike,clipping_planes_vertex:ake,color_fragment:ske,color_pars_fragment:oke,color_pars_vertex:lke,color_vertex:cke,common:uke,cube_uv_reflection_fragment:dke,defaultnormal_vertex:mke,displacementmap_pars_vertex:hke,displacementmap_vertex:pke,emissivemap_fragment:fke,emissivemap_pars_fragment:gke,colorspace_fragment:bke,colorspace_pars_fragment:xke,envmap_fragment:yke,envmap_common_pars_fragment:vke,envmap_pars_fragment:wke,envmap_pars_vertex:Ske,envmap_physical_pars_fragment:Rke,envmap_vertex:_ke,fog_vertex:Nke,fog_pars_vertex:kke,fog_fragment:Cke,fog_pars_fragment:Tke,gradientmap_pars_fragment:Ake,lightmap_fragment:Pke,lightmap_pars_fragment:Mke,lights_lambert_fragment:Eke,lights_lambert_pars_fragment:jke,lights_pars_begin:Dke,lights_toon_fragment:Fke,lights_toon_pars_fragment:Lke,lights_phong_fragment:Oke,lights_phong_pars_fragment:Ike,lights_physical_fragment:zke,lights_physical_pars_fragment:Uke,lights_fragment_begin:Bke,lights_fragment_maps:Hke,lights_fragment_end:$ke,logdepthbuf_fragment:qke,logdepthbuf_pars_fragment:Vke,logdepthbuf_pars_vertex:Gke,logdepthbuf_vertex:Wke,map_fragment:Kke,map_pars_fragment:Yke,map_particle_fragment:Xke,map_particle_pars_fragment:Qke,metalnessmap_fragment:Zke,metalnessmap_pars_fragment:Jke,morphcolor_vertex:eCe,morphnormal_vertex:tCe,morphtarget_pars_vertex:nCe,morphtarget_vertex:rCe,normal_fragment_begin:iCe,normal_fragment_maps:aCe,normal_pars_fragment:sCe,normal_pars_vertex:oCe,normal_vertex:lCe,normalmap_pars_fragment:cCe,clearcoat_normal_fragment_begin:uCe,clearcoat_normal_fragment_maps:dCe,clearcoat_pars_fragment:mCe,iridescence_pars_fragment:hCe,opaque_fragment:pCe,packing:fCe,premultiplied_alpha_fragment:gCe,project_vertex:bCe,dithering_fragment:xCe,dithering_pars_fragment:yCe,roughnessmap_fragment:vCe,roughnessmap_pars_fragment:wCe,shadowmap_pars_fragment:SCe,shadowmap_pars_vertex:_Ce,shadowmap_vertex:NCe,shadowmask_pars_fragment:kCe,skinbase_vertex:CCe,skinning_pars_vertex:TCe,skinning_vertex:ACe,skinnormal_vertex:PCe,specularmap_fragment:MCe,specularmap_pars_fragment:ECe,tonemapping_fragment:jCe,tonemapping_pars_fragment:DCe,transmission_fragment:RCe,transmission_pars_fragment:FCe,uv_pars_fragment:LCe,uv_pars_vertex:OCe,uv_vertex:ICe,worldpos_vertex:zCe,background_vert:UCe,background_frag:BCe,backgroundCube_vert:HCe,backgroundCube_frag:$Ce,cube_vert:qCe,cube_frag:VCe,depth_vert:GCe,depth_frag:WCe,distanceRGBA_vert:KCe,distanceRGBA_frag:YCe,equirect_vert:XCe,equirect_frag:QCe,linedashed_vert:ZCe,linedashed_frag:JCe,meshbasic_vert:eTe,meshbasic_frag:tTe,meshlambert_vert:nTe,meshlambert_frag:rTe,meshmatcap_vert:iTe,meshmatcap_frag:aTe,meshnormal_vert:sTe,meshnormal_frag:oTe,meshphong_vert:lTe,meshphong_frag:cTe,meshphysical_vert:uTe,meshphysical_frag:dTe,meshtoon_vert:mTe,meshtoon_frag:hTe,points_vert:pTe,points_frag:fTe,shadow_vert:gTe,shadow_frag:bTe,sprite_vert:xTe,sprite_frag:yTe},Vt={common:{diffuse:{value:new vn(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new tr},alphaMap:{value:null},alphaMapTransform:{value:new tr},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new tr}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new tr}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new tr}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new tr},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new tr},normalScale:{value:new Fn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new tr},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new tr}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new tr}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new tr}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new vn(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new vn(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new tr},alphaTest:{value:0},uvTransform:{value:new tr}},sprite:{diffuse:{value:new vn(16777215)},opacity:{value:1},center:{value:new Fn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new tr},alphaMap:{value:null},alphaMapTransform:{value:new tr},alphaTest:{value:0}}},go={basic:{uniforms:Is([Vt.common,Vt.specularmap,Vt.envmap,Vt.aomap,Vt.lightmap,Vt.fog]),vertexShader:Gn.meshbasic_vert,fragmentShader:Gn.meshbasic_frag},lambert:{uniforms:Is([Vt.common,Vt.specularmap,Vt.envmap,Vt.aomap,Vt.lightmap,Vt.emissivemap,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.fog,Vt.lights,{emissive:{value:new vn(0)}}]),vertexShader:Gn.meshlambert_vert,fragmentShader:Gn.meshlambert_frag},phong:{uniforms:Is([Vt.common,Vt.specularmap,Vt.envmap,Vt.aomap,Vt.lightmap,Vt.emissivemap,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.fog,Vt.lights,{emissive:{value:new vn(0)},specular:{value:new vn(1118481)},shininess:{value:30}}]),vertexShader:Gn.meshphong_vert,fragmentShader:Gn.meshphong_frag},standard:{uniforms:Is([Vt.common,Vt.envmap,Vt.aomap,Vt.lightmap,Vt.emissivemap,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.roughnessmap,Vt.metalnessmap,Vt.fog,Vt.lights,{emissive:{value:new vn(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Gn.meshphysical_vert,fragmentShader:Gn.meshphysical_frag},toon:{uniforms:Is([Vt.common,Vt.aomap,Vt.lightmap,Vt.emissivemap,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.gradientmap,Vt.fog,Vt.lights,{emissive:{value:new vn(0)}}]),vertexShader:Gn.meshtoon_vert,fragmentShader:Gn.meshtoon_frag},matcap:{uniforms:Is([Vt.common,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,Vt.fog,{matcap:{value:null}}]),vertexShader:Gn.meshmatcap_vert,fragmentShader:Gn.meshmatcap_frag},points:{uniforms:Is([Vt.points,Vt.fog]),vertexShader:Gn.points_vert,fragmentShader:Gn.points_frag},dashed:{uniforms:Is([Vt.common,Vt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Gn.linedashed_vert,fragmentShader:Gn.linedashed_frag},depth:{uniforms:Is([Vt.common,Vt.displacementmap]),vertexShader:Gn.depth_vert,fragmentShader:Gn.depth_frag},normal:{uniforms:Is([Vt.common,Vt.bumpmap,Vt.normalmap,Vt.displacementmap,{opacity:{value:1}}]),vertexShader:Gn.meshnormal_vert,fragmentShader:Gn.meshnormal_frag},sprite:{uniforms:Is([Vt.sprite,Vt.fog]),vertexShader:Gn.sprite_vert,fragmentShader:Gn.sprite_frag},background:{uniforms:{uvTransform:{value:new tr},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Gn.background_vert,fragmentShader:Gn.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:Gn.backgroundCube_vert,fragmentShader:Gn.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Gn.cube_vert,fragmentShader:Gn.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Gn.equirect_vert,fragmentShader:Gn.equirect_frag},distanceRGBA:{uniforms:Is([Vt.common,Vt.displacementmap,{referencePosition:{value:new at},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Gn.distanceRGBA_vert,fragmentShader:Gn.distanceRGBA_frag},shadow:{uniforms:Is([Vt.lights,Vt.fog,{color:{value:new vn(0)},opacity:{value:1}}]),vertexShader:Gn.shadow_vert,fragmentShader:Gn.shadow_frag}};go.physical={uniforms:Is([go.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new tr},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new tr},clearcoatNormalScale:{value:new Fn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new tr},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new tr},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new tr},sheen:{value:0},sheenColor:{value:new vn(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new tr},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new tr},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new tr},transmissionSamplerSize:{value:new Fn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new tr},attenuationDistance:{value:0},attenuationColor:{value:new vn(0)},specularColor:{value:new vn(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new tr},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new tr},anisotropyVector:{value:new Fn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new tr}}]),vertexShader:Gn.meshphysical_vert,fragmentShader:Gn.meshphysical_frag};const i1={r:0,b:0,g:0};function vTe(t,e,n,r,a,s,o){const l=new vn(0);let c=s===!0?0:1,u,d,m=null,p=0,f=null;function y(b,g){let _=!1,N=g.isScene===!0?g.background:null;N&&N.isTexture&&(N=(g.backgroundBlurriness>0?n:e).get(N)),N===null?v(l,c):N&&N.isColor&&(v(N,1),_=!0);const C=t.xr.getEnvironmentBlendMode();C==="additive"?r.buffers.color.setClear(0,0,0,1,o):C==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,o),(t.autoClear||_)&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),N&&(N.isCubeTexture||N.mapping===yT)?(d===void 0&&(d=new Sc(new kw(1,1,1),new $h({name:"BackgroundCubeMaterial",uniforms:Sx(go.backgroundCube.uniforms),vertexShader:go.backgroundCube.vertexShader,fragmentShader:go.backgroundCube.fragmentShader,side:So,depthTest:!1,depthWrite:!1,fog:!1})),d.geometry.deleteAttribute("normal"),d.geometry.deleteAttribute("uv"),d.onBeforeRender=function(k,P,T){this.matrixWorld.copyPosition(T.matrixWorld)},Object.defineProperty(d.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),a.update(d)),d.material.uniforms.envMap.value=N,d.material.uniforms.flipEnvMap.value=N.isCubeTexture&&N.isRenderTargetTexture===!1?-1:1,d.material.uniforms.backgroundBlurriness.value=g.backgroundBlurriness,d.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,d.material.toneMapped=Hr.getTransfer(N.colorSpace)!==oi,(m!==N||p!==N.version||f!==t.toneMapping)&&(d.material.needsUpdate=!0,m=N,p=N.version,f=t.toneMapping),d.layers.enableAll(),b.unshift(d,d.geometry,d.material,0,0,null)):N&&N.isTexture&&(u===void 0&&(u=new Sc(new NO(2,2),new $h({name:"BackgroundMaterial",uniforms:Sx(go.background.uniforms),vertexShader:go.background.vertexShader,fragmentShader:go.background.fragmentShader,side:Hh,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),Object.defineProperty(u.material,"map",{get:function(){return this.uniforms.t2D.value}}),a.update(u)),u.material.uniforms.t2D.value=N,u.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,u.material.toneMapped=Hr.getTransfer(N.colorSpace)!==oi,N.matrixAutoUpdate===!0&&N.updateMatrix(),u.material.uniforms.uvTransform.value.copy(N.matrix),(m!==N||p!==N.version||f!==t.toneMapping)&&(u.material.needsUpdate=!0,m=N,p=N.version,f=t.toneMapping),u.layers.enableAll(),b.unshift(u,u.geometry,u.material,0,0,null))}function v(b,g){b.getRGB(i1,NZ(t)),r.buffers.color.setClear(i1.r,i1.g,i1.b,g,o)}return{getClearColor:function(){return l},setClearColor:function(b,g=1){l.set(b),c=g,v(l,c)},getClearAlpha:function(){return c},setClearAlpha:function(b){c=b,v(l,c)},render:y}}function wTe(t,e,n,r){const a=t.getParameter(t.MAX_VERTEX_ATTRIBS),s=r.isWebGL2?null:e.get("OES_vertex_array_object"),o=r.isWebGL2||s!==null,l={},c=b(null);let u=c,d=!1;function m(I,J,ae,Y,ue){let de=!1;if(o){const he=v(Y,ae,J);u!==he&&(u=he,f(u.object)),de=g(I,Y,ae,ue),de&&_(I,Y,ae,ue)}else{const he=J.wireframe===!0;(u.geometry!==Y.id||u.program!==ae.id||u.wireframe!==he)&&(u.geometry=Y.id,u.program=ae.id,u.wireframe=he,de=!0)}ue!==null&&n.update(ue,t.ELEMENT_ARRAY_BUFFER),(de||d)&&(d=!1,D(I,J,ae,Y),ue!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.get(ue).buffer))}function p(){return r.isWebGL2?t.createVertexArray():s.createVertexArrayOES()}function f(I){return r.isWebGL2?t.bindVertexArray(I):s.bindVertexArrayOES(I)}function y(I){return r.isWebGL2?t.deleteVertexArray(I):s.deleteVertexArrayOES(I)}function v(I,J,ae){const Y=ae.wireframe===!0;let ue=l[I.id];ue===void 0&&(ue={},l[I.id]=ue);let de=ue[J.id];de===void 0&&(de={},ue[J.id]=de);let he=de[Y];return he===void 0&&(he=b(p()),de[Y]=he),he}function b(I){const J=[],ae=[],Y=[];for(let ue=0;ue=0){const pe=ue[ne];let Te=de[ne];if(Te===void 0&&(ne==="instanceMatrix"&&I.instanceMatrix&&(Te=I.instanceMatrix),ne==="instanceColor"&&I.instanceColor&&(Te=I.instanceColor)),pe===void 0||pe.attribute!==Te||Te&&pe.data!==Te.data)return!0;he++}return u.attributesNum!==he||u.index!==Y}function _(I,J,ae,Y){const ue={},de=J.attributes;let he=0;const V=ae.getAttributes();for(const ne in V)if(V[ne].location>=0){let pe=de[ne];pe===void 0&&(ne==="instanceMatrix"&&I.instanceMatrix&&(pe=I.instanceMatrix),ne==="instanceColor"&&I.instanceColor&&(pe=I.instanceColor));const Te={};Te.attribute=pe,pe&&pe.data&&(Te.data=pe.data),ue[ne]=Te,he++}u.attributes=ue,u.attributesNum=he,u.index=Y}function N(){const I=u.newAttributes;for(let J=0,ae=I.length;J=0){let se=ue[V];if(se===void 0&&(V==="instanceMatrix"&&I.instanceMatrix&&(se=I.instanceMatrix),V==="instanceColor"&&I.instanceColor&&(se=I.instanceColor)),se!==void 0){const pe=se.normalized,Te=se.itemSize,q=n.get(se);if(q===void 0)continue;const X=q.buffer,j=q.type,E=q.bytesPerElement,U=r.isWebGL2===!0&&(j===t.INT||j===t.UNSIGNED_INT||se.gpuType===iZ);if(se.isInterleavedBufferAttribute){const K=se.data,H=K.stride,re=se.offset;if(K.isInstancedInterleavedBuffer){for(let O=0;O0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";T="mediump"}return T==="mediump"&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const o=typeof WebGL2RenderingContext<"u"&&t.constructor.name==="WebGL2RenderingContext";let l=n.precision!==void 0?n.precision:"highp";const c=s(l);c!==l&&(console.warn("THREE.WebGLRenderer:",l,"not supported, using",c,"instead."),l=c);const u=o||e.has("WEBGL_draw_buffers"),d=n.logarithmicDepthBuffer===!0,m=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),p=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),f=t.getParameter(t.MAX_TEXTURE_SIZE),y=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),v=t.getParameter(t.MAX_VERTEX_ATTRIBS),b=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),g=t.getParameter(t.MAX_VARYING_VECTORS),_=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),N=p>0,C=o||e.has("OES_texture_float"),k=N&&C,P=o?t.getParameter(t.MAX_SAMPLES):0;return{isWebGL2:o,drawBuffers:u,getMaxAnisotropy:a,getMaxPrecision:s,precision:l,logarithmicDepthBuffer:d,maxTextures:m,maxVertexTextures:p,maxTextureSize:f,maxCubemapSize:y,maxAttributes:v,maxVertexUniforms:b,maxVaryings:g,maxFragmentUniforms:_,vertexTextures:N,floatFragmentTextures:C,floatVertexTextures:k,maxSamples:P}}function NTe(t){const e=this;let n=null,r=0,a=!1,s=!1;const o=new Qm,l=new tr,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(m,p){const f=m.length!==0||p||r!==0||a;return a=p,r=m.length,f},this.beginShadows=function(){s=!0,d(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(m,p){n=d(m,p,0)},this.setState=function(m,p,f){const y=m.clippingPlanes,v=m.clipIntersection,b=m.clipShadows,g=t.get(m);if(!a||y===null||y.length===0||s&&!b)s?d(null):u();else{const _=s?0:r,N=_*4;let C=g.clippingState||null;c.value=C,C=d(y,p,N,f);for(let k=0;k!==N;++k)C[k]=n[k];g.clippingState=C,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=_}};function u(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function d(m,p,f,y){const v=m!==null?m.length:0;let b=null;if(v!==0){if(b=c.value,y!==!0||b===null){const g=f+v*4,_=p.matrixWorldInverse;l.getNormalMatrix(_),(b===null||b.length0){const u=new ONe(c.height/2);return u.fromEquirectangularTexture(t,o),e.set(o,u),o.addEventListener("dispose",a),n(u.texture,o.mapping)}else return null}}return o}function a(o){const l=o.target;l.removeEventListener("dispose",a);const c=e.get(l);c!==void 0&&(e.delete(l),c.dispose())}function s(){e=new WeakMap}return{get:r,dispose:s}}class CTe extends kZ{constructor(e=-1,n=1,r=1,a=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=n,this.top=r,this.bottom=a,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,n,r,a,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=a,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),n=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,a=(this.top+this.bottom)/2;let s=r-e,o=r+e,l=a+n,c=a-n;if(this.view!==null&&this.view.enabled){const u=(this.right-this.left)/this.view.fullWidth/this.zoom,d=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=u*this.view.offsetX,o=s+u*this.view.width,l-=d*this.view.offsetY,c=l-d*this.view.height}this.projectionMatrix.makeOrthographic(s,o,l,c,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.zoom=this.zoom,n.object.left=this.left,n.object.right=this.right,n.object.top=this.top,n.object.bottom=this.bottom,n.object.near=this.near,n.object.far=this.far,this.view!==null&&(n.object.view=Object.assign({},this.view)),n}}const Bb=4,h$=[.125,.215,.35,.446,.526,.582],Kp=20,tj=new CTe,p$=new vn;let nj=null,rj=0,ij=0;const zp=(1+Math.sqrt(5))/2,xb=1/zp,f$=[new at(1,1,1),new at(-1,1,1),new at(1,1,-1),new at(-1,1,-1),new at(0,zp,xb),new at(0,zp,-xb),new at(xb,0,zp),new at(-xb,0,zp),new at(zp,xb,0),new at(-zp,xb,0)];class g${constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,n=0,r=.1,a=100){nj=this._renderer.getRenderTarget(),rj=this._renderer.getActiveCubeFace(),ij=this._renderer.getActiveMipmapLevel(),this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,r,a,s),n>0&&this._blur(s,0,0,n),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,n=null){return this._fromTexture(e,n)}fromCubemap(e,n=null){return this._fromTexture(e,n)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=y$(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=x$(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?N:0,N,N),d.setRenderTarget(a),v&&d.render(y,l),d.render(e,l)}y.geometry.dispose(),y.material.dispose(),d.toneMapping=p,d.autoClear=m,e.background=b}_textureToCubeUV(e,n){const r=this._renderer,a=e.mapping===yx||e.mapping===vx;a?(this._cubemapMaterial===null&&(this._cubemapMaterial=y$()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=x$());const s=a?this._cubemapMaterial:this._equirectMaterial,o=new Sc(this._lodPlanes[0],s),l=s.uniforms;l.envMap.value=e;const c=this._cubeSize;a1(n,0,0,3*c,2*c),r.setRenderTarget(n),r.render(o,tj)}_applyPMREM(e){const n=this._renderer,r=n.autoClear;n.autoClear=!1;for(let a=1;aKp&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${b} samples when the maximum is set to ${Kp}`);const g=[];let _=0;for(let T=0;TN-Bb?a-N+Bb:0),P=4*(this._cubeSize-C);a1(n,k,P,3*C,2*C),c.setRenderTarget(n),c.render(m,tj)}}function TTe(t){const e=[],n=[],r=[];let a=t;const s=t-Bb+1+h$.length;for(let o=0;ot-Bb?c=h$[o-t+Bb-1]:o===0&&(c=0),r.push(c);const u=1/(l-2),d=-u,m=1+u,p=[d,d,m,d,m,m,d,d,m,m,d,m],f=6,y=6,v=3,b=2,g=1,_=new Float32Array(v*y*f),N=new Float32Array(b*y*f),C=new Float32Array(g*y*f);for(let P=0;P2?0:-1,A=[T,D,0,T+2/3,D,0,T+2/3,D+1,0,T,D,0,T+2/3,D+1,0,T,D+1,0];_.set(A,v*y*P),N.set(p,b*y*P);const R=[P,P,P,P,P,P];C.set(R,g*y*P)}const k=new _s;k.setAttribute("position",new el(_,v)),k.setAttribute("uv",new el(N,b)),k.setAttribute("faceIndex",new el(C,g)),e.push(k),a>Bb&&a--}return{lodPlanes:e,sizeLods:n,sigmas:r}}function b$(t,e,n){const r=new Of(t,e,n);return r.texture.mapping=yT,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function a1(t,e,n,r,a){t.viewport.set(e,n,r,a),t.scissor.set(e,n,r,a)}function ATe(t,e,n){const r=new Float32Array(Kp),a=new at(0,1,0);return new $h({name:"SphericalGaussianBlur",defines:{n:Kp,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:a}},vertexShader:kO(),fragmentShader:` precision mediump float; precision mediump int; @@ -7558,7 +7558,7 @@ void main() { gl_Position = vec4( position, 1.0 ); } - `}function PTe(t){let e=new WeakMap,n=null;function r(l){if(l&&l.isTexture){const c=l.mapping,u=c===SR||c===_R,d=c===yx||c===vx;if(u||d)if(l.isRenderTargetTexture&&l.needsPMREMUpdate===!0){l.needsPMREMUpdate=!1;let m=e.get(l);return n===null&&(n=new g$(t)),m=u?n.fromEquirectangular(l,m):n.fromCubemap(l,m),e.set(l,m),m.texture}else{if(e.has(l))return e.get(l).texture;{const m=l.image;if(u&&m&&m.height>0||d&&m&&a(m)){n===null&&(n=new g$(t));const p=u?n.fromEquirectangular(l):n.fromCubemap(l);return e.set(l,p),l.addEventListener("dispose",s),p.texture}else return null}}}return l}function a(l){let c=0;const u=6;for(let d=0;de.maxTextureSize&&(G=Math.ceil(R/e.maxTextureSize),R=e.maxTextureSize);const z=new Float32Array(R*G*4*v),Z=new xZ(z,R,G,v);Z.type=Cd,Z.needsUpdate=!0;const I=A*4;for(let ae=0;ae0)return t;const a=e*n;let s=v$[a];if(s===void 0&&(s=new Float32Array(a),v$[a]=s),e!==0){r.toArray(s,0);for(let o=1,l=0;o!==e;++o)l+=n,t[o].toArray(s,l)}return s}function xa(t,e){if(t.length!==e.length)return!1;for(let n=0,r=t.length;n0||d&&m&&a(m)){n===null&&(n=new g$(t));const p=u?n.fromEquirectangular(l):n.fromCubemap(l);return e.set(l,p),l.addEventListener("dispose",s),p.texture}else return null}}}return l}function a(l){let c=0;const u=6;for(let d=0;de.maxTextureSize&&(G=Math.ceil(R/e.maxTextureSize),R=e.maxTextureSize);const z=new Float32Array(R*G*4*v),Z=new xZ(z,R,G,v);Z.type=Cd,Z.needsUpdate=!0;const I=A*4;for(let ae=0;ae0)return t;const a=e*n;let s=v$[a];if(s===void 0&&(s=new Float32Array(a),v$[a]=s),e!==0){r.toArray(s,0);for(let o=1,l=0;o!==e;++o)l+=n,t[o].toArray(s,l)}return s}function xa(t,e){if(t.length!==e.length)return!1;for(let n=0,r=t.length;n":" "} ${l}: ${n[o]}`)}return r.join(` `)}function EAe(t){const e=Hr.getPrimaries(Hr.workingColorSpace),n=Hr.getPrimaries(t);let r;switch(e===n?r="":e===QN&&n===XN?r="LinearDisplayP3ToLinearSRGB":e===XN&&n===QN&&(r="LinearSRGBToLinearDisplayP3"),t){case Gd:case vT:return[r,"LinearTransferOETF"];case ts:case vO:return[r,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",t),[r,"LinearTransferOETF"]}}function T$(t,e,n){const r=t.getShaderParameter(e,t.COMPILE_STATUS),a=t.getShaderInfoLog(e).trim();if(r&&a==="")return"";const s=/ERROR: 0:(\d+)/.exec(a);if(s){const o=parseInt(s[1]);return n.toUpperCase()+` @@ -7616,7 +7616,7 @@ void main() { squared_mean = squared_mean / samples; float std_dev = sqrt( squared_mean - mean * mean ); gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); -}`;function dPe(t,e,n){let r=new wT;const a=new Fn,s=new Fn,o=new qr,l=new oPe({depthPacking:W1e}),c=new lPe,u={},d=n.maxTextureSize,m={[Hh]:So,[So]:Hh,[yd]:yd},p=new $h({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Fn},radius:{value:4}},vertexShader:cPe,fragmentShader:uPe}),f=p.clone();f.defines.HORIZONTAL_PASS=1;const y=new _s;y.setAttribute("position",new el(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Sc(y,p),b=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=nZ;let g=this.type;this.render=function(k,P,T){if(b.enabled===!1||b.autoUpdate===!1&&b.needsUpdate===!1||k.length===0)return;const D=t.getRenderTarget(),A=t.getActiveCubeFace(),R=t.getActiveMipmapLevel(),G=t.state;G.setBlending(Eh),G.buffers.color.setClear(1,1,1,1),G.buffers.depth.setTest(!0),G.setScissorTest(!1);const z=g!==fd&&this.type===fd,Z=g===fd&&this.type!==fd;for(let I=0,J=k.length;Id||a.y>d)&&(a.x>d&&(s.x=Math.floor(d/ue.x),a.x=s.x*ue.x,Y.mapSize.x=s.x),a.y>d&&(s.y=Math.floor(d/ue.y),a.y=s.y*ue.y,Y.mapSize.y=s.y)),Y.map===null||z===!0||Z===!0){const he=this.type!==fd?{minFilter:es,magFilter:es}:{};Y.map!==null&&Y.map.dispose(),Y.map=new Of(a.x,a.y,he),Y.map.texture.name=ae.name+".shadowMap",Y.camera.updateProjectionMatrix()}t.setRenderTarget(Y.map),t.clear();const de=Y.getViewportCount();for(let he=0;he0||P.map&&P.alphaTest>0){const G=A.uuid,z=P.uuid;let Z=u[G];Z===void 0&&(Z={},u[G]=Z);let I=Z[z];I===void 0&&(I=A.clone(),Z[z]=I),A=I}if(A.visible=P.visible,A.wireframe=P.wireframe,D===fd?A.side=P.shadowSide!==null?P.shadowSide:P.side:A.side=P.shadowSide!==null?P.shadowSide:m[P.side],A.alphaMap=P.alphaMap,A.alphaTest=P.alphaTest,A.map=P.map,A.clipShadows=P.clipShadows,A.clippingPlanes=P.clippingPlanes,A.clipIntersection=P.clipIntersection,A.displacementMap=P.displacementMap,A.displacementScale=P.displacementScale,A.displacementBias=P.displacementBias,A.wireframeLinewidth=P.wireframeLinewidth,A.linewidth=P.linewidth,T.isPointLight===!0&&A.isMeshDistanceMaterial===!0){const G=t.properties.get(A);G.light=T}return A}function C(k,P,T,D,A){if(k.visible===!1)return;if(k.layers.test(P.layers)&&(k.isMesh||k.isLine||k.isPoints)&&(k.castShadow||k.receiveShadow&&A===fd)&&(!k.frustumCulled||r.intersectsObject(k))){k.modelViewMatrix.multiplyMatrices(T.matrixWorldInverse,k.matrixWorld);const z=e.update(k),Z=k.material;if(Array.isArray(Z)){const I=z.groups;for(let J=0,ae=I.length;J=1):he.indexOf("OpenGL ES")!==-1&&(de=parseFloat(/^OpenGL ES (\d)/.exec(he)[1]),ue=de>=2);let V=null,ne={};const se=t.getParameter(t.SCISSOR_BOX),pe=t.getParameter(t.VIEWPORT),Te=new qr().fromArray(se),q=new qr().fromArray(pe);function X(Pe,Ke,Ve,ke){const Ce=new Uint8Array(4),$e=t.createTexture();t.bindTexture(Pe,$e),t.texParameteri(Pe,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(Pe,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let nt=0;nt"u"?!1:/OculusBrowser/g.test(navigator.userAgent),y=new WeakMap;let v;const b=new WeakMap;let g=!1;try{g=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function _(L,F){return g?new OffscreenCanvas(L,F):JN("canvas")}function N(L,F,te,ve){let fe=1;if((L.width>ve||L.height>ve)&&(fe=ve/Math.max(L.width,L.height)),fe<1||F===!0)if(typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&L instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&L instanceof ImageBitmap){const me=F?ZN:Math.floor,je=me(fe*L.width),we=me(fe*L.height);v===void 0&&(v=_(je,we));const Fe=te?_(je,we):v;return Fe.width=je,Fe.height=we,Fe.getContext("2d").drawImage(L,0,0,je,we),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+L.width+"x"+L.height+") to ("+je+"x"+we+")."),Fe}else return"data"in L&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+L.width+"x"+L.height+")."),L;return L}function C(L){return AR(L.width)&&AR(L.height)}function k(L){return l?!1:L.wrapS!==fc||L.wrapT!==fc||L.minFilter!==es&&L.minFilter!==Rl}function P(L,F){return L.generateMipmaps&&F&&L.minFilter!==es&&L.minFilter!==Rl}function T(L){t.generateMipmap(L)}function D(L,F,te,ve,fe=!1){if(l===!1)return F;if(L!==null){if(t[L]!==void 0)return t[L];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+L+"'")}let me=F;if(F===t.RED&&(te===t.FLOAT&&(me=t.R32F),te===t.HALF_FLOAT&&(me=t.R16F),te===t.UNSIGNED_BYTE&&(me=t.R8)),F===t.RED_INTEGER&&(te===t.UNSIGNED_BYTE&&(me=t.R8UI),te===t.UNSIGNED_SHORT&&(me=t.R16UI),te===t.UNSIGNED_INT&&(me=t.R32UI),te===t.BYTE&&(me=t.R8I),te===t.SHORT&&(me=t.R16I),te===t.INT&&(me=t.R32I)),F===t.RG&&(te===t.FLOAT&&(me=t.RG32F),te===t.HALF_FLOAT&&(me=t.RG16F),te===t.UNSIGNED_BYTE&&(me=t.RG8)),F===t.RGBA){const je=fe?YN:Hr.getTransfer(ve);te===t.FLOAT&&(me=t.RGBA32F),te===t.HALF_FLOAT&&(me=t.RGBA16F),te===t.UNSIGNED_BYTE&&(me=je===oi?t.SRGB8_ALPHA8:t.RGBA8),te===t.UNSIGNED_SHORT_4_4_4_4&&(me=t.RGBA4),te===t.UNSIGNED_SHORT_5_5_5_1&&(me=t.RGB5_A1)}return(me===t.R16F||me===t.R32F||me===t.RG16F||me===t.RG32F||me===t.RGBA16F||me===t.RGBA32F)&&e.get("EXT_color_buffer_float"),me}function A(L,F,te){return P(L,te)===!0||L.isFramebufferTexture&&L.minFilter!==es&&L.minFilter!==Rl?Math.log2(Math.max(F.width,F.height))+1:L.mipmaps!==void 0&&L.mipmaps.length>0?L.mipmaps.length:L.isCompressedTexture&&Array.isArray(L.image)?F.mipmaps.length:1}function R(L){return L===es||L===SH||L===jE?t.NEAREST:t.LINEAR}function G(L){const F=L.target;F.removeEventListener("dispose",G),Z(F),F.isVideoTexture&&y.delete(F)}function z(L){const F=L.target;F.removeEventListener("dispose",z),J(F)}function Z(L){const F=r.get(L);if(F.__webglInit===void 0)return;const te=L.source,ve=b.get(te);if(ve){const fe=ve[F.__cacheKey];fe.usedTimes--,fe.usedTimes===0&&I(L),Object.keys(ve).length===0&&b.delete(te)}r.remove(L)}function I(L){const F=r.get(L);t.deleteTexture(F.__webglTexture);const te=L.source,ve=b.get(te);delete ve[F.__cacheKey],o.memory.textures--}function J(L){const F=L.texture,te=r.get(L),ve=r.get(F);if(ve.__webglTexture!==void 0&&(t.deleteTexture(ve.__webglTexture),o.memory.textures--),L.depthTexture&&L.depthTexture.dispose(),L.isWebGLCubeRenderTarget)for(let fe=0;fe<6;fe++){if(Array.isArray(te.__webglFramebuffer[fe]))for(let me=0;me=c&&console.warn("THREE.WebGLTextures: Trying to use "+L+" texture units while this GPU supports only "+c),ae+=1,L}function de(L){const F=[];return F.push(L.wrapS),F.push(L.wrapT),F.push(L.wrapR||0),F.push(L.magFilter),F.push(L.minFilter),F.push(L.anisotropy),F.push(L.internalFormat),F.push(L.format),F.push(L.type),F.push(L.generateMipmaps),F.push(L.premultiplyAlpha),F.push(L.flipY),F.push(L.unpackAlignment),F.push(L.colorSpace),F.join()}function he(L,F){const te=r.get(L);if(L.isVideoTexture&&xe(L),L.isRenderTargetTexture===!1&&L.version>0&&te.__version!==L.version){const ve=L.image;if(ve===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(ve.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{E(te,L,F);return}}n.bindTexture(t.TEXTURE_2D,te.__webglTexture,t.TEXTURE0+F)}function V(L,F){const te=r.get(L);if(L.version>0&&te.__version!==L.version){E(te,L,F);return}n.bindTexture(t.TEXTURE_2D_ARRAY,te.__webglTexture,t.TEXTURE0+F)}function ne(L,F){const te=r.get(L);if(L.version>0&&te.__version!==L.version){E(te,L,F);return}n.bindTexture(t.TEXTURE_3D,te.__webglTexture,t.TEXTURE0+F)}function se(L,F){const te=r.get(L);if(L.version>0&&te.__version!==L.version){U(te,L,F);return}n.bindTexture(t.TEXTURE_CUBE_MAP,te.__webglTexture,t.TEXTURE0+F)}const pe={[NR]:t.REPEAT,[fc]:t.CLAMP_TO_EDGE,[kR]:t.MIRRORED_REPEAT},Te={[es]:t.NEAREST,[SH]:t.NEAREST_MIPMAP_NEAREST,[jE]:t.NEAREST_MIPMAP_LINEAR,[Rl]:t.LINEAR,[O1e]:t.LINEAR_MIPMAP_NEAREST,[j0]:t.LINEAR_MIPMAP_LINEAR},q={[Y1e]:t.NEVER,[tNe]:t.ALWAYS,[X1e]:t.LESS,[hZ]:t.LEQUAL,[Q1e]:t.EQUAL,[eNe]:t.GEQUAL,[Z1e]:t.GREATER,[J1e]:t.NOTEQUAL};function X(L,F,te){if(te?(t.texParameteri(L,t.TEXTURE_WRAP_S,pe[F.wrapS]),t.texParameteri(L,t.TEXTURE_WRAP_T,pe[F.wrapT]),(L===t.TEXTURE_3D||L===t.TEXTURE_2D_ARRAY)&&t.texParameteri(L,t.TEXTURE_WRAP_R,pe[F.wrapR]),t.texParameteri(L,t.TEXTURE_MAG_FILTER,Te[F.magFilter]),t.texParameteri(L,t.TEXTURE_MIN_FILTER,Te[F.minFilter])):(t.texParameteri(L,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(L,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),(L===t.TEXTURE_3D||L===t.TEXTURE_2D_ARRAY)&&t.texParameteri(L,t.TEXTURE_WRAP_R,t.CLAMP_TO_EDGE),(F.wrapS!==fc||F.wrapT!==fc)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),t.texParameteri(L,t.TEXTURE_MAG_FILTER,R(F.magFilter)),t.texParameteri(L,t.TEXTURE_MIN_FILTER,R(F.minFilter)),F.minFilter!==es&&F.minFilter!==Rl&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),F.compareFunction&&(t.texParameteri(L,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(L,t.TEXTURE_COMPARE_FUNC,q[F.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){const ve=e.get("EXT_texture_filter_anisotropic");if(F.magFilter===es||F.minFilter!==jE&&F.minFilter!==j0||F.type===Cd&&e.has("OES_texture_float_linear")===!1||l===!1&&F.type===D0&&e.has("OES_texture_half_float_linear")===!1)return;(F.anisotropy>1||r.get(F).__currentAnisotropy)&&(t.texParameterf(L,ve.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(F.anisotropy,a.getMaxAnisotropy())),r.get(F).__currentAnisotropy=F.anisotropy)}}function j(L,F){let te=!1;L.__webglInit===void 0&&(L.__webglInit=!0,F.addEventListener("dispose",G));const ve=F.source;let fe=b.get(ve);fe===void 0&&(fe={},b.set(ve,fe));const me=de(F);if(me!==L.__cacheKey){fe[me]===void 0&&(fe[me]={texture:t.createTexture(),usedTimes:0},o.memory.textures++,te=!0),fe[me].usedTimes++;const je=fe[L.__cacheKey];je!==void 0&&(fe[L.__cacheKey].usedTimes--,je.usedTimes===0&&I(F)),L.__cacheKey=me,L.__webglTexture=fe[me].texture}return te}function E(L,F,te){let ve=t.TEXTURE_2D;(F.isDataArrayTexture||F.isCompressedArrayTexture)&&(ve=t.TEXTURE_2D_ARRAY),F.isData3DTexture&&(ve=t.TEXTURE_3D);const fe=j(L,F),me=F.source;n.bindTexture(ve,L.__webglTexture,t.TEXTURE0+te);const je=r.get(me);if(me.version!==je.__version||fe===!0){n.activeTexture(t.TEXTURE0+te);const we=Hr.getPrimaries(Hr.workingColorSpace),Fe=F.colorSpace===Ll?null:Hr.getPrimaries(F.colorSpace),He=F.colorSpace===Ll||we===Fe?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,F.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,F.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,F.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,He);const Oe=k(F)&&C(F.image)===!1;let _e=N(F.image,Oe,!1,d);_e=oe(F,_e);const Ae=C(_e)||l,Be=s.convert(F.format,F.colorSpace);let Me=s.convert(F.type),Xe=D(F.internalFormat,Be,Me,F.colorSpace,F.isVideoTexture);X(ve,F,Ae);let ye;const We=F.mipmaps,Pe=l&&F.isVideoTexture!==!0&&Xe!==uZ,Ke=je.__version===void 0||fe===!0,Ve=A(F,_e,Ae);if(F.isDepthTexture)Xe=t.DEPTH_COMPONENT,l?F.type===Cd?Xe=t.DEPTH_COMPONENT32F:F.type===ph?Xe=t.DEPTH_COMPONENT24:F.type===hf?Xe=t.DEPTH24_STENCIL8:Xe=t.DEPTH_COMPONENT16:F.type===Cd&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),F.format===pf&&Xe===t.DEPTH_COMPONENT&&F.type!==yO&&F.type!==ph&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),F.type=ph,Me=s.convert(F.type)),F.format===wx&&Xe===t.DEPTH_COMPONENT&&(Xe=t.DEPTH_STENCIL,F.type!==hf&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),F.type=hf,Me=s.convert(F.type))),Ke&&(Pe?n.texStorage2D(t.TEXTURE_2D,1,Xe,_e.width,_e.height):n.texImage2D(t.TEXTURE_2D,0,Xe,_e.width,_e.height,0,Be,Me,null));else if(F.isDataTexture)if(We.length>0&&Ae){Pe&&Ke&&n.texStorage2D(t.TEXTURE_2D,Ve,Xe,We[0].width,We[0].height);for(let ke=0,Ce=We.length;ke>=1,Ce>>=1}}else if(We.length>0&&Ae){Pe&&Ke&&n.texStorage2D(t.TEXTURE_2D,Ve,Xe,We[0].width,We[0].height);for(let ke=0,Ce=We.length;ke0&&Ke++,n.texStorage2D(t.TEXTURE_CUBE_MAP,Ke,ye,_e[0].width,_e[0].height));for(let ke=0;ke<6;ke++)if(Oe){We?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,0,0,_e[ke].width,_e[ke].height,Me,Xe,_e[ke].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,ye,_e[ke].width,_e[ke].height,0,Me,Xe,_e[ke].data);for(let Ce=0;Ce>me),_e=Math.max(1,F.height>>me);fe===t.TEXTURE_3D||fe===t.TEXTURE_2D_ARRAY?n.texImage3D(fe,me,Fe,Oe,_e,F.depth,0,je,we,null):n.texImage2D(fe,me,Fe,Oe,_e,0,je,we,null)}n.bindFramebuffer(t.FRAMEBUFFER,L),be(F)?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,ve,fe,r.get(te).__webglTexture,0,ce(F)):(fe===t.TEXTURE_2D||fe>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&fe<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,ve,fe,r.get(te).__webglTexture,me),n.bindFramebuffer(t.FRAMEBUFFER,null)}function H(L,F,te){if(t.bindRenderbuffer(t.RENDERBUFFER,L),F.depthBuffer&&!F.stencilBuffer){let ve=l===!0?t.DEPTH_COMPONENT24:t.DEPTH_COMPONENT16;if(te||be(F)){const fe=F.depthTexture;fe&&fe.isDepthTexture&&(fe.type===Cd?ve=t.DEPTH_COMPONENT32F:fe.type===ph&&(ve=t.DEPTH_COMPONENT24));const me=ce(F);be(F)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,me,ve,F.width,F.height):t.renderbufferStorageMultisample(t.RENDERBUFFER,me,ve,F.width,F.height)}else t.renderbufferStorage(t.RENDERBUFFER,ve,F.width,F.height);t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,L)}else if(F.depthBuffer&&F.stencilBuffer){const ve=ce(F);te&&be(F)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,ve,t.DEPTH24_STENCIL8,F.width,F.height):be(F)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,ve,t.DEPTH24_STENCIL8,F.width,F.height):t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,F.width,F.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,L)}else{const ve=F.isWebGLMultipleRenderTargets===!0?F.texture:[F.texture];for(let fe=0;fe0){te.__webglFramebuffer[we]=[];for(let Fe=0;Fe0){te.__webglFramebuffer=[];for(let we=0;we0&&be(L)===!1){const we=me?F:[F];te.__webglMultisampledFramebuffer=t.createFramebuffer(),te.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,te.__webglMultisampledFramebuffer);for(let Fe=0;Fe0)for(let Fe=0;Fe0)for(let Fe=0;Fe0&&be(L)===!1){const F=L.isWebGLMultipleRenderTargets?L.texture:[L.texture],te=L.width,ve=L.height;let fe=t.COLOR_BUFFER_BIT;const me=[],je=L.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,we=r.get(L),Fe=L.isWebGLMultipleRenderTargets===!0;if(Fe)for(let He=0;He0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&F.__useRenderToTexture!==!1}function xe(L){const F=o.render.frame;y.get(L)!==F&&(y.set(L,F),L.update())}function oe(L,F){const te=L.colorSpace,ve=L.format,fe=L.type;return L.isCompressedTexture===!0||L.isVideoTexture===!0||L.format===TR||te!==Gd&&te!==Ll&&(Hr.getTransfer(te)===oi?l===!1?e.has("EXT_sRGB")===!0&&ve===Fl?(L.format=TR,L.minFilter=Rl,L.generateMipmaps=!1):F=gZ.sRGBToLinear(F):(ve!==Fl||fe!==Dh)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",te)),F}this.allocateTextureUnit=ue,this.resetTextureUnits=Y,this.setTexture2D=he,this.setTexture2DArray=V,this.setTexture3D=ne,this.setTextureCube=se,this.rebindTextures=$,this.setupRenderTarget=ee,this.updateRenderTargetMipmap=W,this.updateMultisampleRenderTarget=ie,this.setupDepthRenderbuffer=O,this.setupFrameBufferTexture=K,this.useMultisampledRTT=be}function pPe(t,e,n){const r=n.isWebGL2;function a(s,o=Ll){let l;const c=Hr.getTransfer(o);if(s===Dh)return t.UNSIGNED_BYTE;if(s===aZ)return t.UNSIGNED_SHORT_4_4_4_4;if(s===sZ)return t.UNSIGNED_SHORT_5_5_5_1;if(s===I1e)return t.BYTE;if(s===z1e)return t.SHORT;if(s===yO)return t.UNSIGNED_SHORT;if(s===iZ)return t.INT;if(s===ph)return t.UNSIGNED_INT;if(s===Cd)return t.FLOAT;if(s===D0)return r?t.HALF_FLOAT:(l=e.get("OES_texture_half_float"),l!==null?l.HALF_FLOAT_OES:null);if(s===U1e)return t.ALPHA;if(s===Fl)return t.RGBA;if(s===B1e)return t.LUMINANCE;if(s===H1e)return t.LUMINANCE_ALPHA;if(s===pf)return t.DEPTH_COMPONENT;if(s===wx)return t.DEPTH_STENCIL;if(s===TR)return l=e.get("EXT_sRGB"),l!==null?l.SRGB_ALPHA_EXT:null;if(s===$1e)return t.RED;if(s===oZ)return t.RED_INTEGER;if(s===q1e)return t.RG;if(s===lZ)return t.RG_INTEGER;if(s===cZ)return t.RGBA_INTEGER;if(s===DE||s===RE||s===FE||s===LE)if(c===oi)if(l=e.get("WEBGL_compressed_texture_s3tc_srgb"),l!==null){if(s===DE)return l.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(s===RE)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(s===FE)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(s===LE)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(l=e.get("WEBGL_compressed_texture_s3tc"),l!==null){if(s===DE)return l.COMPRESSED_RGB_S3TC_DXT1_EXT;if(s===RE)return l.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(s===FE)return l.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(s===LE)return l.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(s===_H||s===NH||s===kH||s===CH)if(l=e.get("WEBGL_compressed_texture_pvrtc"),l!==null){if(s===_H)return l.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(s===NH)return l.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(s===kH)return l.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(s===CH)return l.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(s===uZ)return l=e.get("WEBGL_compressed_texture_etc1"),l!==null?l.COMPRESSED_RGB_ETC1_WEBGL:null;if(s===TH||s===AH)if(l=e.get("WEBGL_compressed_texture_etc"),l!==null){if(s===TH)return c===oi?l.COMPRESSED_SRGB8_ETC2:l.COMPRESSED_RGB8_ETC2;if(s===AH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:l.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(s===PH||s===MH||s===EH||s===jH||s===DH||s===RH||s===FH||s===LH||s===OH||s===IH||s===zH||s===UH||s===BH||s===HH)if(l=e.get("WEBGL_compressed_texture_astc"),l!==null){if(s===PH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:l.COMPRESSED_RGBA_ASTC_4x4_KHR;if(s===MH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:l.COMPRESSED_RGBA_ASTC_5x4_KHR;if(s===EH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:l.COMPRESSED_RGBA_ASTC_5x5_KHR;if(s===jH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:l.COMPRESSED_RGBA_ASTC_6x5_KHR;if(s===DH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:l.COMPRESSED_RGBA_ASTC_6x6_KHR;if(s===RH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:l.COMPRESSED_RGBA_ASTC_8x5_KHR;if(s===FH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:l.COMPRESSED_RGBA_ASTC_8x6_KHR;if(s===LH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:l.COMPRESSED_RGBA_ASTC_8x8_KHR;if(s===OH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:l.COMPRESSED_RGBA_ASTC_10x5_KHR;if(s===IH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:l.COMPRESSED_RGBA_ASTC_10x6_KHR;if(s===zH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:l.COMPRESSED_RGBA_ASTC_10x8_KHR;if(s===UH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:l.COMPRESSED_RGBA_ASTC_10x10_KHR;if(s===BH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:l.COMPRESSED_RGBA_ASTC_12x10_KHR;if(s===HH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:l.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(s===OE||s===$H||s===qH)if(l=e.get("EXT_texture_compression_bptc"),l!==null){if(s===OE)return c===oi?l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:l.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(s===$H)return l.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(s===qH)return l.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(s===V1e||s===VH||s===GH||s===WH)if(l=e.get("EXT_texture_compression_rgtc"),l!==null){if(s===OE)return l.COMPRESSED_RED_RGTC1_EXT;if(s===VH)return l.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(s===GH)return l.COMPRESSED_RED_GREEN_RGTC2_EXT;if(s===WH)return l.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return s===hf?r?t.UNSIGNED_INT_24_8:(l=e.get("WEBGL_depth_texture"),l!==null?l.UNSIGNED_INT_24_8_WEBGL:null):t[s]!==void 0?t[s]:null}return{convert:a}}class fPe extends Ko{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class Rv extends Ws{constructor(){super(),this.isGroup=!0,this.type="Group"}}const gPe={type:"move"};class s2{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Rv,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Rv,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new at,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new at),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Rv,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new at,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new at),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const n=this._hand;if(n)for(const r of e.hand.values())this._getHandJoint(n,r)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,n,r){let a=null,s=null,o=null;const l=this._targetRay,c=this._grip,u=this._hand;if(e&&n.session.visibilityState!=="visible-blurred"){if(u&&e.hand){o=!0;for(const v of e.hand.values()){const b=n.getJointPose(v,r),g=this._getHandJoint(u,v);b!==null&&(g.matrix.fromArray(b.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=b.radius),g.visible=b!==null}const d=u.joints["index-finger-tip"],m=u.joints["thumb-tip"],p=d.position.distanceTo(m.position),f=.02,y=.005;u.inputState.pinching&&p>f+y?(u.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!u.inputState.pinching&&p<=f-y&&(u.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=n.getPose(e.gripSpace,r),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1));l!==null&&(a=n.getPose(e.targetRaySpace,r),a===null&&s!==null&&(a=s),a!==null&&(l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,a.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(a.linearVelocity)):l.hasLinearVelocity=!1,a.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(a.angularVelocity)):l.hasAngularVelocity=!1,this.dispatchEvent(gPe)))}return l!==null&&(l.visible=a!==null),c!==null&&(c.visible=s!==null),u!==null&&(u.visible=o!==null),this}_getHandJoint(e,n){if(e.joints[n.jointName]===void 0){const r=new Rv;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[n.jointName]=r,e.add(r)}return e.joints[n.jointName]}}class bPe extends ig{constructor(e,n){super();const r=this;let a=null,s=1,o=null,l="local-floor",c=1,u=null,d=null,m=null,p=null,f=null,y=null;const v=n.getContextAttributes();let b=null,g=null;const _=[],N=[],C=new Fn;let k=null;const P=new Ko;P.layers.enable(1),P.viewport=new qr;const T=new Ko;T.layers.enable(2),T.viewport=new qr;const D=[P,T],A=new fPe;A.layers.enable(1),A.layers.enable(2);let R=null,G=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(se){let pe=_[se];return pe===void 0&&(pe=new s2,_[se]=pe),pe.getTargetRaySpace()},this.getControllerGrip=function(se){let pe=_[se];return pe===void 0&&(pe=new s2,_[se]=pe),pe.getGripSpace()},this.getHand=function(se){let pe=_[se];return pe===void 0&&(pe=new s2,_[se]=pe),pe.getHandSpace()};function z(se){const pe=N.indexOf(se.inputSource);if(pe===-1)return;const Te=_[pe];Te!==void 0&&(Te.update(se.inputSource,se.frame,u||o),Te.dispatchEvent({type:se.type,data:se.inputSource}))}function Z(){a.removeEventListener("select",z),a.removeEventListener("selectstart",z),a.removeEventListener("selectend",z),a.removeEventListener("squeeze",z),a.removeEventListener("squeezestart",z),a.removeEventListener("squeezeend",z),a.removeEventListener("end",Z),a.removeEventListener("inputsourceschange",I);for(let se=0;se<_.length;se++){const pe=N[se];pe!==null&&(N[se]=null,_[se].disconnect(pe))}R=null,G=null,e.setRenderTarget(b),f=null,p=null,m=null,a=null,g=null,ne.stop(),r.isPresenting=!1,e.setPixelRatio(k),e.setSize(C.width,C.height,!1),r.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(se){s=se,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(se){l=se,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return u||o},this.setReferenceSpace=function(se){u=se},this.getBaseLayer=function(){return p!==null?p:f},this.getBinding=function(){return m},this.getFrame=function(){return y},this.getSession=function(){return a},this.setSession=async function(se){if(a=se,a!==null){if(b=e.getRenderTarget(),a.addEventListener("select",z),a.addEventListener("selectstart",z),a.addEventListener("selectend",z),a.addEventListener("squeeze",z),a.addEventListener("squeezestart",z),a.addEventListener("squeezeend",z),a.addEventListener("end",Z),a.addEventListener("inputsourceschange",I),v.xrCompatible!==!0&&await n.makeXRCompatible(),k=e.getPixelRatio(),e.getSize(C),a.renderState.layers===void 0||e.capabilities.isWebGL2===!1){const pe={antialias:a.renderState.layers===void 0?v.antialias:!0,alpha:!0,depth:v.depth,stencil:v.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(a,n,pe),a.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),g=new Of(f.framebufferWidth,f.framebufferHeight,{format:Fl,type:Dh,colorSpace:e.outputColorSpace,stencilBuffer:v.stencil})}else{let pe=null,Te=null,q=null;v.depth&&(q=v.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,pe=v.stencil?wx:pf,Te=v.stencil?hf:ph);const X={colorFormat:n.RGBA8,depthFormat:q,scaleFactor:s};m=new XRWebGLBinding(a,n),p=m.createProjectionLayer(X),a.updateRenderState({layers:[p]}),e.setPixelRatio(1),e.setSize(p.textureWidth,p.textureHeight,!1),g=new Of(p.textureWidth,p.textureHeight,{format:Fl,type:Dh,depthTexture:new AZ(p.textureWidth,p.textureHeight,Te,void 0,void 0,void 0,void 0,void 0,void 0,pe),stencilBuffer:v.stencil,colorSpace:e.outputColorSpace,samples:v.antialias?4:0});const j=e.properties.get(g);j.__ignoreDepthValues=p.ignoreDepthValues}g.isXRRenderTarget=!0,this.setFoveation(c),u=null,o=await a.requestReferenceSpace(l),ne.setContext(a),ne.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(a!==null)return a.environmentBlendMode};function I(se){for(let pe=0;pe=0&&(N[q]=null,_[q].disconnect(Te))}for(let pe=0;pe=N.length){N.push(Te),q=j;break}else if(N[j]===null){N[j]=Te,q=j;break}if(q===-1)break}const X=_[q];X&&X.connect(Te)}}const J=new at,ae=new at;function Y(se,pe,Te){J.setFromMatrixPosition(pe.matrixWorld),ae.setFromMatrixPosition(Te.matrixWorld);const q=J.distanceTo(ae),X=pe.projectionMatrix.elements,j=Te.projectionMatrix.elements,E=X[14]/(X[10]-1),U=X[14]/(X[10]+1),K=(X[9]+1)/X[5],H=(X[9]-1)/X[5],re=(X[8]-1)/X[0],O=(j[8]+1)/j[0],$=E*re,ee=E*O,W=q/(-re+O),ie=W*-re;pe.matrixWorld.decompose(se.position,se.quaternion,se.scale),se.translateX(ie),se.translateZ(W),se.matrixWorld.compose(se.position,se.quaternion,se.scale),se.matrixWorldInverse.copy(se.matrixWorld).invert();const ce=E+W,be=U+W,xe=$-ie,oe=ee+(q-ie),L=K*U/be*ce,F=H*U/be*ce;se.projectionMatrix.makePerspective(xe,oe,L,F,ce,be),se.projectionMatrixInverse.copy(se.projectionMatrix).invert()}function ue(se,pe){pe===null?se.matrixWorld.copy(se.matrix):se.matrixWorld.multiplyMatrices(pe.matrixWorld,se.matrix),se.matrixWorldInverse.copy(se.matrixWorld).invert()}this.updateCamera=function(se){if(a===null)return;A.near=T.near=P.near=se.near,A.far=T.far=P.far=se.far,(R!==A.near||G!==A.far)&&(a.updateRenderState({depthNear:A.near,depthFar:A.far}),R=A.near,G=A.far);const pe=se.parent,Te=A.cameras;ue(A,pe);for(let q=0;q0&&(b.alphaTest.value=g.alphaTest);const _=e.get(g).envMap;if(_&&(b.envMap.value=_,b.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,b.reflectivity.value=g.reflectivity,b.ior.value=g.ior,b.refractionRatio.value=g.refractionRatio),g.lightMap){b.lightMap.value=g.lightMap;const N=t._useLegacyLights===!0?Math.PI:1;b.lightMapIntensity.value=g.lightMapIntensity*N,n(g.lightMap,b.lightMapTransform)}g.aoMap&&(b.aoMap.value=g.aoMap,b.aoMapIntensity.value=g.aoMapIntensity,n(g.aoMap,b.aoMapTransform))}function o(b,g){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,g.map&&(b.map.value=g.map,n(g.map,b.mapTransform))}function l(b,g){b.dashSize.value=g.dashSize,b.totalSize.value=g.dashSize+g.gapSize,b.scale.value=g.scale}function c(b,g,_,N){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,b.size.value=g.size*_,b.scale.value=N*.5,g.map&&(b.map.value=g.map,n(g.map,b.uvTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,n(g.alphaMap,b.alphaMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest)}function u(b,g){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,b.rotation.value=g.rotation,g.map&&(b.map.value=g.map,n(g.map,b.mapTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,n(g.alphaMap,b.alphaMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest)}function d(b,g){b.specular.value.copy(g.specular),b.shininess.value=Math.max(g.shininess,1e-4)}function m(b,g){g.gradientMap&&(b.gradientMap.value=g.gradientMap)}function p(b,g){b.metalness.value=g.metalness,g.metalnessMap&&(b.metalnessMap.value=g.metalnessMap,n(g.metalnessMap,b.metalnessMapTransform)),b.roughness.value=g.roughness,g.roughnessMap&&(b.roughnessMap.value=g.roughnessMap,n(g.roughnessMap,b.roughnessMapTransform)),e.get(g).envMap&&(b.envMapIntensity.value=g.envMapIntensity)}function f(b,g,_){b.ior.value=g.ior,g.sheen>0&&(b.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),b.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(b.sheenColorMap.value=g.sheenColorMap,n(g.sheenColorMap,b.sheenColorMapTransform)),g.sheenRoughnessMap&&(b.sheenRoughnessMap.value=g.sheenRoughnessMap,n(g.sheenRoughnessMap,b.sheenRoughnessMapTransform))),g.clearcoat>0&&(b.clearcoat.value=g.clearcoat,b.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(b.clearcoatMap.value=g.clearcoatMap,n(g.clearcoatMap,b.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(b.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,n(g.clearcoatRoughnessMap,b.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(b.clearcoatNormalMap.value=g.clearcoatNormalMap,n(g.clearcoatNormalMap,b.clearcoatNormalMapTransform),b.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===So&&b.clearcoatNormalScale.value.negate())),g.iridescence>0&&(b.iridescence.value=g.iridescence,b.iridescenceIOR.value=g.iridescenceIOR,b.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],b.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(b.iridescenceMap.value=g.iridescenceMap,n(g.iridescenceMap,b.iridescenceMapTransform)),g.iridescenceThicknessMap&&(b.iridescenceThicknessMap.value=g.iridescenceThicknessMap,n(g.iridescenceThicknessMap,b.iridescenceThicknessMapTransform))),g.transmission>0&&(b.transmission.value=g.transmission,b.transmissionSamplerMap.value=_.texture,b.transmissionSamplerSize.value.set(_.width,_.height),g.transmissionMap&&(b.transmissionMap.value=g.transmissionMap,n(g.transmissionMap,b.transmissionMapTransform)),b.thickness.value=g.thickness,g.thicknessMap&&(b.thicknessMap.value=g.thicknessMap,n(g.thicknessMap,b.thicknessMapTransform)),b.attenuationDistance.value=g.attenuationDistance,b.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(b.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(b.anisotropyMap.value=g.anisotropyMap,n(g.anisotropyMap,b.anisotropyMapTransform))),b.specularIntensity.value=g.specularIntensity,b.specularColor.value.copy(g.specularColor),g.specularColorMap&&(b.specularColorMap.value=g.specularColorMap,n(g.specularColorMap,b.specularColorMapTransform)),g.specularIntensityMap&&(b.specularIntensityMap.value=g.specularIntensityMap,n(g.specularIntensityMap,b.specularIntensityMapTransform))}function y(b,g){g.matcap&&(b.matcap.value=g.matcap)}function v(b,g){const _=e.get(g).light;b.referencePosition.value.setFromMatrixPosition(_.matrixWorld),b.nearDistance.value=_.shadow.camera.near,b.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:a}}function yPe(t,e,n,r){let a={},s={},o=[];const l=n.isWebGL2?t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS):0;function c(_,N){const C=N.program;r.uniformBlockBinding(_,C)}function u(_,N){let C=a[_.id];C===void 0&&(y(_),C=d(_),a[_.id]=C,_.addEventListener("dispose",b));const k=N.program;r.updateUBOMapping(_,k);const P=e.render.frame;s[_.id]!==P&&(p(_),s[_.id]=P)}function d(_){const N=m();_.__bindingPointIndex=N;const C=t.createBuffer(),k=_.__size,P=_.usage;return t.bindBuffer(t.UNIFORM_BUFFER,C),t.bufferData(t.UNIFORM_BUFFER,k,P),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,N,C),C}function m(){for(let _=0;_0){P=C%k;const z=k-P;P!==0&&z-R.boundary<0&&(C+=k-P,A.__offset=C)}C+=R.storage}return P=C%k,P>0&&(C+=k-P),_.__size=C,_.__cache={},this}function v(_){const N={boundary:0,storage:0};return typeof _=="number"?(N.boundary=4,N.storage=4):_.isVector2?(N.boundary=8,N.storage=8):_.isVector3||_.isColor?(N.boundary=16,N.storage=12):_.isVector4?(N.boundary=16,N.storage=16):_.isMatrix3?(N.boundary=48,N.storage=48):_.isMatrix4?(N.boundary=64,N.storage=64):_.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",_),N}function b(_){const N=_.target;N.removeEventListener("dispose",b);const C=o.indexOf(N.__bindingPointIndex);o.splice(C,1),t.deleteBuffer(a[N.id]),delete a[N.id],delete s[N.id]}function g(){for(const _ in a)t.deleteBuffer(a[_]);o=[],a={},s={}}return{bind:c,update:u,dispose:g}}class MR{constructor(e={}){const{canvas:n=gNe(),context:r=null,depth:a=!0,stencil:s=!0,alpha:o=!1,antialias:l=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:u=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:m=!1}=e;this.isWebGLRenderer=!0;let p;r!==null?p=r.getContextAttributes().alpha:p=o;const f=new Uint32Array(4),y=new Int32Array(4);let v=null,b=null;const g=[],_=[];this.domElement=n,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=ts,this._useLegacyLights=!1,this.toneMapping=jh,this.toneMappingExposure=1;const N=this;let C=!1,k=0,P=0,T=null,D=-1,A=null;const R=new qr,G=new qr;let z=null;const Z=new vn(0);let I=0,J=n.width,ae=n.height,Y=1,ue=null,de=null;const he=new qr(0,0,J,ae),V=new qr(0,0,J,ae);let ne=!1;const se=new wT;let pe=!1,Te=!1,q=null;const X=new ri,j=new Fn,E=new at,U={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function K(){return T===null?Y:1}let H=r;function re(De,ot){for(let st=0;st{function ct(){if(Ze.forEach(function(le){ie.get(le).currentProgram.isReady()&&Ze.delete(le)}),Ze.size===0){Ee(De);return}setTimeout(ct,10)}O.get("KHR_parallel_shader_compile")!==null?ct():setTimeout(ct,10)})};let nt=null;function xt(De){nt&&nt(De)}function vt(){qe.stop()}function mt(){qe.start()}const qe=new TZ;qe.setAnimationLoop(xt),typeof self<"u"&&qe.setContext(self),this.setAnimationLoop=function(De){nt=De,ye.setAnimationLoop(De),De===null?qe.stop():qe.start()},ye.addEventListener("sessionstart",vt),ye.addEventListener("sessionend",mt),this.render=function(De,ot){if(ot!==void 0&&ot.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(C===!0)return;De.matrixWorldAutoUpdate===!0&&De.updateMatrixWorld(),ot.parent===null&&ot.matrixWorldAutoUpdate===!0&&ot.updateMatrixWorld(),ye.enabled===!0&&ye.isPresenting===!0&&(ye.cameraAutoUpdate===!0&&ye.updateCamera(ot),ot=ye.getCamera()),De.isScene===!0&&De.onBeforeRender(N,De,ot,T),b=me.get(De,_.length),b.init(),_.push(b),X.multiplyMatrices(ot.projectionMatrix,ot.matrixWorldInverse),se.setFromProjectionMatrix(X),Te=this.localClippingEnabled,pe=je.init(this.clippingPlanes,Te),v=fe.get(De,g.length),v.init(),g.push(v),Nt(De,ot,0,N.sortObjects),v.finish(),N.sortObjects===!0&&v.sort(ue,de),this.info.render.frame++,pe===!0&&je.beginShadows();const st=b.state.shadowsArray;if(we.render(st,De,ot),pe===!0&&je.endShadows(),this.info.autoReset===!0&&this.info.reset(),Fe.render(v,De),b.setupLights(N._useLegacyLights),ot.isArrayCamera){const Ze=ot.cameras;for(let Ee=0,ct=Ze.length;Ee0?b=_[_.length-1]:b=null,g.pop(),g.length>0?v=g[g.length-1]:v=null};function Nt(De,ot,st,Ze){if(De.visible===!1)return;if(De.layers.test(ot.layers)){if(De.isGroup)st=De.renderOrder;else if(De.isLOD)De.autoUpdate===!0&&De.update(ot);else if(De.isLight)b.pushLight(De),De.castShadow&&b.pushShadow(De);else if(De.isSprite){if(!De.frustumCulled||se.intersectsSprite(De)){Ze&&E.setFromMatrixPosition(De.matrixWorld).applyMatrix4(X);const le=F.update(De),Le=De.material;Le.visible&&v.push(De,le,Le,st,E.z,null)}}else if((De.isMesh||De.isLine||De.isPoints)&&(!De.frustumCulled||se.intersectsObject(De))){const le=F.update(De),Le=De.material;if(Ze&&(De.boundingSphere!==void 0?(De.boundingSphere===null&&De.computeBoundingSphere(),E.copy(De.boundingSphere.center)):(le.boundingSphere===null&&le.computeBoundingSphere(),E.copy(le.boundingSphere.center)),E.applyMatrix4(De.matrixWorld).applyMatrix4(X)),Array.isArray(Le)){const Ye=le.groups;for(let Ge=0,Ie=Ye.length;Ge0&&rt(Ee,ct,ot,st),Ze&&ee.viewport(R.copy(Ze)),Ee.length>0&&Rt(Ee,ot,st),ct.length>0&&Rt(ct,ot,st),le.length>0&&Rt(le,ot,st),ee.buffers.depth.setTest(!0),ee.buffers.depth.setMask(!0),ee.buffers.color.setMask(!0),ee.setPolygonOffset(!1)}function rt(De,ot,st,Ze){if((st.isScene===!0?st.overrideMaterial:null)!==null)return;const ct=$.isWebGL2;q===null&&(q=new Of(1,1,{generateMipmaps:!0,type:O.has("EXT_color_buffer_half_float")?D0:Dh,minFilter:j0,samples:ct?4:0})),N.getDrawingBufferSize(j),ct?q.setSize(j.x,j.y):q.setSize(ZN(j.x),ZN(j.y));const le=N.getRenderTarget();N.setRenderTarget(q),N.getClearColor(Z),I=N.getClearAlpha(),I<1&&N.setClearColor(16777215,.5),N.clear();const Le=N.toneMapping;N.toneMapping=jh,Rt(De,st,Ze),ce.updateMultisampleRenderTarget(q),ce.updateRenderTargetMipmap(q);let Ye=!1;for(let Ge=0,Ie=ot.length;Ge0),pt=!!st.morphAttributes.position,dt=!!st.morphAttributes.normal,Je=!!st.morphAttributes.color;let Tt=jh;Ze.toneMapped&&(T===null||T.isXRRenderTarget===!0)&&(Tt=N.toneMapping);const zt=st.morphAttributes.position||st.morphAttributes.normal||st.morphAttributes.color,Ut=zt!==void 0?zt.length:0,It=ie.get(Ze),cn=b.state.lights;if(pe===!0&&(Te===!0||De!==A)){const Gr=De===A&&Ze.id===D;je.setState(Ze,De,Gr)}let Xt=!1;Ze.version===It.__version?(It.needsLights&&It.lightsStateVersion!==cn.state.version||It.outputColorSpace!==Le||Ee.isBatchedMesh&&It.batching===!1||!Ee.isBatchedMesh&&It.batching===!0||Ee.isInstancedMesh&&It.instancing===!1||!Ee.isInstancedMesh&&It.instancing===!0||Ee.isSkinnedMesh&&It.skinning===!1||!Ee.isSkinnedMesh&&It.skinning===!0||Ee.isInstancedMesh&&It.instancingColor===!0&&Ee.instanceColor===null||Ee.isInstancedMesh&&It.instancingColor===!1&&Ee.instanceColor!==null||It.envMap!==Ye||Ze.fog===!0&&It.fog!==ct||It.numClippingPlanes!==void 0&&(It.numClippingPlanes!==je.numPlanes||It.numIntersection!==je.numIntersection)||It.vertexAlphas!==Ge||It.vertexTangents!==Ie||It.morphTargets!==pt||It.morphNormals!==dt||It.morphColors!==Je||It.toneMapping!==Tt||$.isWebGL2===!0&&It.morphTargetsCount!==Ut)&&(Xt=!0):(Xt=!0,It.__version=Ze.version);let tn=It.currentProgram;Xt===!0&&(tn=Kt(Ze,ot,Ee));let wn=!1,kn=!1,Jt=!1;const Sn=tn.getUniforms(),Tn=It.uniforms;if(ee.useProgram(tn.program)&&(wn=!0,kn=!0,Jt=!0),Ze.id!==D&&(D=Ze.id,kn=!0),wn||A!==De){Sn.setValue(H,"projectionMatrix",De.projectionMatrix),Sn.setValue(H,"viewMatrix",De.matrixWorldInverse);const Gr=Sn.map.cameraPosition;Gr!==void 0&&Gr.setValue(H,E.setFromMatrixPosition(De.matrixWorld)),$.logarithmicDepthBuffer&&Sn.setValue(H,"logDepthBufFC",2/(Math.log(De.far+1)/Math.LN2)),(Ze.isMeshPhongMaterial||Ze.isMeshToonMaterial||Ze.isMeshLambertMaterial||Ze.isMeshBasicMaterial||Ze.isMeshStandardMaterial||Ze.isShaderMaterial)&&Sn.setValue(H,"isOrthographic",De.isOrthographicCamera===!0),A!==De&&(A=De,kn=!0,Jt=!0)}if(Ee.isSkinnedMesh){Sn.setOptional(H,Ee,"bindMatrix"),Sn.setOptional(H,Ee,"bindMatrixInverse");const Gr=Ee.skeleton;Gr&&($.floatVertexTextures?(Gr.boneTexture===null&&Gr.computeBoneTexture(),Sn.setValue(H,"boneTexture",Gr.boneTexture,ce)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}Ee.isBatchedMesh&&(Sn.setOptional(H,Ee,"batchingTexture"),Sn.setValue(H,"batchingTexture",Ee._matricesTexture,ce));const ei=st.morphAttributes;if((ei.position!==void 0||ei.normal!==void 0||ei.color!==void 0&&$.isWebGL2===!0)&&He.update(Ee,st,tn),(kn||It.receiveShadow!==Ee.receiveShadow)&&(It.receiveShadow=Ee.receiveShadow,Sn.setValue(H,"receiveShadow",Ee.receiveShadow)),Ze.isMeshGouraudMaterial&&Ze.envMap!==null&&(Tn.envMap.value=Ye,Tn.flipEnvMap.value=Ye.isCubeTexture&&Ye.isRenderTargetTexture===!1?-1:1),kn&&(Sn.setValue(H,"toneMappingExposure",N.toneMappingExposure),It.needsLights&&Hn(Tn,Jt),ct&&Ze.fog===!0&&ve.refreshFogUniforms(Tn,ct),ve.refreshMaterialUniforms(Tn,Ze,Y,ae,q),dN.upload(H,Qt(It),Tn,ce)),Ze.isShaderMaterial&&Ze.uniformsNeedUpdate===!0&&(dN.upload(H,Qt(It),Tn,ce),Ze.uniformsNeedUpdate=!1),Ze.isSpriteMaterial&&Sn.setValue(H,"center",Ee.center),Sn.setValue(H,"modelViewMatrix",Ee.modelViewMatrix),Sn.setValue(H,"normalMatrix",Ee.normalMatrix),Sn.setValue(H,"modelMatrix",Ee.matrixWorld),Ze.isShaderMaterial||Ze.isRawShaderMaterial){const Gr=Ze.uniformsGroups;for(let lr=0,zi=Gr.length;lr0&&ce.useMultisampledRTT(De)===!1?Ee=ie.get(De).__webglMultisampledFramebuffer:Array.isArray(Ie)?Ee=Ie[st]:Ee=Ie,R.copy(De.viewport),G.copy(De.scissor),z=De.scissorTest}else R.copy(he).multiplyScalar(Y).floor(),G.copy(V).multiplyScalar(Y).floor(),z=ne;if(ee.bindFramebuffer(H.FRAMEBUFFER,Ee)&&$.drawBuffers&&Ze&&ee.drawBuffers(De,Ee),ee.viewport(R),ee.scissor(G),ee.setScissorTest(z),ct){const Ye=ie.get(De.texture);H.framebufferTexture2D(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_CUBE_MAP_POSITIVE_X+ot,Ye.__webglTexture,st)}else if(le){const Ye=ie.get(De.texture),Ge=ot||0;H.framebufferTextureLayer(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,Ye.__webglTexture,st||0,Ge)}D=-1},this.readRenderTargetPixels=function(De,ot,st,Ze,Ee,ct,le){if(!(De&&De.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Le=ie.get(De).__webglFramebuffer;if(De.isWebGLCubeRenderTarget&&le!==void 0&&(Le=Le[le]),Le){ee.bindFramebuffer(H.FRAMEBUFFER,Le);try{const Ye=De.texture,Ge=Ye.format,Ie=Ye.type;if(Ge!==Fl&&Ae.convert(Ge)!==H.getParameter(H.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const pt=Ie===D0&&(O.has("EXT_color_buffer_half_float")||$.isWebGL2&&O.has("EXT_color_buffer_float"));if(Ie!==Dh&&Ae.convert(Ie)!==H.getParameter(H.IMPLEMENTATION_COLOR_READ_TYPE)&&!(Ie===Cd&&($.isWebGL2||O.has("OES_texture_float")||O.has("WEBGL_color_buffer_float")))&&!pt){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}ot>=0&&ot<=De.width-Ze&&st>=0&&st<=De.height-Ee&&H.readPixels(ot,st,Ze,Ee,Ae.convert(Ge),Ae.convert(Ie),ct)}finally{const Ye=T!==null?ie.get(T).__webglFramebuffer:null;ee.bindFramebuffer(H.FRAMEBUFFER,Ye)}}},this.copyFramebufferToTexture=function(De,ot,st=0){const Ze=Math.pow(2,-st),Ee=Math.floor(ot.image.width*Ze),ct=Math.floor(ot.image.height*Ze);ce.setTexture2D(ot,0),H.copyTexSubImage2D(H.TEXTURE_2D,st,0,0,De.x,De.y,Ee,ct),ee.unbindTexture()},this.copyTextureToTexture=function(De,ot,st,Ze=0){const Ee=ot.image.width,ct=ot.image.height,le=Ae.convert(st.format),Le=Ae.convert(st.type);ce.setTexture2D(st,0),H.pixelStorei(H.UNPACK_FLIP_Y_WEBGL,st.flipY),H.pixelStorei(H.UNPACK_PREMULTIPLY_ALPHA_WEBGL,st.premultiplyAlpha),H.pixelStorei(H.UNPACK_ALIGNMENT,st.unpackAlignment),ot.isDataTexture?H.texSubImage2D(H.TEXTURE_2D,Ze,De.x,De.y,Ee,ct,le,Le,ot.image.data):ot.isCompressedTexture?H.compressedTexSubImage2D(H.TEXTURE_2D,Ze,De.x,De.y,ot.mipmaps[0].width,ot.mipmaps[0].height,le,ot.mipmaps[0].data):H.texSubImage2D(H.TEXTURE_2D,Ze,De.x,De.y,le,Le,ot.image),Ze===0&&st.generateMipmaps&&H.generateMipmap(H.TEXTURE_2D),ee.unbindTexture()},this.copyTextureToTexture3D=function(De,ot,st,Ze,Ee=0){if(N.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const ct=De.max.x-De.min.x+1,le=De.max.y-De.min.y+1,Le=De.max.z-De.min.z+1,Ye=Ae.convert(Ze.format),Ge=Ae.convert(Ze.type);let Ie;if(Ze.isData3DTexture)ce.setTexture3D(Ze,0),Ie=H.TEXTURE_3D;else if(Ze.isDataArrayTexture)ce.setTexture2DArray(Ze,0),Ie=H.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}H.pixelStorei(H.UNPACK_FLIP_Y_WEBGL,Ze.flipY),H.pixelStorei(H.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Ze.premultiplyAlpha),H.pixelStorei(H.UNPACK_ALIGNMENT,Ze.unpackAlignment);const pt=H.getParameter(H.UNPACK_ROW_LENGTH),dt=H.getParameter(H.UNPACK_IMAGE_HEIGHT),Je=H.getParameter(H.UNPACK_SKIP_PIXELS),Tt=H.getParameter(H.UNPACK_SKIP_ROWS),zt=H.getParameter(H.UNPACK_SKIP_IMAGES),Ut=st.isCompressedTexture?st.mipmaps[0]:st.image;H.pixelStorei(H.UNPACK_ROW_LENGTH,Ut.width),H.pixelStorei(H.UNPACK_IMAGE_HEIGHT,Ut.height),H.pixelStorei(H.UNPACK_SKIP_PIXELS,De.min.x),H.pixelStorei(H.UNPACK_SKIP_ROWS,De.min.y),H.pixelStorei(H.UNPACK_SKIP_IMAGES,De.min.z),st.isDataTexture||st.isData3DTexture?H.texSubImage3D(Ie,Ee,ot.x,ot.y,ot.z,ct,le,Le,Ye,Ge,Ut.data):st.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),H.compressedTexSubImage3D(Ie,Ee,ot.x,ot.y,ot.z,ct,le,Le,Ye,Ut.data)):H.texSubImage3D(Ie,Ee,ot.x,ot.y,ot.z,ct,le,Le,Ye,Ge,Ut),H.pixelStorei(H.UNPACK_ROW_LENGTH,pt),H.pixelStorei(H.UNPACK_IMAGE_HEIGHT,dt),H.pixelStorei(H.UNPACK_SKIP_PIXELS,Je),H.pixelStorei(H.UNPACK_SKIP_ROWS,Tt),H.pixelStorei(H.UNPACK_SKIP_IMAGES,zt),Ee===0&&Ze.generateMipmaps&&H.generateMipmap(Ie),ee.unbindTexture()},this.initTexture=function(De){De.isCubeTexture?ce.setTextureCube(De,0):De.isData3DTexture?ce.setTexture3D(De,0):De.isDataArrayTexture||De.isCompressedArrayTexture?ce.setTexture2DArray(De,0):ce.setTexture2D(De,0),ee.unbindTexture()},this.resetState=function(){k=0,P=0,T=null,ee.reset(),Be.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return cu}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const n=this.getContext();n.drawingBufferColorSpace=e===vO?"display-p3":"srgb",n.unpackColorSpace=Hr.workingColorSpace===vT?"display-p3":"srgb"}get physicallyCorrectLights(){return console.warn("THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead."),!this.useLegacyLights}set physicallyCorrectLights(e){console.warn("THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead."),this.useLegacyLights=!e}get outputEncoding(){return console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace===ts?ff:dZ}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===ff?ts:Gd}get useLegacyLights(){return console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights}set useLegacyLights(e){console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights=e}}class vPe extends MR{}vPe.prototype.isWebGL1Renderer=!0;class CO{constructor(e,n=1,r=1e3){this.isFog=!0,this.name="",this.color=new vn(e),this.near=n,this.far=r}clone(){return new CO(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class wPe extends Ws{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,n){return super.copy(e,n),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const n=super.toJSON(e);return this.fog!==null&&(n.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(n.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(n.object.backgroundIntensity=this.backgroundIntensity),n}}class SPe{constructor(e,n){this.isInterleavedBuffer=!0,this.array=e,this.stride=n,this.count=e!==void 0?e.length/n:0,this.usage=CR,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=Dd()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return console.warn('THREE.InterleavedBuffer: "updateRange" is deprecated and removed in r169. Use "addUpdateRange()" instead.'),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,n,r){e*=this.stride,r*=n.stride;for(let a=0,s=this.stride;a=r.length&&r.push({start:-1,count:-1,z:-1});const s=r[this.index];a.push(s),this.index++,s.start=e.start,s.count=e.count,s.z=n}reset(){this.list.length=0,this.index=0}}const yb="batchId",qm=new ri,F$=new ri,TPe=new ri,L$=new ri,o2=new wT,s1=new Bl,Dp=new pu,mv=new at,l2=new CPe,fs=new Sc,o1=[];function APe(t,e,n=0){const r=e.itemSize;if(t.isInterleavedBufferAttribute||t.array.constructor!==e.array.constructor){const a=t.count;for(let s=0;s65536?new Uint32Array(s):new Uint16Array(s);n.setIndex(new el(l,1))}const o=a>65536?new Uint32Array(r):new Uint16Array(r);n.setAttribute(yb,new el(o,1)),this._geometryInitialized=!0}}_validateGeometry(e){if(e.getAttribute(yb))throw new Error(`BatchedMesh: Geometry cannot use attribute "${yb}"`);const n=this.geometry;if(!!e.getIndex()!=!!n.getIndex())throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const r in n.attributes){if(r===yb)continue;if(!e.hasAttribute(r))throw new Error(`BatchedMesh: Added geometry missing "${r}". All geometries must have consistent attributes.`);const a=e.getAttribute(r),s=n.getAttribute(r);if(a.itemSize!==s.itemSize||a.normalized!==s.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Bl);const e=this._geometryCount,n=this.boundingBox,r=this._active;n.makeEmpty();for(let a=0;a=this._maxGeometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");const a={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let s=null;const o=this._reservedRanges,l=this._drawRanges,c=this._bounds;this._geometryCount!==0&&(s=o[o.length-1]),n===-1?a.vertexCount=e.getAttribute("position").count:a.vertexCount=n,s===null?a.vertexStart=0:a.vertexStart=s.vertexStart+s.vertexCount;const u=e.getIndex(),d=u!==null;if(d&&(r===-1?a.indexCount=u.count:a.indexCount=r,s===null?a.indexStart=0:a.indexStart=s.indexStart+s.indexCount),a.indexStart!==-1&&a.indexStart+a.indexCount>this._maxIndexCount||a.vertexStart+a.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const m=this._visibility,p=this._active,f=this._matricesTexture,y=this._matricesTexture.image.data;m.push(!0),p.push(!0);const v=this._geometryCount;this._geometryCount++,TPe.toArray(y,v*16),f.needsUpdate=!0,o.push(a),l.push({start:d?a.indexStart:a.vertexStart,count:-1}),c.push({boxInitialized:!1,box:new Bl,sphereInitialized:!1,sphere:new pu});const b=this.geometry.getAttribute(yb);for(let g=0;g=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(n);const r=this.geometry,a=r.getIndex()!==null,s=r.getIndex(),o=n.getIndex(),l=this._reservedRanges[e];if(a&&o.count>l.indexCount||n.attributes.position.count>l.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const c=l.vertexStart,u=l.vertexCount;for(const f in r.attributes){if(f===yb)continue;const y=n.getAttribute(f),v=r.getAttribute(f);APe(y,v,c);const b=y.itemSize;for(let g=y.count,_=u;g<_;g++){const N=c+g;for(let C=0;C=n.length||n[e]===!1?this:(n[e]=!1,this._visibilityChanged=!0,this)}getBoundingBoxAt(e,n){if(this._active[e]===!1)return this;const a=this._bounds[e],s=a.box,o=this.geometry;if(a.boxInitialized===!1){s.makeEmpty();const l=o.index,c=o.attributes.position,u=this._drawRanges[e];for(let d=u.start,m=u.start+u.count;d=o||r[e]===!1?this:(n.toArray(s,e*16),a.needsUpdate=!0,this)}getMatrixAt(e,n){const r=this._active,a=this._matricesTexture.image.data,s=this._geometryCount;return e>=s||r[e]===!1?null:n.fromArray(a,e*16)}setVisibleAt(e,n){const r=this._visibility,a=this._active,s=this._geometryCount;return e>=s||a[e]===!1||r[e]===n?this:(r[e]=n,this._visibilityChanged=!0,this)}getVisibleAt(e){const n=this._visibility,r=this._active,a=this._geometryCount;return e>=a||r[e]===!1?!1:n[e]}raycast(e,n){const r=this._visibility,a=this._active,s=this._drawRanges,o=this._geometryCount,l=this.matrixWorld,c=this.geometry;fs.material=this.material,fs.geometry.index=c.index,fs.geometry.attributes=c.attributes,fs.geometry.boundingBox===null&&(fs.geometry.boundingBox=new Bl),fs.geometry.boundingSphere===null&&(fs.geometry.boundingSphere=new pu);for(let u=0;u({...n})),this._reservedRanges=e._reservedRanges.map(n=>({...n})),this._visibility=e._visibility.slice(),this._active=e._active.slice(),this._bounds=e._bounds.map(n=>({boxInitialized:n.boxInitialized,box:n.box.clone(),sphereInitialized:n.sphereInitialized,sphere:n.sphere.clone()})),this._maxGeometryCount=e._maxGeometryCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.slice(),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this}onBeforeRender(e,n,r,a,s){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const o=a.getIndex(),l=o===null?1:o.array.BYTES_PER_ELEMENT,c=this._visibility,u=this._multiDrawStarts,d=this._multiDrawCounts,m=this._drawRanges,p=this.perObjectFrustumCulled;p&&(L$.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse).multiply(this.matrixWorld),o2.setFromProjectionMatrix(L$,e.isWebGPURenderer?R0:cu));let f=0;if(this.sortObjects){F$.copy(this.matrixWorld).invert(),mv.setFromMatrixPosition(r.matrixWorld).applyMatrix4(F$);for(let b=0,g=c.length;bc)continue;p.applyMatrix4(this.matrixWorld);const D=e.ray.origin.distanceTo(p);De.far||n.push({distance:D,point:m.clone().applyMatrix4(this.matrixWorld),index:N,face:null,faceIndex:null,object:this})}}else{const g=Math.max(0,o.start),_=Math.min(b.count,o.start+o.count);for(let N=g,C=_-1;Nc)continue;p.applyMatrix4(this.matrixWorld);const P=e.ray.origin.distanceTo(p);Pe.far||n.push({distance:P,point:m.clone().applyMatrix4(this.matrixWorld),index:N,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const n=this.geometry.morphAttributes,r=Object.keys(n);if(r.length>0){const a=n[r[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=a.length;so.stopPropagation()),this.domElement.addEventListener("keyup",o=>o.stopPropagation()),this.parent.children.push(this),this.parent.controllers.push(this),this.parent.$children.appendChild(this.domElement),this._listenCallback=this._listenCallback.bind(this),this.name(r)}name(e){return this._name=e,this.$name.textContent=e,this}onChange(e){return this._onChange=e,this}_callOnChange(){this.parent._callOnChange(this),this._onChange!==void 0&&this._onChange.call(this,this.getValue()),this._changed=!0}onFinishChange(e){return this._onFinishChange=e,this}_callOnFinishChange(){this._changed&&(this.parent._callOnFinishChange(this),this._onFinishChange!==void 0&&this._onFinishChange.call(this,this.getValue())),this._changed=!1}reset(){return this.setValue(this.initialValue),this._callOnFinishChange(),this}enable(e=!0){return this.disable(!e)}disable(e=!0){return e===this._disabled?this:(this._disabled=e,this.domElement.classList.toggle("disabled",e),this.$disable.toggleAttribute("disabled",e),this)}show(e=!0){return this._hidden=!e,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}options(e){const n=this.parent.add(this.object,this.property,e);return n.name(this._name),this.destroy(),n}min(e){return this}max(e){return this}step(e){return this}decimals(e){return this}listen(e=!0){return this._listening=e,this._listenCallbackID!==void 0&&(cancelAnimationFrame(this._listenCallbackID),this._listenCallbackID=void 0),this._listening&&this._listenCallback(),this}_listenCallback(){this._listenCallbackID=requestAnimationFrame(this._listenCallback);const e=this.save();e!==this._listenPrevValue&&this.updateDisplay(),this._listenPrevValue=e}getValue(){return this.object[this.property]}setValue(e){return this.getValue()!==e&&(this.object[this.property]=e,this._callOnChange(),this.updateDisplay()),this}updateDisplay(){return this}load(e){return this.setValue(e),this._callOnFinishChange(),this}save(){return this.getValue()}destroy(){this.listen(!1),this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.controllers.splice(this.parent.controllers.indexOf(this),1),this.parent.$children.removeChild(this.domElement)}}class BPe extends fu{constructor(e,n,r){super(e,n,r,"boolean","label"),this.$input=document.createElement("input"),this.$input.setAttribute("type","checkbox"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$widget.appendChild(this.$input),this.$input.addEventListener("change",()=>{this.setValue(this.$input.checked),this._callOnFinishChange()}),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.checked=this.getValue(),this}}function jR(t){let e,n;return(e=t.match(/(#|0x)?([a-f0-9]{6})/i))?n=e[2]:(e=t.match(/rgb\(\s*(\d*)\s*,\s*(\d*)\s*,\s*(\d*)\s*\)/))?n=parseInt(e[1]).toString(16).padStart(2,0)+parseInt(e[2]).toString(16).padStart(2,0)+parseInt(e[3]).toString(16).padStart(2,0):(e=t.match(/^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i))&&(n=e[1]+e[1]+e[2]+e[2]+e[3]+e[3]),n?"#"+n:!1}const HPe={isPrimitive:!0,match:t=>typeof t=="string",fromHexString:jR,toHexString:jR},L0={isPrimitive:!0,match:t=>typeof t=="number",fromHexString:t=>parseInt(t.substring(1),16),toHexString:t=>"#"+t.toString(16).padStart(6,0)},$Pe={isPrimitive:!1,match:t=>Array.isArray(t),fromHexString(t,e,n=1){const r=L0.fromHexString(t);e[0]=(r>>16&255)/255*n,e[1]=(r>>8&255)/255*n,e[2]=(r&255)/255*n},toHexString([t,e,n],r=1){r=255/r;const a=t*r<<16^e*r<<8^n*r<<0;return L0.toHexString(a)}},qPe={isPrimitive:!1,match:t=>Object(t)===t,fromHexString(t,e,n=1){const r=L0.fromHexString(t);e.r=(r>>16&255)/255*n,e.g=(r>>8&255)/255*n,e.b=(r&255)/255*n},toHexString({r:t,g:e,b:n},r=1){r=255/r;const a=t*r<<16^e*r<<8^n*r<<0;return L0.toHexString(a)}},VPe=[HPe,L0,$Pe,qPe];function GPe(t){return VPe.find(e=>e.match(t))}class WPe extends fu{constructor(e,n,r,a){super(e,n,r,"color"),this.$input=document.createElement("input"),this.$input.setAttribute("type","color"),this.$input.setAttribute("tabindex",-1),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$text=document.createElement("input"),this.$text.setAttribute("type","text"),this.$text.setAttribute("spellcheck","false"),this.$text.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$display.appendChild(this.$input),this.$widget.appendChild(this.$display),this.$widget.appendChild(this.$text),this._format=GPe(this.initialValue),this._rgbScale=a,this._initialValueHexString=this.save(),this._textFocused=!1,this.$input.addEventListener("input",()=>{this._setValueFromHexString(this.$input.value)}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$text.addEventListener("input",()=>{const s=jR(this.$text.value);s&&this._setValueFromHexString(s)}),this.$text.addEventListener("focus",()=>{this._textFocused=!0,this.$text.select()}),this.$text.addEventListener("blur",()=>{this._textFocused=!1,this.updateDisplay(),this._callOnFinishChange()}),this.$disable=this.$text,this.updateDisplay()}reset(){return this._setValueFromHexString(this._initialValueHexString),this}_setValueFromHexString(e){if(this._format.isPrimitive){const n=this._format.fromHexString(e);this.setValue(n)}else this._format.fromHexString(e,this.getValue(),this._rgbScale),this._callOnChange(),this.updateDisplay()}save(){return this._format.toHexString(this.getValue(),this._rgbScale)}load(e){return this._setValueFromHexString(e),this._callOnFinishChange(),this}updateDisplay(){return this.$input.value=this._format.toHexString(this.getValue(),this._rgbScale),this._textFocused||(this.$text.value=this.$input.value.substring(1)),this.$display.style.backgroundColor=this.$input.value,this}}class m2 extends fu{constructor(e,n,r){super(e,n,r,"function"),this.$button=document.createElement("button"),this.$button.appendChild(this.$name),this.$widget.appendChild(this.$button),this.$button.addEventListener("click",a=>{a.preventDefault(),this.getValue().call(this.object),this._callOnChange()}),this.$button.addEventListener("touchstart",()=>{},{passive:!0}),this.$disable=this.$button}}class KPe extends fu{constructor(e,n,r,a,s,o){super(e,n,r,"number"),this._initInput(),this.min(a),this.max(s);const l=o!==void 0;this.step(l?o:this._getImplicitStep(),l),this.updateDisplay()}decimals(e){return this._decimals=e,this.updateDisplay(),this}min(e){return this._min=e,this._onUpdateMinMax(),this}max(e){return this._max=e,this._onUpdateMinMax(),this}step(e,n=!0){return this._step=e,this._stepExplicit=n,this}updateDisplay(){const e=this.getValue();if(this._hasSlider){let n=(e-this._min)/(this._max-this._min);n=Math.max(0,Math.min(n,1)),this.$fill.style.width=n*100+"%"}return this._inputFocused||(this.$input.value=this._decimals===void 0?e:e.toFixed(this._decimals)),this}_initInput(){this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("aria-labelledby",this.$name.id),window.matchMedia("(pointer: coarse)").matches&&(this.$input.setAttribute("type","number"),this.$input.setAttribute("step","any")),this.$widget.appendChild(this.$input),this.$disable=this.$input;const n=()=>{let _=parseFloat(this.$input.value);isNaN(_)||(this._stepExplicit&&(_=this._snap(_)),this.setValue(this._clamp(_)))},r=_=>{const N=parseFloat(this.$input.value);isNaN(N)||(this._snapClampSetValue(N+_),this.$input.value=this.getValue())},a=_=>{_.key==="Enter"&&this.$input.blur(),_.code==="ArrowUp"&&(_.preventDefault(),r(this._step*this._arrowKeyMultiplier(_))),_.code==="ArrowDown"&&(_.preventDefault(),r(this._step*this._arrowKeyMultiplier(_)*-1))},s=_=>{this._inputFocused&&(_.preventDefault(),r(this._step*this._normalizeMouseWheel(_)))};let o=!1,l,c,u,d,m;const p=5,f=_=>{l=_.clientX,c=u=_.clientY,o=!0,d=this.getValue(),m=0,window.addEventListener("mousemove",y),window.addEventListener("mouseup",v)},y=_=>{if(o){const N=_.clientX-l,C=_.clientY-c;Math.abs(C)>p?(_.preventDefault(),this.$input.blur(),o=!1,this._setDraggingStyle(!0,"vertical")):Math.abs(N)>p&&v()}if(!o){const N=_.clientY-u;m-=N*this._step*this._arrowKeyMultiplier(_),d+m>this._max?m=this._max-d:d+m{this._setDraggingStyle(!1,"vertical"),this._callOnFinishChange(),window.removeEventListener("mousemove",y),window.removeEventListener("mouseup",v)},b=()=>{this._inputFocused=!0},g=()=>{this._inputFocused=!1,this.updateDisplay(),this._callOnFinishChange()};this.$input.addEventListener("input",n),this.$input.addEventListener("keydown",a),this.$input.addEventListener("wheel",s,{passive:!1}),this.$input.addEventListener("mousedown",f),this.$input.addEventListener("focus",b),this.$input.addEventListener("blur",g)}_initSlider(){this._hasSlider=!0,this.$slider=document.createElement("div"),this.$slider.classList.add("slider"),this.$fill=document.createElement("div"),this.$fill.classList.add("fill"),this.$slider.appendChild(this.$fill),this.$widget.insertBefore(this.$slider,this.$input),this.domElement.classList.add("hasSlider");const e=(g,_,N,C,k)=>(g-_)/(N-_)*(k-C)+C,n=g=>{const _=this.$slider.getBoundingClientRect();let N=e(g,_.left,_.right,this._min,this._max);this._snapClampSetValue(N)},r=g=>{this._setDraggingStyle(!0),n(g.clientX),window.addEventListener("mousemove",a),window.addEventListener("mouseup",s)},a=g=>{n(g.clientX)},s=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",s)};let o=!1,l,c;const u=g=>{g.preventDefault(),this._setDraggingStyle(!0),n(g.touches[0].clientX),o=!1},d=g=>{g.touches.length>1||(this._hasScrollBar?(l=g.touches[0].clientX,c=g.touches[0].clientY,o=!0):u(g),window.addEventListener("touchmove",m,{passive:!1}),window.addEventListener("touchend",p))},m=g=>{if(o){const _=g.touches[0].clientX-l,N=g.touches[0].clientY-c;Math.abs(_)>Math.abs(N)?u(g):(window.removeEventListener("touchmove",m),window.removeEventListener("touchend",p))}else g.preventDefault(),n(g.touches[0].clientX)},p=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("touchmove",m),window.removeEventListener("touchend",p)},f=this._callOnFinishChange.bind(this),y=400;let v;const b=g=>{if(Math.abs(g.deltaX)this._max&&(e=this._max),e}_snapClampSetValue(e){this.setValue(this._clamp(this._snap(e)))}get _hasScrollBar(){const e=this.parent.root.$children;return e.scrollHeight>e.clientHeight}get _hasMin(){return this._min!==void 0}get _hasMax(){return this._max!==void 0}}class YPe extends fu{constructor(e,n,r,a){super(e,n,r,"option"),this.$select=document.createElement("select"),this.$select.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$select.addEventListener("change",()=>{this.setValue(this._values[this.$select.selectedIndex]),this._callOnFinishChange()}),this.$select.addEventListener("focus",()=>{this.$display.classList.add("focus")}),this.$select.addEventListener("blur",()=>{this.$display.classList.remove("focus")}),this.$widget.appendChild(this.$select),this.$widget.appendChild(this.$display),this.$disable=this.$select,this.options(a)}options(e){return this._values=Array.isArray(e)?e:Object.values(e),this._names=Array.isArray(e)?e:Object.keys(e),this.$select.replaceChildren(),this._names.forEach(n=>{const r=document.createElement("option");r.textContent=n,this.$select.appendChild(r)}),this.updateDisplay(),this}updateDisplay(){const e=this.getValue(),n=this._values.indexOf(e);return this.$select.selectedIndex=n,this.$display.textContent=n===-1?e:this._names[n],this}}class XPe extends fu{constructor(e,n,r){super(e,n,r,"string"),this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("spellcheck","false"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$input.addEventListener("input",()=>{this.setValue(this.$input.value)}),this.$input.addEventListener("keydown",a=>{a.code==="Enter"&&this.$input.blur()}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$widget.appendChild(this.$input),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.value=this.getValue(),this}}const QPe=`.lil-gui { +}`;function dPe(t,e,n){let r=new wT;const a=new Fn,s=new Fn,o=new qr,l=new oPe({depthPacking:W1e}),c=new lPe,u={},d=n.maxTextureSize,m={[Hh]:So,[So]:Hh,[yd]:yd},p=new $h({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Fn},radius:{value:4}},vertexShader:cPe,fragmentShader:uPe}),f=p.clone();f.defines.HORIZONTAL_PASS=1;const y=new _s;y.setAttribute("position",new el(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Sc(y,p),b=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=nZ;let g=this.type;this.render=function(k,P,T){if(b.enabled===!1||b.autoUpdate===!1&&b.needsUpdate===!1||k.length===0)return;const D=t.getRenderTarget(),A=t.getActiveCubeFace(),R=t.getActiveMipmapLevel(),G=t.state;G.setBlending(Eh),G.buffers.color.setClear(1,1,1,1),G.buffers.depth.setTest(!0),G.setScissorTest(!1);const z=g!==fd&&this.type===fd,Z=g===fd&&this.type!==fd;for(let I=0,J=k.length;Id||a.y>d)&&(a.x>d&&(s.x=Math.floor(d/ue.x),a.x=s.x*ue.x,Y.mapSize.x=s.x),a.y>d&&(s.y=Math.floor(d/ue.y),a.y=s.y*ue.y,Y.mapSize.y=s.y)),Y.map===null||z===!0||Z===!0){const he=this.type!==fd?{minFilter:es,magFilter:es}:{};Y.map!==null&&Y.map.dispose(),Y.map=new Of(a.x,a.y,he),Y.map.texture.name=ae.name+".shadowMap",Y.camera.updateProjectionMatrix()}t.setRenderTarget(Y.map),t.clear();const de=Y.getViewportCount();for(let he=0;he0||P.map&&P.alphaTest>0){const G=A.uuid,z=P.uuid;let Z=u[G];Z===void 0&&(Z={},u[G]=Z);let I=Z[z];I===void 0&&(I=A.clone(),Z[z]=I),A=I}if(A.visible=P.visible,A.wireframe=P.wireframe,D===fd?A.side=P.shadowSide!==null?P.shadowSide:P.side:A.side=P.shadowSide!==null?P.shadowSide:m[P.side],A.alphaMap=P.alphaMap,A.alphaTest=P.alphaTest,A.map=P.map,A.clipShadows=P.clipShadows,A.clippingPlanes=P.clippingPlanes,A.clipIntersection=P.clipIntersection,A.displacementMap=P.displacementMap,A.displacementScale=P.displacementScale,A.displacementBias=P.displacementBias,A.wireframeLinewidth=P.wireframeLinewidth,A.linewidth=P.linewidth,T.isPointLight===!0&&A.isMeshDistanceMaterial===!0){const G=t.properties.get(A);G.light=T}return A}function C(k,P,T,D,A){if(k.visible===!1)return;if(k.layers.test(P.layers)&&(k.isMesh||k.isLine||k.isPoints)&&(k.castShadow||k.receiveShadow&&A===fd)&&(!k.frustumCulled||r.intersectsObject(k))){k.modelViewMatrix.multiplyMatrices(T.matrixWorldInverse,k.matrixWorld);const z=e.update(k),Z=k.material;if(Array.isArray(Z)){const I=z.groups;for(let J=0,ae=I.length;J=1):he.indexOf("OpenGL ES")!==-1&&(de=parseFloat(/^OpenGL ES (\d)/.exec(he)[1]),ue=de>=2);let V=null,ne={};const se=t.getParameter(t.SCISSOR_BOX),pe=t.getParameter(t.VIEWPORT),Te=new qr().fromArray(se),q=new qr().fromArray(pe);function X(Pe,Ke,Ve,ke){const Ce=new Uint8Array(4),$e=t.createTexture();t.bindTexture(Pe,$e),t.texParameteri(Pe,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(Pe,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let nt=0;nt"u"?!1:/OculusBrowser/g.test(navigator.userAgent),y=new WeakMap;let v;const b=new WeakMap;let g=!1;try{g=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function _(L,F){return g?new OffscreenCanvas(L,F):JN("canvas")}function N(L,F,te,ve){let fe=1;if((L.width>ve||L.height>ve)&&(fe=ve/Math.max(L.width,L.height)),fe<1||F===!0)if(typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&L instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&L instanceof ImageBitmap){const me=F?ZN:Math.floor,je=me(fe*L.width),we=me(fe*L.height);v===void 0&&(v=_(je,we));const Fe=te?_(je,we):v;return Fe.width=je,Fe.height=we,Fe.getContext("2d").drawImage(L,0,0,je,we),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+L.width+"x"+L.height+") to ("+je+"x"+we+")."),Fe}else return"data"in L&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+L.width+"x"+L.height+")."),L;return L}function C(L){return AR(L.width)&&AR(L.height)}function k(L){return l?!1:L.wrapS!==fc||L.wrapT!==fc||L.minFilter!==es&&L.minFilter!==Rl}function P(L,F){return L.generateMipmaps&&F&&L.minFilter!==es&&L.minFilter!==Rl}function T(L){t.generateMipmap(L)}function D(L,F,te,ve,fe=!1){if(l===!1)return F;if(L!==null){if(t[L]!==void 0)return t[L];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+L+"'")}let me=F;if(F===t.RED&&(te===t.FLOAT&&(me=t.R32F),te===t.HALF_FLOAT&&(me=t.R16F),te===t.UNSIGNED_BYTE&&(me=t.R8)),F===t.RED_INTEGER&&(te===t.UNSIGNED_BYTE&&(me=t.R8UI),te===t.UNSIGNED_SHORT&&(me=t.R16UI),te===t.UNSIGNED_INT&&(me=t.R32UI),te===t.BYTE&&(me=t.R8I),te===t.SHORT&&(me=t.R16I),te===t.INT&&(me=t.R32I)),F===t.RG&&(te===t.FLOAT&&(me=t.RG32F),te===t.HALF_FLOAT&&(me=t.RG16F),te===t.UNSIGNED_BYTE&&(me=t.RG8)),F===t.RGBA){const je=fe?YN:Hr.getTransfer(ve);te===t.FLOAT&&(me=t.RGBA32F),te===t.HALF_FLOAT&&(me=t.RGBA16F),te===t.UNSIGNED_BYTE&&(me=je===oi?t.SRGB8_ALPHA8:t.RGBA8),te===t.UNSIGNED_SHORT_4_4_4_4&&(me=t.RGBA4),te===t.UNSIGNED_SHORT_5_5_5_1&&(me=t.RGB5_A1)}return(me===t.R16F||me===t.R32F||me===t.RG16F||me===t.RG32F||me===t.RGBA16F||me===t.RGBA32F)&&e.get("EXT_color_buffer_float"),me}function A(L,F,te){return P(L,te)===!0||L.isFramebufferTexture&&L.minFilter!==es&&L.minFilter!==Rl?Math.log2(Math.max(F.width,F.height))+1:L.mipmaps!==void 0&&L.mipmaps.length>0?L.mipmaps.length:L.isCompressedTexture&&Array.isArray(L.image)?F.mipmaps.length:1}function R(L){return L===es||L===SH||L===jE?t.NEAREST:t.LINEAR}function G(L){const F=L.target;F.removeEventListener("dispose",G),Z(F),F.isVideoTexture&&y.delete(F)}function z(L){const F=L.target;F.removeEventListener("dispose",z),J(F)}function Z(L){const F=r.get(L);if(F.__webglInit===void 0)return;const te=L.source,ve=b.get(te);if(ve){const fe=ve[F.__cacheKey];fe.usedTimes--,fe.usedTimes===0&&I(L),Object.keys(ve).length===0&&b.delete(te)}r.remove(L)}function I(L){const F=r.get(L);t.deleteTexture(F.__webglTexture);const te=L.source,ve=b.get(te);delete ve[F.__cacheKey],o.memory.textures--}function J(L){const F=L.texture,te=r.get(L),ve=r.get(F);if(ve.__webglTexture!==void 0&&(t.deleteTexture(ve.__webglTexture),o.memory.textures--),L.depthTexture&&L.depthTexture.dispose(),L.isWebGLCubeRenderTarget)for(let fe=0;fe<6;fe++){if(Array.isArray(te.__webglFramebuffer[fe]))for(let me=0;me=c&&console.warn("THREE.WebGLTextures: Trying to use "+L+" texture units while this GPU supports only "+c),ae+=1,L}function de(L){const F=[];return F.push(L.wrapS),F.push(L.wrapT),F.push(L.wrapR||0),F.push(L.magFilter),F.push(L.minFilter),F.push(L.anisotropy),F.push(L.internalFormat),F.push(L.format),F.push(L.type),F.push(L.generateMipmaps),F.push(L.premultiplyAlpha),F.push(L.flipY),F.push(L.unpackAlignment),F.push(L.colorSpace),F.join()}function he(L,F){const te=r.get(L);if(L.isVideoTexture&&xe(L),L.isRenderTargetTexture===!1&&L.version>0&&te.__version!==L.version){const ve=L.image;if(ve===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(ve.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{E(te,L,F);return}}n.bindTexture(t.TEXTURE_2D,te.__webglTexture,t.TEXTURE0+F)}function V(L,F){const te=r.get(L);if(L.version>0&&te.__version!==L.version){E(te,L,F);return}n.bindTexture(t.TEXTURE_2D_ARRAY,te.__webglTexture,t.TEXTURE0+F)}function ne(L,F){const te=r.get(L);if(L.version>0&&te.__version!==L.version){E(te,L,F);return}n.bindTexture(t.TEXTURE_3D,te.__webglTexture,t.TEXTURE0+F)}function se(L,F){const te=r.get(L);if(L.version>0&&te.__version!==L.version){U(te,L,F);return}n.bindTexture(t.TEXTURE_CUBE_MAP,te.__webglTexture,t.TEXTURE0+F)}const pe={[NR]:t.REPEAT,[fc]:t.CLAMP_TO_EDGE,[kR]:t.MIRRORED_REPEAT},Te={[es]:t.NEAREST,[SH]:t.NEAREST_MIPMAP_NEAREST,[jE]:t.NEAREST_MIPMAP_LINEAR,[Rl]:t.LINEAR,[O1e]:t.LINEAR_MIPMAP_NEAREST,[j0]:t.LINEAR_MIPMAP_LINEAR},q={[Y1e]:t.NEVER,[tNe]:t.ALWAYS,[X1e]:t.LESS,[hZ]:t.LEQUAL,[Q1e]:t.EQUAL,[eNe]:t.GEQUAL,[Z1e]:t.GREATER,[J1e]:t.NOTEQUAL};function X(L,F,te){if(te?(t.texParameteri(L,t.TEXTURE_WRAP_S,pe[F.wrapS]),t.texParameteri(L,t.TEXTURE_WRAP_T,pe[F.wrapT]),(L===t.TEXTURE_3D||L===t.TEXTURE_2D_ARRAY)&&t.texParameteri(L,t.TEXTURE_WRAP_R,pe[F.wrapR]),t.texParameteri(L,t.TEXTURE_MAG_FILTER,Te[F.magFilter]),t.texParameteri(L,t.TEXTURE_MIN_FILTER,Te[F.minFilter])):(t.texParameteri(L,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(L,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),(L===t.TEXTURE_3D||L===t.TEXTURE_2D_ARRAY)&&t.texParameteri(L,t.TEXTURE_WRAP_R,t.CLAMP_TO_EDGE),(F.wrapS!==fc||F.wrapT!==fc)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),t.texParameteri(L,t.TEXTURE_MAG_FILTER,R(F.magFilter)),t.texParameteri(L,t.TEXTURE_MIN_FILTER,R(F.minFilter)),F.minFilter!==es&&F.minFilter!==Rl&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),F.compareFunction&&(t.texParameteri(L,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(L,t.TEXTURE_COMPARE_FUNC,q[F.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){const ve=e.get("EXT_texture_filter_anisotropic");if(F.magFilter===es||F.minFilter!==jE&&F.minFilter!==j0||F.type===Cd&&e.has("OES_texture_float_linear")===!1||l===!1&&F.type===D0&&e.has("OES_texture_half_float_linear")===!1)return;(F.anisotropy>1||r.get(F).__currentAnisotropy)&&(t.texParameterf(L,ve.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(F.anisotropy,a.getMaxAnisotropy())),r.get(F).__currentAnisotropy=F.anisotropy)}}function j(L,F){let te=!1;L.__webglInit===void 0&&(L.__webglInit=!0,F.addEventListener("dispose",G));const ve=F.source;let fe=b.get(ve);fe===void 0&&(fe={},b.set(ve,fe));const me=de(F);if(me!==L.__cacheKey){fe[me]===void 0&&(fe[me]={texture:t.createTexture(),usedTimes:0},o.memory.textures++,te=!0),fe[me].usedTimes++;const je=fe[L.__cacheKey];je!==void 0&&(fe[L.__cacheKey].usedTimes--,je.usedTimes===0&&I(F)),L.__cacheKey=me,L.__webglTexture=fe[me].texture}return te}function E(L,F,te){let ve=t.TEXTURE_2D;(F.isDataArrayTexture||F.isCompressedArrayTexture)&&(ve=t.TEXTURE_2D_ARRAY),F.isData3DTexture&&(ve=t.TEXTURE_3D);const fe=j(L,F),me=F.source;n.bindTexture(ve,L.__webglTexture,t.TEXTURE0+te);const je=r.get(me);if(me.version!==je.__version||fe===!0){n.activeTexture(t.TEXTURE0+te);const we=Hr.getPrimaries(Hr.workingColorSpace),Fe=F.colorSpace===Ll?null:Hr.getPrimaries(F.colorSpace),He=F.colorSpace===Ll||we===Fe?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,F.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,F.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,F.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,He);const Oe=k(F)&&C(F.image)===!1;let _e=N(F.image,Oe,!1,d);_e=oe(F,_e);const Ae=C(_e)||l,Be=s.convert(F.format,F.colorSpace);let Me=s.convert(F.type),Xe=D(F.internalFormat,Be,Me,F.colorSpace,F.isVideoTexture);X(ve,F,Ae);let ye;const We=F.mipmaps,Pe=l&&F.isVideoTexture!==!0&&Xe!==uZ,Ke=je.__version===void 0||fe===!0,Ve=A(F,_e,Ae);if(F.isDepthTexture)Xe=t.DEPTH_COMPONENT,l?F.type===Cd?Xe=t.DEPTH_COMPONENT32F:F.type===ph?Xe=t.DEPTH_COMPONENT24:F.type===hf?Xe=t.DEPTH24_STENCIL8:Xe=t.DEPTH_COMPONENT16:F.type===Cd&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),F.format===pf&&Xe===t.DEPTH_COMPONENT&&F.type!==yO&&F.type!==ph&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),F.type=ph,Me=s.convert(F.type)),F.format===wx&&Xe===t.DEPTH_COMPONENT&&(Xe=t.DEPTH_STENCIL,F.type!==hf&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),F.type=hf,Me=s.convert(F.type))),Ke&&(Pe?n.texStorage2D(t.TEXTURE_2D,1,Xe,_e.width,_e.height):n.texImage2D(t.TEXTURE_2D,0,Xe,_e.width,_e.height,0,Be,Me,null));else if(F.isDataTexture)if(We.length>0&&Ae){Pe&&Ke&&n.texStorage2D(t.TEXTURE_2D,Ve,Xe,We[0].width,We[0].height);for(let ke=0,Ce=We.length;ke>=1,Ce>>=1}}else if(We.length>0&&Ae){Pe&&Ke&&n.texStorage2D(t.TEXTURE_2D,Ve,Xe,We[0].width,We[0].height);for(let ke=0,Ce=We.length;ke0&&Ke++,n.texStorage2D(t.TEXTURE_CUBE_MAP,Ke,ye,_e[0].width,_e[0].height));for(let ke=0;ke<6;ke++)if(Oe){We?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,0,0,_e[ke].width,_e[ke].height,Me,Xe,_e[ke].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,ye,_e[ke].width,_e[ke].height,0,Me,Xe,_e[ke].data);for(let Ce=0;Ce>me),_e=Math.max(1,F.height>>me);fe===t.TEXTURE_3D||fe===t.TEXTURE_2D_ARRAY?n.texImage3D(fe,me,Fe,Oe,_e,F.depth,0,je,we,null):n.texImage2D(fe,me,Fe,Oe,_e,0,je,we,null)}n.bindFramebuffer(t.FRAMEBUFFER,L),be(F)?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,ve,fe,r.get(te).__webglTexture,0,ce(F)):(fe===t.TEXTURE_2D||fe>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&fe<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,ve,fe,r.get(te).__webglTexture,me),n.bindFramebuffer(t.FRAMEBUFFER,null)}function H(L,F,te){if(t.bindRenderbuffer(t.RENDERBUFFER,L),F.depthBuffer&&!F.stencilBuffer){let ve=l===!0?t.DEPTH_COMPONENT24:t.DEPTH_COMPONENT16;if(te||be(F)){const fe=F.depthTexture;fe&&fe.isDepthTexture&&(fe.type===Cd?ve=t.DEPTH_COMPONENT32F:fe.type===ph&&(ve=t.DEPTH_COMPONENT24));const me=ce(F);be(F)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,me,ve,F.width,F.height):t.renderbufferStorageMultisample(t.RENDERBUFFER,me,ve,F.width,F.height)}else t.renderbufferStorage(t.RENDERBUFFER,ve,F.width,F.height);t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,L)}else if(F.depthBuffer&&F.stencilBuffer){const ve=ce(F);te&&be(F)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,ve,t.DEPTH24_STENCIL8,F.width,F.height):be(F)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,ve,t.DEPTH24_STENCIL8,F.width,F.height):t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,F.width,F.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,L)}else{const ve=F.isWebGLMultipleRenderTargets===!0?F.texture:[F.texture];for(let fe=0;fe0){te.__webglFramebuffer[we]=[];for(let Fe=0;Fe0){te.__webglFramebuffer=[];for(let we=0;we0&&be(L)===!1){const we=me?F:[F];te.__webglMultisampledFramebuffer=t.createFramebuffer(),te.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,te.__webglMultisampledFramebuffer);for(let Fe=0;Fe0)for(let Fe=0;Fe0)for(let Fe=0;Fe0&&be(L)===!1){const F=L.isWebGLMultipleRenderTargets?L.texture:[L.texture],te=L.width,ve=L.height;let fe=t.COLOR_BUFFER_BIT;const me=[],je=L.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,we=r.get(L),Fe=L.isWebGLMultipleRenderTargets===!0;if(Fe)for(let He=0;He0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&F.__useRenderToTexture!==!1}function xe(L){const F=o.render.frame;y.get(L)!==F&&(y.set(L,F),L.update())}function oe(L,F){const te=L.colorSpace,ve=L.format,fe=L.type;return L.isCompressedTexture===!0||L.isVideoTexture===!0||L.format===TR||te!==Gd&&te!==Ll&&(Hr.getTransfer(te)===oi?l===!1?e.has("EXT_sRGB")===!0&&ve===Fl?(L.format=TR,L.minFilter=Rl,L.generateMipmaps=!1):F=gZ.sRGBToLinear(F):(ve!==Fl||fe!==Dh)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",te)),F}this.allocateTextureUnit=ue,this.resetTextureUnits=Y,this.setTexture2D=he,this.setTexture2DArray=V,this.setTexture3D=ne,this.setTextureCube=se,this.rebindTextures=$,this.setupRenderTarget=ee,this.updateRenderTargetMipmap=W,this.updateMultisampleRenderTarget=ie,this.setupDepthRenderbuffer=O,this.setupFrameBufferTexture=K,this.useMultisampledRTT=be}function pPe(t,e,n){const r=n.isWebGL2;function a(s,o=Ll){let l;const c=Hr.getTransfer(o);if(s===Dh)return t.UNSIGNED_BYTE;if(s===aZ)return t.UNSIGNED_SHORT_4_4_4_4;if(s===sZ)return t.UNSIGNED_SHORT_5_5_5_1;if(s===I1e)return t.BYTE;if(s===z1e)return t.SHORT;if(s===yO)return t.UNSIGNED_SHORT;if(s===iZ)return t.INT;if(s===ph)return t.UNSIGNED_INT;if(s===Cd)return t.FLOAT;if(s===D0)return r?t.HALF_FLOAT:(l=e.get("OES_texture_half_float"),l!==null?l.HALF_FLOAT_OES:null);if(s===U1e)return t.ALPHA;if(s===Fl)return t.RGBA;if(s===B1e)return t.LUMINANCE;if(s===H1e)return t.LUMINANCE_ALPHA;if(s===pf)return t.DEPTH_COMPONENT;if(s===wx)return t.DEPTH_STENCIL;if(s===TR)return l=e.get("EXT_sRGB"),l!==null?l.SRGB_ALPHA_EXT:null;if(s===$1e)return t.RED;if(s===oZ)return t.RED_INTEGER;if(s===q1e)return t.RG;if(s===lZ)return t.RG_INTEGER;if(s===cZ)return t.RGBA_INTEGER;if(s===DE||s===RE||s===FE||s===LE)if(c===oi)if(l=e.get("WEBGL_compressed_texture_s3tc_srgb"),l!==null){if(s===DE)return l.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(s===RE)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(s===FE)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(s===LE)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(l=e.get("WEBGL_compressed_texture_s3tc"),l!==null){if(s===DE)return l.COMPRESSED_RGB_S3TC_DXT1_EXT;if(s===RE)return l.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(s===FE)return l.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(s===LE)return l.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(s===_H||s===NH||s===kH||s===CH)if(l=e.get("WEBGL_compressed_texture_pvrtc"),l!==null){if(s===_H)return l.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(s===NH)return l.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(s===kH)return l.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(s===CH)return l.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(s===uZ)return l=e.get("WEBGL_compressed_texture_etc1"),l!==null?l.COMPRESSED_RGB_ETC1_WEBGL:null;if(s===TH||s===AH)if(l=e.get("WEBGL_compressed_texture_etc"),l!==null){if(s===TH)return c===oi?l.COMPRESSED_SRGB8_ETC2:l.COMPRESSED_RGB8_ETC2;if(s===AH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:l.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(s===PH||s===MH||s===EH||s===jH||s===DH||s===RH||s===FH||s===LH||s===OH||s===IH||s===zH||s===UH||s===BH||s===HH)if(l=e.get("WEBGL_compressed_texture_astc"),l!==null){if(s===PH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:l.COMPRESSED_RGBA_ASTC_4x4_KHR;if(s===MH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:l.COMPRESSED_RGBA_ASTC_5x4_KHR;if(s===EH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:l.COMPRESSED_RGBA_ASTC_5x5_KHR;if(s===jH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:l.COMPRESSED_RGBA_ASTC_6x5_KHR;if(s===DH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:l.COMPRESSED_RGBA_ASTC_6x6_KHR;if(s===RH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:l.COMPRESSED_RGBA_ASTC_8x5_KHR;if(s===FH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:l.COMPRESSED_RGBA_ASTC_8x6_KHR;if(s===LH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:l.COMPRESSED_RGBA_ASTC_8x8_KHR;if(s===OH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:l.COMPRESSED_RGBA_ASTC_10x5_KHR;if(s===IH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:l.COMPRESSED_RGBA_ASTC_10x6_KHR;if(s===zH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:l.COMPRESSED_RGBA_ASTC_10x8_KHR;if(s===UH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:l.COMPRESSED_RGBA_ASTC_10x10_KHR;if(s===BH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:l.COMPRESSED_RGBA_ASTC_12x10_KHR;if(s===HH)return c===oi?l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:l.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(s===OE||s===$H||s===qH)if(l=e.get("EXT_texture_compression_bptc"),l!==null){if(s===OE)return c===oi?l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:l.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(s===$H)return l.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(s===qH)return l.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(s===V1e||s===VH||s===GH||s===WH)if(l=e.get("EXT_texture_compression_rgtc"),l!==null){if(s===OE)return l.COMPRESSED_RED_RGTC1_EXT;if(s===VH)return l.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(s===GH)return l.COMPRESSED_RED_GREEN_RGTC2_EXT;if(s===WH)return l.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return s===hf?r?t.UNSIGNED_INT_24_8:(l=e.get("WEBGL_depth_texture"),l!==null?l.UNSIGNED_INT_24_8_WEBGL:null):t[s]!==void 0?t[s]:null}return{convert:a}}class fPe extends Ko{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class Rv extends Ws{constructor(){super(),this.isGroup=!0,this.type="Group"}}const gPe={type:"move"};class sj{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Rv,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Rv,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new at,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new at),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Rv,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new at,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new at),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const n=this._hand;if(n)for(const r of e.hand.values())this._getHandJoint(n,r)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,n,r){let a=null,s=null,o=null;const l=this._targetRay,c=this._grip,u=this._hand;if(e&&n.session.visibilityState!=="visible-blurred"){if(u&&e.hand){o=!0;for(const v of e.hand.values()){const b=n.getJointPose(v,r),g=this._getHandJoint(u,v);b!==null&&(g.matrix.fromArray(b.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=b.radius),g.visible=b!==null}const d=u.joints["index-finger-tip"],m=u.joints["thumb-tip"],p=d.position.distanceTo(m.position),f=.02,y=.005;u.inputState.pinching&&p>f+y?(u.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!u.inputState.pinching&&p<=f-y&&(u.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=n.getPose(e.gripSpace,r),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1));l!==null&&(a=n.getPose(e.targetRaySpace,r),a===null&&s!==null&&(a=s),a!==null&&(l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,a.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(a.linearVelocity)):l.hasLinearVelocity=!1,a.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(a.angularVelocity)):l.hasAngularVelocity=!1,this.dispatchEvent(gPe)))}return l!==null&&(l.visible=a!==null),c!==null&&(c.visible=s!==null),u!==null&&(u.visible=o!==null),this}_getHandJoint(e,n){if(e.joints[n.jointName]===void 0){const r=new Rv;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[n.jointName]=r,e.add(r)}return e.joints[n.jointName]}}class bPe extends ig{constructor(e,n){super();const r=this;let a=null,s=1,o=null,l="local-floor",c=1,u=null,d=null,m=null,p=null,f=null,y=null;const v=n.getContextAttributes();let b=null,g=null;const _=[],N=[],C=new Fn;let k=null;const P=new Ko;P.layers.enable(1),P.viewport=new qr;const T=new Ko;T.layers.enable(2),T.viewport=new qr;const D=[P,T],A=new fPe;A.layers.enable(1),A.layers.enable(2);let R=null,G=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(se){let pe=_[se];return pe===void 0&&(pe=new sj,_[se]=pe),pe.getTargetRaySpace()},this.getControllerGrip=function(se){let pe=_[se];return pe===void 0&&(pe=new sj,_[se]=pe),pe.getGripSpace()},this.getHand=function(se){let pe=_[se];return pe===void 0&&(pe=new sj,_[se]=pe),pe.getHandSpace()};function z(se){const pe=N.indexOf(se.inputSource);if(pe===-1)return;const Te=_[pe];Te!==void 0&&(Te.update(se.inputSource,se.frame,u||o),Te.dispatchEvent({type:se.type,data:se.inputSource}))}function Z(){a.removeEventListener("select",z),a.removeEventListener("selectstart",z),a.removeEventListener("selectend",z),a.removeEventListener("squeeze",z),a.removeEventListener("squeezestart",z),a.removeEventListener("squeezeend",z),a.removeEventListener("end",Z),a.removeEventListener("inputsourceschange",I);for(let se=0;se<_.length;se++){const pe=N[se];pe!==null&&(N[se]=null,_[se].disconnect(pe))}R=null,G=null,e.setRenderTarget(b),f=null,p=null,m=null,a=null,g=null,ne.stop(),r.isPresenting=!1,e.setPixelRatio(k),e.setSize(C.width,C.height,!1),r.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(se){s=se,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(se){l=se,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return u||o},this.setReferenceSpace=function(se){u=se},this.getBaseLayer=function(){return p!==null?p:f},this.getBinding=function(){return m},this.getFrame=function(){return y},this.getSession=function(){return a},this.setSession=async function(se){if(a=se,a!==null){if(b=e.getRenderTarget(),a.addEventListener("select",z),a.addEventListener("selectstart",z),a.addEventListener("selectend",z),a.addEventListener("squeeze",z),a.addEventListener("squeezestart",z),a.addEventListener("squeezeend",z),a.addEventListener("end",Z),a.addEventListener("inputsourceschange",I),v.xrCompatible!==!0&&await n.makeXRCompatible(),k=e.getPixelRatio(),e.getSize(C),a.renderState.layers===void 0||e.capabilities.isWebGL2===!1){const pe={antialias:a.renderState.layers===void 0?v.antialias:!0,alpha:!0,depth:v.depth,stencil:v.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(a,n,pe),a.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),g=new Of(f.framebufferWidth,f.framebufferHeight,{format:Fl,type:Dh,colorSpace:e.outputColorSpace,stencilBuffer:v.stencil})}else{let pe=null,Te=null,q=null;v.depth&&(q=v.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,pe=v.stencil?wx:pf,Te=v.stencil?hf:ph);const X={colorFormat:n.RGBA8,depthFormat:q,scaleFactor:s};m=new XRWebGLBinding(a,n),p=m.createProjectionLayer(X),a.updateRenderState({layers:[p]}),e.setPixelRatio(1),e.setSize(p.textureWidth,p.textureHeight,!1),g=new Of(p.textureWidth,p.textureHeight,{format:Fl,type:Dh,depthTexture:new AZ(p.textureWidth,p.textureHeight,Te,void 0,void 0,void 0,void 0,void 0,void 0,pe),stencilBuffer:v.stencil,colorSpace:e.outputColorSpace,samples:v.antialias?4:0});const j=e.properties.get(g);j.__ignoreDepthValues=p.ignoreDepthValues}g.isXRRenderTarget=!0,this.setFoveation(c),u=null,o=await a.requestReferenceSpace(l),ne.setContext(a),ne.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(a!==null)return a.environmentBlendMode};function I(se){for(let pe=0;pe=0&&(N[q]=null,_[q].disconnect(Te))}for(let pe=0;pe=N.length){N.push(Te),q=j;break}else if(N[j]===null){N[j]=Te,q=j;break}if(q===-1)break}const X=_[q];X&&X.connect(Te)}}const J=new at,ae=new at;function Y(se,pe,Te){J.setFromMatrixPosition(pe.matrixWorld),ae.setFromMatrixPosition(Te.matrixWorld);const q=J.distanceTo(ae),X=pe.projectionMatrix.elements,j=Te.projectionMatrix.elements,E=X[14]/(X[10]-1),U=X[14]/(X[10]+1),K=(X[9]+1)/X[5],H=(X[9]-1)/X[5],re=(X[8]-1)/X[0],O=(j[8]+1)/j[0],$=E*re,ee=E*O,W=q/(-re+O),ie=W*-re;pe.matrixWorld.decompose(se.position,se.quaternion,se.scale),se.translateX(ie),se.translateZ(W),se.matrixWorld.compose(se.position,se.quaternion,se.scale),se.matrixWorldInverse.copy(se.matrixWorld).invert();const ce=E+W,be=U+W,xe=$-ie,oe=ee+(q-ie),L=K*U/be*ce,F=H*U/be*ce;se.projectionMatrix.makePerspective(xe,oe,L,F,ce,be),se.projectionMatrixInverse.copy(se.projectionMatrix).invert()}function ue(se,pe){pe===null?se.matrixWorld.copy(se.matrix):se.matrixWorld.multiplyMatrices(pe.matrixWorld,se.matrix),se.matrixWorldInverse.copy(se.matrixWorld).invert()}this.updateCamera=function(se){if(a===null)return;A.near=T.near=P.near=se.near,A.far=T.far=P.far=se.far,(R!==A.near||G!==A.far)&&(a.updateRenderState({depthNear:A.near,depthFar:A.far}),R=A.near,G=A.far);const pe=se.parent,Te=A.cameras;ue(A,pe);for(let q=0;q0&&(b.alphaTest.value=g.alphaTest);const _=e.get(g).envMap;if(_&&(b.envMap.value=_,b.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,b.reflectivity.value=g.reflectivity,b.ior.value=g.ior,b.refractionRatio.value=g.refractionRatio),g.lightMap){b.lightMap.value=g.lightMap;const N=t._useLegacyLights===!0?Math.PI:1;b.lightMapIntensity.value=g.lightMapIntensity*N,n(g.lightMap,b.lightMapTransform)}g.aoMap&&(b.aoMap.value=g.aoMap,b.aoMapIntensity.value=g.aoMapIntensity,n(g.aoMap,b.aoMapTransform))}function o(b,g){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,g.map&&(b.map.value=g.map,n(g.map,b.mapTransform))}function l(b,g){b.dashSize.value=g.dashSize,b.totalSize.value=g.dashSize+g.gapSize,b.scale.value=g.scale}function c(b,g,_,N){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,b.size.value=g.size*_,b.scale.value=N*.5,g.map&&(b.map.value=g.map,n(g.map,b.uvTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,n(g.alphaMap,b.alphaMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest)}function u(b,g){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,b.rotation.value=g.rotation,g.map&&(b.map.value=g.map,n(g.map,b.mapTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,n(g.alphaMap,b.alphaMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest)}function d(b,g){b.specular.value.copy(g.specular),b.shininess.value=Math.max(g.shininess,1e-4)}function m(b,g){g.gradientMap&&(b.gradientMap.value=g.gradientMap)}function p(b,g){b.metalness.value=g.metalness,g.metalnessMap&&(b.metalnessMap.value=g.metalnessMap,n(g.metalnessMap,b.metalnessMapTransform)),b.roughness.value=g.roughness,g.roughnessMap&&(b.roughnessMap.value=g.roughnessMap,n(g.roughnessMap,b.roughnessMapTransform)),e.get(g).envMap&&(b.envMapIntensity.value=g.envMapIntensity)}function f(b,g,_){b.ior.value=g.ior,g.sheen>0&&(b.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),b.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(b.sheenColorMap.value=g.sheenColorMap,n(g.sheenColorMap,b.sheenColorMapTransform)),g.sheenRoughnessMap&&(b.sheenRoughnessMap.value=g.sheenRoughnessMap,n(g.sheenRoughnessMap,b.sheenRoughnessMapTransform))),g.clearcoat>0&&(b.clearcoat.value=g.clearcoat,b.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(b.clearcoatMap.value=g.clearcoatMap,n(g.clearcoatMap,b.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(b.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,n(g.clearcoatRoughnessMap,b.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(b.clearcoatNormalMap.value=g.clearcoatNormalMap,n(g.clearcoatNormalMap,b.clearcoatNormalMapTransform),b.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===So&&b.clearcoatNormalScale.value.negate())),g.iridescence>0&&(b.iridescence.value=g.iridescence,b.iridescenceIOR.value=g.iridescenceIOR,b.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],b.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(b.iridescenceMap.value=g.iridescenceMap,n(g.iridescenceMap,b.iridescenceMapTransform)),g.iridescenceThicknessMap&&(b.iridescenceThicknessMap.value=g.iridescenceThicknessMap,n(g.iridescenceThicknessMap,b.iridescenceThicknessMapTransform))),g.transmission>0&&(b.transmission.value=g.transmission,b.transmissionSamplerMap.value=_.texture,b.transmissionSamplerSize.value.set(_.width,_.height),g.transmissionMap&&(b.transmissionMap.value=g.transmissionMap,n(g.transmissionMap,b.transmissionMapTransform)),b.thickness.value=g.thickness,g.thicknessMap&&(b.thicknessMap.value=g.thicknessMap,n(g.thicknessMap,b.thicknessMapTransform)),b.attenuationDistance.value=g.attenuationDistance,b.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(b.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(b.anisotropyMap.value=g.anisotropyMap,n(g.anisotropyMap,b.anisotropyMapTransform))),b.specularIntensity.value=g.specularIntensity,b.specularColor.value.copy(g.specularColor),g.specularColorMap&&(b.specularColorMap.value=g.specularColorMap,n(g.specularColorMap,b.specularColorMapTransform)),g.specularIntensityMap&&(b.specularIntensityMap.value=g.specularIntensityMap,n(g.specularIntensityMap,b.specularIntensityMapTransform))}function y(b,g){g.matcap&&(b.matcap.value=g.matcap)}function v(b,g){const _=e.get(g).light;b.referencePosition.value.setFromMatrixPosition(_.matrixWorld),b.nearDistance.value=_.shadow.camera.near,b.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:a}}function yPe(t,e,n,r){let a={},s={},o=[];const l=n.isWebGL2?t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS):0;function c(_,N){const C=N.program;r.uniformBlockBinding(_,C)}function u(_,N){let C=a[_.id];C===void 0&&(y(_),C=d(_),a[_.id]=C,_.addEventListener("dispose",b));const k=N.program;r.updateUBOMapping(_,k);const P=e.render.frame;s[_.id]!==P&&(p(_),s[_.id]=P)}function d(_){const N=m();_.__bindingPointIndex=N;const C=t.createBuffer(),k=_.__size,P=_.usage;return t.bindBuffer(t.UNIFORM_BUFFER,C),t.bufferData(t.UNIFORM_BUFFER,k,P),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,N,C),C}function m(){for(let _=0;_0){P=C%k;const z=k-P;P!==0&&z-R.boundary<0&&(C+=k-P,A.__offset=C)}C+=R.storage}return P=C%k,P>0&&(C+=k-P),_.__size=C,_.__cache={},this}function v(_){const N={boundary:0,storage:0};return typeof _=="number"?(N.boundary=4,N.storage=4):_.isVector2?(N.boundary=8,N.storage=8):_.isVector3||_.isColor?(N.boundary=16,N.storage=12):_.isVector4?(N.boundary=16,N.storage=16):_.isMatrix3?(N.boundary=48,N.storage=48):_.isMatrix4?(N.boundary=64,N.storage=64):_.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",_),N}function b(_){const N=_.target;N.removeEventListener("dispose",b);const C=o.indexOf(N.__bindingPointIndex);o.splice(C,1),t.deleteBuffer(a[N.id]),delete a[N.id],delete s[N.id]}function g(){for(const _ in a)t.deleteBuffer(a[_]);o=[],a={},s={}}return{bind:c,update:u,dispose:g}}class MR{constructor(e={}){const{canvas:n=gNe(),context:r=null,depth:a=!0,stencil:s=!0,alpha:o=!1,antialias:l=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:u=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:m=!1}=e;this.isWebGLRenderer=!0;let p;r!==null?p=r.getContextAttributes().alpha:p=o;const f=new Uint32Array(4),y=new Int32Array(4);let v=null,b=null;const g=[],_=[];this.domElement=n,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=ts,this._useLegacyLights=!1,this.toneMapping=jh,this.toneMappingExposure=1;const N=this;let C=!1,k=0,P=0,T=null,D=-1,A=null;const R=new qr,G=new qr;let z=null;const Z=new vn(0);let I=0,J=n.width,ae=n.height,Y=1,ue=null,de=null;const he=new qr(0,0,J,ae),V=new qr(0,0,J,ae);let ne=!1;const se=new wT;let pe=!1,Te=!1,q=null;const X=new ri,j=new Fn,E=new at,U={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function K(){return T===null?Y:1}let H=r;function re(De,ot){for(let st=0;st{function ct(){if(Ze.forEach(function(le){ie.get(le).currentProgram.isReady()&&Ze.delete(le)}),Ze.size===0){Ee(De);return}setTimeout(ct,10)}O.get("KHR_parallel_shader_compile")!==null?ct():setTimeout(ct,10)})};let nt=null;function xt(De){nt&&nt(De)}function vt(){qe.stop()}function mt(){qe.start()}const qe=new TZ;qe.setAnimationLoop(xt),typeof self<"u"&&qe.setContext(self),this.setAnimationLoop=function(De){nt=De,ye.setAnimationLoop(De),De===null?qe.stop():qe.start()},ye.addEventListener("sessionstart",vt),ye.addEventListener("sessionend",mt),this.render=function(De,ot){if(ot!==void 0&&ot.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(C===!0)return;De.matrixWorldAutoUpdate===!0&&De.updateMatrixWorld(),ot.parent===null&&ot.matrixWorldAutoUpdate===!0&&ot.updateMatrixWorld(),ye.enabled===!0&&ye.isPresenting===!0&&(ye.cameraAutoUpdate===!0&&ye.updateCamera(ot),ot=ye.getCamera()),De.isScene===!0&&De.onBeforeRender(N,De,ot,T),b=me.get(De,_.length),b.init(),_.push(b),X.multiplyMatrices(ot.projectionMatrix,ot.matrixWorldInverse),se.setFromProjectionMatrix(X),Te=this.localClippingEnabled,pe=je.init(this.clippingPlanes,Te),v=fe.get(De,g.length),v.init(),g.push(v),Nt(De,ot,0,N.sortObjects),v.finish(),N.sortObjects===!0&&v.sort(ue,de),this.info.render.frame++,pe===!0&&je.beginShadows();const st=b.state.shadowsArray;if(we.render(st,De,ot),pe===!0&&je.endShadows(),this.info.autoReset===!0&&this.info.reset(),Fe.render(v,De),b.setupLights(N._useLegacyLights),ot.isArrayCamera){const Ze=ot.cameras;for(let Ee=0,ct=Ze.length;Ee0?b=_[_.length-1]:b=null,g.pop(),g.length>0?v=g[g.length-1]:v=null};function Nt(De,ot,st,Ze){if(De.visible===!1)return;if(De.layers.test(ot.layers)){if(De.isGroup)st=De.renderOrder;else if(De.isLOD)De.autoUpdate===!0&&De.update(ot);else if(De.isLight)b.pushLight(De),De.castShadow&&b.pushShadow(De);else if(De.isSprite){if(!De.frustumCulled||se.intersectsSprite(De)){Ze&&E.setFromMatrixPosition(De.matrixWorld).applyMatrix4(X);const le=F.update(De),Le=De.material;Le.visible&&v.push(De,le,Le,st,E.z,null)}}else if((De.isMesh||De.isLine||De.isPoints)&&(!De.frustumCulled||se.intersectsObject(De))){const le=F.update(De),Le=De.material;if(Ze&&(De.boundingSphere!==void 0?(De.boundingSphere===null&&De.computeBoundingSphere(),E.copy(De.boundingSphere.center)):(le.boundingSphere===null&&le.computeBoundingSphere(),E.copy(le.boundingSphere.center)),E.applyMatrix4(De.matrixWorld).applyMatrix4(X)),Array.isArray(Le)){const Ye=le.groups;for(let Ge=0,Ie=Ye.length;Ge0&&rt(Ee,ct,ot,st),Ze&&ee.viewport(R.copy(Ze)),Ee.length>0&&Rt(Ee,ot,st),ct.length>0&&Rt(ct,ot,st),le.length>0&&Rt(le,ot,st),ee.buffers.depth.setTest(!0),ee.buffers.depth.setMask(!0),ee.buffers.color.setMask(!0),ee.setPolygonOffset(!1)}function rt(De,ot,st,Ze){if((st.isScene===!0?st.overrideMaterial:null)!==null)return;const ct=$.isWebGL2;q===null&&(q=new Of(1,1,{generateMipmaps:!0,type:O.has("EXT_color_buffer_half_float")?D0:Dh,minFilter:j0,samples:ct?4:0})),N.getDrawingBufferSize(j),ct?q.setSize(j.x,j.y):q.setSize(ZN(j.x),ZN(j.y));const le=N.getRenderTarget();N.setRenderTarget(q),N.getClearColor(Z),I=N.getClearAlpha(),I<1&&N.setClearColor(16777215,.5),N.clear();const Le=N.toneMapping;N.toneMapping=jh,Rt(De,st,Ze),ce.updateMultisampleRenderTarget(q),ce.updateRenderTargetMipmap(q);let Ye=!1;for(let Ge=0,Ie=ot.length;Ge0),pt=!!st.morphAttributes.position,dt=!!st.morphAttributes.normal,Je=!!st.morphAttributes.color;let Tt=jh;Ze.toneMapped&&(T===null||T.isXRRenderTarget===!0)&&(Tt=N.toneMapping);const zt=st.morphAttributes.position||st.morphAttributes.normal||st.morphAttributes.color,Ut=zt!==void 0?zt.length:0,It=ie.get(Ze),cn=b.state.lights;if(pe===!0&&(Te===!0||De!==A)){const Gr=De===A&&Ze.id===D;je.setState(Ze,De,Gr)}let Xt=!1;Ze.version===It.__version?(It.needsLights&&It.lightsStateVersion!==cn.state.version||It.outputColorSpace!==Le||Ee.isBatchedMesh&&It.batching===!1||!Ee.isBatchedMesh&&It.batching===!0||Ee.isInstancedMesh&&It.instancing===!1||!Ee.isInstancedMesh&&It.instancing===!0||Ee.isSkinnedMesh&&It.skinning===!1||!Ee.isSkinnedMesh&&It.skinning===!0||Ee.isInstancedMesh&&It.instancingColor===!0&&Ee.instanceColor===null||Ee.isInstancedMesh&&It.instancingColor===!1&&Ee.instanceColor!==null||It.envMap!==Ye||Ze.fog===!0&&It.fog!==ct||It.numClippingPlanes!==void 0&&(It.numClippingPlanes!==je.numPlanes||It.numIntersection!==je.numIntersection)||It.vertexAlphas!==Ge||It.vertexTangents!==Ie||It.morphTargets!==pt||It.morphNormals!==dt||It.morphColors!==Je||It.toneMapping!==Tt||$.isWebGL2===!0&&It.morphTargetsCount!==Ut)&&(Xt=!0):(Xt=!0,It.__version=Ze.version);let tn=It.currentProgram;Xt===!0&&(tn=Kt(Ze,ot,Ee));let wn=!1,kn=!1,Jt=!1;const Sn=tn.getUniforms(),Tn=It.uniforms;if(ee.useProgram(tn.program)&&(wn=!0,kn=!0,Jt=!0),Ze.id!==D&&(D=Ze.id,kn=!0),wn||A!==De){Sn.setValue(H,"projectionMatrix",De.projectionMatrix),Sn.setValue(H,"viewMatrix",De.matrixWorldInverse);const Gr=Sn.map.cameraPosition;Gr!==void 0&&Gr.setValue(H,E.setFromMatrixPosition(De.matrixWorld)),$.logarithmicDepthBuffer&&Sn.setValue(H,"logDepthBufFC",2/(Math.log(De.far+1)/Math.LN2)),(Ze.isMeshPhongMaterial||Ze.isMeshToonMaterial||Ze.isMeshLambertMaterial||Ze.isMeshBasicMaterial||Ze.isMeshStandardMaterial||Ze.isShaderMaterial)&&Sn.setValue(H,"isOrthographic",De.isOrthographicCamera===!0),A!==De&&(A=De,kn=!0,Jt=!0)}if(Ee.isSkinnedMesh){Sn.setOptional(H,Ee,"bindMatrix"),Sn.setOptional(H,Ee,"bindMatrixInverse");const Gr=Ee.skeleton;Gr&&($.floatVertexTextures?(Gr.boneTexture===null&&Gr.computeBoneTexture(),Sn.setValue(H,"boneTexture",Gr.boneTexture,ce)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}Ee.isBatchedMesh&&(Sn.setOptional(H,Ee,"batchingTexture"),Sn.setValue(H,"batchingTexture",Ee._matricesTexture,ce));const ei=st.morphAttributes;if((ei.position!==void 0||ei.normal!==void 0||ei.color!==void 0&&$.isWebGL2===!0)&&He.update(Ee,st,tn),(kn||It.receiveShadow!==Ee.receiveShadow)&&(It.receiveShadow=Ee.receiveShadow,Sn.setValue(H,"receiveShadow",Ee.receiveShadow)),Ze.isMeshGouraudMaterial&&Ze.envMap!==null&&(Tn.envMap.value=Ye,Tn.flipEnvMap.value=Ye.isCubeTexture&&Ye.isRenderTargetTexture===!1?-1:1),kn&&(Sn.setValue(H,"toneMappingExposure",N.toneMappingExposure),It.needsLights&&Hn(Tn,Jt),ct&&Ze.fog===!0&&ve.refreshFogUniforms(Tn,ct),ve.refreshMaterialUniforms(Tn,Ze,Y,ae,q),dN.upload(H,Qt(It),Tn,ce)),Ze.isShaderMaterial&&Ze.uniformsNeedUpdate===!0&&(dN.upload(H,Qt(It),Tn,ce),Ze.uniformsNeedUpdate=!1),Ze.isSpriteMaterial&&Sn.setValue(H,"center",Ee.center),Sn.setValue(H,"modelViewMatrix",Ee.modelViewMatrix),Sn.setValue(H,"normalMatrix",Ee.normalMatrix),Sn.setValue(H,"modelMatrix",Ee.matrixWorld),Ze.isShaderMaterial||Ze.isRawShaderMaterial){const Gr=Ze.uniformsGroups;for(let lr=0,zi=Gr.length;lr0&&ce.useMultisampledRTT(De)===!1?Ee=ie.get(De).__webglMultisampledFramebuffer:Array.isArray(Ie)?Ee=Ie[st]:Ee=Ie,R.copy(De.viewport),G.copy(De.scissor),z=De.scissorTest}else R.copy(he).multiplyScalar(Y).floor(),G.copy(V).multiplyScalar(Y).floor(),z=ne;if(ee.bindFramebuffer(H.FRAMEBUFFER,Ee)&&$.drawBuffers&&Ze&&ee.drawBuffers(De,Ee),ee.viewport(R),ee.scissor(G),ee.setScissorTest(z),ct){const Ye=ie.get(De.texture);H.framebufferTexture2D(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_CUBE_MAP_POSITIVE_X+ot,Ye.__webglTexture,st)}else if(le){const Ye=ie.get(De.texture),Ge=ot||0;H.framebufferTextureLayer(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,Ye.__webglTexture,st||0,Ge)}D=-1},this.readRenderTargetPixels=function(De,ot,st,Ze,Ee,ct,le){if(!(De&&De.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Le=ie.get(De).__webglFramebuffer;if(De.isWebGLCubeRenderTarget&&le!==void 0&&(Le=Le[le]),Le){ee.bindFramebuffer(H.FRAMEBUFFER,Le);try{const Ye=De.texture,Ge=Ye.format,Ie=Ye.type;if(Ge!==Fl&&Ae.convert(Ge)!==H.getParameter(H.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const pt=Ie===D0&&(O.has("EXT_color_buffer_half_float")||$.isWebGL2&&O.has("EXT_color_buffer_float"));if(Ie!==Dh&&Ae.convert(Ie)!==H.getParameter(H.IMPLEMENTATION_COLOR_READ_TYPE)&&!(Ie===Cd&&($.isWebGL2||O.has("OES_texture_float")||O.has("WEBGL_color_buffer_float")))&&!pt){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}ot>=0&&ot<=De.width-Ze&&st>=0&&st<=De.height-Ee&&H.readPixels(ot,st,Ze,Ee,Ae.convert(Ge),Ae.convert(Ie),ct)}finally{const Ye=T!==null?ie.get(T).__webglFramebuffer:null;ee.bindFramebuffer(H.FRAMEBUFFER,Ye)}}},this.copyFramebufferToTexture=function(De,ot,st=0){const Ze=Math.pow(2,-st),Ee=Math.floor(ot.image.width*Ze),ct=Math.floor(ot.image.height*Ze);ce.setTexture2D(ot,0),H.copyTexSubImage2D(H.TEXTURE_2D,st,0,0,De.x,De.y,Ee,ct),ee.unbindTexture()},this.copyTextureToTexture=function(De,ot,st,Ze=0){const Ee=ot.image.width,ct=ot.image.height,le=Ae.convert(st.format),Le=Ae.convert(st.type);ce.setTexture2D(st,0),H.pixelStorei(H.UNPACK_FLIP_Y_WEBGL,st.flipY),H.pixelStorei(H.UNPACK_PREMULTIPLY_ALPHA_WEBGL,st.premultiplyAlpha),H.pixelStorei(H.UNPACK_ALIGNMENT,st.unpackAlignment),ot.isDataTexture?H.texSubImage2D(H.TEXTURE_2D,Ze,De.x,De.y,Ee,ct,le,Le,ot.image.data):ot.isCompressedTexture?H.compressedTexSubImage2D(H.TEXTURE_2D,Ze,De.x,De.y,ot.mipmaps[0].width,ot.mipmaps[0].height,le,ot.mipmaps[0].data):H.texSubImage2D(H.TEXTURE_2D,Ze,De.x,De.y,le,Le,ot.image),Ze===0&&st.generateMipmaps&&H.generateMipmap(H.TEXTURE_2D),ee.unbindTexture()},this.copyTextureToTexture3D=function(De,ot,st,Ze,Ee=0){if(N.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const ct=De.max.x-De.min.x+1,le=De.max.y-De.min.y+1,Le=De.max.z-De.min.z+1,Ye=Ae.convert(Ze.format),Ge=Ae.convert(Ze.type);let Ie;if(Ze.isData3DTexture)ce.setTexture3D(Ze,0),Ie=H.TEXTURE_3D;else if(Ze.isDataArrayTexture)ce.setTexture2DArray(Ze,0),Ie=H.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}H.pixelStorei(H.UNPACK_FLIP_Y_WEBGL,Ze.flipY),H.pixelStorei(H.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Ze.premultiplyAlpha),H.pixelStorei(H.UNPACK_ALIGNMENT,Ze.unpackAlignment);const pt=H.getParameter(H.UNPACK_ROW_LENGTH),dt=H.getParameter(H.UNPACK_IMAGE_HEIGHT),Je=H.getParameter(H.UNPACK_SKIP_PIXELS),Tt=H.getParameter(H.UNPACK_SKIP_ROWS),zt=H.getParameter(H.UNPACK_SKIP_IMAGES),Ut=st.isCompressedTexture?st.mipmaps[0]:st.image;H.pixelStorei(H.UNPACK_ROW_LENGTH,Ut.width),H.pixelStorei(H.UNPACK_IMAGE_HEIGHT,Ut.height),H.pixelStorei(H.UNPACK_SKIP_PIXELS,De.min.x),H.pixelStorei(H.UNPACK_SKIP_ROWS,De.min.y),H.pixelStorei(H.UNPACK_SKIP_IMAGES,De.min.z),st.isDataTexture||st.isData3DTexture?H.texSubImage3D(Ie,Ee,ot.x,ot.y,ot.z,ct,le,Le,Ye,Ge,Ut.data):st.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),H.compressedTexSubImage3D(Ie,Ee,ot.x,ot.y,ot.z,ct,le,Le,Ye,Ut.data)):H.texSubImage3D(Ie,Ee,ot.x,ot.y,ot.z,ct,le,Le,Ye,Ge,Ut),H.pixelStorei(H.UNPACK_ROW_LENGTH,pt),H.pixelStorei(H.UNPACK_IMAGE_HEIGHT,dt),H.pixelStorei(H.UNPACK_SKIP_PIXELS,Je),H.pixelStorei(H.UNPACK_SKIP_ROWS,Tt),H.pixelStorei(H.UNPACK_SKIP_IMAGES,zt),Ee===0&&Ze.generateMipmaps&&H.generateMipmap(Ie),ee.unbindTexture()},this.initTexture=function(De){De.isCubeTexture?ce.setTextureCube(De,0):De.isData3DTexture?ce.setTexture3D(De,0):De.isDataArrayTexture||De.isCompressedArrayTexture?ce.setTexture2DArray(De,0):ce.setTexture2D(De,0),ee.unbindTexture()},this.resetState=function(){k=0,P=0,T=null,ee.reset(),Be.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return cu}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const n=this.getContext();n.drawingBufferColorSpace=e===vO?"display-p3":"srgb",n.unpackColorSpace=Hr.workingColorSpace===vT?"display-p3":"srgb"}get physicallyCorrectLights(){return console.warn("THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead."),!this.useLegacyLights}set physicallyCorrectLights(e){console.warn("THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead."),this.useLegacyLights=!e}get outputEncoding(){return console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace===ts?ff:dZ}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===ff?ts:Gd}get useLegacyLights(){return console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights}set useLegacyLights(e){console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights=e}}class vPe extends MR{}vPe.prototype.isWebGL1Renderer=!0;class CO{constructor(e,n=1,r=1e3){this.isFog=!0,this.name="",this.color=new vn(e),this.near=n,this.far=r}clone(){return new CO(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class wPe extends Ws{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,n){return super.copy(e,n),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const n=super.toJSON(e);return this.fog!==null&&(n.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(n.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(n.object.backgroundIntensity=this.backgroundIntensity),n}}class SPe{constructor(e,n){this.isInterleavedBuffer=!0,this.array=e,this.stride=n,this.count=e!==void 0?e.length/n:0,this.usage=CR,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=Dd()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return console.warn('THREE.InterleavedBuffer: "updateRange" is deprecated and removed in r169. Use "addUpdateRange()" instead.'),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,n,r){e*=this.stride,r*=n.stride;for(let a=0,s=this.stride;a=r.length&&r.push({start:-1,count:-1,z:-1});const s=r[this.index];a.push(s),this.index++,s.start=e.start,s.count=e.count,s.z=n}reset(){this.list.length=0,this.index=0}}const yb="batchId",qm=new ri,F$=new ri,TPe=new ri,L$=new ri,oj=new wT,s1=new Bl,Dp=new pu,mv=new at,lj=new CPe,fs=new Sc,o1=[];function APe(t,e,n=0){const r=e.itemSize;if(t.isInterleavedBufferAttribute||t.array.constructor!==e.array.constructor){const a=t.count;for(let s=0;s65536?new Uint32Array(s):new Uint16Array(s);n.setIndex(new el(l,1))}const o=a>65536?new Uint32Array(r):new Uint16Array(r);n.setAttribute(yb,new el(o,1)),this._geometryInitialized=!0}}_validateGeometry(e){if(e.getAttribute(yb))throw new Error(`BatchedMesh: Geometry cannot use attribute "${yb}"`);const n=this.geometry;if(!!e.getIndex()!=!!n.getIndex())throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const r in n.attributes){if(r===yb)continue;if(!e.hasAttribute(r))throw new Error(`BatchedMesh: Added geometry missing "${r}". All geometries must have consistent attributes.`);const a=e.getAttribute(r),s=n.getAttribute(r);if(a.itemSize!==s.itemSize||a.normalized!==s.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Bl);const e=this._geometryCount,n=this.boundingBox,r=this._active;n.makeEmpty();for(let a=0;a=this._maxGeometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");const a={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let s=null;const o=this._reservedRanges,l=this._drawRanges,c=this._bounds;this._geometryCount!==0&&(s=o[o.length-1]),n===-1?a.vertexCount=e.getAttribute("position").count:a.vertexCount=n,s===null?a.vertexStart=0:a.vertexStart=s.vertexStart+s.vertexCount;const u=e.getIndex(),d=u!==null;if(d&&(r===-1?a.indexCount=u.count:a.indexCount=r,s===null?a.indexStart=0:a.indexStart=s.indexStart+s.indexCount),a.indexStart!==-1&&a.indexStart+a.indexCount>this._maxIndexCount||a.vertexStart+a.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const m=this._visibility,p=this._active,f=this._matricesTexture,y=this._matricesTexture.image.data;m.push(!0),p.push(!0);const v=this._geometryCount;this._geometryCount++,TPe.toArray(y,v*16),f.needsUpdate=!0,o.push(a),l.push({start:d?a.indexStart:a.vertexStart,count:-1}),c.push({boxInitialized:!1,box:new Bl,sphereInitialized:!1,sphere:new pu});const b=this.geometry.getAttribute(yb);for(let g=0;g=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(n);const r=this.geometry,a=r.getIndex()!==null,s=r.getIndex(),o=n.getIndex(),l=this._reservedRanges[e];if(a&&o.count>l.indexCount||n.attributes.position.count>l.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const c=l.vertexStart,u=l.vertexCount;for(const f in r.attributes){if(f===yb)continue;const y=n.getAttribute(f),v=r.getAttribute(f);APe(y,v,c);const b=y.itemSize;for(let g=y.count,_=u;g<_;g++){const N=c+g;for(let C=0;C=n.length||n[e]===!1?this:(n[e]=!1,this._visibilityChanged=!0,this)}getBoundingBoxAt(e,n){if(this._active[e]===!1)return this;const a=this._bounds[e],s=a.box,o=this.geometry;if(a.boxInitialized===!1){s.makeEmpty();const l=o.index,c=o.attributes.position,u=this._drawRanges[e];for(let d=u.start,m=u.start+u.count;d=o||r[e]===!1?this:(n.toArray(s,e*16),a.needsUpdate=!0,this)}getMatrixAt(e,n){const r=this._active,a=this._matricesTexture.image.data,s=this._geometryCount;return e>=s||r[e]===!1?null:n.fromArray(a,e*16)}setVisibleAt(e,n){const r=this._visibility,a=this._active,s=this._geometryCount;return e>=s||a[e]===!1||r[e]===n?this:(r[e]=n,this._visibilityChanged=!0,this)}getVisibleAt(e){const n=this._visibility,r=this._active,a=this._geometryCount;return e>=a||r[e]===!1?!1:n[e]}raycast(e,n){const r=this._visibility,a=this._active,s=this._drawRanges,o=this._geometryCount,l=this.matrixWorld,c=this.geometry;fs.material=this.material,fs.geometry.index=c.index,fs.geometry.attributes=c.attributes,fs.geometry.boundingBox===null&&(fs.geometry.boundingBox=new Bl),fs.geometry.boundingSphere===null&&(fs.geometry.boundingSphere=new pu);for(let u=0;u({...n})),this._reservedRanges=e._reservedRanges.map(n=>({...n})),this._visibility=e._visibility.slice(),this._active=e._active.slice(),this._bounds=e._bounds.map(n=>({boxInitialized:n.boxInitialized,box:n.box.clone(),sphereInitialized:n.sphereInitialized,sphere:n.sphere.clone()})),this._maxGeometryCount=e._maxGeometryCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.slice(),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this}onBeforeRender(e,n,r,a,s){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const o=a.getIndex(),l=o===null?1:o.array.BYTES_PER_ELEMENT,c=this._visibility,u=this._multiDrawStarts,d=this._multiDrawCounts,m=this._drawRanges,p=this.perObjectFrustumCulled;p&&(L$.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse).multiply(this.matrixWorld),oj.setFromProjectionMatrix(L$,e.isWebGPURenderer?R0:cu));let f=0;if(this.sortObjects){F$.copy(this.matrixWorld).invert(),mv.setFromMatrixPosition(r.matrixWorld).applyMatrix4(F$);for(let b=0,g=c.length;bc)continue;p.applyMatrix4(this.matrixWorld);const D=e.ray.origin.distanceTo(p);De.far||n.push({distance:D,point:m.clone().applyMatrix4(this.matrixWorld),index:N,face:null,faceIndex:null,object:this})}}else{const g=Math.max(0,o.start),_=Math.min(b.count,o.start+o.count);for(let N=g,C=_-1;Nc)continue;p.applyMatrix4(this.matrixWorld);const P=e.ray.origin.distanceTo(p);Pe.far||n.push({distance:P,point:m.clone().applyMatrix4(this.matrixWorld),index:N,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const n=this.geometry.morphAttributes,r=Object.keys(n);if(r.length>0){const a=n[r[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=a.length;so.stopPropagation()),this.domElement.addEventListener("keyup",o=>o.stopPropagation()),this.parent.children.push(this),this.parent.controllers.push(this),this.parent.$children.appendChild(this.domElement),this._listenCallback=this._listenCallback.bind(this),this.name(r)}name(e){return this._name=e,this.$name.textContent=e,this}onChange(e){return this._onChange=e,this}_callOnChange(){this.parent._callOnChange(this),this._onChange!==void 0&&this._onChange.call(this,this.getValue()),this._changed=!0}onFinishChange(e){return this._onFinishChange=e,this}_callOnFinishChange(){this._changed&&(this.parent._callOnFinishChange(this),this._onFinishChange!==void 0&&this._onFinishChange.call(this,this.getValue())),this._changed=!1}reset(){return this.setValue(this.initialValue),this._callOnFinishChange(),this}enable(e=!0){return this.disable(!e)}disable(e=!0){return e===this._disabled?this:(this._disabled=e,this.domElement.classList.toggle("disabled",e),this.$disable.toggleAttribute("disabled",e),this)}show(e=!0){return this._hidden=!e,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}options(e){const n=this.parent.add(this.object,this.property,e);return n.name(this._name),this.destroy(),n}min(e){return this}max(e){return this}step(e){return this}decimals(e){return this}listen(e=!0){return this._listening=e,this._listenCallbackID!==void 0&&(cancelAnimationFrame(this._listenCallbackID),this._listenCallbackID=void 0),this._listening&&this._listenCallback(),this}_listenCallback(){this._listenCallbackID=requestAnimationFrame(this._listenCallback);const e=this.save();e!==this._listenPrevValue&&this.updateDisplay(),this._listenPrevValue=e}getValue(){return this.object[this.property]}setValue(e){return this.getValue()!==e&&(this.object[this.property]=e,this._callOnChange(),this.updateDisplay()),this}updateDisplay(){return this}load(e){return this.setValue(e),this._callOnFinishChange(),this}save(){return this.getValue()}destroy(){this.listen(!1),this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.controllers.splice(this.parent.controllers.indexOf(this),1),this.parent.$children.removeChild(this.domElement)}}class BPe extends fu{constructor(e,n,r){super(e,n,r,"boolean","label"),this.$input=document.createElement("input"),this.$input.setAttribute("type","checkbox"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$widget.appendChild(this.$input),this.$input.addEventListener("change",()=>{this.setValue(this.$input.checked),this._callOnFinishChange()}),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.checked=this.getValue(),this}}function jR(t){let e,n;return(e=t.match(/(#|0x)?([a-f0-9]{6})/i))?n=e[2]:(e=t.match(/rgb\(\s*(\d*)\s*,\s*(\d*)\s*,\s*(\d*)\s*\)/))?n=parseInt(e[1]).toString(16).padStart(2,0)+parseInt(e[2]).toString(16).padStart(2,0)+parseInt(e[3]).toString(16).padStart(2,0):(e=t.match(/^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i))&&(n=e[1]+e[1]+e[2]+e[2]+e[3]+e[3]),n?"#"+n:!1}const HPe={isPrimitive:!0,match:t=>typeof t=="string",fromHexString:jR,toHexString:jR},L0={isPrimitive:!0,match:t=>typeof t=="number",fromHexString:t=>parseInt(t.substring(1),16),toHexString:t=>"#"+t.toString(16).padStart(6,0)},$Pe={isPrimitive:!1,match:t=>Array.isArray(t),fromHexString(t,e,n=1){const r=L0.fromHexString(t);e[0]=(r>>16&255)/255*n,e[1]=(r>>8&255)/255*n,e[2]=(r&255)/255*n},toHexString([t,e,n],r=1){r=255/r;const a=t*r<<16^e*r<<8^n*r<<0;return L0.toHexString(a)}},qPe={isPrimitive:!1,match:t=>Object(t)===t,fromHexString(t,e,n=1){const r=L0.fromHexString(t);e.r=(r>>16&255)/255*n,e.g=(r>>8&255)/255*n,e.b=(r&255)/255*n},toHexString({r:t,g:e,b:n},r=1){r=255/r;const a=t*r<<16^e*r<<8^n*r<<0;return L0.toHexString(a)}},VPe=[HPe,L0,$Pe,qPe];function GPe(t){return VPe.find(e=>e.match(t))}class WPe extends fu{constructor(e,n,r,a){super(e,n,r,"color"),this.$input=document.createElement("input"),this.$input.setAttribute("type","color"),this.$input.setAttribute("tabindex",-1),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$text=document.createElement("input"),this.$text.setAttribute("type","text"),this.$text.setAttribute("spellcheck","false"),this.$text.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$display.appendChild(this.$input),this.$widget.appendChild(this.$display),this.$widget.appendChild(this.$text),this._format=GPe(this.initialValue),this._rgbScale=a,this._initialValueHexString=this.save(),this._textFocused=!1,this.$input.addEventListener("input",()=>{this._setValueFromHexString(this.$input.value)}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$text.addEventListener("input",()=>{const s=jR(this.$text.value);s&&this._setValueFromHexString(s)}),this.$text.addEventListener("focus",()=>{this._textFocused=!0,this.$text.select()}),this.$text.addEventListener("blur",()=>{this._textFocused=!1,this.updateDisplay(),this._callOnFinishChange()}),this.$disable=this.$text,this.updateDisplay()}reset(){return this._setValueFromHexString(this._initialValueHexString),this}_setValueFromHexString(e){if(this._format.isPrimitive){const n=this._format.fromHexString(e);this.setValue(n)}else this._format.fromHexString(e,this.getValue(),this._rgbScale),this._callOnChange(),this.updateDisplay()}save(){return this._format.toHexString(this.getValue(),this._rgbScale)}load(e){return this._setValueFromHexString(e),this._callOnFinishChange(),this}updateDisplay(){return this.$input.value=this._format.toHexString(this.getValue(),this._rgbScale),this._textFocused||(this.$text.value=this.$input.value.substring(1)),this.$display.style.backgroundColor=this.$input.value,this}}class mj extends fu{constructor(e,n,r){super(e,n,r,"function"),this.$button=document.createElement("button"),this.$button.appendChild(this.$name),this.$widget.appendChild(this.$button),this.$button.addEventListener("click",a=>{a.preventDefault(),this.getValue().call(this.object),this._callOnChange()}),this.$button.addEventListener("touchstart",()=>{},{passive:!0}),this.$disable=this.$button}}class KPe extends fu{constructor(e,n,r,a,s,o){super(e,n,r,"number"),this._initInput(),this.min(a),this.max(s);const l=o!==void 0;this.step(l?o:this._getImplicitStep(),l),this.updateDisplay()}decimals(e){return this._decimals=e,this.updateDisplay(),this}min(e){return this._min=e,this._onUpdateMinMax(),this}max(e){return this._max=e,this._onUpdateMinMax(),this}step(e,n=!0){return this._step=e,this._stepExplicit=n,this}updateDisplay(){const e=this.getValue();if(this._hasSlider){let n=(e-this._min)/(this._max-this._min);n=Math.max(0,Math.min(n,1)),this.$fill.style.width=n*100+"%"}return this._inputFocused||(this.$input.value=this._decimals===void 0?e:e.toFixed(this._decimals)),this}_initInput(){this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("aria-labelledby",this.$name.id),window.matchMedia("(pointer: coarse)").matches&&(this.$input.setAttribute("type","number"),this.$input.setAttribute("step","any")),this.$widget.appendChild(this.$input),this.$disable=this.$input;const n=()=>{let _=parseFloat(this.$input.value);isNaN(_)||(this._stepExplicit&&(_=this._snap(_)),this.setValue(this._clamp(_)))},r=_=>{const N=parseFloat(this.$input.value);isNaN(N)||(this._snapClampSetValue(N+_),this.$input.value=this.getValue())},a=_=>{_.key==="Enter"&&this.$input.blur(),_.code==="ArrowUp"&&(_.preventDefault(),r(this._step*this._arrowKeyMultiplier(_))),_.code==="ArrowDown"&&(_.preventDefault(),r(this._step*this._arrowKeyMultiplier(_)*-1))},s=_=>{this._inputFocused&&(_.preventDefault(),r(this._step*this._normalizeMouseWheel(_)))};let o=!1,l,c,u,d,m;const p=5,f=_=>{l=_.clientX,c=u=_.clientY,o=!0,d=this.getValue(),m=0,window.addEventListener("mousemove",y),window.addEventListener("mouseup",v)},y=_=>{if(o){const N=_.clientX-l,C=_.clientY-c;Math.abs(C)>p?(_.preventDefault(),this.$input.blur(),o=!1,this._setDraggingStyle(!0,"vertical")):Math.abs(N)>p&&v()}if(!o){const N=_.clientY-u;m-=N*this._step*this._arrowKeyMultiplier(_),d+m>this._max?m=this._max-d:d+m{this._setDraggingStyle(!1,"vertical"),this._callOnFinishChange(),window.removeEventListener("mousemove",y),window.removeEventListener("mouseup",v)},b=()=>{this._inputFocused=!0},g=()=>{this._inputFocused=!1,this.updateDisplay(),this._callOnFinishChange()};this.$input.addEventListener("input",n),this.$input.addEventListener("keydown",a),this.$input.addEventListener("wheel",s,{passive:!1}),this.$input.addEventListener("mousedown",f),this.$input.addEventListener("focus",b),this.$input.addEventListener("blur",g)}_initSlider(){this._hasSlider=!0,this.$slider=document.createElement("div"),this.$slider.classList.add("slider"),this.$fill=document.createElement("div"),this.$fill.classList.add("fill"),this.$slider.appendChild(this.$fill),this.$widget.insertBefore(this.$slider,this.$input),this.domElement.classList.add("hasSlider");const e=(g,_,N,C,k)=>(g-_)/(N-_)*(k-C)+C,n=g=>{const _=this.$slider.getBoundingClientRect();let N=e(g,_.left,_.right,this._min,this._max);this._snapClampSetValue(N)},r=g=>{this._setDraggingStyle(!0),n(g.clientX),window.addEventListener("mousemove",a),window.addEventListener("mouseup",s)},a=g=>{n(g.clientX)},s=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",s)};let o=!1,l,c;const u=g=>{g.preventDefault(),this._setDraggingStyle(!0),n(g.touches[0].clientX),o=!1},d=g=>{g.touches.length>1||(this._hasScrollBar?(l=g.touches[0].clientX,c=g.touches[0].clientY,o=!0):u(g),window.addEventListener("touchmove",m,{passive:!1}),window.addEventListener("touchend",p))},m=g=>{if(o){const _=g.touches[0].clientX-l,N=g.touches[0].clientY-c;Math.abs(_)>Math.abs(N)?u(g):(window.removeEventListener("touchmove",m),window.removeEventListener("touchend",p))}else g.preventDefault(),n(g.touches[0].clientX)},p=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("touchmove",m),window.removeEventListener("touchend",p)},f=this._callOnFinishChange.bind(this),y=400;let v;const b=g=>{if(Math.abs(g.deltaX)this._max&&(e=this._max),e}_snapClampSetValue(e){this.setValue(this._clamp(this._snap(e)))}get _hasScrollBar(){const e=this.parent.root.$children;return e.scrollHeight>e.clientHeight}get _hasMin(){return this._min!==void 0}get _hasMax(){return this._max!==void 0}}class YPe extends fu{constructor(e,n,r,a){super(e,n,r,"option"),this.$select=document.createElement("select"),this.$select.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$select.addEventListener("change",()=>{this.setValue(this._values[this.$select.selectedIndex]),this._callOnFinishChange()}),this.$select.addEventListener("focus",()=>{this.$display.classList.add("focus")}),this.$select.addEventListener("blur",()=>{this.$display.classList.remove("focus")}),this.$widget.appendChild(this.$select),this.$widget.appendChild(this.$display),this.$disable=this.$select,this.options(a)}options(e){return this._values=Array.isArray(e)?e:Object.values(e),this._names=Array.isArray(e)?e:Object.keys(e),this.$select.replaceChildren(),this._names.forEach(n=>{const r=document.createElement("option");r.textContent=n,this.$select.appendChild(r)}),this.updateDisplay(),this}updateDisplay(){const e=this.getValue(),n=this._values.indexOf(e);return this.$select.selectedIndex=n,this.$display.textContent=n===-1?e:this._names[n],this}}class XPe extends fu{constructor(e,n,r){super(e,n,r,"string"),this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("spellcheck","false"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$input.addEventListener("input",()=>{this.setValue(this.$input.value)}),this.$input.addEventListener("keydown",a=>{a.code==="Enter"&&this.$input.blur()}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$widget.appendChild(this.$input),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.value=this.getValue(),this}}const QPe=`.lil-gui { font-family: var(--font-family); font-size: var(--font-size); line-height: 1; @@ -8037,11 +8037,11 @@ void main() { @font-face { font-family: "lil-gui"; src: url("data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAAUsAAsAAAAACJwAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAAH4AAADAImwmYE9TLzIAAAGIAAAAPwAAAGBKqH5SY21hcAAAAcgAAAD0AAACrukyyJBnbHlmAAACvAAAAF8AAACEIZpWH2hlYWQAAAMcAAAAJwAAADZfcj2zaGhlYQAAA0QAAAAYAAAAJAC5AHhobXR4AAADXAAAABAAAABMAZAAAGxvY2EAAANsAAAAFAAAACgCEgIybWF4cAAAA4AAAAAeAAAAIAEfABJuYW1lAAADoAAAASIAAAIK9SUU/XBvc3QAAATEAAAAZgAAAJCTcMc2eJxVjbEOgjAURU+hFRBK1dGRL+ALnAiToyMLEzFpnPz/eAshwSa97517c/MwwJmeB9kwPl+0cf5+uGPZXsqPu4nvZabcSZldZ6kfyWnomFY/eScKqZNWupKJO6kXN3K9uCVoL7iInPr1X5baXs3tjuMqCtzEuagm/AAlzQgPAAB4nGNgYRBlnMDAysDAYM/gBiT5oLQBAwuDJAMDEwMrMwNWEJDmmsJwgCFeXZghBcjlZMgFCzOiKOIFAB71Bb8AeJy1kjFuwkAQRZ+DwRAwBtNQRUGKQ8OdKCAWUhAgKLhIuAsVSpWz5Bbkj3dEgYiUIszqWdpZe+Z7/wB1oCYmIoboiwiLT2WjKl/jscrHfGg/pKdMkyklC5Zs2LEfHYpjcRoPzme9MWWmk3dWbK9ObkWkikOetJ554fWyoEsmdSlt+uR0pCJR34b6t/TVg1SY3sYvdf8vuiKrpyaDXDISiegp17p7579Gp3p++y7HPAiY9pmTibljrr85qSidtlg4+l25GLCaS8e6rRxNBmsnERunKbaOObRz7N72ju5vdAjYpBXHgJylOAVsMseDAPEP8LYoUHicY2BiAAEfhiAGJgZWBgZ7RnFRdnVJELCQlBSRlATJMoLV2DK4glSYs6ubq5vbKrJLSbGrgEmovDuDJVhe3VzcXFwNLCOILB/C4IuQ1xTn5FPilBTj5FPmBAB4WwoqAHicY2BkYGAA4sk1sR/j+W2+MnAzpDBgAyEMQUCSg4EJxAEAwUgFHgB4nGNgZGBgSGFggJMhDIwMqEAYAByHATJ4nGNgAIIUNEwmAABl3AGReJxjYAACIQYlBiMGJ3wQAEcQBEV4nGNgZGBgEGZgY2BiAAEQyQWEDAz/wXwGAAsPATIAAHicXdBNSsNAHAXwl35iA0UQXYnMShfS9GPZA7T7LgIu03SSpkwzYTIt1BN4Ak/gKTyAeCxfw39jZkjymzcvAwmAW/wgwHUEGDb36+jQQ3GXGot79L24jxCP4gHzF/EIr4jEIe7wxhOC3g2TMYy4Q7+Lu/SHuEd/ivt4wJd4wPxbPEKMX3GI5+DJFGaSn4qNzk8mcbKSR6xdXdhSzaOZJGtdapd4vVPbi6rP+cL7TGXOHtXKll4bY1Xl7EGnPtp7Xy2n00zyKLVHfkHBa4IcJ2oD3cgggWvt/V/FbDrUlEUJhTn/0azVWbNTNr0Ens8de1tceK9xZmfB1CPjOmPH4kitmvOubcNpmVTN3oFJyjzCvnmrwhJTzqzVj9jiSX911FjeAAB4nG3HMRKCMBBA0f0giiKi4DU8k0V2GWbIZDOh4PoWWvq6J5V8If9NVNQcaDhyouXMhY4rPTcG7jwYmXhKq8Wz+p762aNaeYXom2n3m2dLTVgsrCgFJ7OTmIkYbwIbC6vIB7WmFfAAAA==") format("woff"); -}`;function ZPe(t){const e=document.createElement("style");e.innerHTML=t;const n=document.querySelector("head link[rel=stylesheet], head style");n?document.head.insertBefore(e,n):document.head.appendChild(e)}let K$=!1;class ek{constructor({parent:e,autoPlace:n=e===void 0,container:r,width:a,title:s="Controls",closeFolders:o=!1,injectStyles:l=!0,touchStyles:c=!0}={}){if(this.parent=e,this.root=e?e.root:this,this.children=[],this.controllers=[],this.folders=[],this._closed=!1,this._hidden=!1,this.domElement=document.createElement("div"),this.domElement.classList.add("lil-gui"),this.$title=document.createElement("div"),this.$title.classList.add("title"),this.$title.setAttribute("role","button"),this.$title.setAttribute("aria-expanded",!0),this.$title.setAttribute("tabindex",0),this.$title.addEventListener("click",()=>this.openAnimated(this._closed)),this.$title.addEventListener("keydown",u=>{(u.code==="Enter"||u.code==="Space")&&(u.preventDefault(),this.$title.click())}),this.$title.addEventListener("touchstart",()=>{},{passive:!0}),this.$children=document.createElement("div"),this.$children.classList.add("children"),this.domElement.appendChild(this.$title),this.domElement.appendChild(this.$children),this.title(s),this.parent){this.parent.children.push(this),this.parent.folders.push(this),this.parent.$children.appendChild(this.domElement);return}this.domElement.classList.add("root"),c&&this.domElement.classList.add("allow-touch-styles"),!K$&&l&&(ZPe(QPe),K$=!0),r?r.appendChild(this.domElement):n&&(this.domElement.classList.add("autoPlace"),document.body.appendChild(this.domElement)),a&&this.domElement.style.setProperty("--width",a+"px"),this._closeFolders=o}add(e,n,r,a,s){if(Object(r)===r)return new YPe(this,e,n,r);const o=e[n];switch(typeof o){case"number":return new KPe(this,e,n,r,a,s);case"boolean":return new BPe(this,e,n);case"string":return new XPe(this,e,n);case"function":return new m2(this,e,n)}console.error(`gui.add failed +}`;function ZPe(t){const e=document.createElement("style");e.innerHTML=t;const n=document.querySelector("head link[rel=stylesheet], head style");n?document.head.insertBefore(e,n):document.head.appendChild(e)}let K$=!1;class ek{constructor({parent:e,autoPlace:n=e===void 0,container:r,width:a,title:s="Controls",closeFolders:o=!1,injectStyles:l=!0,touchStyles:c=!0}={}){if(this.parent=e,this.root=e?e.root:this,this.children=[],this.controllers=[],this.folders=[],this._closed=!1,this._hidden=!1,this.domElement=document.createElement("div"),this.domElement.classList.add("lil-gui"),this.$title=document.createElement("div"),this.$title.classList.add("title"),this.$title.setAttribute("role","button"),this.$title.setAttribute("aria-expanded",!0),this.$title.setAttribute("tabindex",0),this.$title.addEventListener("click",()=>this.openAnimated(this._closed)),this.$title.addEventListener("keydown",u=>{(u.code==="Enter"||u.code==="Space")&&(u.preventDefault(),this.$title.click())}),this.$title.addEventListener("touchstart",()=>{},{passive:!0}),this.$children=document.createElement("div"),this.$children.classList.add("children"),this.domElement.appendChild(this.$title),this.domElement.appendChild(this.$children),this.title(s),this.parent){this.parent.children.push(this),this.parent.folders.push(this),this.parent.$children.appendChild(this.domElement);return}this.domElement.classList.add("root"),c&&this.domElement.classList.add("allow-touch-styles"),!K$&&l&&(ZPe(QPe),K$=!0),r?r.appendChild(this.domElement):n&&(this.domElement.classList.add("autoPlace"),document.body.appendChild(this.domElement)),a&&this.domElement.style.setProperty("--width",a+"px"),this._closeFolders=o}add(e,n,r,a,s){if(Object(r)===r)return new YPe(this,e,n,r);const o=e[n];switch(typeof o){case"number":return new KPe(this,e,n,r,a,s);case"boolean":return new BPe(this,e,n);case"string":return new XPe(this,e,n);case"function":return new mj(this,e,n)}console.error(`gui.add failed property:`,n,` object:`,e,` - value:`,o)}addColor(e,n,r=1){return new WPe(this,e,n,r)}addFolder(e){const n=new ek({parent:this,title:e});return this.root._closeFolders&&n.close(),n}load(e,n=!0){return e.controllers&&this.controllers.forEach(r=>{r instanceof m2||r._name in e.controllers&&r.load(e.controllers[r._name])}),n&&e.folders&&this.folders.forEach(r=>{r._title in e.folders&&r.load(e.folders[r._title])}),this}save(e=!0){const n={controllers:{},folders:{}};return this.controllers.forEach(r=>{if(!(r instanceof m2)){if(r._name in n.controllers)throw new Error(`Cannot save GUI with duplicate property "${r._name}"`);n.controllers[r._name]=r.save()}}),e&&this.folders.forEach(r=>{if(r._title in n.folders)throw new Error(`Cannot save GUI with duplicate folder "${r._title}"`);n.folders[r._title]=r.save()}),n}open(e=!0){return this._setClosed(!e),this.$title.setAttribute("aria-expanded",!this._closed),this.domElement.classList.toggle("closed",this._closed),this}close(){return this.open(!1)}_setClosed(e){this._closed!==e&&(this._closed=e,this._callOnOpenClose(this))}show(e=!0){return this._hidden=!e,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}openAnimated(e=!0){return this._setClosed(!e),this.$title.setAttribute("aria-expanded",!this._closed),requestAnimationFrame(()=>{const n=this.$children.clientHeight;this.$children.style.height=n+"px",this.domElement.classList.add("transition");const r=s=>{s.target===this.$children&&(this.$children.style.height="",this.domElement.classList.remove("transition"),this.$children.removeEventListener("transitionend",r))};this.$children.addEventListener("transitionend",r);const a=e?this.$children.scrollHeight:0;this.domElement.classList.toggle("closed",!e),requestAnimationFrame(()=>{this.$children.style.height=a+"px"})}),this}title(e){return this._title=e,this.$title.textContent=e,this}reset(e=!0){return(e?this.controllersRecursive():this.controllers).forEach(r=>r.reset()),this}onChange(e){return this._onChange=e,this}_callOnChange(e){this.parent&&this.parent._callOnChange(e),this._onChange!==void 0&&this._onChange.call(this,{object:e.object,property:e.property,value:e.getValue(),controller:e})}onFinishChange(e){return this._onFinishChange=e,this}_callOnFinishChange(e){this.parent&&this.parent._callOnFinishChange(e),this._onFinishChange!==void 0&&this._onFinishChange.call(this,{object:e.object,property:e.property,value:e.getValue(),controller:e})}onOpenClose(e){return this._onOpenClose=e,this}_callOnOpenClose(e){this.parent&&this.parent._callOnOpenClose(e),this._onOpenClose!==void 0&&this._onOpenClose.call(this,e)}destroy(){this.parent&&(this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.folders.splice(this.parent.folders.indexOf(this),1)),this.domElement.parentElement&&this.domElement.parentElement.removeChild(this.domElement),Array.from(this.children).forEach(e=>e.destroy())}controllersRecursive(){let e=Array.from(this.controllers);return this.folders.forEach(n=>{e=e.concat(n.controllersRecursive())}),e}foldersRecursive(){let e=Array.from(this.folders);return this.folders.forEach(n=>{e=e.concat(n.foldersRecursive())}),e}}function h2(t,e,n,r){return new(n||(n=Promise))((function(a,s){function o(u){try{c(r.next(u))}catch(d){s(d)}}function l(u){try{c(r.throw(u))}catch(d){s(d)}}function c(u){var d;u.done?a(u.value):(d=u.value,d instanceof n?d:new n((function(m){m(d)}))).then(o,l)}c((r=r.apply(t,[])).next())}))}class TO{constructor(e,n,r,a){this.size=e,this.width=n,this.height=r,this.charLength=a,this.chars=""}static parse(e){const n=e.split(" "),r=n[0],a=r.split("x");return new TO(r,+a[0],+a[1],+n[1])}get src(){return"data:image/jpeg;base64,"+this.chars}get isValid(){return this.chars.length==this.charLength&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(this.chars)}}class AO{constructor(e,n,r,a){this.src=e,this.gcode=n,this.params=r,this.comment=a}}class Y$ extends AO{constructor(e,n,r,a){super(e,n,r,a),this.params=r}}class Vm extends AO{constructor(e,n,r,a){super(e,n,void 0,r),this.toolIndex=a}}class X${constructor(e,n,r,a=0){this.layer=e,this.commands=n,this.lineNumber=r,this.height=a}}class tk{constructor(e){this.lines=[],this.preamble=new X$(-1,[],0),this.layers=[],this.curZ=0,this.maxZ=0,this.metadata={thumbnails:{}},this.tolerance=0,this.tolerance=e??this.tolerance}parseGCode(e){const n=Array.isArray(e)?e:e.split(` -`);this.lines=this.lines.concat(n);const r=this.lines2commands(n);this.groupIntoLayers(r);const a=this.parseMetadata(r.filter((s=>s.comment))).thumbnails;for(const[s,o]of Object.entries(a))this.metadata.thumbnails[s]=o;return{layers:this.layers,metadata:this.metadata}}lines2commands(e){return e.map((n=>this.parseCommand(n)))}parseCommand(e,n=!0){var r;const a=e.trim().split(";"),s=a[0],o=n&&a[1]||void 0,l=s.split(/([a-zA-Z])/g).slice(1).map((d=>d.trim())),c=l.length?`${(r=l[0])===null||r===void 0?void 0:r.toLowerCase()}${l[1]}`:"",u=this.parseParams(l.slice(2));switch(c){case"g0":case"g00":case"g1":case"g01":case"g2":case"g02":case"g3":case"g03":return new Y$(e,c,u,o);case"t0":return new Vm(e,c,o,0);case"t1":return new Vm(e,c,o,1);case"t2":return new Vm(e,c,o,2);case"t3":return new Vm(e,c,o,3);case"t4":return new Vm(e,c,o,4);case"t5":return new Vm(e,c,o,5);case"t6":return new Vm(e,c,o,6);case"t7":return new Vm(e,c,o,7);default:return new AO(e,c,u,o)}}parseMove(e){return e.reduce(((n,r)=>{const a=r.charAt(0).toLowerCase();return a!="x"&&a!="y"&&a!="z"&&a!="e"&&a!="r"&&a!="f"&&a!="i"&&a!="j"||(n[a]=parseFloat(r.slice(1))),n}),{})}isAlpha(e){const n=e.charCodeAt(0);return n>=97&&n<=122||n>=65&&n<=90}parseParams(e){return e.reduce(((n,r,a,s)=>{if(a%2==0)return n;let o=s[a-1];return o=o.toLowerCase(),this.isAlpha(o)&&(n[o]=parseFloat(r)),n}),{})}groupIntoLayers(e){var n;for(let r=0;r0&&(s.x!=null||s.y!=null)&&Math.abs(this.curZ-(this.maxZ||-1/0))>this.tolerance){const o=Math.abs(this.curZ-this.maxZ);this.maxZ=this.curZ,this.layers.push(new X$(this.layers.length,[],r,o))}}this.maxLayer.commands.push(a)}return this.layers}get maxLayer(){var e;return(e=this.layers[this.layers.length-1])!==null&&e!==void 0?e:this.preamble}parseMetadata(e){const n={};let r;for(const a of e){const s=a.comment;if(!s)continue;const o=s.indexOf("thumbnail begin"),l=s.indexOf("thumbnail end");o>-1?r=TO.parse(s.slice(o+15).trim()):r&&(l==-1?r.chars+=s.trim():(r.isValid&&(n[r.size]=r),r=void 0))}return{thumbnails:n}}}tk.prototype.parseGcode=tk.prototype.parseGCode;const Q$={type:"change"},p2={type:"start"},Z$={type:"end"},u1=new SO,J$=new Qm,JPe=Math.cos(70*pZ.DEG2RAD);class eMe extends ig{constructor(e,n){super(),this.object=e,this.domElement=n,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new at,this.cursor=new at,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:tb.ROTATE,MIDDLE:tb.DOLLY,RIGHT:tb.PAN},this.touches={ONE:nb.ROTATE,TWO:nb.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return l.phi},this.getAzimuthalAngle=function(){return l.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function($){$.addEventListener("keydown",K),this._domElementKeyEvents=$},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",K),this._domElementKeyEvents=null},this.saveState=function(){r.target0.copy(r.target),r.position0.copy(r.object.position),r.zoom0=r.object.zoom},this.reset=function(){r.target.copy(r.target0),r.object.position.copy(r.position0),r.object.zoom=r.zoom0,r.object.updateProjectionMatrix(),r.dispatchEvent(Q$),r.update(),s=a.NONE},this.update=(function(){const $=new at,ee=new If().setFromUnitVectors(e.up,new at(0,1,0)),W=ee.clone().invert(),ie=new at,ce=new If,be=new at,xe=2*Math.PI;return function(oe=null){const L=r.object.position;$.copy(L).sub(r.target),$.applyQuaternion(ee),l.setFromVector3($),r.autoRotate&&s===a.NONE&&R((function(fe){return fe!==null?2*Math.PI/60*r.autoRotateSpeed*fe:2*Math.PI/60/60*r.autoRotateSpeed})(oe)),r.enableDamping?(l.theta+=c.theta*r.dampingFactor,l.phi+=c.phi*r.dampingFactor):(l.theta+=c.theta,l.phi+=c.phi);let F=r.minAzimuthAngle,te=r.maxAzimuthAngle;isFinite(F)&&isFinite(te)&&(F<-Math.PI?F+=xe:F>Math.PI&&(F-=xe),te<-Math.PI?te+=xe:te>Math.PI&&(te-=xe),l.theta=F<=te?Math.max(F,Math.min(te,l.theta)):l.theta>(F+te)/2?Math.max(F,l.theta):Math.min(te,l.theta)),l.phi=Math.max(r.minPolarAngle,Math.min(r.maxPolarAngle,l.phi)),l.makeSafe(),r.enableDamping===!0?r.target.addScaledVector(d,r.dampingFactor):r.target.add(d),r.target.sub(r.cursor),r.target.clampLength(r.minTargetRadius,r.maxTargetRadius),r.target.add(r.cursor),r.zoomToCursor&&P||r.object.isOrthographicCamera?l.radius=ue(l.radius):l.radius=ue(l.radius*u),$.setFromSpherical(l),$.applyQuaternion(W),L.copy(r.target).add($),r.object.lookAt(r.target),r.enableDamping===!0?(c.theta*=1-r.dampingFactor,c.phi*=1-r.dampingFactor,d.multiplyScalar(1-r.dampingFactor)):(c.set(0,0,0),d.set(0,0,0));let ve=!1;if(r.zoomToCursor&&P){let fe=null;if(r.object.isPerspectiveCamera){const me=$.length();fe=ue(me*u);const je=me-fe;r.object.position.addScaledVector(C,je),r.object.updateMatrixWorld()}else if(r.object.isOrthographicCamera){const me=new at(k.x,k.y,0);me.unproject(r.object),r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom/u)),r.object.updateProjectionMatrix(),ve=!0;const je=new at(k.x,k.y,0);je.unproject(r.object),r.object.position.sub(je).add(me),r.object.updateMatrixWorld(),fe=$.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),r.zoomToCursor=!1;fe!==null&&(this.screenSpacePanning?r.target.set(0,0,-1).transformDirection(r.object.matrix).multiplyScalar(fe).add(r.object.position):(u1.origin.copy(r.object.position),u1.direction.set(0,0,-1).transformDirection(r.object.matrix),Math.abs(r.object.up.dot(u1.direction))o||8*(1-ce.dot(r.object.quaternion))>o||be.distanceToSquared(r.target)>0)&&(r.dispatchEvent(Q$),ie.copy(r.object.position),ce.copy(r.object.quaternion),be.copy(r.target),!0)}})(),this.dispose=function(){r.domElement.removeEventListener("contextmenu",H),r.domElement.removeEventListener("pointerdown",X),r.domElement.removeEventListener("pointercancel",E),r.domElement.removeEventListener("wheel",U),r.domElement.removeEventListener("pointermove",j),r.domElement.removeEventListener("pointerup",E),r._domElementKeyEvents!==null&&(r._domElementKeyEvents.removeEventListener("keydown",K),r._domElementKeyEvents=null)};const r=this,a={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let s=a.NONE;const o=1e-6,l=new G$,c=new G$;let u=1;const d=new at,m=new Fn,p=new Fn,f=new Fn,y=new Fn,v=new Fn,b=new Fn,g=new Fn,_=new Fn,N=new Fn,C=new at,k=new Fn;let P=!1;const T=[],D={};function A(){return Math.pow(.95,r.zoomSpeed)}function R($){c.theta-=$}function G($){c.phi-=$}const z=(function(){const $=new at;return function(ee,W){$.setFromMatrixColumn(W,0),$.multiplyScalar(-ee),d.add($)}})(),Z=(function(){const $=new at;return function(ee,W){r.screenSpacePanning===!0?$.setFromMatrixColumn(W,1):($.setFromMatrixColumn(W,0),$.crossVectors(r.object.up,$)),$.multiplyScalar(ee),d.add($)}})(),I=(function(){const $=new at;return function(ee,W){const ie=r.domElement;if(r.object.isPerspectiveCamera){const ce=r.object.position;$.copy(ce).sub(r.target);let be=$.length();be*=Math.tan(r.object.fov/2*Math.PI/180),z(2*ee*be/ie.clientHeight,r.object.matrix),Z(2*W*be/ie.clientHeight,r.object.matrix)}else r.object.isOrthographicCamera?(z(ee*(r.object.right-r.object.left)/r.object.zoom/ie.clientWidth,r.object.matrix),Z(W*(r.object.top-r.object.bottom)/r.object.zoom/ie.clientHeight,r.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),r.enablePan=!1)}})();function J($){r.object.isPerspectiveCamera||r.object.isOrthographicCamera?u/=$:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function ae($){r.object.isPerspectiveCamera||r.object.isOrthographicCamera?u*=$:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function Y($){if(!r.zoomToCursor)return;P=!0;const ee=r.domElement.getBoundingClientRect(),W=$.clientX-ee.left,ie=$.clientY-ee.top,ce=ee.width,be=ee.height;k.x=W/ce*2-1,k.y=-ie/be*2+1,C.set(k.x,k.y,1).unproject(r.object).sub(r.object.position).normalize()}function ue($){return Math.max(r.minDistance,Math.min(r.maxDistance,$))}function de($){m.set($.clientX,$.clientY)}function he($){y.set($.clientX,$.clientY)}function V(){if(T.length===1)m.set(T[0].pageX,T[0].pageY);else{const $=.5*(T[0].pageX+T[1].pageX),ee=.5*(T[0].pageY+T[1].pageY);m.set($,ee)}}function ne(){if(T.length===1)y.set(T[0].pageX,T[0].pageY);else{const $=.5*(T[0].pageX+T[1].pageX),ee=.5*(T[0].pageY+T[1].pageY);y.set($,ee)}}function se(){const $=T[0].pageX-T[1].pageX,ee=T[0].pageY-T[1].pageY,W=Math.sqrt($*$+ee*ee);g.set(0,W)}function pe($){if(T.length==1)p.set($.pageX,$.pageY);else{const W=O($),ie=.5*($.pageX+W.x),ce=.5*($.pageY+W.y);p.set(ie,ce)}f.subVectors(p,m).multiplyScalar(r.rotateSpeed);const ee=r.domElement;R(2*Math.PI*f.x/ee.clientHeight),G(2*Math.PI*f.y/ee.clientHeight),m.copy(p)}function Te($){if(T.length===1)v.set($.pageX,$.pageY);else{const ee=O($),W=.5*($.pageX+ee.x),ie=.5*($.pageY+ee.y);v.set(W,ie)}b.subVectors(v,y).multiplyScalar(r.panSpeed),I(b.x,b.y),y.copy(v)}function q($){const ee=O($),W=$.pageX-ee.x,ie=$.pageY-ee.y,ce=Math.sqrt(W*W+ie*ie);_.set(0,ce),N.set(0,Math.pow(_.y/g.y,r.zoomSpeed)),J(N.y),g.copy(_)}function X($){r.enabled!==!1&&(T.length===0&&(r.domElement.setPointerCapture($.pointerId),r.domElement.addEventListener("pointermove",j),r.domElement.addEventListener("pointerup",E)),(function(ee){T.push(ee)})($),$.pointerType==="touch"?(function(ee){switch(re(ee),T.length){case 1:switch(r.touches.ONE){case nb.ROTATE:if(r.enableRotate===!1)return;V(),s=a.TOUCH_ROTATE;break;case nb.PAN:if(r.enablePan===!1)return;ne(),s=a.TOUCH_PAN;break;default:s=a.NONE}break;case 2:switch(r.touches.TWO){case nb.DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;r.enableZoom&&se(),r.enablePan&&ne(),s=a.TOUCH_DOLLY_PAN;break;case nb.DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;r.enableZoom&&se(),r.enableRotate&&V(),s=a.TOUCH_DOLLY_ROTATE;break;default:s=a.NONE}break;default:s=a.NONE}s!==a.NONE&&r.dispatchEvent(p2)})($):(function(ee){let W;switch(ee.button){case 0:W=r.mouseButtons.LEFT;break;case 1:W=r.mouseButtons.MIDDLE;break;case 2:W=r.mouseButtons.RIGHT;break;default:W=-1}switch(W){case tb.DOLLY:if(r.enableZoom===!1)return;(function(ie){Y(ie),g.set(ie.clientX,ie.clientY)})(ee),s=a.DOLLY;break;case tb.ROTATE:if(ee.ctrlKey||ee.metaKey||ee.shiftKey){if(r.enablePan===!1)return;he(ee),s=a.PAN}else{if(r.enableRotate===!1)return;de(ee),s=a.ROTATE}break;case tb.PAN:if(ee.ctrlKey||ee.metaKey||ee.shiftKey){if(r.enableRotate===!1)return;de(ee),s=a.ROTATE}else{if(r.enablePan===!1)return;he(ee),s=a.PAN}break;default:s=a.NONE}s!==a.NONE&&r.dispatchEvent(p2)})($))}function j($){r.enabled!==!1&&($.pointerType==="touch"?(function(ee){switch(re(ee),s){case a.TOUCH_ROTATE:if(r.enableRotate===!1)return;pe(ee),r.update();break;case a.TOUCH_PAN:if(r.enablePan===!1)return;Te(ee),r.update();break;case a.TOUCH_DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;(function(W){r.enableZoom&&q(W),r.enablePan&&Te(W)})(ee),r.update();break;case a.TOUCH_DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;(function(W){r.enableZoom&&q(W),r.enableRotate&&pe(W)})(ee),r.update();break;default:s=a.NONE}})($):(function(ee){switch(s){case a.ROTATE:if(r.enableRotate===!1)return;(function(W){p.set(W.clientX,W.clientY),f.subVectors(p,m).multiplyScalar(r.rotateSpeed);const ie=r.domElement;R(2*Math.PI*f.x/ie.clientHeight),G(2*Math.PI*f.y/ie.clientHeight),m.copy(p),r.update()})(ee);break;case a.DOLLY:if(r.enableZoom===!1)return;(function(W){_.set(W.clientX,W.clientY),N.subVectors(_,g),N.y>0?J(A()):N.y<0&&ae(A()),g.copy(_),r.update()})(ee);break;case a.PAN:if(r.enablePan===!1)return;(function(W){v.set(W.clientX,W.clientY),b.subVectors(v,y).multiplyScalar(r.panSpeed),I(b.x,b.y),y.copy(v),r.update()})(ee)}})($))}function E($){(function(ee){delete D[ee.pointerId];for(let W=0;W0&&J(A()),r.update()})($),r.dispatchEvent(Z$))}function K($){r.enabled!==!1&&r.enablePan!==!1&&(function(ee){let W=!1;switch(ee.code){case r.keys.UP:ee.ctrlKey||ee.metaKey||ee.shiftKey?G(2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):I(0,r.keyPanSpeed),W=!0;break;case r.keys.BOTTOM:ee.ctrlKey||ee.metaKey||ee.shiftKey?G(-2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):I(0,-r.keyPanSpeed),W=!0;break;case r.keys.LEFT:ee.ctrlKey||ee.metaKey||ee.shiftKey?R(2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):I(r.keyPanSpeed,0),W=!0;break;case r.keys.RIGHT:ee.ctrlKey||ee.metaKey||ee.shiftKey?R(-2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):I(-r.keyPanSpeed,0),W=!0}W&&(ee.preventDefault(),r.update())})($)}function H($){r.enabled!==!1&&$.preventDefault()}function re($){let ee=D[$.pointerId];ee===void 0&&(ee=new Fn,D[$.pointerId]=ee),ee.set($.pageX,$.pageY)}function O($){const ee=$.pointerId===T[0].pointerId?T[1]:T[0];return D[ee.pointerId]}r.domElement.addEventListener("contextmenu",H),r.domElement.addEventListener("pointerdown",X),r.domElement.addEventListener("pointercancel",E),r.domElement.addEventListener("wheel",U,{passive:!1}),this.update()}}Vt.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new Fn(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},go.line={uniforms:_O.merge([Vt.common,Vt.fog,Vt.line]),vertexShader:` + value:`,o)}addColor(e,n,r=1){return new WPe(this,e,n,r)}addFolder(e){const n=new ek({parent:this,title:e});return this.root._closeFolders&&n.close(),n}load(e,n=!0){return e.controllers&&this.controllers.forEach(r=>{r instanceof mj||r._name in e.controllers&&r.load(e.controllers[r._name])}),n&&e.folders&&this.folders.forEach(r=>{r._title in e.folders&&r.load(e.folders[r._title])}),this}save(e=!0){const n={controllers:{},folders:{}};return this.controllers.forEach(r=>{if(!(r instanceof mj)){if(r._name in n.controllers)throw new Error(`Cannot save GUI with duplicate property "${r._name}"`);n.controllers[r._name]=r.save()}}),e&&this.folders.forEach(r=>{if(r._title in n.folders)throw new Error(`Cannot save GUI with duplicate folder "${r._title}"`);n.folders[r._title]=r.save()}),n}open(e=!0){return this._setClosed(!e),this.$title.setAttribute("aria-expanded",!this._closed),this.domElement.classList.toggle("closed",this._closed),this}close(){return this.open(!1)}_setClosed(e){this._closed!==e&&(this._closed=e,this._callOnOpenClose(this))}show(e=!0){return this._hidden=!e,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}openAnimated(e=!0){return this._setClosed(!e),this.$title.setAttribute("aria-expanded",!this._closed),requestAnimationFrame(()=>{const n=this.$children.clientHeight;this.$children.style.height=n+"px",this.domElement.classList.add("transition");const r=s=>{s.target===this.$children&&(this.$children.style.height="",this.domElement.classList.remove("transition"),this.$children.removeEventListener("transitionend",r))};this.$children.addEventListener("transitionend",r);const a=e?this.$children.scrollHeight:0;this.domElement.classList.toggle("closed",!e),requestAnimationFrame(()=>{this.$children.style.height=a+"px"})}),this}title(e){return this._title=e,this.$title.textContent=e,this}reset(e=!0){return(e?this.controllersRecursive():this.controllers).forEach(r=>r.reset()),this}onChange(e){return this._onChange=e,this}_callOnChange(e){this.parent&&this.parent._callOnChange(e),this._onChange!==void 0&&this._onChange.call(this,{object:e.object,property:e.property,value:e.getValue(),controller:e})}onFinishChange(e){return this._onFinishChange=e,this}_callOnFinishChange(e){this.parent&&this.parent._callOnFinishChange(e),this._onFinishChange!==void 0&&this._onFinishChange.call(this,{object:e.object,property:e.property,value:e.getValue(),controller:e})}onOpenClose(e){return this._onOpenClose=e,this}_callOnOpenClose(e){this.parent&&this.parent._callOnOpenClose(e),this._onOpenClose!==void 0&&this._onOpenClose.call(this,e)}destroy(){this.parent&&(this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.folders.splice(this.parent.folders.indexOf(this),1)),this.domElement.parentElement&&this.domElement.parentElement.removeChild(this.domElement),Array.from(this.children).forEach(e=>e.destroy())}controllersRecursive(){let e=Array.from(this.controllers);return this.folders.forEach(n=>{e=e.concat(n.controllersRecursive())}),e}foldersRecursive(){let e=Array.from(this.folders);return this.folders.forEach(n=>{e=e.concat(n.foldersRecursive())}),e}}function hj(t,e,n,r){return new(n||(n=Promise))((function(a,s){function o(u){try{c(r.next(u))}catch(d){s(d)}}function l(u){try{c(r.throw(u))}catch(d){s(d)}}function c(u){var d;u.done?a(u.value):(d=u.value,d instanceof n?d:new n((function(m){m(d)}))).then(o,l)}c((r=r.apply(t,[])).next())}))}class TO{constructor(e,n,r,a){this.size=e,this.width=n,this.height=r,this.charLength=a,this.chars=""}static parse(e){const n=e.split(" "),r=n[0],a=r.split("x");return new TO(r,+a[0],+a[1],+n[1])}get src(){return"data:image/jpeg;base64,"+this.chars}get isValid(){return this.chars.length==this.charLength&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(this.chars)}}class AO{constructor(e,n,r,a){this.src=e,this.gcode=n,this.params=r,this.comment=a}}class Y$ extends AO{constructor(e,n,r,a){super(e,n,r,a),this.params=r}}class Vm extends AO{constructor(e,n,r,a){super(e,n,void 0,r),this.toolIndex=a}}class X${constructor(e,n,r,a=0){this.layer=e,this.commands=n,this.lineNumber=r,this.height=a}}class tk{constructor(e){this.lines=[],this.preamble=new X$(-1,[],0),this.layers=[],this.curZ=0,this.maxZ=0,this.metadata={thumbnails:{}},this.tolerance=0,this.tolerance=e??this.tolerance}parseGCode(e){const n=Array.isArray(e)?e:e.split(` +`);this.lines=this.lines.concat(n);const r=this.lines2commands(n);this.groupIntoLayers(r);const a=this.parseMetadata(r.filter((s=>s.comment))).thumbnails;for(const[s,o]of Object.entries(a))this.metadata.thumbnails[s]=o;return{layers:this.layers,metadata:this.metadata}}lines2commands(e){return e.map((n=>this.parseCommand(n)))}parseCommand(e,n=!0){var r;const a=e.trim().split(";"),s=a[0],o=n&&a[1]||void 0,l=s.split(/([a-zA-Z])/g).slice(1).map((d=>d.trim())),c=l.length?`${(r=l[0])===null||r===void 0?void 0:r.toLowerCase()}${l[1]}`:"",u=this.parseParams(l.slice(2));switch(c){case"g0":case"g00":case"g1":case"g01":case"g2":case"g02":case"g3":case"g03":return new Y$(e,c,u,o);case"t0":return new Vm(e,c,o,0);case"t1":return new Vm(e,c,o,1);case"t2":return new Vm(e,c,o,2);case"t3":return new Vm(e,c,o,3);case"t4":return new Vm(e,c,o,4);case"t5":return new Vm(e,c,o,5);case"t6":return new Vm(e,c,o,6);case"t7":return new Vm(e,c,o,7);default:return new AO(e,c,u,o)}}parseMove(e){return e.reduce(((n,r)=>{const a=r.charAt(0).toLowerCase();return a!="x"&&a!="y"&&a!="z"&&a!="e"&&a!="r"&&a!="f"&&a!="i"&&a!="j"||(n[a]=parseFloat(r.slice(1))),n}),{})}isAlpha(e){const n=e.charCodeAt(0);return n>=97&&n<=122||n>=65&&n<=90}parseParams(e){return e.reduce(((n,r,a,s)=>{if(a%2==0)return n;let o=s[a-1];return o=o.toLowerCase(),this.isAlpha(o)&&(n[o]=parseFloat(r)),n}),{})}groupIntoLayers(e){var n;for(let r=0;r0&&(s.x!=null||s.y!=null)&&Math.abs(this.curZ-(this.maxZ||-1/0))>this.tolerance){const o=Math.abs(this.curZ-this.maxZ);this.maxZ=this.curZ,this.layers.push(new X$(this.layers.length,[],r,o))}}this.maxLayer.commands.push(a)}return this.layers}get maxLayer(){var e;return(e=this.layers[this.layers.length-1])!==null&&e!==void 0?e:this.preamble}parseMetadata(e){const n={};let r;for(const a of e){const s=a.comment;if(!s)continue;const o=s.indexOf("thumbnail begin"),l=s.indexOf("thumbnail end");o>-1?r=TO.parse(s.slice(o+15).trim()):r&&(l==-1?r.chars+=s.trim():(r.isValid&&(n[r.size]=r),r=void 0))}return{thumbnails:n}}}tk.prototype.parseGcode=tk.prototype.parseGCode;const Q$={type:"change"},pj={type:"start"},Z$={type:"end"},u1=new SO,J$=new Qm,JPe=Math.cos(70*pZ.DEG2RAD);class eMe extends ig{constructor(e,n){super(),this.object=e,this.domElement=n,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new at,this.cursor=new at,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:tb.ROTATE,MIDDLE:tb.DOLLY,RIGHT:tb.PAN},this.touches={ONE:nb.ROTATE,TWO:nb.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return l.phi},this.getAzimuthalAngle=function(){return l.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function($){$.addEventListener("keydown",K),this._domElementKeyEvents=$},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",K),this._domElementKeyEvents=null},this.saveState=function(){r.target0.copy(r.target),r.position0.copy(r.object.position),r.zoom0=r.object.zoom},this.reset=function(){r.target.copy(r.target0),r.object.position.copy(r.position0),r.object.zoom=r.zoom0,r.object.updateProjectionMatrix(),r.dispatchEvent(Q$),r.update(),s=a.NONE},this.update=(function(){const $=new at,ee=new If().setFromUnitVectors(e.up,new at(0,1,0)),W=ee.clone().invert(),ie=new at,ce=new If,be=new at,xe=2*Math.PI;return function(oe=null){const L=r.object.position;$.copy(L).sub(r.target),$.applyQuaternion(ee),l.setFromVector3($),r.autoRotate&&s===a.NONE&&R((function(fe){return fe!==null?2*Math.PI/60*r.autoRotateSpeed*fe:2*Math.PI/60/60*r.autoRotateSpeed})(oe)),r.enableDamping?(l.theta+=c.theta*r.dampingFactor,l.phi+=c.phi*r.dampingFactor):(l.theta+=c.theta,l.phi+=c.phi);let F=r.minAzimuthAngle,te=r.maxAzimuthAngle;isFinite(F)&&isFinite(te)&&(F<-Math.PI?F+=xe:F>Math.PI&&(F-=xe),te<-Math.PI?te+=xe:te>Math.PI&&(te-=xe),l.theta=F<=te?Math.max(F,Math.min(te,l.theta)):l.theta>(F+te)/2?Math.max(F,l.theta):Math.min(te,l.theta)),l.phi=Math.max(r.minPolarAngle,Math.min(r.maxPolarAngle,l.phi)),l.makeSafe(),r.enableDamping===!0?r.target.addScaledVector(d,r.dampingFactor):r.target.add(d),r.target.sub(r.cursor),r.target.clampLength(r.minTargetRadius,r.maxTargetRadius),r.target.add(r.cursor),r.zoomToCursor&&P||r.object.isOrthographicCamera?l.radius=ue(l.radius):l.radius=ue(l.radius*u),$.setFromSpherical(l),$.applyQuaternion(W),L.copy(r.target).add($),r.object.lookAt(r.target),r.enableDamping===!0?(c.theta*=1-r.dampingFactor,c.phi*=1-r.dampingFactor,d.multiplyScalar(1-r.dampingFactor)):(c.set(0,0,0),d.set(0,0,0));let ve=!1;if(r.zoomToCursor&&P){let fe=null;if(r.object.isPerspectiveCamera){const me=$.length();fe=ue(me*u);const je=me-fe;r.object.position.addScaledVector(C,je),r.object.updateMatrixWorld()}else if(r.object.isOrthographicCamera){const me=new at(k.x,k.y,0);me.unproject(r.object),r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom/u)),r.object.updateProjectionMatrix(),ve=!0;const je=new at(k.x,k.y,0);je.unproject(r.object),r.object.position.sub(je).add(me),r.object.updateMatrixWorld(),fe=$.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),r.zoomToCursor=!1;fe!==null&&(this.screenSpacePanning?r.target.set(0,0,-1).transformDirection(r.object.matrix).multiplyScalar(fe).add(r.object.position):(u1.origin.copy(r.object.position),u1.direction.set(0,0,-1).transformDirection(r.object.matrix),Math.abs(r.object.up.dot(u1.direction))o||8*(1-ce.dot(r.object.quaternion))>o||be.distanceToSquared(r.target)>0)&&(r.dispatchEvent(Q$),ie.copy(r.object.position),ce.copy(r.object.quaternion),be.copy(r.target),!0)}})(),this.dispose=function(){r.domElement.removeEventListener("contextmenu",H),r.domElement.removeEventListener("pointerdown",X),r.domElement.removeEventListener("pointercancel",E),r.domElement.removeEventListener("wheel",U),r.domElement.removeEventListener("pointermove",j),r.domElement.removeEventListener("pointerup",E),r._domElementKeyEvents!==null&&(r._domElementKeyEvents.removeEventListener("keydown",K),r._domElementKeyEvents=null)};const r=this,a={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let s=a.NONE;const o=1e-6,l=new G$,c=new G$;let u=1;const d=new at,m=new Fn,p=new Fn,f=new Fn,y=new Fn,v=new Fn,b=new Fn,g=new Fn,_=new Fn,N=new Fn,C=new at,k=new Fn;let P=!1;const T=[],D={};function A(){return Math.pow(.95,r.zoomSpeed)}function R($){c.theta-=$}function G($){c.phi-=$}const z=(function(){const $=new at;return function(ee,W){$.setFromMatrixColumn(W,0),$.multiplyScalar(-ee),d.add($)}})(),Z=(function(){const $=new at;return function(ee,W){r.screenSpacePanning===!0?$.setFromMatrixColumn(W,1):($.setFromMatrixColumn(W,0),$.crossVectors(r.object.up,$)),$.multiplyScalar(ee),d.add($)}})(),I=(function(){const $=new at;return function(ee,W){const ie=r.domElement;if(r.object.isPerspectiveCamera){const ce=r.object.position;$.copy(ce).sub(r.target);let be=$.length();be*=Math.tan(r.object.fov/2*Math.PI/180),z(2*ee*be/ie.clientHeight,r.object.matrix),Z(2*W*be/ie.clientHeight,r.object.matrix)}else r.object.isOrthographicCamera?(z(ee*(r.object.right-r.object.left)/r.object.zoom/ie.clientWidth,r.object.matrix),Z(W*(r.object.top-r.object.bottom)/r.object.zoom/ie.clientHeight,r.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),r.enablePan=!1)}})();function J($){r.object.isPerspectiveCamera||r.object.isOrthographicCamera?u/=$:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function ae($){r.object.isPerspectiveCamera||r.object.isOrthographicCamera?u*=$:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function Y($){if(!r.zoomToCursor)return;P=!0;const ee=r.domElement.getBoundingClientRect(),W=$.clientX-ee.left,ie=$.clientY-ee.top,ce=ee.width,be=ee.height;k.x=W/ce*2-1,k.y=-ie/be*2+1,C.set(k.x,k.y,1).unproject(r.object).sub(r.object.position).normalize()}function ue($){return Math.max(r.minDistance,Math.min(r.maxDistance,$))}function de($){m.set($.clientX,$.clientY)}function he($){y.set($.clientX,$.clientY)}function V(){if(T.length===1)m.set(T[0].pageX,T[0].pageY);else{const $=.5*(T[0].pageX+T[1].pageX),ee=.5*(T[0].pageY+T[1].pageY);m.set($,ee)}}function ne(){if(T.length===1)y.set(T[0].pageX,T[0].pageY);else{const $=.5*(T[0].pageX+T[1].pageX),ee=.5*(T[0].pageY+T[1].pageY);y.set($,ee)}}function se(){const $=T[0].pageX-T[1].pageX,ee=T[0].pageY-T[1].pageY,W=Math.sqrt($*$+ee*ee);g.set(0,W)}function pe($){if(T.length==1)p.set($.pageX,$.pageY);else{const W=O($),ie=.5*($.pageX+W.x),ce=.5*($.pageY+W.y);p.set(ie,ce)}f.subVectors(p,m).multiplyScalar(r.rotateSpeed);const ee=r.domElement;R(2*Math.PI*f.x/ee.clientHeight),G(2*Math.PI*f.y/ee.clientHeight),m.copy(p)}function Te($){if(T.length===1)v.set($.pageX,$.pageY);else{const ee=O($),W=.5*($.pageX+ee.x),ie=.5*($.pageY+ee.y);v.set(W,ie)}b.subVectors(v,y).multiplyScalar(r.panSpeed),I(b.x,b.y),y.copy(v)}function q($){const ee=O($),W=$.pageX-ee.x,ie=$.pageY-ee.y,ce=Math.sqrt(W*W+ie*ie);_.set(0,ce),N.set(0,Math.pow(_.y/g.y,r.zoomSpeed)),J(N.y),g.copy(_)}function X($){r.enabled!==!1&&(T.length===0&&(r.domElement.setPointerCapture($.pointerId),r.domElement.addEventListener("pointermove",j),r.domElement.addEventListener("pointerup",E)),(function(ee){T.push(ee)})($),$.pointerType==="touch"?(function(ee){switch(re(ee),T.length){case 1:switch(r.touches.ONE){case nb.ROTATE:if(r.enableRotate===!1)return;V(),s=a.TOUCH_ROTATE;break;case nb.PAN:if(r.enablePan===!1)return;ne(),s=a.TOUCH_PAN;break;default:s=a.NONE}break;case 2:switch(r.touches.TWO){case nb.DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;r.enableZoom&&se(),r.enablePan&&ne(),s=a.TOUCH_DOLLY_PAN;break;case nb.DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;r.enableZoom&&se(),r.enableRotate&&V(),s=a.TOUCH_DOLLY_ROTATE;break;default:s=a.NONE}break;default:s=a.NONE}s!==a.NONE&&r.dispatchEvent(pj)})($):(function(ee){let W;switch(ee.button){case 0:W=r.mouseButtons.LEFT;break;case 1:W=r.mouseButtons.MIDDLE;break;case 2:W=r.mouseButtons.RIGHT;break;default:W=-1}switch(W){case tb.DOLLY:if(r.enableZoom===!1)return;(function(ie){Y(ie),g.set(ie.clientX,ie.clientY)})(ee),s=a.DOLLY;break;case tb.ROTATE:if(ee.ctrlKey||ee.metaKey||ee.shiftKey){if(r.enablePan===!1)return;he(ee),s=a.PAN}else{if(r.enableRotate===!1)return;de(ee),s=a.ROTATE}break;case tb.PAN:if(ee.ctrlKey||ee.metaKey||ee.shiftKey){if(r.enableRotate===!1)return;de(ee),s=a.ROTATE}else{if(r.enablePan===!1)return;he(ee),s=a.PAN}break;default:s=a.NONE}s!==a.NONE&&r.dispatchEvent(pj)})($))}function j($){r.enabled!==!1&&($.pointerType==="touch"?(function(ee){switch(re(ee),s){case a.TOUCH_ROTATE:if(r.enableRotate===!1)return;pe(ee),r.update();break;case a.TOUCH_PAN:if(r.enablePan===!1)return;Te(ee),r.update();break;case a.TOUCH_DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;(function(W){r.enableZoom&&q(W),r.enablePan&&Te(W)})(ee),r.update();break;case a.TOUCH_DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;(function(W){r.enableZoom&&q(W),r.enableRotate&&pe(W)})(ee),r.update();break;default:s=a.NONE}})($):(function(ee){switch(s){case a.ROTATE:if(r.enableRotate===!1)return;(function(W){p.set(W.clientX,W.clientY),f.subVectors(p,m).multiplyScalar(r.rotateSpeed);const ie=r.domElement;R(2*Math.PI*f.x/ie.clientHeight),G(2*Math.PI*f.y/ie.clientHeight),m.copy(p),r.update()})(ee);break;case a.DOLLY:if(r.enableZoom===!1)return;(function(W){_.set(W.clientX,W.clientY),N.subVectors(_,g),N.y>0?J(A()):N.y<0&&ae(A()),g.copy(_),r.update()})(ee);break;case a.PAN:if(r.enablePan===!1)return;(function(W){v.set(W.clientX,W.clientY),b.subVectors(v,y).multiplyScalar(r.panSpeed),I(b.x,b.y),y.copy(v),r.update()})(ee)}})($))}function E($){(function(ee){delete D[ee.pointerId];for(let W=0;W0&&J(A()),r.update()})($),r.dispatchEvent(Z$))}function K($){r.enabled!==!1&&r.enablePan!==!1&&(function(ee){let W=!1;switch(ee.code){case r.keys.UP:ee.ctrlKey||ee.metaKey||ee.shiftKey?G(2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):I(0,r.keyPanSpeed),W=!0;break;case r.keys.BOTTOM:ee.ctrlKey||ee.metaKey||ee.shiftKey?G(-2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):I(0,-r.keyPanSpeed),W=!0;break;case r.keys.LEFT:ee.ctrlKey||ee.metaKey||ee.shiftKey?R(2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):I(r.keyPanSpeed,0),W=!0;break;case r.keys.RIGHT:ee.ctrlKey||ee.metaKey||ee.shiftKey?R(-2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):I(-r.keyPanSpeed,0),W=!0}W&&(ee.preventDefault(),r.update())})($)}function H($){r.enabled!==!1&&$.preventDefault()}function re($){let ee=D[$.pointerId];ee===void 0&&(ee=new Fn,D[$.pointerId]=ee),ee.set($.pageX,$.pageY)}function O($){const ee=$.pointerId===T[0].pointerId?T[1]:T[0];return D[ee.pointerId]}r.domElement.addEventListener("contextmenu",H),r.domElement.addEventListener("pointerdown",X),r.domElement.addEventListener("pointercancel",E),r.domElement.addEventListener("wheel",U,{passive:!1}),this.update()}}Vt.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new Fn(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},go.line={uniforms:_O.merge([Vt.common,Vt.fog,Vt.line]),vertexShader:` #include #include #include @@ -8428,7 +8428,7 @@ void main() { #include } - `};class FZ extends $h{constructor(e){super({type:"LineMaterial",uniforms:_O.clone(go.line.uniforms),vertexShader:go.line.vertexShader,fragmentShader:go.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return"USE_DASH"in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?(this.defines.USE_ALPHA_TO_COVERAGE="",this.extensions.derivatives=!0):(delete this.defines.USE_ALPHA_TO_COVERAGE,this.extensions.derivatives=!1))}}const eq=new Bl,d1=new at;class LZ extends IPe{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type="LineSegmentsGeometry",this.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),this.setAttribute("position",new Ki([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],3)),this.setAttribute("uv",new Ki([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(e){const n=this.attributes.instanceStart,r=this.attributes.instanceEnd;return n!==void 0&&(n.applyMatrix4(e),r.applyMatrix4(e),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let n;e instanceof Float32Array?n=e:Array.isArray(e)&&(n=new Float32Array(e));const r=new ER(n,6,1);return this.setAttribute("instanceStart",new fh(r,3,0)),this.setAttribute("instanceEnd",new fh(r,3,3)),this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let n;e instanceof Float32Array?n=e:Array.isArray(e)&&(n=new Float32Array(e));const r=new ER(n,6,1);return this.setAttribute("instanceColorStart",new fh(r,3,0)),this.setAttribute("instanceColorEnd",new fh(r,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new EPe(e.geometry)),this}fromLineSegments(e){const n=e.geometry;return this.setPositions(n.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Bl);const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;e!==void 0&&n!==void 0&&(this.boundingBox.setFromBufferAttribute(e),eq.setFromBufferAttribute(n),this.boundingBox.union(eq))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new pu),this.boundingBox===null&&this.computeBoundingBox();const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;if(e!==void 0&&n!==void 0){const r=this.boundingSphere.center;this.boundingBox.getCenter(r);let a=0;for(let s=0,o=e.count;sk&&Ya.z>k)continue;if(Ka.z>k){const z=Ka.z-Ya.z,Z=(Ka.z-k)/z;Ka.lerp(Ya,Z)}else if(Ya.z>k){const z=Ya.z-Ka.z,Z=(Ya.z-k)/z;Ya.lerp(Ka,Z)}Ka.applyMatrix4(y),Ya.applyMatrix4(y),Ka.multiplyScalar(1/Ka.w),Ya.multiplyScalar(1/Ya.w),Ka.x*=v.x/2,Ka.y*=v.y/2,Ya.x*=v.x/2,Ya.y*=v.y/2,Xa.start.copy(Ka),Xa.start.z=0,Xa.end.copy(Ya),Xa.end.z=0;const D=Xa.closestPointToPointParameter(f2,!0);Xa.at(D,rq);const A=pZ.lerp(Ka.z,Ya.z,D),R=A>=-1&&A<=1,G=f2.distanceTo(rq)<.5*Yp;if(R&&G){Xa.start.fromBufferAttribute(_,P),Xa.end.fromBufferAttribute(N,P),Xa.start.applyMatrix4(b),Xa.end.applyMatrix4(b);const z=new at,Z=new at;Kc.distanceSqToSegment(Xa.start,Xa.end,Z,z),f.push({point:Z,pointOnLine:z,distance:Kc.origin.distanceTo(Z),object:m,face:null,faceIndex:P,uv:null,uv1:null})}}})(this,a,n)))}}class nMe extends _T{constructor(e,n,r,a,s=4473924,o=8947848){s=new vn(s),o=new vn(o);const l=Math.round(e/n);r=Math.round(r/a)*a/2;const c=[],u=[];let d=0;for(let p=-1*(e=l*n/2);p<=e;p+=n){c.push(p,0,-1*r,p,0,r);const f=p===0?s:o;f.toArray(u,d),d+=3,f.toArray(u,d),d+=3,f.toArray(u,d),d+=3,f.toArray(u,d),d+=3}for(let p=-1*r;p<=r;p+=a){c.push(-1*e,0,p,e,0,p);const f=p===0?s:o;f.toArray(u,d),d+=3,f.toArray(u,d),d+=3,f.toArray(u,d),d+=3,f.toArray(u,d),d+=3}const m=new _s;m.setAttribute("position",new Ki(c,3)),m.setAttribute("color",new Ki(u,3)),super(m,new Cw({vertexColors:!0,toneMapped:!1}))}}function rMe(t,e,n,r){const a=(function(o,l,c){o*=.5,l*=.5,c*=.5;const u=new _s,d=[];return d.push(-o,-l,-c,-o,l,-c,-o,l,-c,o,l,-c,o,l,-c,o,-l,-c,o,-l,-c,-o,-l,-c,-o,-l,c,-o,l,c,-o,l,c,o,l,c,o,l,c,o,-l,c,o,-l,c,-o,-l,c,-o,-l,-c,-o,-l,c,-o,l,-c,-o,l,c,o,l,-c,o,l,c,o,-l,-c,o,-l,c),u.setAttribute("position",new Ki(d,3)),u})(t,e,n),s=new _T(a,new DPe({color:new vn(r),dashSize:3,gapSize:1}));return s.computeLineDistances(),s}var Qv=function(){var t=0,e=document.createElement("div");function n(d){return e.appendChild(d.dom),d}function r(d){for(var m=0;m=s+1e3&&(l.update(1e3*o/(d-s),100),s=d,o=0,u)){var m=performance.memory;u.update(m.usedJSHeapSize/1048576,m.jsHeapSizeLimit/1048576)}return d},update:function(){a=this.end()},domElement:e,setMode:r}};Qv.Panel=function(t,e,n){var r=1/0,a=0,s=Math.round,o=s(window.devicePixelRatio||1),l=80*o,c=48*o,u=3*o,d=2*o,m=3*o,p=15*o,f=74*o,y=30*o,v=document.createElement("canvas");v.width=l,v.height=c,v.style.cssText="width:80px;height:48px";var b=v.getContext("2d");return b.font="bold "+9*o+"px Helvetica,Arial,sans-serif",b.textBaseline="top",b.fillStyle=n,b.fillRect(0,0,l,c),b.fillStyle=e,b.fillText(t,u,d),b.fillRect(m,p,f,y),b.fillStyle=n,b.globalAlpha=.9,b.fillRect(m,p,f,y),{dom:v,update:function(g,_){r=Math.min(r,g),a=Math.max(a,g),b.fillStyle=n,b.globalAlpha=1,b.fillRect(0,0,l,p),b.fillStyle=e,b.fillText(s(g)+" "+t+" ("+s(r)+"-"+s(a)+")",u,d),b.drawImage(v,m+o,p,f-o,y,m,p,f-o,y),b.fillRect(m+f-o,p,o,y),b.fillStyle=n,b.globalAlpha=.9,b.fillRect(m+f-o,p,o,s((1-g/_)*y))}}};var iMe=Qv;class aq{constructor(e,n){this.openFolders=[],this.watchedObject=e,this.options=n,this.gui=new ek,this.gui.title("Dev info"),this.setup()}setup(){this.loadOpenFolders(),this.options&&!this.options.renderer||this.setupRedererFolder(),this.options&&!this.options.camera||this.setupCameraFolder(),this.options&&!this.options.parser||this.setupParserFolder(),this.options&&!this.options.buildVolume||this.setupBuildVolumeFolder(),this.options&&!this.options.devHelpers||this.setupDevHelpers()}reset(){this.gui.destroy(),this.gui=new ek,this.gui.title("Dev info"),this.setup()}loadOpenFolders(){this.openFolders=JSON.parse(localStorage.getItem("dev-gui-open")||"{}").open||[]}saveOpenFolders(){this.openFolders=this.gui.foldersRecursive().filter((e=>!e._closed)).map((e=>e._title)),console.log(this.openFolders),localStorage.setItem("dev-gui-open",JSON.stringify({open:this.openFolders}))}setupRedererFolder(){const e=this.gui.addFolder("Render Info");this.openFolders.includes("Render Info")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.renderer.info.render,"triangles").listen(),e.add(this.watchedObject.renderer.info.render,"calls").listen(),e.add(this.watchedObject.renderer.info.render,"lines").listen(),e.add(this.watchedObject.renderer.info.render,"points").listen(),e.add(this.watchedObject.renderer.info.memory,"geometries").listen(),e.add(this.watchedObject.renderer.info.memory,"textures").listen(),e.add(this.watchedObject,"_lastRenderTime").listen()}setupCameraFolder(){const e=this.gui.addFolder("Camera");this.openFolders.includes("Camera")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()}));const n=e.addFolder("Camera position");n.add(this.watchedObject.camera.position,"x").listen(),n.add(this.watchedObject.camera.position,"y").listen(),n.add(this.watchedObject.camera.position,"z").listen();const r=e.addFolder("Camera rotation");r.add(this.watchedObject.camera.rotation,"x").listen(),r.add(this.watchedObject.camera.rotation,"y").listen(),r.add(this.watchedObject.camera.rotation,"z").listen()}setupParserFolder(){const e=this.gui.addFolder("Parser");this.openFolders.includes("Parser")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.parser,"curZ").listen(),e.add(this.watchedObject.parser,"maxZ").listen(),e.add(this.watchedObject.parser,"tolerance").listen(),e.add(this.watchedObject.parser.layers,"length").name("layers.count").listen(),e.add(this.watchedObject.parser.lines,"length").name("lines.count").listen()}setupBuildVolumeFolder(){const e=this.gui.addFolder("Build Volume");this.openFolders.includes("Build Volume")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.buildVolume,"x").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject.buildVolume,"y").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject.buildVolume,"z").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()}))}setupDevHelpers(){const e=this.gui.addFolder("Dev Helpers");this.openFolders.includes("Dev Helpers")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject,"_wireframe").listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject,"render").listen(),e.add(this.watchedObject,"clear").listen()}}class aMe extends _s{constructor(e=[new at],n=.6,r=.2,a=8){super(),this.type="ExtrusionGeometry",this.parameters={points:e,lineWidth:n,lineHeight:r,radialSegments:a,closed:!1};const s=new at,o=new at,l=new Fn,c=[],u=[],d=[],m=[];function p(f){const[y,v,b]=(function(g){const _=e[g],N=new at,C=new at,k=new at,P=new at;N.copy(_).sub(e[g-1]||_).normalize().add((e[g+1]||_).clone().sub(_).normalize()).normalize();let T=Number.MAX_VALUE;const D=Math.abs(N.x),A=Math.abs(N.y),R=Math.abs(N.z);return D<=T&&(T=D,C.set(1,0,0)),A<=T&&(T=A,C.set(0,1,0)),R<=T&&C.set(0,0,1),P.crossVectors(N,C).normalize(),C.crossVectors(N,P),k.crossVectors(N,C),[_,C,k]})(f);for(let g=0;g<=a;g++){const _=g/a*Math.PI*2,N=Math.sin(_),C=-Math.cos(_);o.x=C*v.x+N*b.x,o.y=C*v.y+N*b.y,o.z=C*v.z+N*b.z,o.normalize(),u.push(o.x,o.y,o.z),s.x=y.x+n*o.x*.5,s.y=y.y+n*o.y*.5,s.z=y.z+r*o.z*.5,c.push(s.x,s.y,s.z)}}(function(){for(let f=0;fthis.animate())),this.controls.update(),this.renderer.render(this.scene,this.camera),(e=this.stats)===null||e===void 0||e.update()}processGCode(e){this.parser.parseGCode(e),this.render()}initScene(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0]);for(;this.disposables.length>0;){const e=this.disposables.pop();e&&e.dispose()}if(this.debug&&this.buildVolume){const e=new UPe(Math.max(this.buildVolume.x/2,this.buildVolume.y/2)+20);this.scene.add(e)}if(this.buildVolume&&this.drawBuildVolume(),this.renderTubes){console.warn("Volumetric rendering is experimental. It may not work as expected or change in the future.");const e=new OPe(13421772,.3*Math.PI),n=new LPe(16777215,Math.PI,void 0,.001);n.position.set(0,500,500),this.scene.add(e),this.scene.add(n)}}createGroup(e){const n=new Rv;return n.name=e,n.quaternion.setFromEuler(new Nw(-Math.PI/2,0,0)),this.buildVolume?n.position.set(-this.buildVolume.x/2,0,this.buildVolume.y/2):n.position.set(-100,0,100),n}render(){const e=performance.now();this.group=this.createGroup("allLayers"),this.state=Zv.initial,this.initScene();for(let n=0;n0?e:1)}))}renderFrameLoop(e){return new Promise((n=>{const r=()=>{this.renderLayerIndex>this.layers.length-1?n():(this.renderFrame(e),requestAnimationFrame(r))};r()}))}renderFrame(e){this.group=this.createGroup("layer"+this.renderLayerIndex);for(let n=0;nthis.maxLayerIndex)return;const d=this.layers[e],m={extrusion:[],travel:[],z:this.state.z,height:d.height};for(const p of d.commands)if(p.gcode!="g20"){if(p.gcode.startsWith("t")){this.doRenderExtrusion(m,e),m.extrusion=[];const f=p;this.state.t=f.toolIndex}else if(["g0","g00","g1","g01","g2","g02","g3","g03"].indexOf(p.gcode)>-1){const f=p,y={x:(n=f.params.x)!==null&&n!==void 0?n:this.state.x,y:(r=f.params.y)!==null&&r!==void 0?r:this.state.y,z:(a=f.params.z)!==null&&a!==void 0?a:this.state.z,r:(s=f.params.r)!==null&&s!==void 0?s:this.state.r,e:(o=f.params.e)!==null&&o!==void 0?o:this.state.e,i:(l=f.params.i)!==null&&l!==void 0?l:this.state.i,j:(c=f.params.j)!==null&&c!==void 0?c:this.state.j,t:this.state.t};if(e>=this.minLayerIndex){const v=((u=f.params.e)!==null&&u!==void 0?u:0)>0||this.nonTravelmoves.indexOf(p.gcode)>-1;(y.x!=this.state.x||y.y!=this.state.y||y.z!=this.state.z)&&(v&&this.renderExtrusion||!v&&this.renderTravel)&&(p.gcode=="g2"||p.gcode=="g3"||p.gcode=="g02"||p.gcode=="g03"?this.addArcSegment(m,this.state,y,v,p.gcode=="g2"||p.gcode=="g02"):this.addLineSegment(m,this.state,y,v))}this.state.x=y.x,this.state.y=y.y,this.state.z=y.z,this.beyondFirstMove||(this.beyondFirstMove=!0)}}else this.setInches();this.doRenderExtrusion(m,e)}doRenderExtrusion(e,n){var r,a;if(this.renderExtrusion){let s=this.currentToolColor;if(!this.singleLayerMode&&!this.renderTubes&&!this.disableGradient){const o=.1+.7*n/this.layers.length;s.getHSL(b2),s=new vn().setHSL(b2.h,b2.s,o)}if(n==this.layers.length-1){const o=(r=this._topLayerColor)!==null&&r!==void 0?r:s,l=(a=this._lastSegmentColor)!==null&&a!==void 0?a:o,c=e.extrusion.splice(-3),u=e.extrusion.splice(-3);this.renderTubes?(this.addTubeLine(e.extrusion,o.getHex(),e.height),this.addTubeLine([...u,...c],l.getHex(),e.height)):(this.addLine(e.extrusion,o.getHex()),this.addLine([...u,...c],l.getHex()))}else this.renderTubes?this.addTubeLine(e.extrusion,s.getHex(),e.height):this.addLine(e.extrusion,s.getHex())}this.renderTravel&&this.addLine(e.travel,this._travelColor.getHex())}setInches(){this.beyondFirstMove?console.warn("Switching units after movement is already made is discouraged and is not supported."):this.inches=!0}drawBuildVolume(){if(!this.buildVolume)return;this.scene.add(new nMe(this.buildVolume.x,10,this.buildVolume.y,10));const e=rMe(this.buildVolume.x,this.buildVolume.z,this.buildVolume.y,8947848);e.position.setY(this.buildVolume.z/2),this.scene.add(e)}clear(){this.resetState(),this.parser=new tk(this.minLayerThreshold)}resetState(){var e;this.startLayer=1,this.endLayer=1/0,this.singleLayerMode=!1,this.beyondFirstMove=!1,this.state=Zv.initial,(e=this.devGui)===null||e===void 0||e.reset(),this._geometries={}}resize(){const[e,n]=[this.canvas.offsetWidth,this.canvas.offsetHeight];this.camera.aspect=e/n,this.camera.updateProjectionMatrix(),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(e,n,!1)}addLineSegment(e,n,r,a){(a?e.extrusion:e.travel).push(n.x,n.y,n.z,r.x,r.y,r.z)}addArcSegment(e,n,r,a,s){const o=a?e.extrusion:e.travel,l=n.x,c=n.y,u=n.z,d=r.x,m=r.y,p=r.z;let f=r.r,y=r.i,v=r.j;if(f){const J=d-l,ae=m-c,Y=Math.sqrt(Math.pow(J/2,2)+Math.pow(ae/2,2));f=Math.max(f,Y);const ue=Math.pow(J,2)+Math.pow(ae,2),de=Math.pow(f,2)-ue/4;let he=Math.sqrt(de/ue);(s&&f<0||!s&&f>0)&&(he=-he),y=J/2+ae*he,v=ae/2-J*he}const b=l==d&&c==m,g=l+y,_=c+v,N=Math.sqrt(y*y+v*v),C=Math.atan2(-v,-y),k=Math.atan2(m-_,d-g);let P;b?P=2*Math.PI:(P=s?C-k:k-C,P<0&&(P+=2*Math.PI));let T=N*P/1.8;this.inches&&(T*=25),T<1&&(T=1);let D=P/T;D*=s?-1:1;const A=[];A.push({x:l,y:c,z:u});const R=(u-p)/T;let G=l,z=c,Z=u,I=C;for(let J=0;J0)return void this.addThickLine(e,n);const a=new _s;a.setAttribute("position",new Ki(e,3)),this.disposables.push(a);const s=new Cw({color:n});this.disposables.push(s);const o=new _T(a,s);(r=this.group)===null||r===void 0||r.add(o)}addTubeLine(e,n,r=.2){let a=[];const s=[];for(let o=0;o{var l;const c=new aMe(o,this.extrusionWidth,this.lineHeight||r,4);(l=this._geometries)[n]||(l[n]=[]),this._geometries[n].push(c)}))}addThickLine(e,n){var r;if(!e.length||!this.lineWidth)return;const a=new LZ;this.disposables.push(a);const s=new FZ({color:n,linewidth:this.lineWidth/(1e3*window.devicePixelRatio)});this.disposables.push(s),a.setPositions(e);const o=new tMe(a,s);(r=this.group)===null||r===void 0||r.add(o)}dispose(){this.disposables.forEach((e=>e.dispose())),this.disposables=[],this.controls.dispose(),this.renderer.dispose(),this.cancelAnimation()}cancelAnimation(){this.animationFrameId!==void 0&&cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0}_enableDropHandler(){console.warn("Drag and drop is deprecated as a library feature. See the demo how to implement your own."),this.canvas.addEventListener("dragover",(e=>{e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),this.canvas.classList.add("dragging")})),this.canvas.addEventListener("dragleave",(e=>{e.stopPropagation(),e.preventDefault(),this.canvas.classList.remove("dragging")})),this.canvas.addEventListener("drop",(e=>h2(this,void 0,void 0,(function*(){var n,r;e.stopPropagation(),e.preventDefault(),this.canvas.classList.remove("dragging");const a=((r=(n=e.dataTransfer)===null||n===void 0?void 0:n.files)!==null&&r!==void 0?r:[])[0];this.clear(),yield this._readFromStream(a.stream()),this.render()}))))}batchGeometries(){if(this._geometries)for(const e in this._geometries){const n=this.createBatchMesh(parseInt(e));for(;this._geometries[e].length>0;){const r=this._geometries[e].pop();n.addGeometry(r)}}}createBatchMesh(e){var n;const r=this._geometries[e],a=new jPe({color:e,wireframe:this._wireframe});this.disposables.push(a);const s=r.reduce(((l,c)=>3*c.attributes.position.count+l),0),o=new PPe(r.length,s,void 0,a);return this.disposables.push(o),(n=this.group)===null||n===void 0||n.add(o),o}_readFromStream(e){var n,r;return h2(this,void 0,void 0,(function*(){const a=e.getReader();let s,o="",l=0;do{console.debug("reading from stream"),s=yield a.read(),l+=(r=(n=s.value)===null||n===void 0?void 0:n.length)!==null&&r!==void 0?r:0;const u=(c=s.value,new TextDecoder("utf-8").decode(c)),d=u.lastIndexOf(` + `};class FZ extends $h{constructor(e){super({type:"LineMaterial",uniforms:_O.clone(go.line.uniforms),vertexShader:go.line.vertexShader,fragmentShader:go.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return"USE_DASH"in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?(this.defines.USE_ALPHA_TO_COVERAGE="",this.extensions.derivatives=!0):(delete this.defines.USE_ALPHA_TO_COVERAGE,this.extensions.derivatives=!1))}}const eq=new Bl,d1=new at;class LZ extends IPe{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type="LineSegmentsGeometry",this.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),this.setAttribute("position",new Ki([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],3)),this.setAttribute("uv",new Ki([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(e){const n=this.attributes.instanceStart,r=this.attributes.instanceEnd;return n!==void 0&&(n.applyMatrix4(e),r.applyMatrix4(e),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let n;e instanceof Float32Array?n=e:Array.isArray(e)&&(n=new Float32Array(e));const r=new ER(n,6,1);return this.setAttribute("instanceStart",new fh(r,3,0)),this.setAttribute("instanceEnd",new fh(r,3,3)),this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let n;e instanceof Float32Array?n=e:Array.isArray(e)&&(n=new Float32Array(e));const r=new ER(n,6,1);return this.setAttribute("instanceColorStart",new fh(r,3,0)),this.setAttribute("instanceColorEnd",new fh(r,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new EPe(e.geometry)),this}fromLineSegments(e){const n=e.geometry;return this.setPositions(n.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Bl);const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;e!==void 0&&n!==void 0&&(this.boundingBox.setFromBufferAttribute(e),eq.setFromBufferAttribute(n),this.boundingBox.union(eq))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new pu),this.boundingBox===null&&this.computeBoundingBox();const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;if(e!==void 0&&n!==void 0){const r=this.boundingSphere.center;this.boundingBox.getCenter(r);let a=0;for(let s=0,o=e.count;sk&&Ya.z>k)continue;if(Ka.z>k){const z=Ka.z-Ya.z,Z=(Ka.z-k)/z;Ka.lerp(Ya,Z)}else if(Ya.z>k){const z=Ya.z-Ka.z,Z=(Ya.z-k)/z;Ya.lerp(Ka,Z)}Ka.applyMatrix4(y),Ya.applyMatrix4(y),Ka.multiplyScalar(1/Ka.w),Ya.multiplyScalar(1/Ya.w),Ka.x*=v.x/2,Ka.y*=v.y/2,Ya.x*=v.x/2,Ya.y*=v.y/2,Xa.start.copy(Ka),Xa.start.z=0,Xa.end.copy(Ya),Xa.end.z=0;const D=Xa.closestPointToPointParameter(fj,!0);Xa.at(D,rq);const A=pZ.lerp(Ka.z,Ya.z,D),R=A>=-1&&A<=1,G=fj.distanceTo(rq)<.5*Yp;if(R&&G){Xa.start.fromBufferAttribute(_,P),Xa.end.fromBufferAttribute(N,P),Xa.start.applyMatrix4(b),Xa.end.applyMatrix4(b);const z=new at,Z=new at;Kc.distanceSqToSegment(Xa.start,Xa.end,Z,z),f.push({point:Z,pointOnLine:z,distance:Kc.origin.distanceTo(Z),object:m,face:null,faceIndex:P,uv:null,uv1:null})}}})(this,a,n)))}}class nMe extends _T{constructor(e,n,r,a,s=4473924,o=8947848){s=new vn(s),o=new vn(o);const l=Math.round(e/n);r=Math.round(r/a)*a/2;const c=[],u=[];let d=0;for(let p=-1*(e=l*n/2);p<=e;p+=n){c.push(p,0,-1*r,p,0,r);const f=p===0?s:o;f.toArray(u,d),d+=3,f.toArray(u,d),d+=3,f.toArray(u,d),d+=3,f.toArray(u,d),d+=3}for(let p=-1*r;p<=r;p+=a){c.push(-1*e,0,p,e,0,p);const f=p===0?s:o;f.toArray(u,d),d+=3,f.toArray(u,d),d+=3,f.toArray(u,d),d+=3,f.toArray(u,d),d+=3}const m=new _s;m.setAttribute("position",new Ki(c,3)),m.setAttribute("color",new Ki(u,3)),super(m,new Cw({vertexColors:!0,toneMapped:!1}))}}function rMe(t,e,n,r){const a=(function(o,l,c){o*=.5,l*=.5,c*=.5;const u=new _s,d=[];return d.push(-o,-l,-c,-o,l,-c,-o,l,-c,o,l,-c,o,l,-c,o,-l,-c,o,-l,-c,-o,-l,-c,-o,-l,c,-o,l,c,-o,l,c,o,l,c,o,l,c,o,-l,c,o,-l,c,-o,-l,c,-o,-l,-c,-o,-l,c,-o,l,-c,-o,l,c,o,l,-c,o,l,c,o,-l,-c,o,-l,c),u.setAttribute("position",new Ki(d,3)),u})(t,e,n),s=new _T(a,new DPe({color:new vn(r),dashSize:3,gapSize:1}));return s.computeLineDistances(),s}var Qv=function(){var t=0,e=document.createElement("div");function n(d){return e.appendChild(d.dom),d}function r(d){for(var m=0;m=s+1e3&&(l.update(1e3*o/(d-s),100),s=d,o=0,u)){var m=performance.memory;u.update(m.usedJSHeapSize/1048576,m.jsHeapSizeLimit/1048576)}return d},update:function(){a=this.end()},domElement:e,setMode:r}};Qv.Panel=function(t,e,n){var r=1/0,a=0,s=Math.round,o=s(window.devicePixelRatio||1),l=80*o,c=48*o,u=3*o,d=2*o,m=3*o,p=15*o,f=74*o,y=30*o,v=document.createElement("canvas");v.width=l,v.height=c,v.style.cssText="width:80px;height:48px";var b=v.getContext("2d");return b.font="bold "+9*o+"px Helvetica,Arial,sans-serif",b.textBaseline="top",b.fillStyle=n,b.fillRect(0,0,l,c),b.fillStyle=e,b.fillText(t,u,d),b.fillRect(m,p,f,y),b.fillStyle=n,b.globalAlpha=.9,b.fillRect(m,p,f,y),{dom:v,update:function(g,_){r=Math.min(r,g),a=Math.max(a,g),b.fillStyle=n,b.globalAlpha=1,b.fillRect(0,0,l,p),b.fillStyle=e,b.fillText(s(g)+" "+t+" ("+s(r)+"-"+s(a)+")",u,d),b.drawImage(v,m+o,p,f-o,y,m,p,f-o,y),b.fillRect(m+f-o,p,o,y),b.fillStyle=n,b.globalAlpha=.9,b.fillRect(m+f-o,p,o,s((1-g/_)*y))}}};var iMe=Qv;class aq{constructor(e,n){this.openFolders=[],this.watchedObject=e,this.options=n,this.gui=new ek,this.gui.title("Dev info"),this.setup()}setup(){this.loadOpenFolders(),this.options&&!this.options.renderer||this.setupRedererFolder(),this.options&&!this.options.camera||this.setupCameraFolder(),this.options&&!this.options.parser||this.setupParserFolder(),this.options&&!this.options.buildVolume||this.setupBuildVolumeFolder(),this.options&&!this.options.devHelpers||this.setupDevHelpers()}reset(){this.gui.destroy(),this.gui=new ek,this.gui.title("Dev info"),this.setup()}loadOpenFolders(){this.openFolders=JSON.parse(localStorage.getItem("dev-gui-open")||"{}").open||[]}saveOpenFolders(){this.openFolders=this.gui.foldersRecursive().filter((e=>!e._closed)).map((e=>e._title)),console.log(this.openFolders),localStorage.setItem("dev-gui-open",JSON.stringify({open:this.openFolders}))}setupRedererFolder(){const e=this.gui.addFolder("Render Info");this.openFolders.includes("Render Info")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.renderer.info.render,"triangles").listen(),e.add(this.watchedObject.renderer.info.render,"calls").listen(),e.add(this.watchedObject.renderer.info.render,"lines").listen(),e.add(this.watchedObject.renderer.info.render,"points").listen(),e.add(this.watchedObject.renderer.info.memory,"geometries").listen(),e.add(this.watchedObject.renderer.info.memory,"textures").listen(),e.add(this.watchedObject,"_lastRenderTime").listen()}setupCameraFolder(){const e=this.gui.addFolder("Camera");this.openFolders.includes("Camera")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()}));const n=e.addFolder("Camera position");n.add(this.watchedObject.camera.position,"x").listen(),n.add(this.watchedObject.camera.position,"y").listen(),n.add(this.watchedObject.camera.position,"z").listen();const r=e.addFolder("Camera rotation");r.add(this.watchedObject.camera.rotation,"x").listen(),r.add(this.watchedObject.camera.rotation,"y").listen(),r.add(this.watchedObject.camera.rotation,"z").listen()}setupParserFolder(){const e=this.gui.addFolder("Parser");this.openFolders.includes("Parser")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.parser,"curZ").listen(),e.add(this.watchedObject.parser,"maxZ").listen(),e.add(this.watchedObject.parser,"tolerance").listen(),e.add(this.watchedObject.parser.layers,"length").name("layers.count").listen(),e.add(this.watchedObject.parser.lines,"length").name("lines.count").listen()}setupBuildVolumeFolder(){const e=this.gui.addFolder("Build Volume");this.openFolders.includes("Build Volume")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.buildVolume,"x").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject.buildVolume,"y").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject.buildVolume,"z").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()}))}setupDevHelpers(){const e=this.gui.addFolder("Dev Helpers");this.openFolders.includes("Dev Helpers")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject,"_wireframe").listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject,"render").listen(),e.add(this.watchedObject,"clear").listen()}}class aMe extends _s{constructor(e=[new at],n=.6,r=.2,a=8){super(),this.type="ExtrusionGeometry",this.parameters={points:e,lineWidth:n,lineHeight:r,radialSegments:a,closed:!1};const s=new at,o=new at,l=new Fn,c=[],u=[],d=[],m=[];function p(f){const[y,v,b]=(function(g){const _=e[g],N=new at,C=new at,k=new at,P=new at;N.copy(_).sub(e[g-1]||_).normalize().add((e[g+1]||_).clone().sub(_).normalize()).normalize();let T=Number.MAX_VALUE;const D=Math.abs(N.x),A=Math.abs(N.y),R=Math.abs(N.z);return D<=T&&(T=D,C.set(1,0,0)),A<=T&&(T=A,C.set(0,1,0)),R<=T&&C.set(0,0,1),P.crossVectors(N,C).normalize(),C.crossVectors(N,P),k.crossVectors(N,C),[_,C,k]})(f);for(let g=0;g<=a;g++){const _=g/a*Math.PI*2,N=Math.sin(_),C=-Math.cos(_);o.x=C*v.x+N*b.x,o.y=C*v.y+N*b.y,o.z=C*v.z+N*b.z,o.normalize(),u.push(o.x,o.y,o.z),s.x=y.x+n*o.x*.5,s.y=y.y+n*o.y*.5,s.z=y.z+r*o.z*.5,c.push(s.x,s.y,s.z)}}(function(){for(let f=0;fthis.animate())),this.controls.update(),this.renderer.render(this.scene,this.camera),(e=this.stats)===null||e===void 0||e.update()}processGCode(e){this.parser.parseGCode(e),this.render()}initScene(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0]);for(;this.disposables.length>0;){const e=this.disposables.pop();e&&e.dispose()}if(this.debug&&this.buildVolume){const e=new UPe(Math.max(this.buildVolume.x/2,this.buildVolume.y/2)+20);this.scene.add(e)}if(this.buildVolume&&this.drawBuildVolume(),this.renderTubes){console.warn("Volumetric rendering is experimental. It may not work as expected or change in the future.");const e=new OPe(13421772,.3*Math.PI),n=new LPe(16777215,Math.PI,void 0,.001);n.position.set(0,500,500),this.scene.add(e),this.scene.add(n)}}createGroup(e){const n=new Rv;return n.name=e,n.quaternion.setFromEuler(new Nw(-Math.PI/2,0,0)),this.buildVolume?n.position.set(-this.buildVolume.x/2,0,this.buildVolume.y/2):n.position.set(-100,0,100),n}render(){const e=performance.now();this.group=this.createGroup("allLayers"),this.state=Zv.initial,this.initScene();for(let n=0;n0?e:1)}))}renderFrameLoop(e){return new Promise((n=>{const r=()=>{this.renderLayerIndex>this.layers.length-1?n():(this.renderFrame(e),requestAnimationFrame(r))};r()}))}renderFrame(e){this.group=this.createGroup("layer"+this.renderLayerIndex);for(let n=0;nthis.maxLayerIndex)return;const d=this.layers[e],m={extrusion:[],travel:[],z:this.state.z,height:d.height};for(const p of d.commands)if(p.gcode!="g20"){if(p.gcode.startsWith("t")){this.doRenderExtrusion(m,e),m.extrusion=[];const f=p;this.state.t=f.toolIndex}else if(["g0","g00","g1","g01","g2","g02","g3","g03"].indexOf(p.gcode)>-1){const f=p,y={x:(n=f.params.x)!==null&&n!==void 0?n:this.state.x,y:(r=f.params.y)!==null&&r!==void 0?r:this.state.y,z:(a=f.params.z)!==null&&a!==void 0?a:this.state.z,r:(s=f.params.r)!==null&&s!==void 0?s:this.state.r,e:(o=f.params.e)!==null&&o!==void 0?o:this.state.e,i:(l=f.params.i)!==null&&l!==void 0?l:this.state.i,j:(c=f.params.j)!==null&&c!==void 0?c:this.state.j,t:this.state.t};if(e>=this.minLayerIndex){const v=((u=f.params.e)!==null&&u!==void 0?u:0)>0||this.nonTravelmoves.indexOf(p.gcode)>-1;(y.x!=this.state.x||y.y!=this.state.y||y.z!=this.state.z)&&(v&&this.renderExtrusion||!v&&this.renderTravel)&&(p.gcode=="g2"||p.gcode=="g3"||p.gcode=="g02"||p.gcode=="g03"?this.addArcSegment(m,this.state,y,v,p.gcode=="g2"||p.gcode=="g02"):this.addLineSegment(m,this.state,y,v))}this.state.x=y.x,this.state.y=y.y,this.state.z=y.z,this.beyondFirstMove||(this.beyondFirstMove=!0)}}else this.setInches();this.doRenderExtrusion(m,e)}doRenderExtrusion(e,n){var r,a;if(this.renderExtrusion){let s=this.currentToolColor;if(!this.singleLayerMode&&!this.renderTubes&&!this.disableGradient){const o=.1+.7*n/this.layers.length;s.getHSL(bj),s=new vn().setHSL(bj.h,bj.s,o)}if(n==this.layers.length-1){const o=(r=this._topLayerColor)!==null&&r!==void 0?r:s,l=(a=this._lastSegmentColor)!==null&&a!==void 0?a:o,c=e.extrusion.splice(-3),u=e.extrusion.splice(-3);this.renderTubes?(this.addTubeLine(e.extrusion,o.getHex(),e.height),this.addTubeLine([...u,...c],l.getHex(),e.height)):(this.addLine(e.extrusion,o.getHex()),this.addLine([...u,...c],l.getHex()))}else this.renderTubes?this.addTubeLine(e.extrusion,s.getHex(),e.height):this.addLine(e.extrusion,s.getHex())}this.renderTravel&&this.addLine(e.travel,this._travelColor.getHex())}setInches(){this.beyondFirstMove?console.warn("Switching units after movement is already made is discouraged and is not supported."):this.inches=!0}drawBuildVolume(){if(!this.buildVolume)return;this.scene.add(new nMe(this.buildVolume.x,10,this.buildVolume.y,10));const e=rMe(this.buildVolume.x,this.buildVolume.z,this.buildVolume.y,8947848);e.position.setY(this.buildVolume.z/2),this.scene.add(e)}clear(){this.resetState(),this.parser=new tk(this.minLayerThreshold)}resetState(){var e;this.startLayer=1,this.endLayer=1/0,this.singleLayerMode=!1,this.beyondFirstMove=!1,this.state=Zv.initial,(e=this.devGui)===null||e===void 0||e.reset(),this._geometries={}}resize(){const[e,n]=[this.canvas.offsetWidth,this.canvas.offsetHeight];this.camera.aspect=e/n,this.camera.updateProjectionMatrix(),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(e,n,!1)}addLineSegment(e,n,r,a){(a?e.extrusion:e.travel).push(n.x,n.y,n.z,r.x,r.y,r.z)}addArcSegment(e,n,r,a,s){const o=a?e.extrusion:e.travel,l=n.x,c=n.y,u=n.z,d=r.x,m=r.y,p=r.z;let f=r.r,y=r.i,v=r.j;if(f){const J=d-l,ae=m-c,Y=Math.sqrt(Math.pow(J/2,2)+Math.pow(ae/2,2));f=Math.max(f,Y);const ue=Math.pow(J,2)+Math.pow(ae,2),de=Math.pow(f,2)-ue/4;let he=Math.sqrt(de/ue);(s&&f<0||!s&&f>0)&&(he=-he),y=J/2+ae*he,v=ae/2-J*he}const b=l==d&&c==m,g=l+y,_=c+v,N=Math.sqrt(y*y+v*v),C=Math.atan2(-v,-y),k=Math.atan2(m-_,d-g);let P;b?P=2*Math.PI:(P=s?C-k:k-C,P<0&&(P+=2*Math.PI));let T=N*P/1.8;this.inches&&(T*=25),T<1&&(T=1);let D=P/T;D*=s?-1:1;const A=[];A.push({x:l,y:c,z:u});const R=(u-p)/T;let G=l,z=c,Z=u,I=C;for(let J=0;J0)return void this.addThickLine(e,n);const a=new _s;a.setAttribute("position",new Ki(e,3)),this.disposables.push(a);const s=new Cw({color:n});this.disposables.push(s);const o=new _T(a,s);(r=this.group)===null||r===void 0||r.add(o)}addTubeLine(e,n,r=.2){let a=[];const s=[];for(let o=0;o{var l;const c=new aMe(o,this.extrusionWidth,this.lineHeight||r,4);(l=this._geometries)[n]||(l[n]=[]),this._geometries[n].push(c)}))}addThickLine(e,n){var r;if(!e.length||!this.lineWidth)return;const a=new LZ;this.disposables.push(a);const s=new FZ({color:n,linewidth:this.lineWidth/(1e3*window.devicePixelRatio)});this.disposables.push(s),a.setPositions(e);const o=new tMe(a,s);(r=this.group)===null||r===void 0||r.add(o)}dispose(){this.disposables.forEach((e=>e.dispose())),this.disposables=[],this.controls.dispose(),this.renderer.dispose(),this.cancelAnimation()}cancelAnimation(){this.animationFrameId!==void 0&&cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0}_enableDropHandler(){console.warn("Drag and drop is deprecated as a library feature. See the demo how to implement your own."),this.canvas.addEventListener("dragover",(e=>{e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),this.canvas.classList.add("dragging")})),this.canvas.addEventListener("dragleave",(e=>{e.stopPropagation(),e.preventDefault(),this.canvas.classList.remove("dragging")})),this.canvas.addEventListener("drop",(e=>hj(this,void 0,void 0,(function*(){var n,r;e.stopPropagation(),e.preventDefault(),this.canvas.classList.remove("dragging");const a=((r=(n=e.dataTransfer)===null||n===void 0?void 0:n.files)!==null&&r!==void 0?r:[])[0];this.clear(),yield this._readFromStream(a.stream()),this.render()}))))}batchGeometries(){if(this._geometries)for(const e in this._geometries){const n=this.createBatchMesh(parseInt(e));for(;this._geometries[e].length>0;){const r=this._geometries[e].pop();n.addGeometry(r)}}}createBatchMesh(e){var n;const r=this._geometries[e],a=new jPe({color:e,wireframe:this._wireframe});this.disposables.push(a);const s=r.reduce(((l,c)=>3*c.attributes.position.count+l),0),o=new PPe(r.length,s,void 0,a);return this.disposables.push(o),(n=this.group)===null||n===void 0||n.add(o),o}_readFromStream(e){var n,r;return hj(this,void 0,void 0,(function*(){const a=e.getReader();let s,o="",l=0;do{console.debug("reading from stream"),s=yield a.read(),l+=(r=(n=s.value)===null||n===void 0?void 0:n.length)!==null&&r!==void 0?r:0;const u=(c=s.value,new TextDecoder("utf-8").decode(c)),d=u.lastIndexOf(` `),m=u.slice(0,d);this.parser.parseGCode(o+m),o=u.slice(d)}while(!s.done);var c;console.debug("read from stream",l)}))}initGui(){typeof this.devMode=="boolean"&&this.devMode===!0?this.devGui=new aq(this):typeof this.devMode=="object"&&(this.devGui=new aq(this,this.devMode))}initStats(){var e;this.stats&&(typeof this.devMode=="object"&&(this.statsContainer=this.devMode.statsContainer),((e=this.statsContainer)!==null&&e!==void 0?e:document.body).appendChild(this.stats.dom),this.stats.dom.classList.add("stats"),this.initGui())}}ex.defaultExtrusionColor=new vn("hotpink");function OZ({gcodeUrl:t,buildVolume:e={x:256,y:256,z:256},filamentColors:n,className:r=""}){const a=w.useRef(null),s=w.useRef(null),o=w.useRef(null),l=w.useRef(!1),[c,u]=w.useState(!0),[d,m]=w.useState(null),[p,f]=w.useState(!1),[y,v]=w.useState(0),[b,g]=w.useState(0),_=w.useMemo(()=>JSON.stringify(n),[n]);w.useEffect(()=>{if(!a.current||l.current)return;l.current=!0;const k=a.current,P=k.parentElement?.getBoundingClientRect();P&&(k.width=P.width,k.height=P.height);const T=n&&n.length>1,D=n?.[0]||"#00ae42",A=new ex({canvas:k,buildVolume:e,backgroundColor:1710618,extrusionColor:T?n:D,disableGradient:!0,lineHeight:.2,lineWidth:2,renderTravel:!1,renderExtrusion:!0});s.current=A;const R={},G=qd();G&&(R.Authorization=`Bearer ${G}`),fetch(t,{headers:R}).then(async Z=>{if(!Z.ok)throw Z.status===404&&(await Z.json().catch(()=>({}))).detail?.includes("sliced")?(f(!0),new Error("not_sliced")):new Error("Failed to load G-code");return Z.text()}).then(Z=>{const I=new Set,J=/^(\s*)T(\d+)(\s*;.*)?$/gim;let ae;for(;(ae=J.exec(Z))!==null;){const ne=parseInt(ae[2],10);ne<=15&&I.add(ne)}const Y=new Map,ue=Array.from(I).sort((ne,se)=>ne-se);ue.forEach((ne,se)=>{Y.set(ne,se%8)});const de=[];ue.forEach((ne,se)=>{const pe=n?.[ne]||"#00ae42";de[se%8]=pe});const he=Z.split(` `).map(ne=>{const se=ne.match(/^(\s*)T(\d+)(\s*;.*)?$/i);if(se){const pe=parseInt(se[2],10);if(pe>15)return`; FILTERED: ${ne.trim()}`;const Te=Y.get(pe)??0;return`${se[1]}T${Te}${se[3]||""}`}return ne}).join(` `);de.length>0&&(A.extrusionColor=de),A.processGCode(he);const V=A.layers?.length||0;g(V),v(V),A.render(),u(!1)}).catch(Z=>{Z.message!=="not_sliced"&&m(Z.message),u(!1)});const z=()=>{if(k.parentElement&&s.current){const Z=k.parentElement.getBoundingClientRect();k.width=Z.width,k.height=Z.height,s.current.resize()}};return window.addEventListener("resize",z),()=>{window.removeEventListener("resize",z),o.current&&cancelAnimationFrame(o.current),s.current&&(s.current.dispose(),s.current=null),l.current=!1}},[t,_]);const N=w.useCallback(k=>{if(!s.current)return;const P=Math.max(1,Math.min(k,b));v(P),o.current&&cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{s.current&&(s.current.endLayer=P,s.current.render())})},[b]),C=k=>{N(parseInt(k.target.value,10))};return i.jsxs("div",{className:`relative flex flex-col h-full ${r}`,children:[i.jsxs("div",{className:"flex-1 relative bg-bambu-dark rounded-lg overflow-hidden",children:[i.jsx("canvas",{ref:a,className:"w-full h-full"}),c&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:i.jsxs("div",{className:"text-center",children:[i.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green mx-auto mb-2"}),i.jsx("p",{className:"text-bambu-gray text-sm",children:"Loading G-code..."})]})}),p&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:i.jsxs("div",{className:"text-center max-w-sm px-4",children:[i.jsx(qpe,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),i.jsx("p",{className:"text-white font-medium mb-2",children:"G-code not available"}),i.jsx("p",{className:"text-bambu-gray text-sm",children:"This file hasn't been sliced yet. G-code preview is only available after slicing in Bambu Studio or Orca Slicer."})]})}),d&&!p&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:i.jsx("div",{className:"text-center text-red-400",children:i.jsx("p",{className:"text-sm",children:d})})})]}),!c&&!d&&!p&&b>0&&i.jsx("div",{className:"mt-4 px-2",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Gi,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("button",{onClick:()=>N(y-1),disabled:y<=1,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:i.jsx(Cc,{className:"w-4 h-4"})}),i.jsx("input",{type:"range",min:1,max:b,value:y,onChange:C,className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer accent-bambu-green"}),i.jsx("button",{onClick:()=>N(y+1),disabled:y>=b,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:i.jsx(fa,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-sm text-bambu-gray min-w-[80px] text-right",children:[y," / ",b]})]})})]})}function sMe({printerId:t,filePath:e,filename:n,onClose:r}){const[a,s]=w.useState(null),[o,l]=w.useState([]),[c,u]=w.useState(!1),[d,m]=w.useState(null),p=n.toLowerCase().split(".").pop()||"",f=p==="3mf"||p==="stl",y=p==="gcode"||p==="3mf";w.useEffect(()=>{s(f?"3d":y?"gcode":null)},[f,y]),w.useEffect(()=>{l([]),m(null),f&&(u(!0),ge.getPrinterFilePlates(t,e).then(g=>l(g.plates||[])).catch(()=>l([])).finally(()=>u(!1)))},[e,f,t]);const v=o.length>1,b=d==null?null:o.find(g=>g.index===d)??null;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-6",onClick:r,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-4xl h-[80vh] flex flex-col",onClick:g=>g.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white truncate flex-1 mr-4",children:n}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:r,children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[i.jsxs("button",{onClick:()=>f&&s("3d"),disabled:!f,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${a==="3d"?"text-bambu-green border-b-2 border-bambu-green":f?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(ia,{className:"w-4 h-4"}),"3D Model",!f&&i.jsx("span",{className:"text-xs",children:"(not available)"})]}),i.jsxs("button",{onClick:()=>y&&s("gcode"),disabled:!y,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${a==="gcode"?"text-bambu-green border-b-2 border-bambu-green":y?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(Bs,{className:"w-4 h-4"}),"G-code Preview",!y&&i.jsx("span",{className:"text-xs",children:"(not sliced)"})]})]}),i.jsx("div",{className:"flex-1 overflow-hidden p-4",children:a==="3d"&&f?i.jsxs("div",{className:"w-full h-full flex flex-col gap-3",children:[v&&i.jsxs("div",{className:"rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[i.jsx(ia,{className:"w-4 h-4"}),"Plates",c&&i.jsx(ft,{className:"w-3 h-3 animate-spin"})]}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:[i.jsxs("button",{type:"button",onClick:()=>m(null),className:`flex items-center gap-2 rounded-lg border p-2 text-left transition-colors ${d==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:i.jsx(ia,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white font-medium truncate",children:"All Plates"}),i.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[o.length," plate",o.length!==1?"s":""]})]}),d==null&&i.jsx(Ks,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]}),o.map(g=>i.jsxs("button",{type:"button",onClick:()=>m(g.index),className:`flex items-center gap-2 rounded-lg border p-2 text-left transition-colors ${d===g.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[g.has_thumbnail?i.jsx("img",{src:ge.getPrinterFilePlateThumbnail(t,g.index,e),alt:`Plate ${g.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:i.jsx(ia,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white font-medium truncate",children:g.name||`Plate ${g.index}`}),i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:g.objects.length>0?g.objects.slice(0,2).join(", ")+(g.objects.length>2?"…":""):`${g.filaments.length} filament${g.filaments.length!==1?"s":""}`})]}),d===g.index&&i.jsx(Ks,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},g.index))]}),b&&i.jsxs("div",{className:"mt-3 text-xs text-bambu-gray flex flex-wrap gap-x-4 gap-y-1",children:[i.jsxs("span",{children:["Plate ",b.index]}),b.print_time_seconds!=null&&i.jsxs("span",{children:["ETA ",Math.round(b.print_time_seconds/60)," min"]}),b.filament_used_grams!=null&&i.jsxs("span",{children:[b.filament_used_grams.toFixed(1)," g"]}),b.filaments.length>0&&i.jsxs("span",{children:[b.filaments.length," filament",b.filaments.length!==1?"s":""]})]})]}),i.jsx("div",{className:"flex-1",children:i.jsx(tZ,{url:ge.getPrinterFileDownloadUrl(t,e),fileType:p,selectedPlateId:d,className:"w-full h-full"})})]}):a==="gcode"&&y?i.jsx(OZ,{gcodeUrl:ge.getPrinterFileGcodeUrl(t,e),className:"w-full h-full"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:"No preview available for this file"})})]})})}function sq(t){if(t===0)return"0 GB";const e=t/(1024*1024*1024);return e>=1?`${e.toFixed(1)} GB`:`${(t/(1024*1024)).toFixed(0)} MB`}function oMe(t,e){if(e)return YX;switch(t.toLowerCase().split(".").pop()||""){case"3mf":return mf;case"gcode":return Bs;case"mp4":case"avi":return kh;case"png":case"jpg":case"jpeg":return Ud;default:return iT}}const lMe=[{value:"name-asc",label:"Name (A-Z)"},{value:"name-desc",label:"Name (Z-A)"},{value:"size-asc",label:"Size (smallest)"},{value:"size-desc",label:"Size (largest)"},{value:"date-asc",label:"Date (oldest)"},{value:"date-desc",label:"Date (newest)"}];function cMe({printerId:t,printerName:e,onClose:n}){const{t:r}=Dt(),{showToast:a}=bn(),s=sn(),[o,l]=w.useState("/"),[c,u]=w.useState(new Set),[d,m]=w.useState(""),[p,f]=w.useState([]),[y,v]=w.useState("name-asc"),[b,g]=w.useState(null),[_,N]=w.useState(null);w.useEffect(()=>{const Y=ue=>{ue.key==="Escape"&&n()};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[n]);const{data:C,isLoading:k,refetch:P}=et({queryKey:["printerFiles",t,o],queryFn:()=>ge.getPrinterFiles(t,o),refetchInterval:3e4}),{data:T}=et({queryKey:["printerStorage",t],queryFn:()=>ge.getPrinterStorage(t),staleTime:3e4}),D=gt({mutationFn:async Y=>{for(const ue of Y)await ge.deletePrinterFile(t,ue)},onSuccess:()=>{a(r("printerFiles.toast.filesDeleted",{count:p.length})),s.invalidateQueries({queryKey:["printerFiles",t]}),u(new Set),f([])},onError:Y=>{a(r("printerFiles.toast.deleteFailed",{error:Y.message}),"error")}}),A=Y=>{l(Y),u(new Set)},R=()=>{if(o==="/")return;const Y=o.split("/").filter(Boolean);Y.pop(),l(Y.length?"/"+Y.join("/"):"/"),u(new Set)},G=(Y,ue)=>{ue.stopPropagation(),u(de=>{const he=new Set(de);return he.has(Y)?he.delete(Y):he.add(Y),he})},z=()=>{if(!C?.files)return;const Y=C.files.filter(ue=>!ue.is_directory&&(!d||ue.name.toLowerCase().includes(d.toLowerCase()))).map(ue=>ue.path);u(new Set(Y))},Z=()=>{u(new Set)},I=async()=>{if(c.size===0)return;const Y=Array.from(c);if(Y.length===1){ge.downloadPrinterFile(t,Y[0]).catch(ue=>{console.error("Printer file download failed:",ue)}),u(new Set);return}g({current:0,total:Y.length});try{const ue=await ge.downloadPrinterFilesAsZip(t,Y),de=URL.createObjectURL(ue),he=document.createElement("a");he.href=de,he.download=`${e.replace(/[^a-zA-Z0-9]/g,"_")}-files.zip`,document.body.appendChild(he),he.click(),document.body.removeChild(he),URL.revokeObjectURL(de),a(`Downloaded ${Y.length} files as ZIP`),u(new Set)}catch(ue){a(`Download failed: ${ue instanceof Error?ue.message:"Unknown error"}`,"error")}finally{g(null)}},J=()=>{c.size!==0&&f(Array.from(c))},ae=[{path:"/",label:"Root"},{path:"/cache",label:"Cache"},{path:"/model",label:"Models"},{path:"/timelapse",label:"Timelapse"}];return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:n,children:[i.jsxs("div",{className:"w-full max-w-3xl max-h-[85vh] flex flex-col bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden",onClick:Y=>Y.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Vx,{className:"w-5 h-5 text-bambu-green"}),i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("printerFiles.title")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:e})]})]}),i.jsxs("div",{className:"flex items-center gap-4",children:[T&&(T.used_bytes!=null||T.free_bytes!=null)&&i.jsxs("div",{className:"text-sm text-bambu-gray flex items-center gap-2",children:[T.used_bytes!=null&&i.jsxs("span",{children:[r("printerFiles.storageUsed")," ",sq(T.used_bytes)]}),T.used_bytes!=null&&T.free_bytes!=null&&i.jsx("span",{className:"text-bambu-dark-tertiary",children:"|"}),T.free_bytes!=null&&i.jsxs("span",{children:[r("printerFiles.storageFree")," ",sq(T.free_bytes)]})]}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",title:"Close file manager","aria-label":"Close file manager",children:i.jsx(Ht,{className:"w-5 h-5"})})]})]}),i.jsxs("div",{className:"flex items-center gap-2 p-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0",children:[ae.map(Y=>i.jsx("button",{onClick:()=>{A(Y.path),m("")},className:`px-3 py-1 text-sm rounded-full transition-colors ${o===Y.path?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:Y.label},Y.path)),i.jsx("div",{className:"flex-1"}),i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:r("printerFiles.filterPlaceholder"),value:d,onChange:Y=>m(Y.target.value),className:"w-40 pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"relative flex items-center gap-1",children:[i.jsx(qL,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("select",{value:y,onChange:Y=>v(Y.target.value),className:"appearance-none bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm py-1.5 pl-2 pr-6 focus:border-bambu-green focus:outline-none cursor-pointer",title:"Sort files","aria-label":"Sort files",children:lMe.map(Y=>i.jsx("option",{value:Y.value,children:Y.label},Y.value))})]}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>P(),disabled:k,children:i.jsx(Sr,{className:`w-4 h-4 ${k?"animate-spin":""}`})})]}),i.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark text-sm flex-shrink-0",children:[i.jsx("button",{onClick:R,disabled:o==="/",className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-50 disabled:cursor-not-allowed",title:"Go to parent folder","aria-label":"Go to parent folder",children:i.jsx(Cc,{className:"w-4 h-4"})}),i.jsx("span",{className:"text-bambu-gray font-mono",children:o})]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:k?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):C?.files?.length?i.jsx("div",{className:"space-y-1",children:[...C.files].filter(Y=>!d||Y.name.toLowerCase().includes(d.toLowerCase())).sort((Y,ue)=>{if(Y.is_directory&&!ue.is_directory)return-1;if(!Y.is_directory&&ue.is_directory)return 1;switch(y){case"name-asc":return Y.name.localeCompare(ue.name);case"name-desc":return ue.name.localeCompare(Y.name);case"size-asc":return Y.size-ue.size;case"size-desc":return ue.size-Y.size;case"date-asc":{const de=Y.mtime?Qn(Y.mtime)?.getTime()??0:0,he=ue.mtime?Qn(ue.mtime)?.getTime()??0:0;return de-he}case"date-desc":{const de=Y.mtime?Qn(Y.mtime)?.getTime()??0:0;return(ue.mtime?Qn(ue.mtime)?.getTime()??0:0)-de}default:return Y.name.localeCompare(ue.name)}}).map(Y=>{const ue=oMe(Y.name,Y.is_directory),de=c.has(Y.path);return i.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-colors ${de?"bg-bambu-green/20 border border-bambu-green/50":"hover:bg-bambu-dark-tertiary"}`,onClick:()=>{Y.is_directory&&A(Y.path)},children:[Y.is_directory?null:i.jsx("button",{onClick:he=>G(Y.path,he),className:"flex-shrink-0 text-bambu-gray hover:text-white",children:de?i.jsx(Ks,{className:"w-5 h-5 text-bambu-green"}):i.jsx(rl,{className:"w-5 h-5"})}),i.jsx(ue,{className:`w-5 h-5 flex-shrink-0 ${Y.is_directory?"text-bambu-green":"text-bambu-gray"}`}),i.jsx("span",{className:"flex-1 text-white truncate",children:Y.name}),!Y.is_directory&&i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:xo(Y.size)}),(Y.name.toLowerCase().endsWith(".3mf")||Y.name.toLowerCase().endsWith(".gcode")||Y.name.toLowerCase().endsWith(".stl"))&&i.jsx("button",{onClick:he=>{he.stopPropagation(),N({path:Y.path,name:Y.name})},className:"p-1 rounded hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green",title:"3D View",children:i.jsx(ia,{className:"w-4 h-4"})})]}),Y.is_directory&&i.jsx(Cc,{className:"w-4 h-4 text-bambu-gray rotate-180"})]},Y.path)})}):i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:"No files in this directory"})}),i.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("div",{className:"text-sm text-bambu-gray",children:c.size>0?`${c.size} selected`:d?`${C?.files?.filter(Y=>Y.name.toLowerCase().includes(d.toLowerCase())).length||0} of ${C?.files?.length||0} items`:`${C?.files?.length||0} items`}),C?.files?.some(Y=>!Y.is_directory)&&i.jsx("div",{className:"flex items-center gap-2",children:c.size>0?i.jsxs("button",{onClick:Z,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",children:[i.jsx(ebe,{className:"w-4 h-4"}),"Deselect All"]}):i.jsxs("button",{onClick:z,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",children:[i.jsx(Ks,{className:"w-4 h-4"}),"Select All"]})})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{variant:"secondary",disabled:c.size===0||b!==null,onClick:I,children:b?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),b.current,"/",b.total]}):i.jsxs(i.Fragment,{children:[i.jsx(fi,{className:"w-4 h-4"}),"Download",c.size>1?` (${c.size})`:""]})}),i.jsxs(ze,{variant:"secondary",disabled:c.size===0||D.isPending,onClick:J,className:"text-red-400 hover:text-red-300",children:[D.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(nn,{className:"w-4 h-4"}),r("printerFiles.deleteButton"),c.size>1?` (${c.size})`:""]})]})]})]}),p.length>0&&i.jsx(Nn,{title:p.length>1?r("printerFiles.deleteFiles",{count:p.length}):r("fileManager.deleteFile"),message:p.length>1?r("printerFiles.deleteFilesConfirm",{count:p.length}):r("printerFiles.deleteFileConfirm",{name:p[0].split("/").pop()}),confirmText:r("common.delete"),variant:"danger",onConfirm:()=>{D.mutate(p)},onCancel:()=>f([])}),_&&i.jsx(sMe,{printerId:t,filePath:_.path,filename:_.name,onClose:()=>N(null)})]})}function PO({on:t,className:e="w-5 h-5"}){const n=t?"#facc15":"none",r=t?"#78350f":"currentColor",a=t?1:0;return i.jsxs("svg",{viewBox:"0 0 32 32",fill:"none",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[i.jsxs("g",{stroke:r,opacity:a,children:[i.jsx("line",{x1:"16",y1:"2",x2:"16",y2:"6"}),i.jsx("line",{x1:"6.1",y1:"6.1",x2:"8.9",y2:"8.9"}),i.jsx("line",{x1:"25.9",y1:"6.1",x2:"23.1",y2:"8.9"}),i.jsx("line",{x1:"2",y1:"16",x2:"6",y2:"16"}),i.jsx("line",{x1:"30",y1:"16",x2:"26",y2:"16"})]}),i.jsx("path",{d:"M12 24v-2.3c0-.9-.4-1.7-1-2.3C9.2 17.6 8 15.4 8 13c0-4.4 3.6-8 8-8s8 3.6 8 8c0 2.4-1.2 4.6-3 6.4-.6.6-1 1.4-1 2.3V24",fill:n,stroke:r}),i.jsx("path",{d:"M12 24h8",stroke:r}),i.jsx("path",{d:"M12 27h8",stroke:r}),i.jsx("path",{d:"M13 30h6",stroke:r})]})}const NT=({className:t})=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[i.jsx("rect",{x:"2",y:"15",width:"5",height:"5",rx:"0.5"}),i.jsx("rect",{x:"9.5",y:"15",width:"5",height:"5",rx:"0.5",fill:"currentColor",opacity:"0.3"}),i.jsx("rect",{x:"17",y:"15",width:"5",height:"5",rx:"0.5"}),i.jsx("path",{d:"M4 12 C4 6, 14 6, 14 12"}),i.jsx("polyline",{points:"12,10 14,12 12,14"})]});function MO({printerId:t,isOpen:e,onClose:n}){const{t:r}=Dt(),{showToast:a}=bn(),{hasPermission:s}=Ar(),[o,l]=w.useState(null),[c,u]=w.useState(!1),{data:d}=et({queryKey:["printerStatus",t],queryFn:()=>ge.getPrinterStatus(t),refetchInterval:3e4,enabled:e}),{data:m,refetch:p}=et({queryKey:["printableObjects",t],queryFn:()=>ge.getPrintableObjects(t),enabled:e,refetchInterval:e?5e3:!1}),f=gt({mutationFn:y=>ge.skipObjects(t,y),onSuccess:y=>{a(y.message||r("printers.skipObjects.objectsSkipped")),l(null),p()},onError:y=>a(y.message||r("printers.toast.failedToSkipObjects"),"error")});return e?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:n,onKeyDown:y=>{y.key==="Escape"&&(c?u(!1):n())},tabIndex:-1,ref:y=>y?.focus(),children:[i.jsx("div",{className:"absolute inset-0 bg-black/50 z-0"}),i.jsxs("div",{className:"relative z-10 bg-white dark:bg-bambu-dark border border-gray-200 dark:border-bambu-dark-tertiary rounded-xl shadow-2xl w-[560px] max-h-[85vh] flex flex-col overflow-hidden",onClick:y=>y.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-bambu-dark-tertiary bg-gray-50 dark:bg-bambu-dark",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(NT,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-sm font-medium text-gray-900 dark:text-white",children:r("printers.skipObjects.title")})]}),i.jsx("button",{onClick:n,className:"p-1 text-gray-500 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white rounded transition-colors",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),m?m.objects.length===0?i.jsxs("div",{className:"text-center py-8 px-4 text-bambu-gray",children:[i.jsx("p",{className:"text-sm",children:r("printers.noObjectsFound")}),i.jsx("p",{className:"text-xs mt-1 opacity-70",children:r("printers.objectsLoadedOnPrintStart")})]}):i.jsxs("div",{className:"flex flex-col overflow-hidden",children:[i.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 bg-blue-50 dark:bg-blue-500/10 border-b border-gray-200 dark:border-bambu-dark-tertiary",children:[i.jsx("div",{className:"flex-shrink-0 w-8 h-8 rounded-lg bg-blue-100 dark:bg-blue-500/20 flex items-center justify-center",children:i.jsx(sge,{className:"w-4 h-4 text-blue-500 dark:text-blue-400"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-300",children:r("printers.skipObjects.matchIdsInfo")}),i.jsx("p",{className:"text-[10px] text-blue-500/70 dark:text-blue-300/60",children:r("printers.skipObjects.printerShowsIds")})]}),i.jsxs("div",{className:"flex-shrink-0 text-xs text-gray-500 dark:text-bambu-gray",children:[m.skipped_count,"/",m.total," ",r("printers.skipObjects.skipped")]})]}),(d?.layer_num??0)<=1&&i.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-amber-50 dark:bg-amber-500/10 border-b border-gray-200 dark:border-bambu-dark-tertiary",children:[i.jsx(Li,{className:"w-4 h-4 text-amber-500 dark:text-amber-400 flex-shrink-0"}),i.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:r("printers.skipObjects.waitForLayer",{layer:d?.layer_num??0})})]}),i.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[i.jsx("div",{className:"w-52 flex-shrink-0 p-4 border-r border-gray-200 dark:border-bambu-dark-tertiary bg-gray-50 dark:bg-bambu-dark-secondary overflow-y-auto",children:i.jsxs("div",{className:"relative cursor-pointer group",onClick:()=>u(!0),children:[d?.cover_url?i.jsx("img",{src:`${d.cover_url}?view=top`,alt:r("printers.printPreview"),className:"w-full aspect-square object-contain rounded-lg bg-gray-900 dark:bg-gray-900 border border-gray-300 dark:border-gray-600"}):i.jsx("div",{className:"w-full aspect-square rounded-lg bg-gray-100 dark:bg-bambu-dark flex items-center justify-center",children:i.jsx(ia,{className:"w-8 h-8 text-gray-300 dark:text-bambu-gray/30"})}),i.jsx("div",{className:"absolute top-2 right-2 p-1 bg-black/60 rounded opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx(oT,{className:"w-3.5 h-3.5 text-white"})}),m.objects.length>0&&i.jsx("div",{className:"absolute inset-0 pointer-events-none",children:m.objects.map((y,v)=>{let b,g;if(y.x!=null&&y.y!=null&&m.bbox_all){const[_,N,C,k]=m.bbox_all,P=C-_,T=k-N,D=8,A=100-D*2;b=D+(y.x-_)/P*A,g=D+(k-y.y)/T*A,b=Math.max(5,Math.min(95,b)),g=Math.max(5,Math.min(95,g))}else if(y.x!=null&&y.y!=null)b=y.x/256*100,g=100-y.y/256*100,b=Math.max(5,Math.min(95,b)),g=Math.max(5,Math.min(95,g));else{const _=Math.ceil(Math.sqrt(m.objects.length)),N=Math.floor(v/_),C=v%_,k=Math.ceil(m.objects.length/_);b=15+C*(70/_)+35/_,g=15+N*(70/k)+35/k}return i.jsx("div",{className:`absolute flex items-center justify-center w-6 h-6 rounded-full text-[10px] font-bold shadow-lg ${y.skipped?"bg-red-500 text-white line-through":"bg-bambu-green text-black"}`,style:{left:`${b}%`,top:`${g}%`,transform:"translate(-50%, -50%)"},title:y.name,children:y.id},y.id)})}),i.jsx("div",{className:"absolute bottom-2 right-2 px-2 py-1 bg-white/90 dark:bg-black/80 rounded text-[10px] text-gray-700 dark:text-white shadow-sm",children:r("printers.skipObjects.activeCount",{count:m.objects.filter(y=>!y.skipped).length})})]})}),i.jsx("div",{className:"flex-1 min-w-0 overflow-y-auto",children:m.objects.map(y=>i.jsxs("div",{className:` @@ -8437,13 +8437,13 @@ void main() { `,children:[i.jsxs("div",{className:` w-12 h-12 flex-shrink-0 rounded-lg flex flex-col items-center justify-center ${y.skipped?"bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/40":"bg-green-100 dark:bg-bambu-green/20 border border-green-300 dark:border-bambu-green/40"} - `,children:[i.jsx("span",{className:`text-lg font-mono font-bold ${y.skipped?"text-red-500 dark:text-red-400":"text-green-600 dark:text-bambu-green"}`,children:y.id}),i.jsx("span",{className:`text-[8px] uppercase tracking-wider ${y.skipped?"text-red-400/60":"text-green-500/60 dark:text-bambu-green/60"}`,children:"ID"})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("span",{className:`block text-sm truncate ${y.skipped?"text-red-500 dark:text-red-400 line-through":"text-gray-900 dark:text-white"}`,children:y.name}),y.skipped&&i.jsx("span",{className:"text-[10px] text-red-400/60",children:r("printers.willBeSkipped")})]}),y.skipped?i.jsx("span",{className:"px-4 py-2 text-xs text-red-500 dark:text-red-400/70 bg-red-100 dark:bg-red-500/10 rounded-lg",children:r("printers.skipObjects.skipped")}):i.jsx("button",{onClick:()=>l({id:y.id,name:y.name}),disabled:f.isPending||(d?.layer_num??0)<=1||!s("printers:control"),className:`px-4 py-2 text-xs font-medium rounded-lg transition-colors ${(d?.layer_num??0)<=1||!s("printers:control")?"bg-gray-100 dark:bg-bambu-dark text-gray-400 dark:text-bambu-gray/50 cursor-not-allowed":"bg-red-100 dark:bg-red-500/20 text-red-600 dark:text-red-400 hover:bg-red-200 dark:hover:bg-red-500/30 border border-red-300 dark:border-red-500/30"}`,title:s("printers:control")?(d?.layer_num??0)<=1?r("printers.skipObjects.waitForLayer",{layer:d?.layer_num??0}):r("printers.skipObjects.skip"):r("printers.permission.noControl"),children:r("printers.skipObjects.skip")})]},y.id))})]})]}):i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(ft,{className:"w-5 h-5 animate-spin text-bambu-gray"})})]})]}),o&&i.jsx(Nn,{variant:"warning",title:r("printers.skipObjects.confirmTitle"),message:r("printers.skipObjects.confirmMessage",{name:o.name}),confirmText:r("printers.skipObjects.skip"),isLoading:f.isPending,onConfirm:()=>f.mutate([o.id]),onCancel:()=>l(null)}),c&&m&&i.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-60",onClick:()=>u(!1),children:[i.jsx("button",{onClick:()=>u(!1),className:"absolute top-4 right-4 p-2 text-white/70 hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-6 h-6"})}),i.jsxs("div",{className:"relative max-w-[600px] max-h-[80vh] aspect-square",onClick:y=>y.stopPropagation(),children:[d?.cover_url?i.jsx("img",{src:`${d.cover_url}?view=top`,alt:r("printers.printPreview"),className:"w-full h-full object-contain rounded-lg bg-gray-900"}):i.jsx("div",{className:"w-full h-full rounded-lg bg-gray-800 flex items-center justify-center",children:i.jsx(ia,{className:"w-16 h-16 text-gray-500"})}),m.objects.length>0&&i.jsx("div",{className:"absolute inset-0 pointer-events-none",children:m.objects.map((y,v)=>{let b,g;if(y.x!=null&&y.y!=null&&m.bbox_all){const[_,N,C,k]=m.bbox_all,P=C-_,T=k-N,D=8,A=100-D*2;b=D+(y.x-_)/P*A,g=D+(k-y.y)/T*A,b=Math.max(5,Math.min(95,b)),g=Math.max(5,Math.min(95,g))}else if(y.x!=null&&y.y!=null)b=y.x/256*100,g=100-y.y/256*100,b=Math.max(5,Math.min(95,b)),g=Math.max(5,Math.min(95,g));else{const _=Math.ceil(Math.sqrt(m.objects.length)),N=Math.floor(v/_),C=v%_,k=Math.ceil(m.objects.length/_);b=15+C*(70/_)+35/_,g=15+N*(70/k)+35/k}return i.jsx("div",{className:`absolute flex items-center justify-center w-6 h-6 rounded-full text-[10px] font-bold shadow-lg ${y.skipped?"bg-red-500 text-white line-through":"bg-bambu-green text-black"}`,style:{left:`${b}%`,top:`${g}%`,transform:"translate(-50%, -50%)"},title:y.name,children:y.id},y.id)})}),i.jsx("div",{className:"absolute bottom-2 right-2 px-2 py-1 bg-white/90 dark:bg-black/80 rounded text-[10px] text-gray-700 dark:text-white shadow-sm",children:r("printers.skipObjects.activeCount",{count:m.objects.filter(y=>!y.skipped).length})})]})]})]}):null}const uMe="embeddedCameraState_",oq=5,dMe=2e3,mMe=3e4,hMe=5e3,x2={x:window.innerWidth-420,y:20,width:400,height:300};function pMe({printerId:t,printerName:e,viewerIndex:n=0,onClose:r}){const{t:a}=Dt(),s=sn(),{showToast:o}=bn(),{hasPermission:l}=Ar(),c=`${uMe}${t}`,u=()=>{try{const $e=localStorage.getItem(c);if($e){const nt=JSON.parse($e);return{x:Math.min(Math.max(0,nt.x),window.innerWidth-100),y:Math.min(Math.max(0,nt.y),window.innerHeight-100),width:Math.max(200,Math.min(nt.width,window.innerWidth-20)),height:Math.max(150,Math.min(nt.height,window.innerHeight-20))}}}catch{}const Ce=n*30;return{...x2,x:Math.max(0,x2.x-Ce),y:Math.max(0,x2.y+Ce)}},[d,m]=w.useState(u),[p,f]=w.useState(!1),[y,v]=w.useState(!1),[b,g]=w.useState({x:0,y:0}),[_,N]=w.useState(!1),[C,k]=w.useState(!1),[P,T]=w.useState(1),[D,A]=w.useState({x:0,y:0}),[R,G]=w.useState(!1),[z,Z]=w.useState({x:0,y:0}),[I,J]=w.useState(null),[ae,Y]=w.useState(null),[ue,de]=w.useState(!1),[he,V]=w.useState(!0),[ne,se]=w.useState(Date.now()),[pe,Te]=w.useState(0),[q,X]=w.useState(!1),[j,E]=w.useState(0),U=w.useRef(null),K=w.useRef(null),H=w.useRef(null),re=w.useRef(null),O=w.useRef(null),[$,ee]=w.useState(!1),{data:W}=et({queryKey:["printer",t],queryFn:()=>ge.getPrinter(t),enabled:t>0}),{data:ie}=et({queryKey:["printerStatus",t],queryFn:()=>ge.getPrinterStatus(t),refetchInterval:3e4,enabled:t>0}),ce=gt({mutationFn:Ce=>ge.setChamberLight(t,Ce),onMutate:async Ce=>{await s.cancelQueries({queryKey:["printerStatus",t]});const $e=s.getQueryData(["printerStatus",t]);return s.setQueryData(["printerStatus",t],nt=>({...nt,chamber_light:Ce})),{previousStatus:$e}},onSuccess:(Ce,$e)=>{o(`Chamber light ${$e?"on":"off"}`)},onError:(Ce,$e,nt)=>{nt?.previousStatus&&s.setQueryData(["printerStatus",t],nt.previousStatus),o(Ce.message||a("printers.toast.failedToControlChamberLight"),"error")}}),be=(ie?.state==="RUNNING"||ie?.state==="PAUSE")&&(ie?.printable_objects_count??0)>=2;w.useEffect(()=>{const Ce=setTimeout(()=>{localStorage.setItem(c,JSON.stringify(d))},500);return()=>clearTimeout(Ce)},[d,c]);const xe=w.useRef(!1);w.useEffect(()=>{xe.current=!1;const Ce=`/api/v1/printers/${t}/camera/stop`,$e=()=>{if(t>0&&!xe.current){xe.current=!0;const xt={},vt=qd();vt&&(xt.Authorization=`Bearer ${vt}`),fetch(Ce,{method:"POST",keepalive:!0,headers:xt}).catch(()=>{})}},nt=K.current;return()=>{nt&&(nt.src=""),$e(),H.current&&clearTimeout(H.current),re.current&&clearInterval(re.current),O.current&&clearInterval(O.current)}},[t]),w.useEffect(()=>{if(he){const Ce=setTimeout(()=>V(!1),3e3);return()=>clearTimeout(Ce)}},[he,ne]);const oe=w.useCallback(()=>{if(pe>=oq){X(!1),de(!0);return}const Ce=Math.min(dMe*Math.pow(2,pe),mMe);X(!0),E(Math.ceil(Ce/1e3)),re.current=setInterval(()=>{E($e=>$e<=1?(re.current&&clearInterval(re.current),0):$e-1)},1e3),H.current=setTimeout(()=>{Te($e=>$e+1),X(!1),V(!0),de(!1),K.current&&(K.current.src=""),se(Date.now())},Ce)},[pe]);w.useEffect(()=>{if(he||q||_){O.current&&(clearInterval(O.current),O.current=null);return}return O.current=setInterval(async()=>{try{const Ce=await ge.getCameraStatus(t);(Ce.stalled||!Ce.active&&!ue)&&(O.current&&(clearInterval(O.current),O.current=null),V(!1),oe())}catch{}},hMe),()=>{O.current&&(clearInterval(O.current),O.current=null)}},[he,ue,q,_,t,oe]),w.useEffect(()=>{const Ce=()=>{const $e=!!document.fullscreenElement;k($e),$e||(T(1),A({x:0,y:0}))};return document.addEventListener("fullscreenchange",Ce),()=>document.removeEventListener("fullscreenchange",Ce)},[]);const L=()=>{U.current&&(document.fullscreenElement?document.exitFullscreen():U.current.requestFullscreen())},F=()=>{T(Ce=>Math.min(Ce+.5,4))},te=()=>{T(Ce=>{const $e=Math.max(Ce-.5,1);return $e===1&&A({x:0,y:0}),$e})},ve=Ce=>{Ce.preventDefault(),Ce.deltaY<0?F():te()},fe=Ce=>{P>1&&(Ce.preventDefault(),G(!0),Z({x:Ce.clientX-D.x,y:Ce.clientY-D.y}))},me=w.useCallback(()=>{if(!U.current||!K.current)return{x:200,y:150};const Ce=U.current.getBoundingClientRect(),$e=Ce.width*(P-1)/2,nt=Ce.height*(P-1)/2;return{x:Math.max(50,$e),y:Math.max(50,nt)}},[P]),je=Ce=>{if(R&&P>1){const $e=Ce.clientX-z.x,nt=Ce.clientY-z.y,xt=me();A({x:Math.max(-xt.x,Math.min(xt.x,$e)),y:Math.max(-xt.y,Math.min(xt.y,nt))})}},we=()=>{G(!1)},Fe=Ce=>{if(Ce.length<2)return 0;const $e=Ce[0].clientX-Ce[1].clientX,nt=Ce[0].clientY-Ce[1].clientY;return Math.sqrt($e*$e+nt*nt)},He=Ce=>Ce.length<2?{x:Ce[0].clientX,y:Ce[0].clientY}:{x:(Ce[0].clientX+Ce[1].clientX)/2,y:(Ce[0].clientY+Ce[1].clientY)/2},Oe=Ce=>{Ce.touches.length===2?(Ce.preventDefault(),J(Fe(Ce.touches)),Y(He(Ce.touches))):Ce.touches.length===1&&P>1&&(Ce.preventDefault(),G(!0),Z({x:Ce.touches[0].clientX-D.x,y:Ce.touches[0].clientY-D.y}))},_e=Ce=>{if(Ce.touches.length===2&&I!==null){Ce.preventDefault();const $e=Fe(Ce.touches),nt=$e/I;T(vt=>{const mt=Math.max(1,Math.min(4,vt*nt));return mt===1&&A({x:0,y:0}),mt}),J($e);const xt=He(Ce.touches);if(ae){const vt=me();A(mt=>({x:Math.max(-vt.x,Math.min(vt.x,mt.x+(xt.x-ae.x))),y:Math.max(-vt.y,Math.min(vt.y,mt.y+(xt.y-ae.y)))}))}Y(xt)}else if(Ce.touches.length===1&&R&&P>1){Ce.preventDefault();const $e=Ce.touches[0].clientX-z.x,nt=Ce.touches[0].clientY-z.y,xt=me();A({x:Math.max(-xt.x,Math.min(xt.x,$e)),y:Math.max(-xt.y,Math.min(xt.y,nt))})}},Ae=Ce=>{Ce.touches.length<2&&(J(null),Y(null)),Ce.touches.length===0&&G(!1)},Be=()=>{T(1),A({x:0,y:0})},Me=()=>{V(!1),pe{V(!1),de(!1),Te(0),X(!1),H.current&&clearTimeout(H.current),re.current&&clearInterval(re.current)},ye=()=>{V(!0),de(!1),Te(0),X(!1),H.current&&clearTimeout(H.current),re.current&&clearInterval(re.current);const Ce={},$e=qd();$e&&(Ce.Authorization=`Bearer ${$e}`),fetch(`/api/v1/printers/${t}/camera/stop`,{method:"POST",headers:Ce}).catch(()=>{}),K.current&&(K.current.src=""),setTimeout(()=>se(Date.now()),100)},We=Ce=>{Ce.target.closest(".no-drag")||(f(!0),g({x:Ce.clientX-d.x,y:Ce.clientY-d.y}))},Pe=Ce=>{if(Ce.target.closest(".no-drag"))return;const $e=Ce.touches[0];f(!0),g({x:$e.clientX-d.x,y:$e.clientY-d.y})},Ke=Ce=>{Ce.stopPropagation(),v(!0)},Ve=Ce=>{Ce.stopPropagation(),v(!0)};w.useEffect(()=>{const Ce=xt=>{if(p)m(vt=>({...vt,x:Math.max(0,Math.min(xt.clientX-b.x,window.innerWidth-vt.width)),y:Math.max(0,Math.min(xt.clientY-b.y,window.innerHeight-vt.height))}));else if(y&&U.current){const vt=U.current.getBoundingClientRect();m(mt=>({...mt,width:Math.max(200,Math.min(xt.clientX-vt.left,window.innerWidth-mt.x-10)),height:Math.max(150,Math.min(xt.clientY-vt.top,window.innerHeight-mt.y-10))}))}},$e=xt=>{if(!p&&!y)return;xt.preventDefault();const vt=xt.touches[0];if(p)m(mt=>({...mt,x:Math.max(0,Math.min(vt.clientX-b.x,window.innerWidth-mt.width)),y:Math.max(0,Math.min(vt.clientY-b.y,window.innerHeight-mt.height))}));else if(y&&U.current){const mt=U.current.getBoundingClientRect();m(qe=>({...qe,width:Math.max(200,Math.min(vt.clientX-mt.left,window.innerWidth-qe.x-10)),height:Math.max(150,Math.min(vt.clientY-mt.top,window.innerHeight-qe.y-10))}))}},nt=()=>{f(!1),v(!1)};if(p||y)return document.addEventListener("mousemove",Ce),document.addEventListener("mouseup",nt),document.addEventListener("touchmove",$e,{passive:!1}),document.addEventListener("touchend",nt),document.addEventListener("touchcancel",nt),()=>{document.removeEventListener("mousemove",Ce),document.removeEventListener("mouseup",nt),document.removeEventListener("touchmove",$e),document.removeEventListener("touchend",nt),document.removeEventListener("touchcancel",nt)}},[p,y,b]);const ke=`/api/v1/printers/${t}/camera/stream?fps=15&t=${ne}`;return i.jsxs("div",{ref:U,className:`${C?"fixed inset-0 z-[100]":"fixed z-40 rounded-lg shadow-2xl border border-bambu-dark-tertiary"} bg-bambu-dark-secondary overflow-hidden`,style:C?void 0:{left:d.x,top:d.y,width:_?200:d.width,height:_?40:d.height,cursor:p?"grabbing":"default"},children:[i.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-bambu-dark border-b border-bambu-dark-tertiary cursor-grab active:cursor-grabbing",onMouseDown:We,onTouchStart:Pe,children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-white truncate",children:[i.jsx(Th,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"truncate",children:W?.name||e})]}),i.jsxs("div",{className:"flex items-center gap-1 no-drag",children:[i.jsx("button",{onClick:()=>ce.mutate(!ie?.chamber_light),disabled:!ie?.connected||ce.isPending||!l("printers:control"),className:`p-1 rounded disabled:opacity-50 ${ie?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:l("printers:control")?a("camera.chamberLight"):a("printers.permission.noControl"),children:i.jsx(PO,{on:ie?.chamber_light??!1,className:"w-3.5 h-3.5"})}),i.jsx("button",{onClick:()=>ee(!0),disabled:!be||!l("printers:control"),className:`p-1 rounded disabled:opacity-50 ${be&&l("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:l("printers:control")?a(be?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):a("printers.permission.noControl"),children:i.jsx(NT,{className:"w-3.5 h-3.5 text-bambu-gray"})}),i.jsx("button",{onClick:ye,disabled:he||q,className:"p-1 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:"Refresh stream",children:i.jsx(Sr,{className:`w-3.5 h-3.5 text-bambu-gray ${he?"animate-spin":""}`})}),i.jsx("button",{onClick:L,className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:C?"Exit fullscreen":"Fullscreen",children:C?i.jsx(JX,{className:"w-3.5 h-3.5 text-bambu-gray"}):i.jsx(ife,{className:"w-3.5 h-3.5 text-bambu-gray"})}),i.jsx("button",{onClick:()=>N(!_),className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:_?"Expand":"Minimize",children:_?i.jsx(oT,{className:"w-3.5 h-3.5 text-bambu-gray"}):i.jsx(WL,{className:"w-3.5 h-3.5 text-bambu-gray"})}),i.jsx("button",{onClick:r,className:"p-1 hover:bg-red-500/20 rounded",title:"Close",children:i.jsx(Ht,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-red-400"})})]})]}),!_&&i.jsxs("div",{className:"relative w-full bg-black flex items-center justify-center overflow-hidden h-[calc(100%-40px)]",onWheel:ve,onMouseMove:je,onMouseUp:we,onMouseLeave:we,onTouchStart:Oe,onTouchMove:_e,onTouchEnd:Ae,style:{touchAction:"none"},children:[he&&!q&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:i.jsx(Sr,{className:"w-6 h-6 text-bambu-gray animate-spin"})}),q&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:i.jsxs("div",{className:"text-center p-2",children:[i.jsx(zh,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Reconnecting in ",j,"s..."]})]})}),ue&&!q&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:i.jsxs("div",{className:"text-center p-2",children:[i.jsx(jn,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Camera unavailable"}),i.jsx("button",{onClick:ye,className:"px-2 py-1 text-xs bg-bambu-green text-white rounded hover:bg-bambu-green/80",children:"Retry"})]})}),i.jsx("img",{ref:K,src:ke,alt:"Camera stream",className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${P}) translate(${D.x/P}px, ${D.y/P}px) rotate(${W?.camera_rotation||0}deg)`,...W?.camera_rotation===90||W?.camera_rotation===270?{maxWidth:"100%",maxHeight:"100%"}:{},cursor:P>1?R?"grabbing":"grab":"default"},onError:Me,onLoad:Xe,onMouseDown:fe,draggable:!1},ne),i.jsxs("div",{className:"absolute bottom-2 left-2 flex items-center gap-1 bg-black/60 rounded px-1.5 py-1 no-drag",children:[i.jsx("button",{onClick:te,disabled:P<=1,className:"p-1 hover:bg-white/10 rounded disabled:opacity-30",title:"Zoom out",children:i.jsx(JL,{className:"w-3.5 h-3.5 text-white"})}),i.jsxs("button",{onClick:Be,className:"px-1.5 py-0.5 text-xs text-white hover:bg-white/10 rounded min-w-[32px]",title:"Reset zoom",children:[Math.round(P*100),"%"]}),i.jsx("button",{onClick:F,disabled:P>=4,className:"p-1 hover:bg-white/10 rounded disabled:opacity-30",title:"Zoom in",children:i.jsx(ZL,{className:"w-3.5 h-3.5 text-white"})})]}),!C&&i.jsx("div",{className:"absolute bottom-0 right-0 w-6 h-6 cursor-se-resize no-drag hover:bg-white/10 rounded-tl transition-colors",onMouseDown:Ke,onTouchStart:Ve,title:"Drag to resize",children:i.jsx("svg",{className:"w-6 h-6 text-bambu-gray/70 hover:text-bambu-gray",viewBox:"0 0 24 24",fill:"currentColor",children:i.jsx("path",{d:"M22 22H20V20H22V22ZM22 18H20V16H22V18ZM18 22H16V20H18V22ZM22 14H20V12H22V14ZM18 18H16V16H18V18ZM14 22H12V20H14V22ZM22 10H20V8H22V10ZM18 14H16V12H18V14ZM14 18H12V16H14V18ZM10 22H8V20H10V22Z"})})})]}),i.jsx(MO,{printerId:t,isOpen:$,onClose:()=>ee(!1)})]})}function fMe({printerId:t,printerName:e,onClose:n}){const{t:r}=Dt(),a=sn(),[s,o]=w.useState(!0),[l,c]=w.useState(new Set),[u,d]=w.useState(""),[m,p]=w.useState("all"),f=w.useRef(null),{data:y,isLoading:v,refetch:b}=et({queryKey:["mqtt-logs",t],queryFn:()=>ge.getMQTTLogs(t),refetchInterval:1e3}),g=gt({mutationFn:()=>ge.enableMQTTLogging(t),onSuccess:()=>{a.invalidateQueries({queryKey:["mqtt-logs",t]})}}),_=gt({mutationFn:()=>ge.disableMQTTLogging(t),onSuccess:()=>{a.invalidateQueries({queryKey:["mqtt-logs",t]})}}),N=gt({mutationFn:()=>ge.clearMQTTLogs(t),onSuccess:()=>{a.invalidateQueries({queryKey:["mqtt-logs",t]})}});w.useEffect(()=>{const R=G=>{G.key==="Escape"&&n()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[n]),w.useEffect(()=>{s&&f.current&&(f.current.scrollTop=f.current.scrollHeight)},[y?.logs,s]);const C=R=>{c(G=>{const z=new Set(G);return z.has(R)?z.delete(R):z.add(R),z})},k=R=>new Date(R).toLocaleTimeString("en-US",{hour12:!1,fractionalSecondDigits:3}),P=(R,G)=>{if(R==null)return"";const z=typeof R=="string"?JSON.parse(R):R,Z=JSON.stringify(z,null,G?2:0);return!G&&Z.length>100?Z.substring(0,100)+"...":Z},T=y?.logging_enabled??!1,D=w.useMemo(()=>y?.logs??[],[y?.logs]),A=w.useMemo(()=>D.filter(R=>{if(m!=="all"&&R.direction!==m)return!1;if(u.trim()){const G=u.toLowerCase(),z=R.topic.toLowerCase().includes(G),I=JSON.stringify(R.payload).toLowerCase().includes(G);return z||I}return!0}),[D,u,m]);return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg max-w-4xl w-full max-h-[85vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("mqttDebug.title")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:e})]}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[T?i.jsxs(ze,{size:"sm",variant:"secondary",onClick:()=>_.mutate(),disabled:_.isPending,children:[i.jsx(rl,{className:"w-4 h-4"}),r("mqttDebug.stopLogging")]}):i.jsxs(ze,{size:"sm",onClick:()=>g.mutate(),disabled:g.isPending,children:[i.jsx(Co,{className:"w-4 h-4"}),r("mqttDebug.startLogging")]}),i.jsxs(ze,{size:"sm",variant:"secondary",onClick:()=>N.mutate(),disabled:N.isPending||D.length===0,children:[i.jsx(nn,{className:"w-4 h-4"}),r("mqttDebug.clearLog")]}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:()=>b(),disabled:v,children:i.jsx(Sr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),i.jsx("div",{className:"flex-1"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:s,onChange:R=>o(R.target.checked),className:"rounded border-bambu-dark-tertiary"}),"Auto-scroll"]}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[A.length,"/",D.length]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(Rr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:r("mqttDebug.searchPlaceholder"),value:u,onChange:R=>d(R.target.value),className:"w-full pl-8 pr-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),u&&i.jsx("button",{onClick:()=>d(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark rounded border border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>p("all"),className:`px-2 py-1.5 text-xs rounded-l transition-colors ${m==="all"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:r("mqttDebug.all")}),i.jsxs("button",{onClick:()=>p("in"),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${m==="in"?"bg-blue-500 text-white":"text-bambu-gray hover:text-white"}`,children:[i.jsx(cx,{className:"w-3 h-3"}),r("mqttDebug.incoming")]}),i.jsxs("button",{onClick:()=>p("out"),className:`px-2 py-1.5 text-xs rounded-r transition-colors flex items-center gap-1 ${m==="out"?"bg-green-500 text-white":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Af,{className:"w-3 h-3"}),r("mqttDebug.outgoing")]})]})]})]}),i.jsx("div",{ref:f,className:"flex-1 overflow-auto p-4 font-mono text-xs bg-black min-h-[400px]",children:D.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bambu-gray",children:[i.jsx("p",{className:"mb-2",children:r("mqttDebug.noMessages")}),!T&&i.jsx("p",{className:"text-sm",children:r("mqttDebug.startLoggingHint")})]}):A.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bambu-gray",children:[i.jsx("p",{className:"mb-2",children:r("mqttDebug.noMessagesMatch")}),i.jsx("p",{className:"text-sm",children:r("mqttDebug.adjustFilterHint")})]}):i.jsx("div",{className:"space-y-1",children:A.map((R,G)=>{const z=l.has(G),Z=R.direction==="in";return i.jsxs("div",{className:`p-2 rounded cursor-pointer hover:bg-bambu-dark-secondary transition-colors ${z?"bg-bambu-dark-secondary":""}`,onClick:()=>C(G),children:[i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("span",{className:"text-bambu-gray shrink-0",children:k(R.timestamp)}),i.jsx("span",{className:`shrink-0 ${Z?"text-blue-400":"text-green-400"}`,title:r(Z?"mqttDebug.incoming":"mqttDebug.outgoing"),children:Z?i.jsx(cx,{className:"w-3 h-3"}):i.jsx(Af,{className:"w-3 h-3"})}),i.jsx("span",{className:"text-purple-400 shrink-0",children:R.topic})]}),z?i.jsx("pre",{className:"mt-2 p-3 bg-gray-900 border border-gray-700 rounded text-green-400 overflow-x-auto whitespace-pre-wrap break-all max-h-96 overflow-y-auto text-xs",children:P(R.payload,!0)}):i.jsx("pre",{className:"mt-1 text-white/80 truncate",children:P(R.payload,!1)})]},G)})})}),i.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary",children:[i.jsx("div",{className:"text-sm text-bambu-gray",children:T?i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),r("mqttDebug.loggingActive")]}):i.jsx("span",{children:r("mqttDebug.loggingStopped")})}),i.jsx(ze,{variant:"secondary",onClick:n,children:r("common.close")})]})]})})}const DR={"0300_4000":"Z axis homing failed; the task has been stopped.","0300_4001":"The printer timed out waiting for the nozzle to cool down before homing.","0300_4002":"Auto Bed Leveling failed; the task has been stopped.","0300_4005":"The hotend cooling fan speed is abnormal.","0300_4006":"The nozzle is clogged.","0300_4008":"The AMS failed to change filament.","0300_4009":"Homing XY axis failed.","0300_400A":"Mechanical resonance frequency identification failed.","0300_400B":"Internal communication exception","0300_400C":"The task was canceled.","0300_400D":"Resume failed after power loss.","0300_400E":"The motor self-check failed.","0300_400F":"The power supply voltage does not match the printer.","0300_4010":"Nozzle offset calibration failed.","0300_4011":"Flow Dynamics Calibration failed; please reinitiate printing or calibration.","0300_4013":"Printing cannot be initiated while AMS is drying.","0300_4014":"Homing Z axis failed: temperature control abnormality.","0300_4015":"Nozzle clumping detection calibration failed. Please go to 'Assistant' for troubleshooting.","0300_4016":"Nozzle cleaning failed. Please click the Assistant for troubleshooting.","0300_401F":"The hotend is not installed, and the toolhead cannot perform homing. Please install the hotend and then continue.","0300_4020":"The nozzle presence detection failed. Please check the Assistant for details.","0300_4021":"Nozzle offset calibration sensor signal abnormality detected. Please check the sensor and retry.","0300_4042":"The Laser Safety Window is not properly installed. The task has been stopped.","0300_4044":"The Flame Sensor is abnormal. The sensor may be short-circuited. Please troubleshoot the issue before starting a print job.","0300_404B":"Task aborted because the front door or top cover is open.","0300_404D":"The current temperature of the hotend, heatbed, or chamber is too high. Please wait for it to cool down to room temperature before restarting the task.","0300_4050":"Liveview Camera calibration timeout; please restart the printer.","0300_4052":"Blade Z-axis homing failed","0300_4057":"Z-axis step loss detected. The task has stopped. Please check if there are any obstructions beneath the heatbed.","0300_4066":"Calibration of motion precision failed.","0300_4067":"Calibration result is over the threshold.","0300_4068":"Step loss occurred during the motion accuracy enhancement process. Please try again.","0300_8000":"Printing was paused for unknown reason. You can select 'Resume' to resume the print job.","0300_8001":"Printing was paused by the user. You can select 'Resume' to continue printing.","0300_8002":"First layer defects were detected by the Micro Lidar. Please check the quality of the printed model before continuing your print.","0300_8003":"Spaghetti defects were detected by the AI Print Monitoring. Please check the quality of the printed model before continuing your print.","0300_8004":"Filament ran out. Please load new filament.","0300_8005":"Toolhead front cover fell off. Please remount the front cover and check to make sure your print is going okay.","0300_8006":"The build plate marker was not detected. Please confirm the build plate is correctly positioned on the heatbed with all four corners aligned, and the marker is visible.","0300_8007":"There was an unfinished print job when the printer lost power. If the model is still adhered to the build plate, you can try resuming the print job.","0300_8008":"Nozzle temperature malfunction","0300_8009":"Heatbed temperature malfunction","0300_800A":"A Filament pile-up was detected by AI Print Monitoring. Please clean filament from the waste chute.","0300_800B":"The cutter is stuck. Please make sure the cutter handle is out and check the filament sensor cable connection.","0300_800C":"Skipped step detected: auto-recover complete; please resume print and check if there are any layer shift problems.","0300_800D":"Detected that the extruder is not extruding normally. If the defects are acceptable, select 'Resume' to resume the print job.","0300_800E":"The print file is not available. Please check to see if the storage media has been removed.","0300_800F":"The door seems to be open, so printing was paused.","0300_8010":"The hotend cooling fan speed is abnormal.","0300_8011":"Detected build plate is not the same as the Gcode file. Please adjust slicer settings or use the correct plate.","0300_8013":"Printing paused due to the pause command added to the printing file.","0300_8014":"The nozzle is covered with filament, or the build plate is installed incorrectly. Please cancel this print and clean the nozzle or adjust the build plate according to the actual status. You can als...","0300_8015":"The filament on external spool has run out; please load new filament. If the filament is loaded, please select 'Resume'.","0300_8016":"The nozzle is clogged with filament. Please cancel this print and clean the nozzle or select 'Resume' to resume the print job.","0300_8017":"Foreign objects detected on heatbed. Please check and clean the heatbed. Then, select 'Resume' to resume the print job.","0300_8018":"Chamber temperature malfunction.","0300_8019":"No build plate is placed.","0300_801A":"Filament extrusion error; please check the assistant for troubleshooting. After resolving the issue, decide whether to cancel or resume the print job based on the actual print status.","0300_801B":"Nozzle temperature problem detected. Refer to Assistant to re-connect the hotend connector. POWER OFF the printer before this operation to avoid short circuits.","0300_801C":"The extrusion resistance is abnormal. The extruder may be clogged; please refer to the assistant. After trouble shooting, you can select 'Resume' to resume the print job.","0300_801D":"The extruder servo motor position sensor is malfunctioning. Please power off the printer first and check if the connection cable is loose.","0300_801E":"The extrusion motor is overloaded, please check the Assistant for details.","0300_8021":"The nozzle may not be installed or not properly installed. Please ensure the nozzle is correctly installed before proceeding.","0300_8022":"The heatbed may be obstructed while moving downward. Please clear any objects beneath the heatbed and check for any resistance or jamming during its movement.","0300_8028":"Nozzle offset calibration sensor error. If using a single hotend or the calibration function is disabled, you may ignore this and continue printing; otherwise, it is recommended to check the sensor...","0300_8041":"Platform detection timeout: please restart the printer.","0300_8042":"Task paused because the door is open.","0300_8043":"The laser module is abnormal.","0300_8044":"Fire was detected inside the chamber.","0300_8045":"Material detection timeout: please restart the printer.","0300_8046":"Foreign object detect timeout: please restart the printer.","0300_8047":"Quick-release lever detection time out: please restart the printer.","0300_8048":"Laser Module unlock has timed out, and the task cannot proceed. Please restart the printer and try again.","0300_8049":"The current plate is invalid.","0300_804A":"Emergency stop button improperly installed. Please reinstall according to the Wiki before proceeding.","0300_804B":"Task paused. The Laser Safety Window is open.","0300_804E":"This is a printing task. Please detach the Laser/Cutting Module from the Toolhead.","0300_804F":"The loading/unloading process is currently ongoing. Please stop the process or remove the laser/cutting module.","0300_8050":"This device does not support the 40W Laser Module. Please remove it or replace it with a 10W Laser Module.","0300_8051":"The cutting module has dropped or the cutting module cable is disconnected; please check the module.","0300_8053":"Laser module detected. Please install the right nozzle correctly to ensure proper Laser Module Mounting Calibration.","0300_8054":"Please place the paper required for Print Then Cut.","0300_8055":"The module mounted on the toolhead does not match the task. Please install the correct module.","0300_8057":"The rotary attachment is disconnected. Please ensure it is properly installed and the cable is securely plugged in.","0300_8058":"The rotary attachment is detected. Please remove it before continuing.","0300_8061":"The mode of Airflow System failed to activate; check the air door condition.","0300_8062":"The chamber temperature is too high. It may be due to high environmental temperature.","0300_8063":"The chamber temperature is too high. Please open the top cover and front door to cool down.","0300_8064":"The chamber temperature is too high. Please open the top cover and front door to cool down. (Open door detection for this print job will be set to 'Notification' level)","0300_8065":"The temperature of the MC module is too high. Please check the Wiki for possible explanations.","0300_8071":"The Toolhead Enhanced Cooling Fan module is malfunctioning.","0300_807D":"Fire Extinguisher not detected, the automatic extinguishing function will be unavailable.","0300_807E":"Fire Extinguisher not detected, the automatic extinguishing function will be unavailable.","0300_807F":"Fire Extinguisher is malfunctioning.","0300_8080":"Fire extinguisher motor reset failed.","0300_8081":"Fire extinguisher cylinder not installed. Please confirm on the extinguisher page.","0300_8082":"The Fire Extinguisher Gas Cylinder is empty.","0300_C012":"Please heat the nozzle to above 170°C.","0300_C056":"A minor fire was detected inside the chamber, and the Auto Fire Extinguishing process has been aborted.","0300_C070":"The fire extinguisher has been detected and is ready for use after the laser module is connected.","0500_4001":"Failed to connect to Bambu Cloud. Please check your network connection.","0500_4002":"Unsupported print file path or name. Please resend the print job.","0500_4003":"Printing stopped because the printer was unable to parse the file. Please resend your print job.","0500_4004":"Device is busy and cannot start new task. Please wait for current task to complete before sending new task.","0500_4005":"Print jobs are not allowed to be sent while updating firmware.","0500_4006":"There is not enough free storage space for the print job. Restoring to factory settings can free up available space.","0500_4007":"The device requires a repair upgrade, and printing is currently unavailable.","0500_4008":"Starting printing failed; please power cycle the printer and resend the print job.","0500_4009":"Print jobs are not allowed to be sent while updating logs.","0500_400A":"The file name is not supported. Please rename and restart the print job.","0500_400B":"There was a problem downloading a file. Please check your network connection and resend the print job.","0500_400C":"Please insert a MicroSD card and restart the print job.","0500_400D":"Please run a self-test and restart the print job.","0500_400E":"Printing was cancelled.","0500_400F":"AMS is initializing and cannot be upgraded at the moment. Please try again later.","0500_4010":"AMS is drying and cannot be upgraded at the moment. Please try again later.","0500_4011":"The printer is loading or unloading filament and cannot be upgraded at the moment. Please try again later.","0500_4012":"The device is printing and cannot be upgraded at the moment. Please try again later.","0500_4013":"AMS is in operation and cannot be upgraded at the moment. Please try again when it is idle.","0500_4014":"Slicing for the print job failed. Please check your settings and restart the print job.","0500_4015":"There is not enough free storage space for the print job. Please format or clear files from the MicroSD card to free up space.","0500_4016":"The MicroSD Card is write-protected. Please replace the MicroSD Card.","0500_4017":"Binding failed. Please retry or restart the printer and retry.","0500_4018":"Binding configuration information parsing failed; please try again.","0500_4019":"The printer has already been bound. Please unbind it and try again.","0500_401A":"Cloud access failed. Possible reasons include network instability caused by interference, inability to access the internet, or router firewall configuration restrictions. You can try moving the pri...","0500_401B":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_401C":"Cloud access is rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_401D":"Cloud access failed, which may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0500_401E":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_401F":"Authorization timed out. Please make sure that your phone or PC has access to the internet, and ensure that the Bambu Studio/Bambu Handy APP is running in the foreground during the binding operation.","0500_4020":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_4021":"Cloud access failed, which may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0500_4022":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_4023":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_4024":"Cloud access failed. Possible reasons include network instability caused by interference, inability to access the internet, or router firewall configuration restrictions. You can try moving the pri...","0500_4025":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_4026":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_4027":"Cloud access failed; this may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0500_4028":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_4029":"Cloud access is rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_402A":"Failed to connect to the router, which may be caused by wireless interference or being too far away from the router. Please try again or move the printer closer to the router and try again.","0500_402B":"Router connection failed due to incorrect password. Please check the password and try again.","0500_402C":"Failed to obtain IP address, which may be caused by wireless interference resulting in data transmission failure or the DHCP address pool of the router being full. Please move the printer closer to...","0500_402D":"System exception","0500_402E":"System does not support the file system currently used by the USB flash drive. Please replace or format the USB flash drive to FAT32.","0500_402F":"The MicroSD card sector data is damaged. Please use the SD card repair tool to repair or format it. If it still cannot be identified, please replace the MicroSD card.","0500_4030":"The device is currently upgrading. Please try again when it is idle.","0500_4031":"The accessory firmware does not match the printer. Please update it on the 'Firmware' page.","0500_4033":"The AMS firmware does not match the printer. Please update it on the 'Firmware' page.","0500_4034":"The Laser Module firmware does not match the printer. Please update it on the 'Firmware' page.","0500_4035":"The BirdsEye Camera is malfunctioning. Please try restarting the device. If the issue persists after multiple restarts, check the camera connection status or contact customer support.","0500_4037":"Your sliced file is not compatible with current printer model. This file can't be printed on this printer.","0500_4038":"The nozzle diameter in sliced file is not consistent with the current nozzle setting. This file can't be printed.","0500_4039":"The current task does not allow the installation of the laser/cutting module, and the task has been halted.","0500_403A":"The current temperature is too low. In order to protect you and your printer, printing tasks, moving an axis and other operations are disabled. Please move the printer to an environment above 10 de...","0500_403B":"Laser/cutting tasks cannot be initiated on the machine at the moment. Please use the computer software to start the task.","0500_403C":"The current nozzle setting does not match the slicing file. Continuing to print may affect print quality. It is recommended to re-slice before starting the print.","0500_403D":"The toolhead module is not set up. Please set it up before initiating the task.","0500_403E":"The current tool head does not support initialization.","0500_403F":"Failed to download print job; please check your network connection.","0500_4040":"The printer has reached its power limit. Please connect a dedicated power adapter to this AMS to enable drying.","0500_4041":"The AMS drying cannot be started during printing.","0500_4042":"Due to power limitations, starting AMS drying will pause current operations such as nozzle heating and fan running. Do you want to proceed with drying?","0500_4043":"Due to power limitations, only one AMS is allowed to use the device's power for drying.","0500_4044":"BirdsEye Camera malfunction: please contact customer support.","0500_4045":"Hotend check in progress. This operation is temporarily unavailable. Please wait.","0500_4050":"Error detected on the print board.","0500_4052":"Error detected on the hot end.","0500_4054":"Error detected on the mat.","0500_405D":"Laser module Serial Number error: unable to calibrate or make project.","0500_4065":"The task requires a Laser Platform, but the current one is a Cutting Platform. Please replace it, measure the material thickness in the software, and then restart the task.","0500_4070":"The laser or cutter module is connected, so the device cannot initiate a 3D printing task.","0500_4075":"No Laser Platform was detected, which may affect thickness measurement accuracy. Please place the laser platform correctly and ensure the rear markers are not blocked, then restart the thickness me...","0500_4076":"Please place the Laser Platform correctly and ensure the rear markers are not blocked, then restart the thickness measurement in the software before initiating the task.","0500_4097":"The device cannot detect the Laser Module. Please reconnect the module cable or restart the printer.","0500_4098":"The device cannot detect AMS A. Please reconnect the AMS cable or restart the printer.","0500_4099":"The firmware of Cutting Module does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0500_409A":"The firmware of the Air Pump does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0500_409B":"The firmware of the Laser Module does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0500_409D":"The firmware of AMS A does not match the printer; the device cannot continue working. Please upgrade it on the 'Firmware' page.","0500_409E":"The device cannot detect the Cutting Module. Please reconnect the module cable or restart the printer.","0500_409F":"The device cannot detect the Air Pump. Please reconnect the module cable or restart the printer.","0500_40A0":"The Rotary Attachment module is not detected. Please reconnect the cable or restart the printer.","0500_40A1":"The Auto Fire Extinguishing System is not detected. Please reconnect the module cable or restart the printer.","0500_40A3":"AMS(or AMS lite) A communication is abnormal. Please reconnect the module cable or restart the printer.","0500_40A4":"The current firmware only supports 1 AMS Lite. Please remove all AMS units before reconnecting the supported AMS Lite device.","0500_40A5":"The current firmware only supports AMS/AMS 2 Pro/AMS HT, with a maximum of 4 units. Please remove all AMS units before reconnecting the supported one.","0500_8013":"The print file is not available. Please check to see if the storage media has been removed.","0500_8036":"Your sliced file is not consistent with the current printer model. Continue?","0500_803C":"The current nozzle setting does not match the slicing file. Continuing to print may affect print quality. It is recommended to re-slice before starting the print.","0500_8040":"Toolhead front cover is detached. Moving the toolhead may damage the printer. Do you want to continue?","0500_8041":"The filament in hotend is too cold. Extrusion may damage the extruder. Still feeding in/out the filament?","0500_8048":"The module on the toolhead is not calibrated. Please cancel the task to perform calibration or switch to a calibrated module.","0500_8051":"Detected build plate is not the same as the Gcode file. Please adjust slicer settings or use the correct plate.","0500_8053":"Nozzle mismatch was detected during printing. Please initiate the print after re-slicing, or continue printing after replacing with the correct nozzle. Caution: the hotend temperature is high.","0500_8055":"Laser module is installed, but a Cutting Platform is detected. Please place a Laser Platform and perform laser calibration.","0500_8056":"Cutting module is installed, but the laser platform is detected. Please place the cutting platform for calibration.","0500_8058":"Please place the light grip cutting mat correctly and ensure the marker is exposed.","0500_8059":"Cutting platform base is not correctly aligned. Please ensure that the four corners of the platform are aligned with the heatbed.","0500_805A":"Please place the cutting mat on cutting protection base.","0500_805B":"The cutting mat type is unknown; please replace it with the correct cutting mat.","0500_805C":"The grip cutting mat type does not match; please place a LightGrip cutting mat.","0500_805E":"Cutting module Serial Number error: unable to calibrate or make project.","0500_8060":"The current module on toolhead does not meet requirements. Please replace the module as per the on-screen instructions.","0500_8061":"No print plate detected. Please make sure it is placed correctly.","0500_8062":"The print plate marker was not detected. Please confirm the print plate is correctly positioned on the heatbed with all four corners aligned, and the marker is visible. If strong light is shining o...","0500_8063":"The platform is not detected during calibration; please make sure the Laser Platform is properly placed.","0500_8064":"Please place the Laser Platform correctly and ensure the rear markers are not blocked for laser calibration.","0500_8066":"The task requires a Cutting Platform, but the current one is a Laser Platform. Please replace it with a Cutting Platform (Cutting Protection Base + LightGrip cutting mat).","0500_8067":"Please place a LightGrip cutting mat on the cutting protection base.","0500_8068":"Please place the strong grip cutting mat correctly and ensure the marker is exposed.","0500_8069":"Unable to recognize the left and right hotends. They might be third party hotends, or the hotend marks may be dirty. Please manually set the hotend types.","0500_806A":"Unable to recognize the left and right hotends. They might be third party hotends, or the hotend marks may be dirty. Please set hotend types on printer screen before next print.","0500_806B":"Quick-release Lever is not locked. Please press down the external toolhead module to ensure it is properly seated, then push down the level to lock it in place.","0500_806C":"Please place the cutting platform correctly and ensure the marker is exposed.","0500_806D":"Material not detected. Please confirm placement and continue.","0500_806E":"Foreign objects detected on heatbed; please check and clean up the heatbed.","0500_806F":"The grip cutting mat type does not match; please place a StrongGrip cutting mat.","0500_8071":"No cutting platform was detected. Please confirm that it has been correctly placed.","0500_8072":"Live View camera is blocked","0500_8073":"Heatbed limit block is obstructed or contaminated. Please clean and ensure the limit block is visible, otherwise platform position offset detection may be inaccurate.","0500_8074":"The Laser Platform is offset. Please ensure that the four corners of the platform are aligned with the heatbed, and the marker is not obstructed.","0500_8077":"The visual marker was not detected. Please ensure the paper is properly placed.","0500_8078":"Current material does not match the sliced file settings. Please load the correct material and ensure the QR code on the material is not damaged or dirty.","0500_8079":"Please place the Laser Test Material (350g paperboard) and position support strips underneath to prevent material warping.","0500_807A":"The foreign object detection function is not working. You can continue the task or check the assistant for troubleshooting.","0500_807B":"Please place the cutting platform (cutting protection base + LightGrip cutting mat).","0500_807C":"Please place the cutting platform (cutting protection base + StrongGrip cutting mat).","0500_807D":"This task requires a Cutting Platform, but the current one is a Laser Platform. Please replace it with a Cutting Platform (Cutting Protection Base + StrongGrip Cutting Mat).","0500_807E":"Please place a StrongGrip cutting mat on the cutting protection base.","0500_8080":"The left and right hotends are not installed.","0500_8081":"The left and right hotends are not installed.","0500_8082":"Please remove the protective film on the Opaque Glossy Acrylic before processing","0500_8083":"Material is not allowed in Mounting Calibration. Please remove the material from the platform.","0500_8084":"The Live View Camera is dirty; please clean it and continue.","0500_8085":"Toolhead camera is obstructed","0500_8086":"Toolhead Camera is dirty, which affects the AI function; please clean the lens surface.","0500_8087":"BirdsEye camera is obstructed","0500_8088":"The Birdseye Camera is dirty","0500_8089":"Task paused due to Presence Check failed. Please check the printer to continue.","0500_808A":"The BirdsEye Camera is installed offset. Please refer to the assistant to reinstall it.","0500_808B":"The BirdsEye Camera setup failed. Please remove all objects and the mat on the heatbed to ensure the heatbed markers are visible. Meanwhile, please ensure the BirdsEye Camera is installed correctly...","0500_808C":"Detected build plate offset. Please align the build plate with the heatbed, and then continue.","0500_808D":"The Cutting Module offset calibration failed, which may result in inaccurate cuts. Please ensure the cutting material is properly positioned and check whether the cutting blade tip is worn.","0500_808E":"BirdsEye Camera initialization failed. The toolhead camera did not detect the Heatbed features. Please clean the Heatbed, remove all objects and pads, and ensure the bed markings are visible. Check...","0500_808F":"Nozzle camera lens is dirty, affecting AI monitoring. Clean the lens with a non-woven cloth and a small amount of alcohol. Beware of hotend heat; wait for it to cool before handling.","0500_8090":"Please attach the 80g White Printing Paper to the center area of the platform.","0500_8091":"The Cutting Module offset calibration failed, which may result in inaccurate cuts. Please ensure the 80g white printer paper(letter paper thickness) is properly positioned and check whether the cut...","0500_8092":"Toolhead Camera initialization failed. This print can still continue, but some AI functions will be disabled. If you encounter this issue again after restarting, please contact customer support.","0500_8093":"The nozzle silicone sleeve is not installed; there is a risk of temperature control failure. Please install it correctly and try again.","0500_80A0":"The visual encoder board was not detected. Please check if the board is properly placed and aligned at all four corners, and ensure the positioning markings are clear and free from wear.","0500_C010":"MicroSD Card read/write exception: please reinsert or replace the MicroSD Card.","0500_C032":"Laser/Cutting module connected to the toolhead. The drying process has been automatically stopped.","0500_C036":"This is a printing task. Please detach the Laser/Cutting Module from the Toolhead.","0500_C07F":"Device is busy and cannot perform this operation. To proceed, please pause or stop the current task.","0501_4017":"Binding failed. Please retry or restart the printer and retry.","0501_4018":"Binding configuration information parsing failed; please try again.","0501_4019":"The printer has already been bound. Please unbind it and try again.","0501_401A":"Cloud access failed. Possible reasons include network instability caused by interference, inability to access the internet, or router firewall configuration restrictions. You can try moving the pri...","0501_401B":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_401C":"Cloud access is rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_401D":"Cloud access failed, which may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0501_401E":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_401F":"Authorization timed out. Please make sure that your phone or PC has access to the internet, and ensure that the Bambu Studio/Bambu Handy APP is running in the foreground during the binding operation.","0501_4020":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_4021":"Cloud access failed, which may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0501_4022":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_4023":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_4024":"Cloud access failed. Possible reasons include network instability caused by interference, inability to access the internet, or router firewall configuration restrictions. You can try moving the pri...","0501_4025":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_4026":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_4027":"Cloud access failed; this may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0501_4028":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_4029":"Cloud access is rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_4031":"Device discovery binding is in progress, and the QR code cannot be displayed on the screen. You can wait for the binding to finish or abort the device discovery binding process in the APP/Studio an...","0501_4032":"QR code binding is in progress, so device discovery binding cannot be performed. You can scan the QR code on the screen for binding or exit the QR code display page on screen and try device discove...","0501_4033":"Your APP region does not match with your printer; please download the APP in the corresponding region and register your account again.","0501_4034":"The slicing progress has not been updated for a long time, and the printing task has exited. Please confirm the parameters and reinitiate printing.","0501_4035":"The device is in the process of binding and cannot respond to new binding requests.","0501_4038":"The regional settings do not match the printer; please check the printer's regional settings.","0501_4039":"Device login has expired; please try to bind again.","0501_4098":"The device cannot detect AMS B. Please reconnect the AMS cable or restart the printer.","0501_409D":"The firmware of AMS B does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0501_40A3":"AMS(or AMS lite) B communication is abnormal. Please reconnect the module cable or restart the printer.","0502_4001":"Current filament will be used in this print job. Settings cannot be changed.","0502_4002":"Please go to “Settings > Calibration” to run the Motion Accuracy Enhancement Calibration before turning on Motion Accuracy Enhancement mode.","0502_4003":"The printer is currently printing and the motion accuracy enhancement feature cannot be turned on or off.","0502_4004":"Some features are not supported by the current device. Please check the Studio feature settings or update the firmware to the latest version.","0502_4005":"The AMS has not been calibrated yet, so printing cannot be initiated.","0502_4006":"Unknown module detected; please try updating the firmware to the latest version.","0502_400D":"Failed to start a new task: filament loading/unloading not completed.","0502_400E":"Failed to start a new task: The nozzle cold pull was not completed.","0502_4013":"This device is not compatible with the 40W laser module. Please replace it with a 10W laser module or remove it.","0502_4098":"The device cannot detect AMS C. Please reconnect the AMS cable or restart the printer.","0502_409D":"The firmware of AMS C does not match the printer; the device cannot continue working. Please upgrade it on the 'Firmware' page.","0502_40A3":"AMS(or AMS lite) C communication is abnormal. Please reconnect the module cable or restart the printer.","0502_C00F":"The device is busy and cannot perform nozzle identification.","0502_C010":"Due to printer power limitations, printing, calibration, controls and other actions cannot be performed during AMS drying. Please stop the drying process before proceeding with any other operation.","0502_C011":"Currently in 2D production mode. Please continue the operation on the printer","0502_C012":"The task cannot be paused.","0502_C014":"The AMS Remaining Filament Estimation is enabled by default and cannot be disabled.","0502_C024":"The flow dynamic calibration records have exceeded the storage limit. Please delete some historical records in the slicer software before adding new calibration data.","0503_4098":"The device cannot detect AMS D. Please reconnect the AMS cable or restart the printer.","0503_409D":"The firmware of AMS D does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0503_40A3":"AMS(or AMS lite) D communication is abnormal. Please reconnect the module cable or restart the printer.","0580_4096":"The device cannot detect AMS-HT A. Please reconnect the AMS-HT cable or restart the printer.","0580_409C":"The firmware of AMS-HT A does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0580_40A2":"AMS-HT A communication is abnormal. Please reconnect the module cable or restart the printer.","0581_4096":"The device cannot detect AMS-HT B. Please reconnect the AMS-HT cable or restart the printer.","0581_409C":"The firmware of AMS-HT B does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0581_40A2":"AMS-HT B communication is abnormal. Please reconnect the module cable or restart the printer.","0582_4096":"The device cannot detect AMS-HT C. Please reconnect the AMS-HT cable or restart the printer.","0582_409C":"The firmware of AMS-HT C does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0582_40A2":"AMS-HT C communication is abnormal. Please reconnect the module cable or restart the printer.","0583_4096":"The device cannot detect AMS-HT D. Please reconnect the AMS-HT cable or restart the printer.","0583_409C":"The firmware of AMS-HT D does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0583_40A2":"AMS-HT D communication is abnormal. Please reconnect the module cable or restart the printer.","0584_4096":"The device cannot detect AMS-HT F. Please reconnect the AMS-HT cable or restart the printer.","0584_409C":"The firmware of AMS-HT E does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0584_40A2":"AMS-HT E communication is abnormal. Please reconnect the module cable or restart the printer.","0585_4096":"The device cannot detect AMS-HT E. Please reconnect the AMS-HT cable or restart the printer.","0585_409C":"The firmware of AMS-HT F does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0585_40A2":"AMS-HT F communication is abnormal. Please reconnect the module cable or restart the printer.","0586_4096":"The device cannot detect AMS-HT G. Please reconnect the AMS-HT cable or restart the printer.","0586_409C":"The firmware of AMS-HT G does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0586_40A2":"AMS-HT G communication is abnormal. Please reconnect the module cable or restart the printer.","0587_4096":"The device cannot detect AMS-HT H. Please reconnect the AMS-HT cable or restart the printer.","0587_409C":"The firmware of AMS-HT H does not match the printer; the device cannot continue working. Please upgrade it on the 'Firmware' page.","0587_40A2":"AMS-HT H communication is abnormal. Please reconnect the module cable or restart the printer.","05FE_8053":"The left nozzle is not matched with slicing file. Please initiate the print after re-slicing, or continue printing after replacing with the correct nozzle. Caution: the hotend temperature is high.","05FE_8069":"Unable to recognize the left hotend. It might be a third party hotend, or the hotend mark may be dirty. Please manually set the hotend type.","05FE_806A":"Unable to recognize the left hotend. It might be a third party hotend, or the hotend mark may be dirty. Please set hotend type on printer screen before next print.","05FE_8080":"The left hotend is not installed.","05FE_8081":"The left hotend is not installed.","05FF_8053":"The right nozzle is not matched with slicing file. Please initiate the print after re-slicing, or continue printing after replacing with the correct nozzle. Caution: the hotend temperature is high.","05FF_8069":"Unable to recognize the right hotend. It might be a third party hotend, or the hotend mark may be dirty. Please manually set the hotend type.","05FF_806A":"Unable to recognize the right hotend. It might be a third party hotend, or the hotend mark may be dirty. Please set hotend type on printer screen before next print.","05FF_8080":"The right hotend is not installed.","05FF_8081":"The right hotend is not installed.","0700_4001":"The AMS has been disabled for a print, but it still has filament loaded. Please unload the AMS filament and switch to the spool holder filament for printing.","0700_4025":"Failed to read the filament information.","0700_8001":"Failed to cut the filament. Please check the cutter.","0700_8002":"The cutter is stuck. Please make sure the cutter handle is out.","0700_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0700_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0700_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0700_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0700_8007":"Extruding filament failed. The extruder might be clogged.","0700_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS A to the extruder is properly connected.","0700_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0700_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0700_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0700_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0700_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0700_8017":"AMS A is drying. Please stop drying process before loading/unloading material.","0700_8021":"AMS setup failed; please refer to the assistant.","0700_8023":"AMS A cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0700_C069":"An error occurred during AMS A drying. Please go to Assistant for more details.","0700_C06A":"AMS A is reading RFID. Unable to start drying. Please try again later.","0700_C06B":"AMS A is changing filament. Unable to start drying. Please try again later.","0700_C06C":"AMS A is in Feed Assist Mode. Unable to start drying. Please try again later.","0700_C06D":"AMS A is assisting in filament insertion. Unable to start drying. Please try again later.","0700_C06E":"AMS A motor is performing self-test. Unable to start drying. Please try again later.","0701_4001":"Filament is still loaded from the AMS after it has been disabled. Please unload the filament, load from the spool holder, and restart printing.","0701_4025":"Failed to read the filament information.","0701_8001":"Failed to cut the filament. Please check the cutter.","0701_8002":"The cutter is stuck. Please make sure the cutter handle is out.","0701_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0701_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0701_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0701_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0701_8007":"Extruding filament failed. The extruder might be clogged.","0701_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS B to the extruder is properly connected.","0701_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0701_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0701_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0701_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0701_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0701_8017":"AMS B is drying. Please stop drying process before loading/unloading material.","0701_8021":"AMS setup failed; please refer to the assistant.","0701_8023":"AMS B cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0701_C069":"An error occurred during AMS B drying. Please go to Assistant for more details.","0701_C06A":"AMS B is reading RFID. Unable to start drying. Please try again later.","0701_C06B":"AMS B is changing filament. Unable to start drying. Please try again later.","0701_C06C":"AMS B is in Feed Assist Mode. Unable to start drying. Please try again later.","0701_C06D":"AMS B is assisting in filament insertion. Unable to start drying. Please try again later.","0701_C06E":"AMS B motor is performing self-test. Unable to start drying. Please try again later.","0702_4001":"Filament is still loaded from the AMS after it has been disabled. Please unload the filament, load from the spool holder, and restart printing.","0702_4025":"Failed to read the filament information.","0702_8001":"Failed to cut the filament. Please check the cutter.","0702_8002":"The cutter is stuck. Please make sure the cutter handle is out.","0702_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0702_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0702_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0702_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0702_8007":"Extruding filament failed. The extruder might be clogged.","0702_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS C to the extruder is properly connected.","0702_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0702_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0702_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0702_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0702_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0702_8017":"AMS C is drying. Please stop drying process before loading/unloading material.","0702_8021":"AMS setup failed; please refer to the assistant.","0702_8023":"AMS C cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0702_C069":"An error occurred during AMS C drying. Please go to Assistant for more details.","0702_C06A":"AMS C is reading RFID. Unable to start drying. Please try again later.","0702_C06B":"AMS C is changing filament. Unable to start drying. Please try again later.","0702_C06C":"AMS C is in Feed Assist Mode. Unable to start drying. Please try again later.","0702_C06D":"AMS C is assisting in filament insertion. Unable to start drying. Please try again later.","0702_C06E":"AMS C motor is performing self-test. Unable to start drying. Please try again later.","0703_4001":"Filament is still loaded from the AMS after it has been disabled. Please unload the filament, load from the spool holder, and restart printing.","0703_4025":"Failed to read the filament information.","0703_8001":"Failed to cut the filament. Please check the cutter.","0703_8002":"The cutter is stuck. Please make sure the cutter handle is out.","0703_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0703_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0703_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0703_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0703_8007":"Extruding filament failed. The extruder might be clogged.","0703_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS D to the extruder is properly connected.","0703_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0703_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0703_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0703_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0703_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0703_8017":"AMS D is drying. Please stop drying process before loading/unloading material.","0703_8021":"AMS setup failed; please refer to the assistant.","0703_8023":"AMS D cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0703_C069":"An error occurred during AMS D drying. Please go to Assistant for more details.","0703_C06A":"AMS D is reading RFID. Unable to start drying. Please try again later.","0703_C06B":"AMS D is changing filament. Unable to start drying. Please try again later.","0703_C06C":"AMS D is in Feed Assist Mode. Unable to start drying. Please try again later.","0703_C06D":"AMS D is assisting in filament insertion. Unable to start drying. Please try again later.","0703_C06E":"AMS D motor is performing self-test. Unable to start drying. Please try again later.","0704_4025":"Failed to read the filament information.","0704_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0704_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0704_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0704_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0704_8007":"Extruding filament failed. The extruder might be clogged.","0704_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS E to the extruder is properly connected.","0704_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0704_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0704_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0704_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0704_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0704_8021":"AMS setup failed; please refer to the assistant.","0704_8023":"AMS E cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0705_4025":"Failed to read the filament information.","0705_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0705_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0705_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0705_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0705_8007":"Extruding filament failed. The extruder might be clogged.","0705_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS F to the extruder is properly connected.","0705_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0705_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0705_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0705_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0705_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0705_8021":"AMS setup failed; please refer to the assistant.","0705_8023":"AMS F cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0706_4025":"Failed to read the filament information.","0706_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0706_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0706_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0706_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0706_8007":"Extruding filament failed. The extruder might be clogged.","0706_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS G to the extruder is properly connected.","0706_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0706_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0706_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0706_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0706_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0706_8021":"AMS setup failed; please refer to the assistant.","0706_8023":"AMS G cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0707_4025":"Failed to read the filament information.","0707_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0707_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0707_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0707_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0707_8007":"Extruding filament failed. The extruder might be clogged.","0707_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS H to the extruder is properly connected.","0707_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0707_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0707_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0707_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0707_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0707_8021":"AMS setup failed; please refer to the assistant.","0707_8023":"AMS H cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","07FE_8001":"Failed to cut the filament of the left extruder. Please check the cutter.","07FE_8002":"The cutter of the left extruder is stuck. Please pull out the cutter handle.","07FE_8003":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder. (Connect a PTFE tube if you are ab...","07FE_8004":"Failed to pull back the filament from the left extruder. Please check whether the filament is stuck inside the extruder.","07FE_8005":"Failed to feed the filament outside the AMS. Please clip the end of the filament flat and check to see if the spool is stuck.","07FE_8006":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","07FE_8007":"Please observe the nozzle of the left extruder. If the filament has been extruded, select 'Continue'; if it has not, please push the filament forward slightly, and then select 'Retry'.","07FE_8010":"Check if the left external filament spool or filament is stuck.","07FE_8011":"The external filament connected to the left extruder has run out; please load a new filament.","07FE_8012":"Failed to get mapping table; please select 'Resume' to retry.","07FE_8013":"Timeout purging old filament of the left extruder: Please check if the filament is stuck or the extruder is clogged.","07FE_8020":"Extruder change failed; please refer to the assistant.","07FE_8021":"AMS setup failed; please refer to the assistant.","07FE_8024":"Extruder position calibration failed; please refer to the assistant.","07FE_8025":"Cold pull timed out. Please promptly operate or check whether the filament is broken inside the extruder, and click the Assistant for details.","07FE_8030":"The filament specified in the slicer has been used up. Printing is paused. Please go to the machine to replace the material and resume printing.","07FE_C003":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube i...","07FE_C006":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","07FE_C008":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube i...","07FE_C009":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","07FE_C00A":"Please observe the nozzle of the left extruder. If the filament has been extruded, select 'Continue'; if not, please push the filament forward slightly and then select 'Retry'.","07FE_C010":"Insert the filament (over 30cm long) until it stops. You might see slight smoke during flushing. After insertion, close the front door and top cover.","07FE_C011":"Please manually and slowly pull out the filament from the extruder. Then click “Continue”.","07FE_C012":"Press the black PTFE tube coupler and unplug the PTFE tube. After completing the operation, click 'Continue.'","07FF_4001":"Filament is still loaded from the AMS after it has been disabled. Please unload the filament, load from the spool holder, and restart printing.","07FF_8001":"Failed to cut the filament of the right extruder. Please check the cutter.","07FF_8002":"The cutter is stuck. Please make sure the cutter handle is out.","07FF_8003":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder. (Connect a PTFE tube if you are a...","07FF_8004":"Failed to pull back the filament from the right extruder. Please check whether the filament is stuck inside the extruder.","07FF_8005":"Failed to feed the filament outside the AMS. Please clip the end of the filament flat and check to see if the spool is stuck.","07FF_8006":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","07FF_8007":"Please observe the nozzle of the right extruder. If the filament has been extruded, select 'Continue'; if it has not, please push the filament forward slightly, and then select 'Retry'.","07FF_8010":"Check if the external filament spool or filament is stuck.","07FF_8011":"External filament has run out; please load a new filament.","07FF_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","07FF_8013":"Timeout purging old filament of the right extruder: Please check if the filament is stuck or the extruder is clogged.","07FF_8020":"Extruder change failed; please refer to the assistant.","07FF_8021":"AMS setup failed; please refer to the assistant.","07FF_8024":"Extruder position calibration failed; please refer to the assistant.","07FF_8025":"Cold pull timed out. Please promptly operate or check whether the filament is broken inside the extruder, and click the Assistant for details.","07FF_8030":"The filament specified in the slicer has been used up. Printing is paused. Please go to the machine to replace the material and resume printing.","07FF_C003":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube ...","07FF_C006":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","07FF_C008":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube ...","07FF_C009":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","07FF_C00A":"Please observe the nozzle of the right extruder. If the filament has been extruded, select 'Continue'; if not, please push the filament forward slightly and then select 'Retry'.","07FF_C010":"Insert the filament (over 30cm long) until it stops. You might see slight smoke during flushing. After insertion, close the front door and top cover.","07FF_C011":"Hold the driven wheel bracket, slowly pull the filament from the extruder, then press 'Continue'.","07FF_C012":"Press the black PTFE tube coupler and unplug the PTFE tube. After completing the operation, click 'Continue.'","0C00_4020":"The setup of BirdsEye Camera failed. Please clear all objects and remove the mat. Make sure the marker is not obstructed. Meanwhile, clean both the BirdsEye Camera and Toolhead Camera, and remove a...","0C00_4021":"The setup of BirdsEye Camera failed; please reboot the printer.","0C00_4022":"The setup of BirdsEye Camera failed. Please check if the laser module is working properly.","0C00_4024":"The Birdseye Camera is installed offset. Please refer to the assistant to reinstall it.","0C00_4025":"The Birdseye Camera is dirty. Please clean it and restart the process.","0C00_4026":"The Live View Camera initialization failed; please reboot the printer.","0C00_4027":"The Live View Camera calibration failed. Please refer to the assistant for details and recalibrate the camera after processing.","0C00_4029":"Material not detected. Please confirm placement and continue.","0C00_402A":"The visual marker was not detected. Please re-paste the paper in the correct position.","0C00_402C":"Device data link error. Please reboot the printer","0C00_402D":"The toolhead camera is not working properly; please reboot the device.","0C00_403D":"The vision encoder plate was not detected. Please confirm it is correctly positioned on the heatbed.","0C00_403E":"The high-precision nozzle offset calibration has failed, possibly due to a damaged pattern or the similarity of the colors of the two selected filaments. Please clear the printed pattern and replac...","0C00_4041":"Toolhead camera calibration failed. Please ensure the Calibration Marker on the heatbed or Height Calibration Marker on the homing area is clean and undamaged, then re-run the calibration process.","0C00_8001":"First layer defects were detected. If the defects are acceptable, select 'Resume' to resume the print job.","0C00_8005":"Purged filament has piled up in the waste chute, which may cause a tool head collision.","0C00_8009":"Build plate localization marker was not found.","0C00_800B":"The heatbed marker was not detected. Please clear all objects and remove the mat. Make sure the marker is not obstructed.","0C00_8015":"Objects detected on the platform; please clean them up in a timely manner.","0C00_8016":"The foreign object detection function is not working. You can continue the task or check assistant for solutions.","0C00_8017":"Foreign objects detected on the platform; please clean them up on time.","0C00_8018":"The foreign object detection function is not working. You can continue the task or view the assistant for troubleshooting.","0C00_8033":"Quick-release Lever is not locked. Please push it down to secure.","0C00_8034":"Liveview Camera initialization failed. This print can still continue, but some AI functions will be disabled. If you encounter this issue again after restarting, please contact customer support.","0C00_803F":"AI detected nozzle clumping. Please check the nozzle condition. Refer to assistant for solutions.","0C00_8040":"AI detected air-printing defect. Please check the hotend extrusion status. Refer to assistant for solutions.","0C00_8042":"The AI print monitor has detected a spaghetti defect. Please check the print and take the necessary action.","0C00_8043":"AI detected nozzle clumping. Please check the nozzle condition. Refer to assistant for solutions.","0C00_C003":"Possible defects were detected in the first layer.","0C00_C004":"Possible spaghetti failure was detected.","0C00_C006":"Purged filament may have piled up in the waste chute.","1000_C001":"High bed temperature may lead to filament clogging in the nozzle. You may open the chamber door.","1000_C002":"Printing CF material with stainless steel may cause nozzle damage.","1000_C003":"Enabling Timelapse in traditional mode may cause defects; please activate this feature as needed.","1001_4001":"Timelapse is not supported as Spiral Vase mode is enabled in slicing presets.","1001_4002":"Timelapse is not supported as the Print sequence is set to 'By object'.","1001_8003":"The time-lapse mode is set to Traditional in the slicing file. This may cause surface defects. Would you like to enable it?","1001_8004":"Prime Tower is not enabled and time-lapse mode is set to Smooth in slicing file. This may cause surface defects. Would you like to enable it?","1200_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","1200_8001":"Cutting the filament failed. Please check to see if the cutter is stuck. Refer to the Assistant for solutions.","1200_8002":"The cutter is stuck. Please pull out the cutter handle.","1200_8003":"Failed to pull out the filament from the extruder. Please check whether the extruder is clogged or whether the filament is broken inside the extruder.","1200_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","1200_8005":"The filament is not inserted. Please insert the filament.","1200_8006":"Unable to feed filament into the extruder. This could be due to tangled filament or a stuck spool. If not, please check if the AMS PTFE tube is connected.","1200_8007":"Failed to extrude the filament. This might be caused by clogged extruder or stuck filament. Refer to the Assistant for solutions.","1200_8010":"Filament or spool may be stuck.","1200_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","1200_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1200_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","1200_8014":"The filament location in the toolhead was not found. Refer to the Assistant for solutions.","1200_8015":"Failed to pull out the filament from the toolhead. Please check if the filament is stuck, or if it is broken inside the extruder or PTFE tube.","1200_8016":"The extruder is not extruding normally. Refer to the Assistant for troubleshooting. There may be defects in this layer, but you may resume if the defects are acceptable.","1201_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","1201_8001":"Failed to cut the filament. Please check the cutter.","1201_8002":"The cutter is stuck. Please pull out the cutter handle.","1201_8003":"Failed to pull out the filament from the extruder. Please check whether the extruder is clogged or whether the filament is broken inside the extruder.","1201_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","1201_8005":"Failed to feed the filament. Please load the filament and then select 'Retry'.","1201_8006":"Failed to feed the filament into the toolhead. Please check whether the filament is stuck.","1201_8007":"Failed to extrude the filament. The extruder may be clogged or the filament may be stuck; please refer to HMS.","1201_8010":"Please check if the spool or filament is stuck.","1201_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","1201_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1201_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","1201_8014":"Failed to check the filament location in the tool head; please refer to the HMS.","1201_8015":"Failed to pull back the filament from the toolhead. Please check if the filament is stuck or the filament is broken inside the extruder.","1201_8016":"The extruder is not extruding normally; please refer to the HMS. After trouble shooting, if the defects are acceptable, please resume printing.","1202_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","1202_8001":"Failed to cut the filament. Please check the cutter.","1202_8002":"The cutter is stuck. Please pull out the cutter handle.","1202_8003":"Failed to pull out the filament from the extruder. Please check whether the extruder is clogged or whether the filament is broken inside the extruder.","1202_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","1202_8005":"The filament is not inserted. Please insert the filament.","1202_8006":"Failed to feed the filament into the toolhead. Please check whether the filament is stuck.","1202_8007":"Failed to extrude the filament. The extruder may be clogged or the filament may be stuck; please refer to HMS.","1202_8010":"Please check if the spool or filament is stuck.","1202_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","1202_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1202_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","1202_8014":"Failed to check the filament location in the tool head; please refer to the HMS.","1202_8015":"Failed to pull back the filament from the toolhead. Please check if the filament is stuck or is broken inside the extruder.","1202_8016":"The extruder is not extruding normally; please refer to the HMS. After trouble shooting, if the defects are acceptable, please resume printing.","1203_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","1203_8001":"Failed to cut the filament. Please check the cutter.","1203_8002":"The cutter is stuck. Please pull out the cutter handle.","1203_8003":"Failed to pull out the filament from the extruder. Please check whether the extruder is clogged or whether the filament is broken inside the extruder.","1203_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","1203_8005":"The filament is not inserted. Please insert the filament.","1203_8006":"Failed to feed the filament into the toolhead. Please check whether the filament is stuck.","1203_8007":"Failed to extrude the filament. The extruder may be clogged or the filament may be stuck; please refer to HMS.","1203_8010":"Please check if the spool or filament is stuck.","1203_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","1203_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1203_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","1203_8014":"Failed to check the filament location in the tool head; please refer to the HMS.","1203_8015":"Failed to pull back the filament from the toolhead. Please check if the filament is stuck or is broken inside the extruder.","1203_8016":"The extruder is not extruding normally; please refer to the HMS. After trouble shooting, if the defects are acceptable, please resume printing.","12FF_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","12FF_8001":"Failed to cut the filament. Please check the cutter.","12FF_8002":"The cutter is stuck. Please pull out the cutter handle.","12FF_8003":"Please pull out the filament on the spool holder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube if you are about to us...","12FF_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","12FF_8005":"The filament is not inserted. Please insert the filament.","12FF_8006":"Please feed filament into the PTFE tube until it can not be pushed any farther.","12FF_8007":"Check nozzle. Select 'Done' if filament was extruded, otherwise push filament forward slightly and select 'Retry.'","12FF_8010":"Please check if the filament or the spool is stuck.","12FF_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","12FF_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","12FF_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","12FF_C003":"Please pull out the filament on the spool holder. If this message persists, please check to see if there is filament broken in the extruder or PTFE Tube. (Connect a PTFE tube if you are about to us...","12FF_C006":"Please feed filament into the PTFE tube until it can not be pushed any farther.","1800_4025":"Failed to read the filament information.","1800_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1800_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1800_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1800_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1800_8007":"Extruding filament failed. The extruder might be clogged.","1800_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT A to the extruder is properly connected.","1800_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1800_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1800_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1800_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1800_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1800_8017":"AMS-HT A is drying. Please stop drying process before loading/unloading material.","1800_8021":"AMS setup failed; please refer to the assistant.","1800_8023":"AMS-HT A cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1800_C069":"An error occurred during AMS-HT A drying. Please go to Assistant for more details.","1800_C06A":"AMS-HT A is reading RFID. Unable to start drying. Please try again later.","1800_C06B":"AMS-HT A is changing filament. Unable to start drying. Please try again later.","1800_C06C":"AMS-HT A is in Feed Assist Mode. Unable to start drying. Please try again later.","1800_C06D":"AMS-HT A is assisting in filament insertion. Unable to start drying. Please try again later.","1800_C06E":"AMS-HT A motor is performing self-test. Unable to start drying. Please try again later.","1801_4025":"Failed to read the filament information.","1801_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1801_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1801_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1801_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1801_8007":"Extruding filament failed. The extruder might be clogged.","1801_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT B to the extruder is properly connected.","1801_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1801_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1801_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1801_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1801_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1801_8017":"AMS-HT B is drying. Please stop drying process before loading/unloading material.","1801_8021":"AMS setup failed; please refer to the assistant.","1801_8023":"AMS-HT B cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1801_C069":"An error occurred during AMS-HT B drying. Please go to Assistant for more details.","1801_C06A":"AMS-HT B is reading RFID. Unable to start drying. Please try again later.","1801_C06B":"AMS-HT B is changing filament. Unable to start drying. Please try again later.","1801_C06C":"AMS-HT B is in Feed Assist Mode. Unable to start drying. Please try again later.","1801_C06D":"AMS-HT B is assisting in filament insertion. Unable to start drying. Please try again later.","1801_C06E":"AMS-HT B motor is performing self-test. Unable to start drying. Please try again later.","1802_4025":"Failed to read the filament information.","1802_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1802_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1802_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1802_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1802_8007":"Extruding filament failed. The extruder might be clogged.","1802_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT C to the extruder is properly connected.","1802_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1802_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1802_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1802_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1802_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1802_8017":"AMS-HT C is drying. Please stop drying process before loading/unloading material.","1802_8021":"AMS setup failed; please refer to the assistant.","1802_8023":"AMS-HT C cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1802_C069":"An error occurred during AMS-HT C drying. Please go to Assistant for more details.","1802_C06A":"AMS-HT C is reading RFID. Unable to start drying. Please try again later.","1802_C06B":"AMS-HT C is changing filament. Unable to start drying. Please try again later.","1802_C06C":"AMS-HT C is in Feed Assist Mode. Unable to start drying. Please try again later.","1802_C06D":"AMS-HT C is assisting in filament insertion. Unable to start drying. Please try again later.","1802_C06E":"AMS-HT C motor is performing self-test. Unable to start drying. Please try again later.","1803_4025":"Failed to read the filament information.","1803_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1803_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1803_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1803_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1803_8007":"Extruding filament failed. The extruder might be clogged.","1803_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT D to the extruder is properly connected.","1803_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1803_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1803_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1803_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1803_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1803_8017":"AMS-HT D is drying. Please stop drying process before loading/unloading material.","1803_8021":"AMS setup failed; please refer to the assistant.","1803_8023":"AMS-HT D cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1803_C069":"An error occurred during AMS-HT D drying. Please go to Assistant for more details.","1803_C06A":"AMS-HT D is reading RFID. Unable to start drying. Please try again later.","1803_C06B":"AMS-HT D is changing filament. Unable to start drying. Please try again later.","1803_C06C":"AMS-HT D is in Feed Assist Mode. Unable to start drying. Please try again later.","1803_C06D":"AMS-HT D is assisting in filament insertion. Unable to start drying. Please try again later.","1803_C06E":"AMS-HT D motor is performing self-test. Unable to start drying. Please try again later.","1804_4025":"Failed to read the filament information.","1804_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1804_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1804_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1804_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1804_8007":"Extruding filament failed. The extruder might be clogged.","1804_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT E to the extruder is properly connected.","1804_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1804_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1804_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1804_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1804_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1804_8021":"AMS setup failed; please refer to the assistant.","1804_8023":"AMS-HT E cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1804_C069":"An error occurred during AMS-HT E drying. Please go to Assistant for more details.","1804_C06A":"AMS-HT E is reading RFID. Unable to start drying. Please try again later.","1804_C06B":"AMS-HT E is changing filament. Unable to start drying. Please try again later.","1804_C06C":"AMS-HT E is in Feed Assist Mode. Unable to start drying. Please try again later.","1804_C06D":"AMS-HT E is assisting in filament insertion. Unable to start drying. Please try again later.","1804_C06E":"AMS-HT E motor is performing self-test. Unable to start drying. Please try again later.","1805_4025":"Failed to read the filament information.","1805_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1805_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1805_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1805_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1805_8007":"Extruding filament failed. The extruder might be clogged.","1805_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT F to the extruder is properly connected.","1805_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1805_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1805_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1805_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1805_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1805_8021":"AMS setup failed; please refer to the assistant.","1805_8023":"AMS-HT F cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1805_C069":"An error occurred during AMS-HT F drying. Please go to Assistant for more details.","1805_C06A":"AMS-HT F is reading RFID. Unable to start drying. Please try again later.","1805_C06B":"AMS-HT F is changing filament. Unable to start drying. Please try again later.","1805_C06C":"AMS-HT F is in Feed Assist Mode. Unable to start drying. Please try again later.","1805_C06D":"AMS-HT F is assisting in filament insertion. Unable to start drying. Please try again later.","1805_C06E":"AMS-HT F motor is performing self-test. Unable to start drying. Please try again later.","1806_4025":"Failed to read the filament information.","1806_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1806_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1806_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1806_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1806_8007":"Extruding filament failed. The extruder might be clogged.","1806_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT G to the extruder is properly connected.","1806_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1806_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1806_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1806_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1806_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1806_8021":"AMS setup failed; please refer to the assistant.","1806_8023":"AMS-HT G cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1806_C069":"An error occurred during AMS-HT G drying. Please go to Assistant for more details.","1806_C06A":"AMS-HT G is reading RFID. Unable to start drying. Please try again later.","1806_C06B":"AMS-HT G is changing filament. Unable to start drying. Please try again later.","1806_C06C":"AMS-HT G is in Feed Assist Mode. Unable to start drying. Please try again later.","1806_C06D":"AMS-HT G is assisting in filament insertion. Unable to start drying. Please try again later.","1806_C06E":"AMS-HT G motor is performing self-test. Unable to start drying. Please try again later.","1807_4025":"Failed to read the filament information.","1807_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1807_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1807_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1807_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1807_8007":"Extruding filament failed. The extruder might be clogged.","1807_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT H to the extruder is properly connected.","1807_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1807_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1807_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1807_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1807_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1807_8021":"AMS setup failed; please refer to the assistant.","1807_8023":"AMS-HT H cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1807_C069":"An error occurred during AMS-HT H drying. Please go to Assistant for more details.","1807_C06A":"AMS-HT H is reading RFID. Unable to start drying. Please try again later.","1807_C06B":"AMS-HT H is changing filament. Unable to start drying. Please try again later.","1807_C06C":"AMS-HT H is in Feed Assist Mode. Unable to start drying. Please try again later.","1807_C06D":"AMS-HT H is assisting in filament insertion. Unable to start drying. Please try again later.","1807_C06E":"AMS-HT H motor is performing self-test. Unable to start drying. Please try again later.","18FE_8001":"Failed to cut the filament of the left extruder. Please check the cutter.","18FE_8002":"The cutter of the left extruder is stuck. Please pull out the cutter handle.","18FE_8003":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder. (Connect a PTFE tube if you are ab...","18FE_8004":"Failed to pull back the filament from the left extruder. Please check whether the filament is stuck inside the extruder.","18FE_8005":"Failed to feed the filament outside the AMS-HT. Please clip the end of the filament flat and check to see if the spool is stuck.","18FE_8006":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","18FE_8007":"Please observe the nozzle of the left extruder. If the filament has been extruded, select 'Continue'; if it has not, please push the filament forward slightly, and then select 'Retry'.","18FE_8011":"The external filament connected to the left extruder has run out; please load a new filament.","18FE_8012":"Failed to get mapping table; please select 'Resume' to retry.","18FE_8013":"Timeout purging old filament of the left extruder: Please check if the filament is stuck or the extruder is clogged.","18FE_8020":"Extruder change failed; please refer to the assistant.","18FE_8021":"AMS setup failed; please refer to the assistant.","18FE_8024":"Extruder position calibration failed; please refer to the assistant.","18FE_C003":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube i...","18FE_C006":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","18FE_C008":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube i...","18FE_C009":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","18FE_C00A":"Please observe the nozzle of the left extruder. If the filament has been extruded, select 'Continue'; if not, please push the filament forward slightly and then select 'Retry'.","18FF_8001":"Failed to cut the filament of the right extruder. Please check the cutter.","18FF_8002":"The cutter of the right extruder is stuck. Please pull out the cutter handle.","18FF_8003":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder. (Connect a PTFE tube if you are a...","18FF_8004":"Failed to pull back the filament from the right extruder. Please check whether the filament is stuck inside the extruder.","18FF_8005":"Failed to feed the filament outside the AMS-HT. Please clip the end of the filament flat and check to see if the spool is stuck.","18FF_8006":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","18FF_8007":"Please observe the nozzle of the right extruder. If the filament has been extruded, select 'Continue'; if it has not, please push the filament forward slightly, and then select 'Retry'.","18FF_8011":"The external filament connected to the right extruder has run out; please load a new filament.","18FF_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","18FF_8013":"Timeout purging old filament of the right extruder: Please check if the filament is stuck or the extruder is clogged.","18FF_8020":"Extruder change failed; please refer to the assistant.","18FF_8021":"AMS setup failed; please refer to the assistant.","18FF_8024":"Extruder position calibration failed; please refer to the assistant.","18FF_C003":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube ...","18FF_C006":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","18FF_C008":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube ...","18FF_C009":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","18FF_C00A":"Please observe the nozzle of the right extruder. If the filament has been extruded, select 'Continue'; if not, please push the filament forward slightly and then select 'Retry'."};function gMe(t){switch(t){case 1:return{label:"Fatal",color:"text-red-500",bgColor:"bg-red-500/20",Icon:jn};case 2:return{label:"Serious",color:"text-red-400",bgColor:"bg-red-500/15",Icon:jn};case 3:return{label:"Warning",color:"text-orange-400",bgColor:"bg-orange-500/20",Icon:Li};default:return{label:"Info",color:"text-blue-400",bgColor:"bg-blue-500/20",Icon:Hs}}}function RR(t,e){const n=t>>16&65535||(t>>8&255)<<8|t&255,r=e&65535;return`${n.toString(16).padStart(4,"0").toUpperCase()}_${r.toString(16).padStart(4,"0").toUpperCase()}`}function nk(t){return t.filter(e=>{const n=parseInt(e.code.replace("0x",""),16)||0,r=RR(e.attr,n);return DR[r]!==void 0})}function bMe(){return"https://wiki.bambulab.com/en/hms/home"}function xMe({printerName:t,errors:e,onClose:n,printerId:r,hasPermission:a}){const{t:s}=Dt(),{showToast:o}=bn(),l=gt({mutationFn:()=>ge.clearHMSErrors(r),onSuccess:()=>{o(s("hmsErrors.clearSuccess"),"success"),n()},onError:()=>{o(s("hmsErrors.clearFailed"),"error")}}),c=e.filter(u=>{const d=parseInt(u.code.replace("0x",""),16)||0,m=RR(u.attr,d);return DR[m]!==void 0});return w.useEffect(()=>{const u=d=>{d.key==="Escape"&&n()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n]),i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg shadow-xl max-w-lg w-full max-h-[80vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(jn,{className:"w-5 h-5 text-orange-400"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:s("hmsErrors.title",{name:t})})]}),i.jsx("button",{onClick:n,className:"p-1 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:c.length===0?i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(Li,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),i.jsx("p",{children:s("hmsErrors.noErrors")})]}):i.jsx("div",{className:"space-y-3",children:c.map((u,d)=>{const{label:m,color:p,bgColor:f,Icon:y}=gMe(u.severity),v=parseInt(u.code.replace("0x",""),16)||0,b=RR(u.attr,v),g=DR[b],_=bMe(),N=b.replace("_","-");return i.jsx("div",{className:`p-4 rounded-lg ${f} border border-white/10`,children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(y,{className:`w-5 h-5 ${p} flex-shrink-0 mt-0.5`}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsxs("span",{className:`font-mono text-sm ${p}`,children:["[",N,"]"]}),i.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${f} ${p}`,children:m})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:g}),i.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-bambu-green hover:underline",children:[i.jsx(ni,{className:"w-3 h-3"}),s("hmsErrors.viewOnWiki")]})]})]})},`${u.code}-${d}`)})})}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex items-center justify-between gap-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:s("hmsErrors.clearInstructions")}),c.length>0&&i.jsxs("button",{onClick:()=>l.mutate(),disabled:!a("printers:control")||l.isPending,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-lg bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex-shrink-0",children:[l.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(nn,{className:"w-4 h-4"}),s("hmsErrors.clearErrors")]})]})]})})}function IZ(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("h2dpro")||e.includes("h2d-pro")?"/img/printers/h2dpro.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 zZ(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 UZ(t,e,n){return t.filter(r=>{if(r.required_filament_types&&r.required_filament_types.length>0&&e!==void 0&&!r.required_filament_types.every(a=>e.has(a.toUpperCase())))return!1;if(r.filament_overrides&&r.filament_overrides.length>0&&n!==void 0){const a=r.filament_overrides.filter(o=>o.force_color_match===!0),s=r.filament_overrides.filter(o=>o.force_color_match!==!0);if(a.length>0&&!a.every(l=>{const c=(l.type||"").toUpperCase(),u=(l.color||"").replace("#","").toLowerCase().slice(0,6);return n.has(`${c}:${u}`)})||s.length>0&&a.length===0&&!s.some(l=>{const c=(l.type||"").toUpperCase(),u=(l.color||"").replace("#","").toLowerCase().slice(0,6);return n.has(`${c}:${u}`)}))return!1}return!0})}function yMe({printerId:t,printerModel:e,printerState:n,plateCleared:r,loadedFilamentTypes:a,loadedFilaments:s}){const{t:o}=Dt(),l=sn(),{showToast:c}=bn(),{hasPermission:u}=Ar(),{data:d}=et({queryKey:["queue",t,"pending",e],queryFn:()=>ge.getQueue(t,"pending",e||void 0),refetchInterval:3e4}),m=gt({mutationFn:()=>ge.clearPlate(t),onSuccess:()=>{l.invalidateQueries({queryKey:["queue",t]}),l.invalidateQueries({queryKey:["printerStatus",t]}),c(o("queue.clearPlateSuccess"),"success")},onError:_=>{c(_.message,"error")}}),p=d?UZ(d,a,s):void 0,f=p?.filter(_=>!_.manual_start)??[],y=p?.length||0;if(y===0)return null;const v=f[0],b=p?.[0];if((n==="FINISH"||n==="FAILED")&&!r&&f.length>0){const _=v||b;return i.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-yellow-400/30",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[i.jsx(Xr,{className:"w-5 h-5 text-yellow-400 flex-shrink-0"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:o("queue.nextInQueue")}),i.jsx("p",{className:"text-sm text-white truncate",children:_?.archive_name||_?.library_file_name||`File #${_?.archive_id||_?.library_file_id}`})]}),y>1&&i.jsxs("span",{className:"text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded flex-shrink-0",children:["+",y-1]})]}),m.isSuccess?i.jsxs("div",{className:"w-full py-2 px-3 rounded-lg bg-bambu-green/10 border border-bambu-green/20 text-bambu-green text-sm flex items-center justify-center gap-2",children:[i.jsx(vc,{className:"w-4 h-4"}),o("queue.plateReady")]}):i.jsxs("button",{onClick:()=>m.mutate(),disabled:m.isPending||!u("printers:clear_plate"),className:"w-full py-2 px-3 rounded-lg bg-bambu-green/20 border border-bambu-green/40 text-bambu-green hover:bg-bambu-green/30 transition-colors text-sm font-medium flex items-center justify-center gap-2 disabled:opacity-50",children:[m.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(vc,{className:"w-4 h-4"}),o("queue.clearPlate")]})]})}return i.jsx(fo,{to:"/queue",className:"block mb-3 p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx(Xr,{className:"w-5 h-5 text-yellow-400 flex-shrink-0"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:o("queue.nextInQueue")}),i.jsx("p",{className:"text-sm text-white truncate",children:b?.archive_name||b?.library_file_name||`File #${b?.archive_id||b?.library_file_id}`})]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(Zn,{className:"w-3 h-3"}),b?.scheduled_time?C0(b.scheduled_time,"system",o):o("time.waiting")]}),y>1&&i.jsxs("span",{className:"text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded",children:["+",y-1]}),i.jsx(fa,{className:"w-4 h-4 text-bambu-gray"})]})]})})}function BZ(t){var e,n,r="";if(typeof t=="string"||typeof t=="number")r+=t;else if(typeof t=="object")if(Array.isArray(t)){var a=t.length;for(e=0;e{var{children:n,width:r,height:a,viewBox:s,className:o,style:l,title:c,desc:u}=t,d=kMe(t,NMe),m=s||{width:r,height:a,x:0,y:0},p=hr("recharts-surface",o);return w.createElement("svg",FR({},ls(d),{className:p,width:r,height:a,style:l,viewBox:"".concat(m.x," ").concat(m.y," ").concat(m.width," ").concat(m.height),ref:e}),w.createElement("title",null,c),w.createElement("desc",null,u),n)}),TMe=["children","className"];function LR(){return LR=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{children:n,className:r}=t,a=AMe(t,TMe),s=hr("recharts-layer",r);return w.createElement("g",LR({className:s},ls(a),{ref:e}),n)}),qZ=w.createContext(null),MMe=()=>w.useContext(qZ);function ti(t){return function(){return t}}const VZ=Math.cos,rk=Math.sin,Rc=Math.sqrt,ik=Math.PI,kT=2*ik,OR=Math.PI,IR=2*OR,Up=1e-6,EMe=IR-Up;function GZ(t){this._+=t[0];for(let e=1,n=t.length;e=0))throw new Error(`invalid digits: ${t}`);if(e>15)return GZ;const n=10**e;return function(r){this._+=r[0];for(let a=1,s=r.length;aUp)if(!(Math.abs(m*c-u*d)>Up)||!s)this._append`L${this._x1=e},${this._y1=n}`;else{let f=r-o,y=a-l,v=c*c+u*u,b=f*f+y*y,g=Math.sqrt(v),_=Math.sqrt(p),N=s*Math.tan((OR-Math.acos((v+p-b)/(2*g*_)))/2),C=N/_,k=N/g;Math.abs(C-1)>Up&&this._append`L${e+C*d},${n+C*m}`,this._append`A${s},${s},0,0,${+(m*f>d*y)},${this._x1=e+k*c},${this._y1=n+k*u}`}}arc(e,n,r,a,s,o){if(e=+e,n=+n,r=+r,o=!!o,r<0)throw new Error(`negative radius: ${r}`);let l=r*Math.cos(a),c=r*Math.sin(a),u=e+l,d=n+c,m=1^o,p=o?a-s:s-a;this._x1===null?this._append`M${u},${d}`:(Math.abs(this._x1-u)>Up||Math.abs(this._y1-d)>Up)&&this._append`L${u},${d}`,r&&(p<0&&(p=p%IR+IR),p>EMe?this._append`A${r},${r},0,1,${m},${e-l},${n-c}A${r},${r},0,1,${m},${this._x1=u},${this._y1=d}`:p>Up&&this._append`A${r},${r},0,${+(p>=OR)},${m},${this._x1=e+r*Math.cos(s)},${this._y1=n+r*Math.sin(s)}`)}rect(e,n,r,a){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+n}h${r=+r}v${+a}h${-r}Z`}toString(){return this._}}function DO(t){let e=3;return t.digits=function(n){if(!arguments.length)return e;if(n==null)e=null;else{const r=Math.floor(n);if(!(r>=0))throw new RangeError(`invalid digits: ${n}`);e=r}return t},()=>new DMe(e)}function RO(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function WZ(t){this._context=t}WZ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e);break}}};function CT(t){return new WZ(t)}function KZ(t){return t[0]}function YZ(t){return t[1]}function XZ(t,e){var n=ti(!0),r=null,a=CT,s=null,o=DO(l);t=typeof t=="function"?t:t===void 0?KZ:ti(t),e=typeof e=="function"?e:e===void 0?YZ:ti(e);function l(c){var u,d=(c=RO(c)).length,m,p=!1,f;for(r==null&&(s=a(f=o())),u=0;u<=d;++u)!(u=f;--y)l.point(N[y],C[y]);l.lineEnd(),l.areaEnd()}g&&(N[p]=+t(b,p,m),C[p]=+e(b,p,m),l.point(r?+r(b,p,m):N[p],n?+n(b,p,m):C[p]))}if(_)return l=null,_+""||null}function d(){return XZ().defined(a).curve(o).context(s)}return u.x=function(m){return arguments.length?(t=typeof m=="function"?m:ti(+m),r=null,u):t},u.x0=function(m){return arguments.length?(t=typeof m=="function"?m:ti(+m),u):t},u.x1=function(m){return arguments.length?(r=m==null?null:typeof m=="function"?m:ti(+m),u):r},u.y=function(m){return arguments.length?(e=typeof m=="function"?m:ti(+m),n=null,u):e},u.y0=function(m){return arguments.length?(e=typeof m=="function"?m:ti(+m),u):e},u.y1=function(m){return arguments.length?(n=m==null?null:typeof m=="function"?m:ti(+m),u):n},u.lineX0=u.lineY0=function(){return d().x(t).y(e)},u.lineY1=function(){return d().x(t).y(n)},u.lineX1=function(){return d().x(r).y(e)},u.defined=function(m){return arguments.length?(a=typeof m=="function"?m:ti(!!m),u):a},u.curve=function(m){return arguments.length?(o=m,s!=null&&(l=o(s)),u):o},u.context=function(m){return arguments.length?(m==null?s=l=null:l=o(s=m),u):s},u}class QZ{constructor(e,n){this._context=e,this._x=n}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,n){switch(e=+e,n=+n,this._point){case 0:{this._point=1,this._line?this._context.lineTo(e,n):this._context.moveTo(e,n);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,n,e,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,e,this._y0,e,n);break}}this._x0=e,this._y0=n}}function RMe(t){return new QZ(t,!0)}function FMe(t){return new QZ(t,!1)}const FO={draw(t,e){const n=Rc(e/ik);t.moveTo(n,0),t.arc(0,0,n,0,kT)}},LMe={draw(t,e){const n=Rc(e/5)/2;t.moveTo(-3*n,-n),t.lineTo(-n,-n),t.lineTo(-n,-3*n),t.lineTo(n,-3*n),t.lineTo(n,-n),t.lineTo(3*n,-n),t.lineTo(3*n,n),t.lineTo(n,n),t.lineTo(n,3*n),t.lineTo(-n,3*n),t.lineTo(-n,n),t.lineTo(-3*n,n),t.closePath()}},ZZ=Rc(1/3),OMe=ZZ*2,IMe={draw(t,e){const n=Rc(e/OMe),r=n*ZZ;t.moveTo(0,-n),t.lineTo(r,0),t.lineTo(0,n),t.lineTo(-r,0),t.closePath()}},zMe={draw(t,e){const n=Rc(e),r=-n/2;t.rect(r,r,n,n)}},UMe=.8908130915292852,JZ=rk(ik/10)/rk(7*ik/10),BMe=rk(kT/10)*JZ,HMe=-VZ(kT/10)*JZ,$Me={draw(t,e){const n=Rc(e*UMe),r=BMe*n,a=HMe*n;t.moveTo(0,-n),t.lineTo(r,a);for(let s=1;s<5;++s){const o=kT*s/5,l=VZ(o),c=rk(o);t.lineTo(c*n,-l*n),t.lineTo(l*r-c*a,c*r+l*a)}t.closePath()}},y2=Rc(3),qMe={draw(t,e){const n=-Rc(e/(y2*3));t.moveTo(0,n*2),t.lineTo(-y2*n,-n),t.lineTo(y2*n,-n),t.closePath()}},_l=-.5,Nl=Rc(3)/2,zR=1/Rc(12),VMe=(zR/2+1)*3,GMe={draw(t,e){const n=Rc(e/VMe),r=n/2,a=n*zR,s=r,o=n*zR+n,l=-s,c=o;t.moveTo(r,a),t.lineTo(s,o),t.lineTo(l,c),t.lineTo(_l*r-Nl*a,Nl*r+_l*a),t.lineTo(_l*s-Nl*o,Nl*s+_l*o),t.lineTo(_l*l-Nl*c,Nl*l+_l*c),t.lineTo(_l*r+Nl*a,_l*a-Nl*r),t.lineTo(_l*s+Nl*o,_l*o-Nl*s),t.lineTo(_l*l+Nl*c,_l*c-Nl*l),t.closePath()}};function WMe(t,e){let n=null,r=DO(a);t=typeof t=="function"?t:ti(t||FO),e=typeof e=="function"?e:ti(e===void 0?64:+e);function a(){let s;if(n||(n=s=r()),t.apply(this,arguments).draw(n,+e.apply(this,arguments)),s)return n=null,s+""||null}return a.type=function(s){return arguments.length?(t=typeof s=="function"?s:ti(s),a):t},a.size=function(s){return arguments.length?(e=typeof s=="function"?s:ti(+s),a):e},a.context=function(s){return arguments.length?(n=s??null,a):n},a}function ak(){}function sk(t,e,n){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+n)/6)}function eJ(t){this._context=t}eJ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:sk(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:sk(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function KMe(t){return new eJ(t)}function tJ(t){this._context=t}tJ.prototype={areaStart:ak,areaEnd:ak,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:sk(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function YMe(t){return new tJ(t)}function nJ(t){this._context=t}nJ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:sk(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function XMe(t){return new nJ(t)}function rJ(t){this._context=t}rJ.prototype={areaStart:ak,areaEnd:ak,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}};function QMe(t){return new rJ(t)}function lq(t){return t<0?-1:1}function cq(t,e,n){var r=t._x1-t._x0,a=e-t._x1,s=(t._y1-t._y0)/(r||a<0&&-0),o=(n-t._y1)/(a||r<0&&-0),l=(s*a+o*r)/(r+a);return(lq(s)+lq(o))*Math.min(Math.abs(s),Math.abs(o),.5*Math.abs(l))||0}function uq(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function v2(t,e,n){var r=t._x0,a=t._y0,s=t._x1,o=t._y1,l=(s-r)/3;t._context.bezierCurveTo(r+l,a+l*e,s-l,o-l*n,s,o)}function ok(t){this._context=t}ok.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:v2(this,this._t0,uq(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var n=NaN;if(t=+t,e=+e,!(t===this._x1&&e===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,v2(this,uq(this,n=cq(this,t,e)),n);break;default:v2(this,this._t0,n=cq(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n}}};function iJ(t){this._context=new aJ(t)}(iJ.prototype=Object.create(ok.prototype)).point=function(t,e){ok.prototype.point.call(this,e,t)};function aJ(t){this._context=t}aJ.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,n,r,a,s){this._context.bezierCurveTo(e,t,r,n,s,a)}};function ZMe(t){return new ok(t)}function JMe(t){return new iJ(t)}function sJ(t){this._context=t}sJ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,n=t.length;if(n)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),n===2)this._context.lineTo(t[1],e[1]);else for(var r=dq(t),a=dq(e),s=0,o=1;o=0;--e)a[e]=(o[e]-a[e+1])/s[e];for(s[n-1]=(t[n]+a[n-1])/2,e=0;e=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var n=this._x*(1-this._t)+t*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,e)}break}}this._x=t,this._y=e}};function tEe(t){return new TT(t,.5)}function nEe(t){return new TT(t,0)}function rEe(t){return new TT(t,1)}function Uf(t,e){if((o=t.length)>1)for(var n=1,r,a,s=t[e[0]],o,l=s.length;n=0;)n[e]=e;return n}function iEe(t,e){return t[e]}function aEe(t){const e=[];return e.key=t,e}function sEe(){var t=ti([]),e=UR,n=Uf,r=iEe;function a(s){var o=Array.from(t.apply(this,arguments),aEe),l,c=o.length,u=-1,d;for(const m of s)for(l=0,++u;l0){for(var n,r,a=0,s=t[0].length,o;a0){for(var n=0,r=t[e[0]],a,s=r.length;n0)||!((s=(a=t[e[0]]).length)>0))){for(var n=0,r=1,a,s,o;r1&&arguments[1]!==void 0?arguments[1]:pEe,n=10**e,r=Math.round(t*n)/n;return Object.is(r,-0)?0:r}function Mi(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r{var l=n[o-1];return typeof l=="string"?a+l+s:l!==void 0?a+gh(l)+s:a+s},"")}var Fa=t=>t===0?0:t>0?1:-1,Mc=t=>typeof t=="number"&&t!=+t,Hf=t=>typeof t=="string"&&t.indexOf("%")===t.length-1,Yt=t=>(typeof t=="number"||t instanceof Number)&&!Mc(t),Kl=t=>Yt(t)||typeof t=="string",fEe=0,O0=t=>{var e=++fEe;return"".concat(t||"").concat(e)},ws=function(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!Yt(e)&&typeof e!="string")return r;var s;if(Hf(e)){if(n==null)return r;var o=e.indexOf("%");s=n*parseFloat(e.slice(0,o))/100}else s=+e;return Mc(s)&&(s=r),a&&n!=null&&s>n&&(s=n),s},lJ=t=>{if(!Array.isArray(t))return!1;for(var e=t.length,n={},r=0;rr&&(typeof e=="function"?e(r):Bf(r,e))===n)}var gi=t=>t===null||typeof t>"u",Tw=t=>gi(t)?t:"".concat(t.charAt(0).toUpperCase()).concat(t.slice(1));function yo(t){return t!=null}function Yh(){}var gEe=["type","size","sizeType"];function BR(){return BR=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var e="symbol".concat(Tw(t));return uJ[e]||FO},NEe=(t,e,n)=>{if(e==="area")return t;switch(n){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var r=18*SEe;return 1.25*t*t*(Math.tan(r)-Math.tan(r*2)*Math.tan(r)**2)}case"triangle":return Math.sqrt(3)*t*t/4;case"wye":return(21-10*Math.sqrt(3))*t*t/8;default:return Math.PI*t*t/4}},kEe=(t,e)=>{uJ["symbol".concat(Tw(t))]=e},zO=t=>{var{type:e="circle",size:n=64,sizeType:r="area"}=t,a=vEe(t,gEe),s=vq(vq({},a),{},{type:e,size:n,sizeType:r}),o="circle";typeof e=="string"&&(o=e);var l=()=>{var p=_Ee(o),f=WMe().type(p).size(NEe(n,r,o)),y=f();if(y!==null)return y},{className:c,cx:u,cy:d}=s,m=ls(s);return Yt(u)&&Yt(d)&&Yt(n)?w.createElement("path",BR({},m,{className:hr("recharts-symbols",c),transform:"translate(".concat(u,", ").concat(d,")"),d:l()})):null};zO.registerSymbol=kEe;var dJ=t=>"radius"in t&&"startAngle"in t&&"endAngle"in t,UO=(t,e)=>{if(!t||typeof t=="function"||typeof t=="boolean")return null;var n=t;if(w.isValidElement(t)&&(n=t.props),typeof n!="object"&&typeof n!="function")return null;var r={};return Object.keys(n).forEach(a=>{EO(a)&&(r[a]=(s=>n[a](n,s)))}),r},CEe=(t,e,n)=>r=>(t(e,n,r),null),Aw=(t,e,n)=>{if(t===null||typeof t!="object"&&typeof t!="function")return null;var r=null;return Object.keys(t).forEach(a=>{var s=t[a];EO(a)&&typeof s=="function"&&(r||(r={}),r[a]=CEe(s,e,n))}),r};function wq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function TEe(t){for(var e=1;e(o[l]===void 0&&r[l]!==void 0&&(o[l]=r[l]),o),n);return s}function lk(){return lk=Object.assign?Object.assign.bind():function(t){for(var e=1;el({id:y.id,name:y.name}),disabled:f.isPending||(d?.layer_num??0)<=1||!s("printers:control"),className:`px-4 py-2 text-xs font-medium rounded-lg transition-colors ${(d?.layer_num??0)<=1||!s("printers:control")?"bg-gray-100 dark:bg-bambu-dark text-gray-400 dark:text-bambu-gray/50 cursor-not-allowed":"bg-red-100 dark:bg-red-500/20 text-red-600 dark:text-red-400 hover:bg-red-200 dark:hover:bg-red-500/30 border border-red-300 dark:border-red-500/30"}`,title:s("printers:control")?(d?.layer_num??0)<=1?r("printers.skipObjects.waitForLayer",{layer:d?.layer_num??0}):r("printers.skipObjects.skip"):r("printers.permission.noControl"),children:r("printers.skipObjects.skip")})]},y.id))})]})]}):i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(ft,{className:"w-5 h-5 animate-spin text-bambu-gray"})})]})]}),o&&i.jsx(Nn,{variant:"warning",title:r("printers.skipObjects.confirmTitle"),message:r("printers.skipObjects.confirmMessage",{name:o.name}),confirmText:r("printers.skipObjects.skip"),isLoading:f.isPending,onConfirm:()=>f.mutate([o.id]),onCancel:()=>l(null)}),c&&m&&i.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-60",onClick:()=>u(!1),children:[i.jsx("button",{onClick:()=>u(!1),className:"absolute top-4 right-4 p-2 text-white/70 hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-6 h-6"})}),i.jsxs("div",{className:"relative max-w-[600px] max-h-[80vh] aspect-square",onClick:y=>y.stopPropagation(),children:[d?.cover_url?i.jsx("img",{src:`${d.cover_url}?view=top`,alt:r("printers.printPreview"),className:"w-full h-full object-contain rounded-lg bg-gray-900"}):i.jsx("div",{className:"w-full h-full rounded-lg bg-gray-800 flex items-center justify-center",children:i.jsx(ia,{className:"w-16 h-16 text-gray-500"})}),m.objects.length>0&&i.jsx("div",{className:"absolute inset-0 pointer-events-none",children:m.objects.map((y,v)=>{let b,g;if(y.x!=null&&y.y!=null&&m.bbox_all){const[_,N,C,k]=m.bbox_all,P=C-_,T=k-N,D=8,A=100-D*2;b=D+(y.x-_)/P*A,g=D+(k-y.y)/T*A,b=Math.max(5,Math.min(95,b)),g=Math.max(5,Math.min(95,g))}else if(y.x!=null&&y.y!=null)b=y.x/256*100,g=100-y.y/256*100,b=Math.max(5,Math.min(95,b)),g=Math.max(5,Math.min(95,g));else{const _=Math.ceil(Math.sqrt(m.objects.length)),N=Math.floor(v/_),C=v%_,k=Math.ceil(m.objects.length/_);b=15+C*(70/_)+35/_,g=15+N*(70/k)+35/k}return i.jsx("div",{className:`absolute flex items-center justify-center w-6 h-6 rounded-full text-[10px] font-bold shadow-lg ${y.skipped?"bg-red-500 text-white line-through":"bg-bambu-green text-black"}`,style:{left:`${b}%`,top:`${g}%`,transform:"translate(-50%, -50%)"},title:y.name,children:y.id},y.id)})}),i.jsx("div",{className:"absolute bottom-2 right-2 px-2 py-1 bg-white/90 dark:bg-black/80 rounded text-[10px] text-gray-700 dark:text-white shadow-sm",children:r("printers.skipObjects.activeCount",{count:m.objects.filter(y=>!y.skipped).length})})]})]})]}):null}const uMe="embeddedCameraState_",oq=5,dMe=2e3,mMe=3e4,hMe=5e3,xj={x:window.innerWidth-420,y:20,width:400,height:300};function pMe({printerId:t,printerName:e,viewerIndex:n=0,onClose:r}){const{t:a}=Dt(),s=sn(),{showToast:o}=bn(),{hasPermission:l}=Ar(),c=`${uMe}${t}`,u=()=>{try{const $e=localStorage.getItem(c);if($e){const nt=JSON.parse($e);return{x:Math.min(Math.max(0,nt.x),window.innerWidth-100),y:Math.min(Math.max(0,nt.y),window.innerHeight-100),width:Math.max(200,Math.min(nt.width,window.innerWidth-20)),height:Math.max(150,Math.min(nt.height,window.innerHeight-20))}}}catch{}const Ce=n*30;return{...xj,x:Math.max(0,xj.x-Ce),y:Math.max(0,xj.y+Ce)}},[d,m]=w.useState(u),[p,f]=w.useState(!1),[y,v]=w.useState(!1),[b,g]=w.useState({x:0,y:0}),[_,N]=w.useState(!1),[C,k]=w.useState(!1),[P,T]=w.useState(1),[D,A]=w.useState({x:0,y:0}),[R,G]=w.useState(!1),[z,Z]=w.useState({x:0,y:0}),[I,J]=w.useState(null),[ae,Y]=w.useState(null),[ue,de]=w.useState(!1),[he,V]=w.useState(!0),[ne,se]=w.useState(Date.now()),[pe,Te]=w.useState(0),[q,X]=w.useState(!1),[j,E]=w.useState(0),U=w.useRef(null),K=w.useRef(null),H=w.useRef(null),re=w.useRef(null),O=w.useRef(null),[$,ee]=w.useState(!1),{data:W}=et({queryKey:["printer",t],queryFn:()=>ge.getPrinter(t),enabled:t>0}),{data:ie}=et({queryKey:["printerStatus",t],queryFn:()=>ge.getPrinterStatus(t),refetchInterval:3e4,enabled:t>0}),ce=gt({mutationFn:Ce=>ge.setChamberLight(t,Ce),onMutate:async Ce=>{await s.cancelQueries({queryKey:["printerStatus",t]});const $e=s.getQueryData(["printerStatus",t]);return s.setQueryData(["printerStatus",t],nt=>({...nt,chamber_light:Ce})),{previousStatus:$e}},onSuccess:(Ce,$e)=>{o(`Chamber light ${$e?"on":"off"}`)},onError:(Ce,$e,nt)=>{nt?.previousStatus&&s.setQueryData(["printerStatus",t],nt.previousStatus),o(Ce.message||a("printers.toast.failedToControlChamberLight"),"error")}}),be=(ie?.state==="RUNNING"||ie?.state==="PAUSE")&&(ie?.printable_objects_count??0)>=2;w.useEffect(()=>{const Ce=setTimeout(()=>{localStorage.setItem(c,JSON.stringify(d))},500);return()=>clearTimeout(Ce)},[d,c]);const xe=w.useRef(!1);w.useEffect(()=>{xe.current=!1;const Ce=`/api/v1/printers/${t}/camera/stop`,$e=()=>{if(t>0&&!xe.current){xe.current=!0;const xt={},vt=qd();vt&&(xt.Authorization=`Bearer ${vt}`),fetch(Ce,{method:"POST",keepalive:!0,headers:xt}).catch(()=>{})}},nt=K.current;return()=>{nt&&(nt.src=""),$e(),H.current&&clearTimeout(H.current),re.current&&clearInterval(re.current),O.current&&clearInterval(O.current)}},[t]),w.useEffect(()=>{if(he){const Ce=setTimeout(()=>V(!1),3e3);return()=>clearTimeout(Ce)}},[he,ne]);const oe=w.useCallback(()=>{if(pe>=oq){X(!1),de(!0);return}const Ce=Math.min(dMe*Math.pow(2,pe),mMe);X(!0),E(Math.ceil(Ce/1e3)),re.current=setInterval(()=>{E($e=>$e<=1?(re.current&&clearInterval(re.current),0):$e-1)},1e3),H.current=setTimeout(()=>{Te($e=>$e+1),X(!1),V(!0),de(!1),K.current&&(K.current.src=""),se(Date.now())},Ce)},[pe]);w.useEffect(()=>{if(he||q||_){O.current&&(clearInterval(O.current),O.current=null);return}return O.current=setInterval(async()=>{try{const Ce=await ge.getCameraStatus(t);(Ce.stalled||!Ce.active&&!ue)&&(O.current&&(clearInterval(O.current),O.current=null),V(!1),oe())}catch{}},hMe),()=>{O.current&&(clearInterval(O.current),O.current=null)}},[he,ue,q,_,t,oe]),w.useEffect(()=>{const Ce=()=>{const $e=!!document.fullscreenElement;k($e),$e||(T(1),A({x:0,y:0}))};return document.addEventListener("fullscreenchange",Ce),()=>document.removeEventListener("fullscreenchange",Ce)},[]);const L=()=>{U.current&&(document.fullscreenElement?document.exitFullscreen():U.current.requestFullscreen())},F=()=>{T(Ce=>Math.min(Ce+.5,4))},te=()=>{T(Ce=>{const $e=Math.max(Ce-.5,1);return $e===1&&A({x:0,y:0}),$e})},ve=Ce=>{Ce.preventDefault(),Ce.deltaY<0?F():te()},fe=Ce=>{P>1&&(Ce.preventDefault(),G(!0),Z({x:Ce.clientX-D.x,y:Ce.clientY-D.y}))},me=w.useCallback(()=>{if(!U.current||!K.current)return{x:200,y:150};const Ce=U.current.getBoundingClientRect(),$e=Ce.width*(P-1)/2,nt=Ce.height*(P-1)/2;return{x:Math.max(50,$e),y:Math.max(50,nt)}},[P]),je=Ce=>{if(R&&P>1){const $e=Ce.clientX-z.x,nt=Ce.clientY-z.y,xt=me();A({x:Math.max(-xt.x,Math.min(xt.x,$e)),y:Math.max(-xt.y,Math.min(xt.y,nt))})}},we=()=>{G(!1)},Fe=Ce=>{if(Ce.length<2)return 0;const $e=Ce[0].clientX-Ce[1].clientX,nt=Ce[0].clientY-Ce[1].clientY;return Math.sqrt($e*$e+nt*nt)},He=Ce=>Ce.length<2?{x:Ce[0].clientX,y:Ce[0].clientY}:{x:(Ce[0].clientX+Ce[1].clientX)/2,y:(Ce[0].clientY+Ce[1].clientY)/2},Oe=Ce=>{Ce.touches.length===2?(Ce.preventDefault(),J(Fe(Ce.touches)),Y(He(Ce.touches))):Ce.touches.length===1&&P>1&&(Ce.preventDefault(),G(!0),Z({x:Ce.touches[0].clientX-D.x,y:Ce.touches[0].clientY-D.y}))},_e=Ce=>{if(Ce.touches.length===2&&I!==null){Ce.preventDefault();const $e=Fe(Ce.touches),nt=$e/I;T(vt=>{const mt=Math.max(1,Math.min(4,vt*nt));return mt===1&&A({x:0,y:0}),mt}),J($e);const xt=He(Ce.touches);if(ae){const vt=me();A(mt=>({x:Math.max(-vt.x,Math.min(vt.x,mt.x+(xt.x-ae.x))),y:Math.max(-vt.y,Math.min(vt.y,mt.y+(xt.y-ae.y)))}))}Y(xt)}else if(Ce.touches.length===1&&R&&P>1){Ce.preventDefault();const $e=Ce.touches[0].clientX-z.x,nt=Ce.touches[0].clientY-z.y,xt=me();A({x:Math.max(-xt.x,Math.min(xt.x,$e)),y:Math.max(-xt.y,Math.min(xt.y,nt))})}},Ae=Ce=>{Ce.touches.length<2&&(J(null),Y(null)),Ce.touches.length===0&&G(!1)},Be=()=>{T(1),A({x:0,y:0})},Me=()=>{V(!1),pe{V(!1),de(!1),Te(0),X(!1),H.current&&clearTimeout(H.current),re.current&&clearInterval(re.current)},ye=()=>{V(!0),de(!1),Te(0),X(!1),H.current&&clearTimeout(H.current),re.current&&clearInterval(re.current);const Ce={},$e=qd();$e&&(Ce.Authorization=`Bearer ${$e}`),fetch(`/api/v1/printers/${t}/camera/stop`,{method:"POST",headers:Ce}).catch(()=>{}),K.current&&(K.current.src=""),setTimeout(()=>se(Date.now()),100)},We=Ce=>{Ce.target.closest(".no-drag")||(f(!0),g({x:Ce.clientX-d.x,y:Ce.clientY-d.y}))},Pe=Ce=>{if(Ce.target.closest(".no-drag"))return;const $e=Ce.touches[0];f(!0),g({x:$e.clientX-d.x,y:$e.clientY-d.y})},Ke=Ce=>{Ce.stopPropagation(),v(!0)},Ve=Ce=>{Ce.stopPropagation(),v(!0)};w.useEffect(()=>{const Ce=xt=>{if(p)m(vt=>({...vt,x:Math.max(0,Math.min(xt.clientX-b.x,window.innerWidth-vt.width)),y:Math.max(0,Math.min(xt.clientY-b.y,window.innerHeight-vt.height))}));else if(y&&U.current){const vt=U.current.getBoundingClientRect();m(mt=>({...mt,width:Math.max(200,Math.min(xt.clientX-vt.left,window.innerWidth-mt.x-10)),height:Math.max(150,Math.min(xt.clientY-vt.top,window.innerHeight-mt.y-10))}))}},$e=xt=>{if(!p&&!y)return;xt.preventDefault();const vt=xt.touches[0];if(p)m(mt=>({...mt,x:Math.max(0,Math.min(vt.clientX-b.x,window.innerWidth-mt.width)),y:Math.max(0,Math.min(vt.clientY-b.y,window.innerHeight-mt.height))}));else if(y&&U.current){const mt=U.current.getBoundingClientRect();m(qe=>({...qe,width:Math.max(200,Math.min(vt.clientX-mt.left,window.innerWidth-qe.x-10)),height:Math.max(150,Math.min(vt.clientY-mt.top,window.innerHeight-qe.y-10))}))}},nt=()=>{f(!1),v(!1)};if(p||y)return document.addEventListener("mousemove",Ce),document.addEventListener("mouseup",nt),document.addEventListener("touchmove",$e,{passive:!1}),document.addEventListener("touchend",nt),document.addEventListener("touchcancel",nt),()=>{document.removeEventListener("mousemove",Ce),document.removeEventListener("mouseup",nt),document.removeEventListener("touchmove",$e),document.removeEventListener("touchend",nt),document.removeEventListener("touchcancel",nt)}},[p,y,b]);const ke=`/api/v1/printers/${t}/camera/stream?fps=15&t=${ne}`;return i.jsxs("div",{ref:U,className:`${C?"fixed inset-0 z-[100]":"fixed z-40 rounded-lg shadow-2xl border border-bambu-dark-tertiary"} bg-bambu-dark-secondary overflow-hidden`,style:C?void 0:{left:d.x,top:d.y,width:_?200:d.width,height:_?40:d.height,cursor:p?"grabbing":"default"},children:[i.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-bambu-dark border-b border-bambu-dark-tertiary cursor-grab active:cursor-grabbing",onMouseDown:We,onTouchStart:Pe,children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-white truncate",children:[i.jsx(Th,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"truncate",children:W?.name||e})]}),i.jsxs("div",{className:"flex items-center gap-1 no-drag",children:[i.jsx("button",{onClick:()=>ce.mutate(!ie?.chamber_light),disabled:!ie?.connected||ce.isPending||!l("printers:control"),className:`p-1 rounded disabled:opacity-50 ${ie?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:l("printers:control")?a("camera.chamberLight"):a("printers.permission.noControl"),children:i.jsx(PO,{on:ie?.chamber_light??!1,className:"w-3.5 h-3.5"})}),i.jsx("button",{onClick:()=>ee(!0),disabled:!be||!l("printers:control"),className:`p-1 rounded disabled:opacity-50 ${be&&l("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:l("printers:control")?a(be?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):a("printers.permission.noControl"),children:i.jsx(NT,{className:"w-3.5 h-3.5 text-bambu-gray"})}),i.jsx("button",{onClick:ye,disabled:he||q,className:"p-1 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:"Refresh stream",children:i.jsx(Sr,{className:`w-3.5 h-3.5 text-bambu-gray ${he?"animate-spin":""}`})}),i.jsx("button",{onClick:L,className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:C?"Exit fullscreen":"Fullscreen",children:C?i.jsx(JX,{className:"w-3.5 h-3.5 text-bambu-gray"}):i.jsx(ife,{className:"w-3.5 h-3.5 text-bambu-gray"})}),i.jsx("button",{onClick:()=>N(!_),className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:_?"Expand":"Minimize",children:_?i.jsx(oT,{className:"w-3.5 h-3.5 text-bambu-gray"}):i.jsx(WL,{className:"w-3.5 h-3.5 text-bambu-gray"})}),i.jsx("button",{onClick:r,className:"p-1 hover:bg-red-500/20 rounded",title:"Close",children:i.jsx(Ht,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-red-400"})})]})]}),!_&&i.jsxs("div",{className:"relative w-full bg-black flex items-center justify-center overflow-hidden h-[calc(100%-40px)]",onWheel:ve,onMouseMove:je,onMouseUp:we,onMouseLeave:we,onTouchStart:Oe,onTouchMove:_e,onTouchEnd:Ae,style:{touchAction:"none"},children:[he&&!q&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:i.jsx(Sr,{className:"w-6 h-6 text-bambu-gray animate-spin"})}),q&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:i.jsxs("div",{className:"text-center p-2",children:[i.jsx(zh,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Reconnecting in ",j,"s..."]})]})}),ue&&!q&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:i.jsxs("div",{className:"text-center p-2",children:[i.jsx(jn,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Camera unavailable"}),i.jsx("button",{onClick:ye,className:"px-2 py-1 text-xs bg-bambu-green text-white rounded hover:bg-bambu-green/80",children:"Retry"})]})}),i.jsx("img",{ref:K,src:ke,alt:"Camera stream",className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${P}) translate(${D.x/P}px, ${D.y/P}px) rotate(${W?.camera_rotation||0}deg)`,...W?.camera_rotation===90||W?.camera_rotation===270?{maxWidth:"100%",maxHeight:"100%"}:{},cursor:P>1?R?"grabbing":"grab":"default"},onError:Me,onLoad:Xe,onMouseDown:fe,draggable:!1},ne),i.jsxs("div",{className:"absolute bottom-2 left-2 flex items-center gap-1 bg-black/60 rounded px-1.5 py-1 no-drag",children:[i.jsx("button",{onClick:te,disabled:P<=1,className:"p-1 hover:bg-white/10 rounded disabled:opacity-30",title:"Zoom out",children:i.jsx(JL,{className:"w-3.5 h-3.5 text-white"})}),i.jsxs("button",{onClick:Be,className:"px-1.5 py-0.5 text-xs text-white hover:bg-white/10 rounded min-w-[32px]",title:"Reset zoom",children:[Math.round(P*100),"%"]}),i.jsx("button",{onClick:F,disabled:P>=4,className:"p-1 hover:bg-white/10 rounded disabled:opacity-30",title:"Zoom in",children:i.jsx(ZL,{className:"w-3.5 h-3.5 text-white"})})]}),!C&&i.jsx("div",{className:"absolute bottom-0 right-0 w-6 h-6 cursor-se-resize no-drag hover:bg-white/10 rounded-tl transition-colors",onMouseDown:Ke,onTouchStart:Ve,title:"Drag to resize",children:i.jsx("svg",{className:"w-6 h-6 text-bambu-gray/70 hover:text-bambu-gray",viewBox:"0 0 24 24",fill:"currentColor",children:i.jsx("path",{d:"M22 22H20V20H22V22ZM22 18H20V16H22V18ZM18 22H16V20H18V22ZM22 14H20V12H22V14ZM18 18H16V16H18V18ZM14 22H12V20H14V22ZM22 10H20V8H22V10ZM18 14H16V12H18V14ZM14 18H12V16H14V18ZM10 22H8V20H10V22Z"})})})]}),i.jsx(MO,{printerId:t,isOpen:$,onClose:()=>ee(!1)})]})}function fMe({printerId:t,printerName:e,onClose:n}){const{t:r}=Dt(),a=sn(),[s,o]=w.useState(!0),[l,c]=w.useState(new Set),[u,d]=w.useState(""),[m,p]=w.useState("all"),f=w.useRef(null),{data:y,isLoading:v,refetch:b}=et({queryKey:["mqtt-logs",t],queryFn:()=>ge.getMQTTLogs(t),refetchInterval:1e3}),g=gt({mutationFn:()=>ge.enableMQTTLogging(t),onSuccess:()=>{a.invalidateQueries({queryKey:["mqtt-logs",t]})}}),_=gt({mutationFn:()=>ge.disableMQTTLogging(t),onSuccess:()=>{a.invalidateQueries({queryKey:["mqtt-logs",t]})}}),N=gt({mutationFn:()=>ge.clearMQTTLogs(t),onSuccess:()=>{a.invalidateQueries({queryKey:["mqtt-logs",t]})}});w.useEffect(()=>{const R=G=>{G.key==="Escape"&&n()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[n]),w.useEffect(()=>{s&&f.current&&(f.current.scrollTop=f.current.scrollHeight)},[y?.logs,s]);const C=R=>{c(G=>{const z=new Set(G);return z.has(R)?z.delete(R):z.add(R),z})},k=R=>new Date(R).toLocaleTimeString("en-US",{hour12:!1,fractionalSecondDigits:3}),P=(R,G)=>{if(R==null)return"";const z=typeof R=="string"?JSON.parse(R):R,Z=JSON.stringify(z,null,G?2:0);return!G&&Z.length>100?Z.substring(0,100)+"...":Z},T=y?.logging_enabled??!1,D=w.useMemo(()=>y?.logs??[],[y?.logs]),A=w.useMemo(()=>D.filter(R=>{if(m!=="all"&&R.direction!==m)return!1;if(u.trim()){const G=u.toLowerCase(),z=R.topic.toLowerCase().includes(G),I=JSON.stringify(R.payload).toLowerCase().includes(G);return z||I}return!0}),[D,u,m]);return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg max-w-4xl w-full max-h-[85vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("mqttDebug.title")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:e})]}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[T?i.jsxs(ze,{size:"sm",variant:"secondary",onClick:()=>_.mutate(),disabled:_.isPending,children:[i.jsx(rl,{className:"w-4 h-4"}),r("mqttDebug.stopLogging")]}):i.jsxs(ze,{size:"sm",onClick:()=>g.mutate(),disabled:g.isPending,children:[i.jsx(Co,{className:"w-4 h-4"}),r("mqttDebug.startLogging")]}),i.jsxs(ze,{size:"sm",variant:"secondary",onClick:()=>N.mutate(),disabled:N.isPending||D.length===0,children:[i.jsx(nn,{className:"w-4 h-4"}),r("mqttDebug.clearLog")]}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:()=>b(),disabled:v,children:i.jsx(Sr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),i.jsx("div",{className:"flex-1"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:s,onChange:R=>o(R.target.checked),className:"rounded border-bambu-dark-tertiary"}),"Auto-scroll"]}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[A.length,"/",D.length]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(Rr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:r("mqttDebug.searchPlaceholder"),value:u,onChange:R=>d(R.target.value),className:"w-full pl-8 pr-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),u&&i.jsx("button",{onClick:()=>d(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark rounded border border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>p("all"),className:`px-2 py-1.5 text-xs rounded-l transition-colors ${m==="all"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:r("mqttDebug.all")}),i.jsxs("button",{onClick:()=>p("in"),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${m==="in"?"bg-blue-500 text-white":"text-bambu-gray hover:text-white"}`,children:[i.jsx(cx,{className:"w-3 h-3"}),r("mqttDebug.incoming")]}),i.jsxs("button",{onClick:()=>p("out"),className:`px-2 py-1.5 text-xs rounded-r transition-colors flex items-center gap-1 ${m==="out"?"bg-green-500 text-white":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Af,{className:"w-3 h-3"}),r("mqttDebug.outgoing")]})]})]})]}),i.jsx("div",{ref:f,className:"flex-1 overflow-auto p-4 font-mono text-xs bg-black min-h-[400px]",children:D.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bambu-gray",children:[i.jsx("p",{className:"mb-2",children:r("mqttDebug.noMessages")}),!T&&i.jsx("p",{className:"text-sm",children:r("mqttDebug.startLoggingHint")})]}):A.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bambu-gray",children:[i.jsx("p",{className:"mb-2",children:r("mqttDebug.noMessagesMatch")}),i.jsx("p",{className:"text-sm",children:r("mqttDebug.adjustFilterHint")})]}):i.jsx("div",{className:"space-y-1",children:A.map((R,G)=>{const z=l.has(G),Z=R.direction==="in";return i.jsxs("div",{className:`p-2 rounded cursor-pointer hover:bg-bambu-dark-secondary transition-colors ${z?"bg-bambu-dark-secondary":""}`,onClick:()=>C(G),children:[i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("span",{className:"text-bambu-gray shrink-0",children:k(R.timestamp)}),i.jsx("span",{className:`shrink-0 ${Z?"text-blue-400":"text-green-400"}`,title:r(Z?"mqttDebug.incoming":"mqttDebug.outgoing"),children:Z?i.jsx(cx,{className:"w-3 h-3"}):i.jsx(Af,{className:"w-3 h-3"})}),i.jsx("span",{className:"text-purple-400 shrink-0",children:R.topic})]}),z?i.jsx("pre",{className:"mt-2 p-3 bg-gray-900 border border-gray-700 rounded text-green-400 overflow-x-auto whitespace-pre-wrap break-all max-h-96 overflow-y-auto text-xs",children:P(R.payload,!0)}):i.jsx("pre",{className:"mt-1 text-white/80 truncate",children:P(R.payload,!1)})]},G)})})}),i.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary",children:[i.jsx("div",{className:"text-sm text-bambu-gray",children:T?i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),r("mqttDebug.loggingActive")]}):i.jsx("span",{children:r("mqttDebug.loggingStopped")})}),i.jsx(ze,{variant:"secondary",onClick:n,children:r("common.close")})]})]})})}const DR={"0300_4000":"Z axis homing failed; the task has been stopped.","0300_4001":"The printer timed out waiting for the nozzle to cool down before homing.","0300_4002":"Auto Bed Leveling failed; the task has been stopped.","0300_4005":"The hotend cooling fan speed is abnormal.","0300_4006":"The nozzle is clogged.","0300_4008":"The AMS failed to change filament.","0300_4009":"Homing XY axis failed.","0300_400A":"Mechanical resonance frequency identification failed.","0300_400B":"Internal communication exception","0300_400C":"The task was canceled.","0300_400D":"Resume failed after power loss.","0300_400E":"The motor self-check failed.","0300_400F":"The power supply voltage does not match the printer.","0300_4010":"Nozzle offset calibration failed.","0300_4011":"Flow Dynamics Calibration failed; please reinitiate printing or calibration.","0300_4013":"Printing cannot be initiated while AMS is drying.","0300_4014":"Homing Z axis failed: temperature control abnormality.","0300_4015":"Nozzle clumping detection calibration failed. Please go to 'Assistant' for troubleshooting.","0300_4016":"Nozzle cleaning failed. Please click the Assistant for troubleshooting.","0300_401F":"The hotend is not installed, and the toolhead cannot perform homing. Please install the hotend and then continue.","0300_4020":"The nozzle presence detection failed. Please check the Assistant for details.","0300_4021":"Nozzle offset calibration sensor signal abnormality detected. Please check the sensor and retry.","0300_4042":"The Laser Safety Window is not properly installed. The task has been stopped.","0300_4044":"The Flame Sensor is abnormal. The sensor may be short-circuited. Please troubleshoot the issue before starting a print job.","0300_404B":"Task aborted because the front door or top cover is open.","0300_404D":"The current temperature of the hotend, heatbed, or chamber is too high. Please wait for it to cool down to room temperature before restarting the task.","0300_4050":"Liveview Camera calibration timeout; please restart the printer.","0300_4052":"Blade Z-axis homing failed","0300_4057":"Z-axis step loss detected. The task has stopped. Please check if there are any obstructions beneath the heatbed.","0300_4066":"Calibration of motion precision failed.","0300_4067":"Calibration result is over the threshold.","0300_4068":"Step loss occurred during the motion accuracy enhancement process. Please try again.","0300_8000":"Printing was paused for unknown reason. You can select 'Resume' to resume the print job.","0300_8001":"Printing was paused by the user. You can select 'Resume' to continue printing.","0300_8002":"First layer defects were detected by the Micro Lidar. Please check the quality of the printed model before continuing your print.","0300_8003":"Spaghetti defects were detected by the AI Print Monitoring. Please check the quality of the printed model before continuing your print.","0300_8004":"Filament ran out. Please load new filament.","0300_8005":"Toolhead front cover fell off. Please remount the front cover and check to make sure your print is going okay.","0300_8006":"The build plate marker was not detected. Please confirm the build plate is correctly positioned on the heatbed with all four corners aligned, and the marker is visible.","0300_8007":"There was an unfinished print job when the printer lost power. If the model is still adhered to the build plate, you can try resuming the print job.","0300_8008":"Nozzle temperature malfunction","0300_8009":"Heatbed temperature malfunction","0300_800A":"A Filament pile-up was detected by AI Print Monitoring. Please clean filament from the waste chute.","0300_800B":"The cutter is stuck. Please make sure the cutter handle is out and check the filament sensor cable connection.","0300_800C":"Skipped step detected: auto-recover complete; please resume print and check if there are any layer shift problems.","0300_800D":"Detected that the extruder is not extruding normally. If the defects are acceptable, select 'Resume' to resume the print job.","0300_800E":"The print file is not available. Please check to see if the storage media has been removed.","0300_800F":"The door seems to be open, so printing was paused.","0300_8010":"The hotend cooling fan speed is abnormal.","0300_8011":"Detected build plate is not the same as the Gcode file. Please adjust slicer settings or use the correct plate.","0300_8013":"Printing paused due to the pause command added to the printing file.","0300_8014":"The nozzle is covered with filament, or the build plate is installed incorrectly. Please cancel this print and clean the nozzle or adjust the build plate according to the actual status. You can als...","0300_8015":"The filament on external spool has run out; please load new filament. If the filament is loaded, please select 'Resume'.","0300_8016":"The nozzle is clogged with filament. Please cancel this print and clean the nozzle or select 'Resume' to resume the print job.","0300_8017":"Foreign objects detected on heatbed. Please check and clean the heatbed. Then, select 'Resume' to resume the print job.","0300_8018":"Chamber temperature malfunction.","0300_8019":"No build plate is placed.","0300_801A":"Filament extrusion error; please check the assistant for troubleshooting. After resolving the issue, decide whether to cancel or resume the print job based on the actual print status.","0300_801B":"Nozzle temperature problem detected. Refer to Assistant to re-connect the hotend connector. POWER OFF the printer before this operation to avoid short circuits.","0300_801C":"The extrusion resistance is abnormal. The extruder may be clogged; please refer to the assistant. After trouble shooting, you can select 'Resume' to resume the print job.","0300_801D":"The extruder servo motor position sensor is malfunctioning. Please power off the printer first and check if the connection cable is loose.","0300_801E":"The extrusion motor is overloaded, please check the Assistant for details.","0300_8021":"The nozzle may not be installed or not properly installed. Please ensure the nozzle is correctly installed before proceeding.","0300_8022":"The heatbed may be obstructed while moving downward. Please clear any objects beneath the heatbed and check for any resistance or jamming during its movement.","0300_8028":"Nozzle offset calibration sensor error. If using a single hotend or the calibration function is disabled, you may ignore this and continue printing; otherwise, it is recommended to check the sensor...","0300_8041":"Platform detection timeout: please restart the printer.","0300_8042":"Task paused because the door is open.","0300_8043":"The laser module is abnormal.","0300_8044":"Fire was detected inside the chamber.","0300_8045":"Material detection timeout: please restart the printer.","0300_8046":"Foreign object detect timeout: please restart the printer.","0300_8047":"Quick-release lever detection time out: please restart the printer.","0300_8048":"Laser Module unlock has timed out, and the task cannot proceed. Please restart the printer and try again.","0300_8049":"The current plate is invalid.","0300_804A":"Emergency stop button improperly installed. Please reinstall according to the Wiki before proceeding.","0300_804B":"Task paused. The Laser Safety Window is open.","0300_804E":"This is a printing task. Please detach the Laser/Cutting Module from the Toolhead.","0300_804F":"The loading/unloading process is currently ongoing. Please stop the process or remove the laser/cutting module.","0300_8050":"This device does not support the 40W Laser Module. Please remove it or replace it with a 10W Laser Module.","0300_8051":"The cutting module has dropped or the cutting module cable is disconnected; please check the module.","0300_8053":"Laser module detected. Please install the right nozzle correctly to ensure proper Laser Module Mounting Calibration.","0300_8054":"Please place the paper required for Print Then Cut.","0300_8055":"The module mounted on the toolhead does not match the task. Please install the correct module.","0300_8057":"The rotary attachment is disconnected. Please ensure it is properly installed and the cable is securely plugged in.","0300_8058":"The rotary attachment is detected. Please remove it before continuing.","0300_8061":"The mode of Airflow System failed to activate; check the air door condition.","0300_8062":"The chamber temperature is too high. It may be due to high environmental temperature.","0300_8063":"The chamber temperature is too high. Please open the top cover and front door to cool down.","0300_8064":"The chamber temperature is too high. Please open the top cover and front door to cool down. (Open door detection for this print job will be set to 'Notification' level)","0300_8065":"The temperature of the MC module is too high. Please check the Wiki for possible explanations.","0300_8071":"The Toolhead Enhanced Cooling Fan module is malfunctioning.","0300_807D":"Fire Extinguisher not detected, the automatic extinguishing function will be unavailable.","0300_807E":"Fire Extinguisher not detected, the automatic extinguishing function will be unavailable.","0300_807F":"Fire Extinguisher is malfunctioning.","0300_8080":"Fire extinguisher motor reset failed.","0300_8081":"Fire extinguisher cylinder not installed. Please confirm on the extinguisher page.","0300_8082":"The Fire Extinguisher Gas Cylinder is empty.","0300_C012":"Please heat the nozzle to above 170°C.","0300_C056":"A minor fire was detected inside the chamber, and the Auto Fire Extinguishing process has been aborted.","0300_C070":"The fire extinguisher has been detected and is ready for use after the laser module is connected.","0500_4001":"Failed to connect to Bambu Cloud. Please check your network connection.","0500_4002":"Unsupported print file path or name. Please resend the print job.","0500_4003":"Printing stopped because the printer was unable to parse the file. Please resend your print job.","0500_4004":"Device is busy and cannot start new task. Please wait for current task to complete before sending new task.","0500_4005":"Print jobs are not allowed to be sent while updating firmware.","0500_4006":"There is not enough free storage space for the print job. Restoring to factory settings can free up available space.","0500_4007":"The device requires a repair upgrade, and printing is currently unavailable.","0500_4008":"Starting printing failed; please power cycle the printer and resend the print job.","0500_4009":"Print jobs are not allowed to be sent while updating logs.","0500_400A":"The file name is not supported. Please rename and restart the print job.","0500_400B":"There was a problem downloading a file. Please check your network connection and resend the print job.","0500_400C":"Please insert a MicroSD card and restart the print job.","0500_400D":"Please run a self-test and restart the print job.","0500_400E":"Printing was cancelled.","0500_400F":"AMS is initializing and cannot be upgraded at the moment. Please try again later.","0500_4010":"AMS is drying and cannot be upgraded at the moment. Please try again later.","0500_4011":"The printer is loading or unloading filament and cannot be upgraded at the moment. Please try again later.","0500_4012":"The device is printing and cannot be upgraded at the moment. Please try again later.","0500_4013":"AMS is in operation and cannot be upgraded at the moment. Please try again when it is idle.","0500_4014":"Slicing for the print job failed. Please check your settings and restart the print job.","0500_4015":"There is not enough free storage space for the print job. Please format or clear files from the MicroSD card to free up space.","0500_4016":"The MicroSD Card is write-protected. Please replace the MicroSD Card.","0500_4017":"Binding failed. Please retry or restart the printer and retry.","0500_4018":"Binding configuration information parsing failed; please try again.","0500_4019":"The printer has already been bound. Please unbind it and try again.","0500_401A":"Cloud access failed. Possible reasons include network instability caused by interference, inability to access the internet, or router firewall configuration restrictions. You can try moving the pri...","0500_401B":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_401C":"Cloud access is rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_401D":"Cloud access failed, which may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0500_401E":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_401F":"Authorization timed out. Please make sure that your phone or PC has access to the internet, and ensure that the Bambu Studio/Bambu Handy APP is running in the foreground during the binding operation.","0500_4020":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_4021":"Cloud access failed, which may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0500_4022":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_4023":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_4024":"Cloud access failed. Possible reasons include network instability caused by interference, inability to access the internet, or router firewall configuration restrictions. You can try moving the pri...","0500_4025":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_4026":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_4027":"Cloud access failed; this may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0500_4028":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_4029":"Cloud access is rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_402A":"Failed to connect to the router, which may be caused by wireless interference or being too far away from the router. Please try again or move the printer closer to the router and try again.","0500_402B":"Router connection failed due to incorrect password. Please check the password and try again.","0500_402C":"Failed to obtain IP address, which may be caused by wireless interference resulting in data transmission failure or the DHCP address pool of the router being full. Please move the printer closer to...","0500_402D":"System exception","0500_402E":"System does not support the file system currently used by the USB flash drive. Please replace or format the USB flash drive to FAT32.","0500_402F":"The MicroSD card sector data is damaged. Please use the SD card repair tool to repair or format it. If it still cannot be identified, please replace the MicroSD card.","0500_4030":"The device is currently upgrading. Please try again when it is idle.","0500_4031":"The accessory firmware does not match the printer. Please update it on the 'Firmware' page.","0500_4033":"The AMS firmware does not match the printer. Please update it on the 'Firmware' page.","0500_4034":"The Laser Module firmware does not match the printer. Please update it on the 'Firmware' page.","0500_4035":"The BirdsEye Camera is malfunctioning. Please try restarting the device. If the issue persists after multiple restarts, check the camera connection status or contact customer support.","0500_4037":"Your sliced file is not compatible with current printer model. This file can't be printed on this printer.","0500_4038":"The nozzle diameter in sliced file is not consistent with the current nozzle setting. This file can't be printed.","0500_4039":"The current task does not allow the installation of the laser/cutting module, and the task has been halted.","0500_403A":"The current temperature is too low. In order to protect you and your printer, printing tasks, moving an axis and other operations are disabled. Please move the printer to an environment above 10 de...","0500_403B":"Laser/cutting tasks cannot be initiated on the machine at the moment. Please use the computer software to start the task.","0500_403C":"The current nozzle setting does not match the slicing file. Continuing to print may affect print quality. It is recommended to re-slice before starting the print.","0500_403D":"The toolhead module is not set up. Please set it up before initiating the task.","0500_403E":"The current tool head does not support initialization.","0500_403F":"Failed to download print job; please check your network connection.","0500_4040":"The printer has reached its power limit. Please connect a dedicated power adapter to this AMS to enable drying.","0500_4041":"The AMS drying cannot be started during printing.","0500_4042":"Due to power limitations, starting AMS drying will pause current operations such as nozzle heating and fan running. Do you want to proceed with drying?","0500_4043":"Due to power limitations, only one AMS is allowed to use the device's power for drying.","0500_4044":"BirdsEye Camera malfunction: please contact customer support.","0500_4045":"Hotend check in progress. This operation is temporarily unavailable. Please wait.","0500_4050":"Error detected on the print board.","0500_4052":"Error detected on the hot end.","0500_4054":"Error detected on the mat.","0500_405D":"Laser module Serial Number error: unable to calibrate or make project.","0500_4065":"The task requires a Laser Platform, but the current one is a Cutting Platform. Please replace it, measure the material thickness in the software, and then restart the task.","0500_4070":"The laser or cutter module is connected, so the device cannot initiate a 3D printing task.","0500_4075":"No Laser Platform was detected, which may affect thickness measurement accuracy. Please place the laser platform correctly and ensure the rear markers are not blocked, then restart the thickness me...","0500_4076":"Please place the Laser Platform correctly and ensure the rear markers are not blocked, then restart the thickness measurement in the software before initiating the task.","0500_4097":"The device cannot detect the Laser Module. Please reconnect the module cable or restart the printer.","0500_4098":"The device cannot detect AMS A. Please reconnect the AMS cable or restart the printer.","0500_4099":"The firmware of Cutting Module does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0500_409A":"The firmware of the Air Pump does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0500_409B":"The firmware of the Laser Module does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0500_409D":"The firmware of AMS A does not match the printer; the device cannot continue working. Please upgrade it on the 'Firmware' page.","0500_409E":"The device cannot detect the Cutting Module. Please reconnect the module cable or restart the printer.","0500_409F":"The device cannot detect the Air Pump. Please reconnect the module cable or restart the printer.","0500_40A0":"The Rotary Attachment module is not detected. Please reconnect the cable or restart the printer.","0500_40A1":"The Auto Fire Extinguishing System is not detected. Please reconnect the module cable or restart the printer.","0500_40A3":"AMS(or AMS lite) A communication is abnormal. Please reconnect the module cable or restart the printer.","0500_40A4":"The current firmware only supports 1 AMS Lite. Please remove all AMS units before reconnecting the supported AMS Lite device.","0500_40A5":"The current firmware only supports AMS/AMS 2 Pro/AMS HT, with a maximum of 4 units. Please remove all AMS units before reconnecting the supported one.","0500_8013":"The print file is not available. Please check to see if the storage media has been removed.","0500_8036":"Your sliced file is not consistent with the current printer model. Continue?","0500_803C":"The current nozzle setting does not match the slicing file. Continuing to print may affect print quality. It is recommended to re-slice before starting the print.","0500_8040":"Toolhead front cover is detached. Moving the toolhead may damage the printer. Do you want to continue?","0500_8041":"The filament in hotend is too cold. Extrusion may damage the extruder. Still feeding in/out the filament?","0500_8048":"The module on the toolhead is not calibrated. Please cancel the task to perform calibration or switch to a calibrated module.","0500_8051":"Detected build plate is not the same as the Gcode file. Please adjust slicer settings or use the correct plate.","0500_8053":"Nozzle mismatch was detected during printing. Please initiate the print after re-slicing, or continue printing after replacing with the correct nozzle. Caution: the hotend temperature is high.","0500_8055":"Laser module is installed, but a Cutting Platform is detected. Please place a Laser Platform and perform laser calibration.","0500_8056":"Cutting module is installed, but the laser platform is detected. Please place the cutting platform for calibration.","0500_8058":"Please place the light grip cutting mat correctly and ensure the marker is exposed.","0500_8059":"Cutting platform base is not correctly aligned. Please ensure that the four corners of the platform are aligned with the heatbed.","0500_805A":"Please place the cutting mat on cutting protection base.","0500_805B":"The cutting mat type is unknown; please replace it with the correct cutting mat.","0500_805C":"The grip cutting mat type does not match; please place a LightGrip cutting mat.","0500_805E":"Cutting module Serial Number error: unable to calibrate or make project.","0500_8060":"The current module on toolhead does not meet requirements. Please replace the module as per the on-screen instructions.","0500_8061":"No print plate detected. Please make sure it is placed correctly.","0500_8062":"The print plate marker was not detected. Please confirm the print plate is correctly positioned on the heatbed with all four corners aligned, and the marker is visible. If strong light is shining o...","0500_8063":"The platform is not detected during calibration; please make sure the Laser Platform is properly placed.","0500_8064":"Please place the Laser Platform correctly and ensure the rear markers are not blocked for laser calibration.","0500_8066":"The task requires a Cutting Platform, but the current one is a Laser Platform. Please replace it with a Cutting Platform (Cutting Protection Base + LightGrip cutting mat).","0500_8067":"Please place a LightGrip cutting mat on the cutting protection base.","0500_8068":"Please place the strong grip cutting mat correctly and ensure the marker is exposed.","0500_8069":"Unable to recognize the left and right hotends. They might be third party hotends, or the hotend marks may be dirty. Please manually set the hotend types.","0500_806A":"Unable to recognize the left and right hotends. They might be third party hotends, or the hotend marks may be dirty. Please set hotend types on printer screen before next print.","0500_806B":"Quick-release Lever is not locked. Please press down the external toolhead module to ensure it is properly seated, then push down the level to lock it in place.","0500_806C":"Please place the cutting platform correctly and ensure the marker is exposed.","0500_806D":"Material not detected. Please confirm placement and continue.","0500_806E":"Foreign objects detected on heatbed; please check and clean up the heatbed.","0500_806F":"The grip cutting mat type does not match; please place a StrongGrip cutting mat.","0500_8071":"No cutting platform was detected. Please confirm that it has been correctly placed.","0500_8072":"Live View camera is blocked","0500_8073":"Heatbed limit block is obstructed or contaminated. Please clean and ensure the limit block is visible, otherwise platform position offset detection may be inaccurate.","0500_8074":"The Laser Platform is offset. Please ensure that the four corners of the platform are aligned with the heatbed, and the marker is not obstructed.","0500_8077":"The visual marker was not detected. Please ensure the paper is properly placed.","0500_8078":"Current material does not match the sliced file settings. Please load the correct material and ensure the QR code on the material is not damaged or dirty.","0500_8079":"Please place the Laser Test Material (350g paperboard) and position support strips underneath to prevent material warping.","0500_807A":"The foreign object detection function is not working. You can continue the task or check the assistant for troubleshooting.","0500_807B":"Please place the cutting platform (cutting protection base + LightGrip cutting mat).","0500_807C":"Please place the cutting platform (cutting protection base + StrongGrip cutting mat).","0500_807D":"This task requires a Cutting Platform, but the current one is a Laser Platform. Please replace it with a Cutting Platform (Cutting Protection Base + StrongGrip Cutting Mat).","0500_807E":"Please place a StrongGrip cutting mat on the cutting protection base.","0500_8080":"The left and right hotends are not installed.","0500_8081":"The left and right hotends are not installed.","0500_8082":"Please remove the protective film on the Opaque Glossy Acrylic before processing","0500_8083":"Material is not allowed in Mounting Calibration. Please remove the material from the platform.","0500_8084":"The Live View Camera is dirty; please clean it and continue.","0500_8085":"Toolhead camera is obstructed","0500_8086":"Toolhead Camera is dirty, which affects the AI function; please clean the lens surface.","0500_8087":"BirdsEye camera is obstructed","0500_8088":"The Birdseye Camera is dirty","0500_8089":"Task paused due to Presence Check failed. Please check the printer to continue.","0500_808A":"The BirdsEye Camera is installed offset. Please refer to the assistant to reinstall it.","0500_808B":"The BirdsEye Camera setup failed. Please remove all objects and the mat on the heatbed to ensure the heatbed markers are visible. Meanwhile, please ensure the BirdsEye Camera is installed correctly...","0500_808C":"Detected build plate offset. Please align the build plate with the heatbed, and then continue.","0500_808D":"The Cutting Module offset calibration failed, which may result in inaccurate cuts. Please ensure the cutting material is properly positioned and check whether the cutting blade tip is worn.","0500_808E":"BirdsEye Camera initialization failed. The toolhead camera did not detect the Heatbed features. Please clean the Heatbed, remove all objects and pads, and ensure the bed markings are visible. Check...","0500_808F":"Nozzle camera lens is dirty, affecting AI monitoring. Clean the lens with a non-woven cloth and a small amount of alcohol. Beware of hotend heat; wait for it to cool before handling.","0500_8090":"Please attach the 80g White Printing Paper to the center area of the platform.","0500_8091":"The Cutting Module offset calibration failed, which may result in inaccurate cuts. Please ensure the 80g white printer paper(letter paper thickness) is properly positioned and check whether the cut...","0500_8092":"Toolhead Camera initialization failed. This print can still continue, but some AI functions will be disabled. If you encounter this issue again after restarting, please contact customer support.","0500_8093":"The nozzle silicone sleeve is not installed; there is a risk of temperature control failure. Please install it correctly and try again.","0500_80A0":"The visual encoder board was not detected. Please check if the board is properly placed and aligned at all four corners, and ensure the positioning markings are clear and free from wear.","0500_C010":"MicroSD Card read/write exception: please reinsert or replace the MicroSD Card.","0500_C032":"Laser/Cutting module connected to the toolhead. The drying process has been automatically stopped.","0500_C036":"This is a printing task. Please detach the Laser/Cutting Module from the Toolhead.","0500_C07F":"Device is busy and cannot perform this operation. To proceed, please pause or stop the current task.","0501_4017":"Binding failed. Please retry or restart the printer and retry.","0501_4018":"Binding configuration information parsing failed; please try again.","0501_4019":"The printer has already been bound. Please unbind it and try again.","0501_401A":"Cloud access failed. Possible reasons include network instability caused by interference, inability to access the internet, or router firewall configuration restrictions. You can try moving the pri...","0501_401B":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_401C":"Cloud access is rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_401D":"Cloud access failed, which may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0501_401E":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_401F":"Authorization timed out. Please make sure that your phone or PC has access to the internet, and ensure that the Bambu Studio/Bambu Handy APP is running in the foreground during the binding operation.","0501_4020":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_4021":"Cloud access failed, which may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0501_4022":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_4023":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_4024":"Cloud access failed. Possible reasons include network instability caused by interference, inability to access the internet, or router firewall configuration restrictions. You can try moving the pri...","0501_4025":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_4026":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_4027":"Cloud access failed; this may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0501_4028":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_4029":"Cloud access is rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_4031":"Device discovery binding is in progress, and the QR code cannot be displayed on the screen. You can wait for the binding to finish or abort the device discovery binding process in the APP/Studio an...","0501_4032":"QR code binding is in progress, so device discovery binding cannot be performed. You can scan the QR code on the screen for binding or exit the QR code display page on screen and try device discove...","0501_4033":"Your APP region does not match with your printer; please download the APP in the corresponding region and register your account again.","0501_4034":"The slicing progress has not been updated for a long time, and the printing task has exited. Please confirm the parameters and reinitiate printing.","0501_4035":"The device is in the process of binding and cannot respond to new binding requests.","0501_4038":"The regional settings do not match the printer; please check the printer's regional settings.","0501_4039":"Device login has expired; please try to bind again.","0501_4098":"The device cannot detect AMS B. Please reconnect the AMS cable or restart the printer.","0501_409D":"The firmware of AMS B does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0501_40A3":"AMS(or AMS lite) B communication is abnormal. Please reconnect the module cable or restart the printer.","0502_4001":"Current filament will be used in this print job. Settings cannot be changed.","0502_4002":"Please go to “Settings > Calibration” to run the Motion Accuracy Enhancement Calibration before turning on Motion Accuracy Enhancement mode.","0502_4003":"The printer is currently printing and the motion accuracy enhancement feature cannot be turned on or off.","0502_4004":"Some features are not supported by the current device. Please check the Studio feature settings or update the firmware to the latest version.","0502_4005":"The AMS has not been calibrated yet, so printing cannot be initiated.","0502_4006":"Unknown module detected; please try updating the firmware to the latest version.","0502_400D":"Failed to start a new task: filament loading/unloading not completed.","0502_400E":"Failed to start a new task: The nozzle cold pull was not completed.","0502_4013":"This device is not compatible with the 40W laser module. Please replace it with a 10W laser module or remove it.","0502_4098":"The device cannot detect AMS C. Please reconnect the AMS cable or restart the printer.","0502_409D":"The firmware of AMS C does not match the printer; the device cannot continue working. Please upgrade it on the 'Firmware' page.","0502_40A3":"AMS(or AMS lite) C communication is abnormal. Please reconnect the module cable or restart the printer.","0502_C00F":"The device is busy and cannot perform nozzle identification.","0502_C010":"Due to printer power limitations, printing, calibration, controls and other actions cannot be performed during AMS drying. Please stop the drying process before proceeding with any other operation.","0502_C011":"Currently in 2D production mode. Please continue the operation on the printer","0502_C012":"The task cannot be paused.","0502_C014":"The AMS Remaining Filament Estimation is enabled by default and cannot be disabled.","0502_C024":"The flow dynamic calibration records have exceeded the storage limit. Please delete some historical records in the slicer software before adding new calibration data.","0503_4098":"The device cannot detect AMS D. Please reconnect the AMS cable or restart the printer.","0503_409D":"The firmware of AMS D does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0503_40A3":"AMS(or AMS lite) D communication is abnormal. Please reconnect the module cable or restart the printer.","0580_4096":"The device cannot detect AMS-HT A. Please reconnect the AMS-HT cable or restart the printer.","0580_409C":"The firmware of AMS-HT A does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0580_40A2":"AMS-HT A communication is abnormal. Please reconnect the module cable or restart the printer.","0581_4096":"The device cannot detect AMS-HT B. Please reconnect the AMS-HT cable or restart the printer.","0581_409C":"The firmware of AMS-HT B does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0581_40A2":"AMS-HT B communication is abnormal. Please reconnect the module cable or restart the printer.","0582_4096":"The device cannot detect AMS-HT C. Please reconnect the AMS-HT cable or restart the printer.","0582_409C":"The firmware of AMS-HT C does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0582_40A2":"AMS-HT C communication is abnormal. Please reconnect the module cable or restart the printer.","0583_4096":"The device cannot detect AMS-HT D. Please reconnect the AMS-HT cable or restart the printer.","0583_409C":"The firmware of AMS-HT D does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0583_40A2":"AMS-HT D communication is abnormal. Please reconnect the module cable or restart the printer.","0584_4096":"The device cannot detect AMS-HT F. Please reconnect the AMS-HT cable or restart the printer.","0584_409C":"The firmware of AMS-HT E does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0584_40A2":"AMS-HT E communication is abnormal. Please reconnect the module cable or restart the printer.","0585_4096":"The device cannot detect AMS-HT E. Please reconnect the AMS-HT cable or restart the printer.","0585_409C":"The firmware of AMS-HT F does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0585_40A2":"AMS-HT F communication is abnormal. Please reconnect the module cable or restart the printer.","0586_4096":"The device cannot detect AMS-HT G. Please reconnect the AMS-HT cable or restart the printer.","0586_409C":"The firmware of AMS-HT G does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0586_40A2":"AMS-HT G communication is abnormal. Please reconnect the module cable or restart the printer.","0587_4096":"The device cannot detect AMS-HT H. Please reconnect the AMS-HT cable or restart the printer.","0587_409C":"The firmware of AMS-HT H does not match the printer; the device cannot continue working. Please upgrade it on the 'Firmware' page.","0587_40A2":"AMS-HT H communication is abnormal. Please reconnect the module cable or restart the printer.","05FE_8053":"The left nozzle is not matched with slicing file. Please initiate the print after re-slicing, or continue printing after replacing with the correct nozzle. Caution: the hotend temperature is high.","05FE_8069":"Unable to recognize the left hotend. It might be a third party hotend, or the hotend mark may be dirty. Please manually set the hotend type.","05FE_806A":"Unable to recognize the left hotend. It might be a third party hotend, or the hotend mark may be dirty. Please set hotend type on printer screen before next print.","05FE_8080":"The left hotend is not installed.","05FE_8081":"The left hotend is not installed.","05FF_8053":"The right nozzle is not matched with slicing file. Please initiate the print after re-slicing, or continue printing after replacing with the correct nozzle. Caution: the hotend temperature is high.","05FF_8069":"Unable to recognize the right hotend. It might be a third party hotend, or the hotend mark may be dirty. Please manually set the hotend type.","05FF_806A":"Unable to recognize the right hotend. It might be a third party hotend, or the hotend mark may be dirty. Please set hotend type on printer screen before next print.","05FF_8080":"The right hotend is not installed.","05FF_8081":"The right hotend is not installed.","0700_4001":"The AMS has been disabled for a print, but it still has filament loaded. Please unload the AMS filament and switch to the spool holder filament for printing.","0700_4025":"Failed to read the filament information.","0700_8001":"Failed to cut the filament. Please check the cutter.","0700_8002":"The cutter is stuck. Please make sure the cutter handle is out.","0700_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0700_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0700_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0700_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0700_8007":"Extruding filament failed. The extruder might be clogged.","0700_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS A to the extruder is properly connected.","0700_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0700_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0700_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0700_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0700_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0700_8017":"AMS A is drying. Please stop drying process before loading/unloading material.","0700_8021":"AMS setup failed; please refer to the assistant.","0700_8023":"AMS A cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0700_C069":"An error occurred during AMS A drying. Please go to Assistant for more details.","0700_C06A":"AMS A is reading RFID. Unable to start drying. Please try again later.","0700_C06B":"AMS A is changing filament. Unable to start drying. Please try again later.","0700_C06C":"AMS A is in Feed Assist Mode. Unable to start drying. Please try again later.","0700_C06D":"AMS A is assisting in filament insertion. Unable to start drying. Please try again later.","0700_C06E":"AMS A motor is performing self-test. Unable to start drying. Please try again later.","0701_4001":"Filament is still loaded from the AMS after it has been disabled. Please unload the filament, load from the spool holder, and restart printing.","0701_4025":"Failed to read the filament information.","0701_8001":"Failed to cut the filament. Please check the cutter.","0701_8002":"The cutter is stuck. Please make sure the cutter handle is out.","0701_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0701_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0701_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0701_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0701_8007":"Extruding filament failed. The extruder might be clogged.","0701_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS B to the extruder is properly connected.","0701_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0701_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0701_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0701_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0701_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0701_8017":"AMS B is drying. Please stop drying process before loading/unloading material.","0701_8021":"AMS setup failed; please refer to the assistant.","0701_8023":"AMS B cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0701_C069":"An error occurred during AMS B drying. Please go to Assistant for more details.","0701_C06A":"AMS B is reading RFID. Unable to start drying. Please try again later.","0701_C06B":"AMS B is changing filament. Unable to start drying. Please try again later.","0701_C06C":"AMS B is in Feed Assist Mode. Unable to start drying. Please try again later.","0701_C06D":"AMS B is assisting in filament insertion. Unable to start drying. Please try again later.","0701_C06E":"AMS B motor is performing self-test. Unable to start drying. Please try again later.","0702_4001":"Filament is still loaded from the AMS after it has been disabled. Please unload the filament, load from the spool holder, and restart printing.","0702_4025":"Failed to read the filament information.","0702_8001":"Failed to cut the filament. Please check the cutter.","0702_8002":"The cutter is stuck. Please make sure the cutter handle is out.","0702_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0702_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0702_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0702_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0702_8007":"Extruding filament failed. The extruder might be clogged.","0702_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS C to the extruder is properly connected.","0702_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0702_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0702_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0702_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0702_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0702_8017":"AMS C is drying. Please stop drying process before loading/unloading material.","0702_8021":"AMS setup failed; please refer to the assistant.","0702_8023":"AMS C cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0702_C069":"An error occurred during AMS C drying. Please go to Assistant for more details.","0702_C06A":"AMS C is reading RFID. Unable to start drying. Please try again later.","0702_C06B":"AMS C is changing filament. Unable to start drying. Please try again later.","0702_C06C":"AMS C is in Feed Assist Mode. Unable to start drying. Please try again later.","0702_C06D":"AMS C is assisting in filament insertion. Unable to start drying. Please try again later.","0702_C06E":"AMS C motor is performing self-test. Unable to start drying. Please try again later.","0703_4001":"Filament is still loaded from the AMS after it has been disabled. Please unload the filament, load from the spool holder, and restart printing.","0703_4025":"Failed to read the filament information.","0703_8001":"Failed to cut the filament. Please check the cutter.","0703_8002":"The cutter is stuck. Please make sure the cutter handle is out.","0703_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0703_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0703_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0703_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0703_8007":"Extruding filament failed. The extruder might be clogged.","0703_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS D to the extruder is properly connected.","0703_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0703_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0703_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0703_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0703_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0703_8017":"AMS D is drying. Please stop drying process before loading/unloading material.","0703_8021":"AMS setup failed; please refer to the assistant.","0703_8023":"AMS D cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0703_C069":"An error occurred during AMS D drying. Please go to Assistant for more details.","0703_C06A":"AMS D is reading RFID. Unable to start drying. Please try again later.","0703_C06B":"AMS D is changing filament. Unable to start drying. Please try again later.","0703_C06C":"AMS D is in Feed Assist Mode. Unable to start drying. Please try again later.","0703_C06D":"AMS D is assisting in filament insertion. Unable to start drying. Please try again later.","0703_C06E":"AMS D motor is performing self-test. Unable to start drying. Please try again later.","0704_4025":"Failed to read the filament information.","0704_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0704_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0704_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0704_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0704_8007":"Extruding filament failed. The extruder might be clogged.","0704_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS E to the extruder is properly connected.","0704_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0704_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0704_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0704_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0704_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0704_8021":"AMS setup failed; please refer to the assistant.","0704_8023":"AMS E cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0705_4025":"Failed to read the filament information.","0705_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0705_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0705_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0705_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0705_8007":"Extruding filament failed. The extruder might be clogged.","0705_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS F to the extruder is properly connected.","0705_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0705_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0705_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0705_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0705_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0705_8021":"AMS setup failed; please refer to the assistant.","0705_8023":"AMS F cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0706_4025":"Failed to read the filament information.","0706_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0706_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0706_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0706_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0706_8007":"Extruding filament failed. The extruder might be clogged.","0706_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS G to the extruder is properly connected.","0706_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0706_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0706_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0706_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0706_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0706_8021":"AMS setup failed; please refer to the assistant.","0706_8023":"AMS G cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0707_4025":"Failed to read the filament information.","0707_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0707_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0707_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0707_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0707_8007":"Extruding filament failed. The extruder might be clogged.","0707_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS H to the extruder is properly connected.","0707_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0707_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0707_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0707_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0707_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0707_8021":"AMS setup failed; please refer to the assistant.","0707_8023":"AMS H cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","07FE_8001":"Failed to cut the filament of the left extruder. Please check the cutter.","07FE_8002":"The cutter of the left extruder is stuck. Please pull out the cutter handle.","07FE_8003":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder. (Connect a PTFE tube if you are ab...","07FE_8004":"Failed to pull back the filament from the left extruder. Please check whether the filament is stuck inside the extruder.","07FE_8005":"Failed to feed the filament outside the AMS. Please clip the end of the filament flat and check to see if the spool is stuck.","07FE_8006":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","07FE_8007":"Please observe the nozzle of the left extruder. If the filament has been extruded, select 'Continue'; if it has not, please push the filament forward slightly, and then select 'Retry'.","07FE_8010":"Check if the left external filament spool or filament is stuck.","07FE_8011":"The external filament connected to the left extruder has run out; please load a new filament.","07FE_8012":"Failed to get mapping table; please select 'Resume' to retry.","07FE_8013":"Timeout purging old filament of the left extruder: Please check if the filament is stuck or the extruder is clogged.","07FE_8020":"Extruder change failed; please refer to the assistant.","07FE_8021":"AMS setup failed; please refer to the assistant.","07FE_8024":"Extruder position calibration failed; please refer to the assistant.","07FE_8025":"Cold pull timed out. Please promptly operate or check whether the filament is broken inside the extruder, and click the Assistant for details.","07FE_8030":"The filament specified in the slicer has been used up. Printing is paused. Please go to the machine to replace the material and resume printing.","07FE_C003":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube i...","07FE_C006":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","07FE_C008":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube i...","07FE_C009":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","07FE_C00A":"Please observe the nozzle of the left extruder. If the filament has been extruded, select 'Continue'; if not, please push the filament forward slightly and then select 'Retry'.","07FE_C010":"Insert the filament (over 30cm long) until it stops. You might see slight smoke during flushing. After insertion, close the front door and top cover.","07FE_C011":"Please manually and slowly pull out the filament from the extruder. Then click “Continue”.","07FE_C012":"Press the black PTFE tube coupler and unplug the PTFE tube. After completing the operation, click 'Continue.'","07FF_4001":"Filament is still loaded from the AMS after it has been disabled. Please unload the filament, load from the spool holder, and restart printing.","07FF_8001":"Failed to cut the filament of the right extruder. Please check the cutter.","07FF_8002":"The cutter is stuck. Please make sure the cutter handle is out.","07FF_8003":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder. (Connect a PTFE tube if you are a...","07FF_8004":"Failed to pull back the filament from the right extruder. Please check whether the filament is stuck inside the extruder.","07FF_8005":"Failed to feed the filament outside the AMS. Please clip the end of the filament flat and check to see if the spool is stuck.","07FF_8006":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","07FF_8007":"Please observe the nozzle of the right extruder. If the filament has been extruded, select 'Continue'; if it has not, please push the filament forward slightly, and then select 'Retry'.","07FF_8010":"Check if the external filament spool or filament is stuck.","07FF_8011":"External filament has run out; please load a new filament.","07FF_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","07FF_8013":"Timeout purging old filament of the right extruder: Please check if the filament is stuck or the extruder is clogged.","07FF_8020":"Extruder change failed; please refer to the assistant.","07FF_8021":"AMS setup failed; please refer to the assistant.","07FF_8024":"Extruder position calibration failed; please refer to the assistant.","07FF_8025":"Cold pull timed out. Please promptly operate or check whether the filament is broken inside the extruder, and click the Assistant for details.","07FF_8030":"The filament specified in the slicer has been used up. Printing is paused. Please go to the machine to replace the material and resume printing.","07FF_C003":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube ...","07FF_C006":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","07FF_C008":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube ...","07FF_C009":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","07FF_C00A":"Please observe the nozzle of the right extruder. If the filament has been extruded, select 'Continue'; if not, please push the filament forward slightly and then select 'Retry'.","07FF_C010":"Insert the filament (over 30cm long) until it stops. You might see slight smoke during flushing. After insertion, close the front door and top cover.","07FF_C011":"Hold the driven wheel bracket, slowly pull the filament from the extruder, then press 'Continue'.","07FF_C012":"Press the black PTFE tube coupler and unplug the PTFE tube. After completing the operation, click 'Continue.'","0C00_4020":"The setup of BirdsEye Camera failed. Please clear all objects and remove the mat. Make sure the marker is not obstructed. Meanwhile, clean both the BirdsEye Camera and Toolhead Camera, and remove a...","0C00_4021":"The setup of BirdsEye Camera failed; please reboot the printer.","0C00_4022":"The setup of BirdsEye Camera failed. Please check if the laser module is working properly.","0C00_4024":"The Birdseye Camera is installed offset. Please refer to the assistant to reinstall it.","0C00_4025":"The Birdseye Camera is dirty. Please clean it and restart the process.","0C00_4026":"The Live View Camera initialization failed; please reboot the printer.","0C00_4027":"The Live View Camera calibration failed. Please refer to the assistant for details and recalibrate the camera after processing.","0C00_4029":"Material not detected. Please confirm placement and continue.","0C00_402A":"The visual marker was not detected. Please re-paste the paper in the correct position.","0C00_402C":"Device data link error. Please reboot the printer","0C00_402D":"The toolhead camera is not working properly; please reboot the device.","0C00_403D":"The vision encoder plate was not detected. Please confirm it is correctly positioned on the heatbed.","0C00_403E":"The high-precision nozzle offset calibration has failed, possibly due to a damaged pattern or the similarity of the colors of the two selected filaments. Please clear the printed pattern and replac...","0C00_4041":"Toolhead camera calibration failed. Please ensure the Calibration Marker on the heatbed or Height Calibration Marker on the homing area is clean and undamaged, then re-run the calibration process.","0C00_8001":"First layer defects were detected. If the defects are acceptable, select 'Resume' to resume the print job.","0C00_8005":"Purged filament has piled up in the waste chute, which may cause a tool head collision.","0C00_8009":"Build plate localization marker was not found.","0C00_800B":"The heatbed marker was not detected. Please clear all objects and remove the mat. Make sure the marker is not obstructed.","0C00_8015":"Objects detected on the platform; please clean them up in a timely manner.","0C00_8016":"The foreign object detection function is not working. You can continue the task or check assistant for solutions.","0C00_8017":"Foreign objects detected on the platform; please clean them up on time.","0C00_8018":"The foreign object detection function is not working. You can continue the task or view the assistant for troubleshooting.","0C00_8033":"Quick-release Lever is not locked. Please push it down to secure.","0C00_8034":"Liveview Camera initialization failed. This print can still continue, but some AI functions will be disabled. If you encounter this issue again after restarting, please contact customer support.","0C00_803F":"AI detected nozzle clumping. Please check the nozzle condition. Refer to assistant for solutions.","0C00_8040":"AI detected air-printing defect. Please check the hotend extrusion status. Refer to assistant for solutions.","0C00_8042":"The AI print monitor has detected a spaghetti defect. Please check the print and take the necessary action.","0C00_8043":"AI detected nozzle clumping. Please check the nozzle condition. Refer to assistant for solutions.","0C00_C003":"Possible defects were detected in the first layer.","0C00_C004":"Possible spaghetti failure was detected.","0C00_C006":"Purged filament may have piled up in the waste chute.","1000_C001":"High bed temperature may lead to filament clogging in the nozzle. You may open the chamber door.","1000_C002":"Printing CF material with stainless steel may cause nozzle damage.","1000_C003":"Enabling Timelapse in traditional mode may cause defects; please activate this feature as needed.","1001_4001":"Timelapse is not supported as Spiral Vase mode is enabled in slicing presets.","1001_4002":"Timelapse is not supported as the Print sequence is set to 'By object'.","1001_8003":"The time-lapse mode is set to Traditional in the slicing file. This may cause surface defects. Would you like to enable it?","1001_8004":"Prime Tower is not enabled and time-lapse mode is set to Smooth in slicing file. This may cause surface defects. Would you like to enable it?","1200_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","1200_8001":"Cutting the filament failed. Please check to see if the cutter is stuck. Refer to the Assistant for solutions.","1200_8002":"The cutter is stuck. Please pull out the cutter handle.","1200_8003":"Failed to pull out the filament from the extruder. Please check whether the extruder is clogged or whether the filament is broken inside the extruder.","1200_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","1200_8005":"The filament is not inserted. Please insert the filament.","1200_8006":"Unable to feed filament into the extruder. This could be due to tangled filament or a stuck spool. If not, please check if the AMS PTFE tube is connected.","1200_8007":"Failed to extrude the filament. This might be caused by clogged extruder or stuck filament. Refer to the Assistant for solutions.","1200_8010":"Filament or spool may be stuck.","1200_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","1200_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1200_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","1200_8014":"The filament location in the toolhead was not found. Refer to the Assistant for solutions.","1200_8015":"Failed to pull out the filament from the toolhead. Please check if the filament is stuck, or if it is broken inside the extruder or PTFE tube.","1200_8016":"The extruder is not extruding normally. Refer to the Assistant for troubleshooting. There may be defects in this layer, but you may resume if the defects are acceptable.","1201_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","1201_8001":"Failed to cut the filament. Please check the cutter.","1201_8002":"The cutter is stuck. Please pull out the cutter handle.","1201_8003":"Failed to pull out the filament from the extruder. Please check whether the extruder is clogged or whether the filament is broken inside the extruder.","1201_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","1201_8005":"Failed to feed the filament. Please load the filament and then select 'Retry'.","1201_8006":"Failed to feed the filament into the toolhead. Please check whether the filament is stuck.","1201_8007":"Failed to extrude the filament. The extruder may be clogged or the filament may be stuck; please refer to HMS.","1201_8010":"Please check if the spool or filament is stuck.","1201_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","1201_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1201_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","1201_8014":"Failed to check the filament location in the tool head; please refer to the HMS.","1201_8015":"Failed to pull back the filament from the toolhead. Please check if the filament is stuck or the filament is broken inside the extruder.","1201_8016":"The extruder is not extruding normally; please refer to the HMS. After trouble shooting, if the defects are acceptable, please resume printing.","1202_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","1202_8001":"Failed to cut the filament. Please check the cutter.","1202_8002":"The cutter is stuck. Please pull out the cutter handle.","1202_8003":"Failed to pull out the filament from the extruder. Please check whether the extruder is clogged or whether the filament is broken inside the extruder.","1202_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","1202_8005":"The filament is not inserted. Please insert the filament.","1202_8006":"Failed to feed the filament into the toolhead. Please check whether the filament is stuck.","1202_8007":"Failed to extrude the filament. The extruder may be clogged or the filament may be stuck; please refer to HMS.","1202_8010":"Please check if the spool or filament is stuck.","1202_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","1202_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1202_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","1202_8014":"Failed to check the filament location in the tool head; please refer to the HMS.","1202_8015":"Failed to pull back the filament from the toolhead. Please check if the filament is stuck or is broken inside the extruder.","1202_8016":"The extruder is not extruding normally; please refer to the HMS. After trouble shooting, if the defects are acceptable, please resume printing.","1203_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","1203_8001":"Failed to cut the filament. Please check the cutter.","1203_8002":"The cutter is stuck. Please pull out the cutter handle.","1203_8003":"Failed to pull out the filament from the extruder. Please check whether the extruder is clogged or whether the filament is broken inside the extruder.","1203_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","1203_8005":"The filament is not inserted. Please insert the filament.","1203_8006":"Failed to feed the filament into the toolhead. Please check whether the filament is stuck.","1203_8007":"Failed to extrude the filament. The extruder may be clogged or the filament may be stuck; please refer to HMS.","1203_8010":"Please check if the spool or filament is stuck.","1203_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","1203_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1203_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","1203_8014":"Failed to check the filament location in the tool head; please refer to the HMS.","1203_8015":"Failed to pull back the filament from the toolhead. Please check if the filament is stuck or is broken inside the extruder.","1203_8016":"The extruder is not extruding normally; please refer to the HMS. After trouble shooting, if the defects are acceptable, please resume printing.","12FF_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","12FF_8001":"Failed to cut the filament. Please check the cutter.","12FF_8002":"The cutter is stuck. Please pull out the cutter handle.","12FF_8003":"Please pull out the filament on the spool holder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube if you are about to us...","12FF_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","12FF_8005":"The filament is not inserted. Please insert the filament.","12FF_8006":"Please feed filament into the PTFE tube until it can not be pushed any farther.","12FF_8007":"Check nozzle. Select 'Done' if filament was extruded, otherwise push filament forward slightly and select 'Retry.'","12FF_8010":"Please check if the filament or the spool is stuck.","12FF_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","12FF_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","12FF_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","12FF_C003":"Please pull out the filament on the spool holder. If this message persists, please check to see if there is filament broken in the extruder or PTFE Tube. (Connect a PTFE tube if you are about to us...","12FF_C006":"Please feed filament into the PTFE tube until it can not be pushed any farther.","1800_4025":"Failed to read the filament information.","1800_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1800_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1800_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1800_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1800_8007":"Extruding filament failed. The extruder might be clogged.","1800_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT A to the extruder is properly connected.","1800_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1800_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1800_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1800_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1800_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1800_8017":"AMS-HT A is drying. Please stop drying process before loading/unloading material.","1800_8021":"AMS setup failed; please refer to the assistant.","1800_8023":"AMS-HT A cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1800_C069":"An error occurred during AMS-HT A drying. Please go to Assistant for more details.","1800_C06A":"AMS-HT A is reading RFID. Unable to start drying. Please try again later.","1800_C06B":"AMS-HT A is changing filament. Unable to start drying. Please try again later.","1800_C06C":"AMS-HT A is in Feed Assist Mode. Unable to start drying. Please try again later.","1800_C06D":"AMS-HT A is assisting in filament insertion. Unable to start drying. Please try again later.","1800_C06E":"AMS-HT A motor is performing self-test. Unable to start drying. Please try again later.","1801_4025":"Failed to read the filament information.","1801_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1801_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1801_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1801_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1801_8007":"Extruding filament failed. The extruder might be clogged.","1801_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT B to the extruder is properly connected.","1801_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1801_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1801_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1801_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1801_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1801_8017":"AMS-HT B is drying. Please stop drying process before loading/unloading material.","1801_8021":"AMS setup failed; please refer to the assistant.","1801_8023":"AMS-HT B cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1801_C069":"An error occurred during AMS-HT B drying. Please go to Assistant for more details.","1801_C06A":"AMS-HT B is reading RFID. Unable to start drying. Please try again later.","1801_C06B":"AMS-HT B is changing filament. Unable to start drying. Please try again later.","1801_C06C":"AMS-HT B is in Feed Assist Mode. Unable to start drying. Please try again later.","1801_C06D":"AMS-HT B is assisting in filament insertion. Unable to start drying. Please try again later.","1801_C06E":"AMS-HT B motor is performing self-test. Unable to start drying. Please try again later.","1802_4025":"Failed to read the filament information.","1802_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1802_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1802_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1802_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1802_8007":"Extruding filament failed. The extruder might be clogged.","1802_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT C to the extruder is properly connected.","1802_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1802_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1802_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1802_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1802_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1802_8017":"AMS-HT C is drying. Please stop drying process before loading/unloading material.","1802_8021":"AMS setup failed; please refer to the assistant.","1802_8023":"AMS-HT C cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1802_C069":"An error occurred during AMS-HT C drying. Please go to Assistant for more details.","1802_C06A":"AMS-HT C is reading RFID. Unable to start drying. Please try again later.","1802_C06B":"AMS-HT C is changing filament. Unable to start drying. Please try again later.","1802_C06C":"AMS-HT C is in Feed Assist Mode. Unable to start drying. Please try again later.","1802_C06D":"AMS-HT C is assisting in filament insertion. Unable to start drying. Please try again later.","1802_C06E":"AMS-HT C motor is performing self-test. Unable to start drying. Please try again later.","1803_4025":"Failed to read the filament information.","1803_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1803_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1803_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1803_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1803_8007":"Extruding filament failed. The extruder might be clogged.","1803_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT D to the extruder is properly connected.","1803_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1803_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1803_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1803_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1803_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1803_8017":"AMS-HT D is drying. Please stop drying process before loading/unloading material.","1803_8021":"AMS setup failed; please refer to the assistant.","1803_8023":"AMS-HT D cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1803_C069":"An error occurred during AMS-HT D drying. Please go to Assistant for more details.","1803_C06A":"AMS-HT D is reading RFID. Unable to start drying. Please try again later.","1803_C06B":"AMS-HT D is changing filament. Unable to start drying. Please try again later.","1803_C06C":"AMS-HT D is in Feed Assist Mode. Unable to start drying. Please try again later.","1803_C06D":"AMS-HT D is assisting in filament insertion. Unable to start drying. Please try again later.","1803_C06E":"AMS-HT D motor is performing self-test. Unable to start drying. Please try again later.","1804_4025":"Failed to read the filament information.","1804_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1804_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1804_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1804_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1804_8007":"Extruding filament failed. The extruder might be clogged.","1804_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT E to the extruder is properly connected.","1804_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1804_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1804_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1804_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1804_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1804_8021":"AMS setup failed; please refer to the assistant.","1804_8023":"AMS-HT E cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1804_C069":"An error occurred during AMS-HT E drying. Please go to Assistant for more details.","1804_C06A":"AMS-HT E is reading RFID. Unable to start drying. Please try again later.","1804_C06B":"AMS-HT E is changing filament. Unable to start drying. Please try again later.","1804_C06C":"AMS-HT E is in Feed Assist Mode. Unable to start drying. Please try again later.","1804_C06D":"AMS-HT E is assisting in filament insertion. Unable to start drying. Please try again later.","1804_C06E":"AMS-HT E motor is performing self-test. Unable to start drying. Please try again later.","1805_4025":"Failed to read the filament information.","1805_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1805_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1805_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1805_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1805_8007":"Extruding filament failed. The extruder might be clogged.","1805_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT F to the extruder is properly connected.","1805_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1805_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1805_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1805_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1805_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1805_8021":"AMS setup failed; please refer to the assistant.","1805_8023":"AMS-HT F cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1805_C069":"An error occurred during AMS-HT F drying. Please go to Assistant for more details.","1805_C06A":"AMS-HT F is reading RFID. Unable to start drying. Please try again later.","1805_C06B":"AMS-HT F is changing filament. Unable to start drying. Please try again later.","1805_C06C":"AMS-HT F is in Feed Assist Mode. Unable to start drying. Please try again later.","1805_C06D":"AMS-HT F is assisting in filament insertion. Unable to start drying. Please try again later.","1805_C06E":"AMS-HT F motor is performing self-test. Unable to start drying. Please try again later.","1806_4025":"Failed to read the filament information.","1806_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1806_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1806_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1806_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1806_8007":"Extruding filament failed. The extruder might be clogged.","1806_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT G to the extruder is properly connected.","1806_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1806_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1806_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1806_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1806_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1806_8021":"AMS setup failed; please refer to the assistant.","1806_8023":"AMS-HT G cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1806_C069":"An error occurred during AMS-HT G drying. Please go to Assistant for more details.","1806_C06A":"AMS-HT G is reading RFID. Unable to start drying. Please try again later.","1806_C06B":"AMS-HT G is changing filament. Unable to start drying. Please try again later.","1806_C06C":"AMS-HT G is in Feed Assist Mode. Unable to start drying. Please try again later.","1806_C06D":"AMS-HT G is assisting in filament insertion. Unable to start drying. Please try again later.","1806_C06E":"AMS-HT G motor is performing self-test. Unable to start drying. Please try again later.","1807_4025":"Failed to read the filament information.","1807_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1807_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1807_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1807_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1807_8007":"Extruding filament failed. The extruder might be clogged.","1807_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT H to the extruder is properly connected.","1807_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1807_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1807_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1807_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1807_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1807_8021":"AMS setup failed; please refer to the assistant.","1807_8023":"AMS-HT H cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1807_C069":"An error occurred during AMS-HT H drying. Please go to Assistant for more details.","1807_C06A":"AMS-HT H is reading RFID. Unable to start drying. Please try again later.","1807_C06B":"AMS-HT H is changing filament. Unable to start drying. Please try again later.","1807_C06C":"AMS-HT H is in Feed Assist Mode. Unable to start drying. Please try again later.","1807_C06D":"AMS-HT H is assisting in filament insertion. Unable to start drying. Please try again later.","1807_C06E":"AMS-HT H motor is performing self-test. Unable to start drying. Please try again later.","18FE_8001":"Failed to cut the filament of the left extruder. Please check the cutter.","18FE_8002":"The cutter of the left extruder is stuck. Please pull out the cutter handle.","18FE_8003":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder. (Connect a PTFE tube if you are ab...","18FE_8004":"Failed to pull back the filament from the left extruder. Please check whether the filament is stuck inside the extruder.","18FE_8005":"Failed to feed the filament outside the AMS-HT. Please clip the end of the filament flat and check to see if the spool is stuck.","18FE_8006":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","18FE_8007":"Please observe the nozzle of the left extruder. If the filament has been extruded, select 'Continue'; if it has not, please push the filament forward slightly, and then select 'Retry'.","18FE_8011":"The external filament connected to the left extruder has run out; please load a new filament.","18FE_8012":"Failed to get mapping table; please select 'Resume' to retry.","18FE_8013":"Timeout purging old filament of the left extruder: Please check if the filament is stuck or the extruder is clogged.","18FE_8020":"Extruder change failed; please refer to the assistant.","18FE_8021":"AMS setup failed; please refer to the assistant.","18FE_8024":"Extruder position calibration failed; please refer to the assistant.","18FE_C003":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube i...","18FE_C006":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","18FE_C008":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube i...","18FE_C009":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","18FE_C00A":"Please observe the nozzle of the left extruder. If the filament has been extruded, select 'Continue'; if not, please push the filament forward slightly and then select 'Retry'.","18FF_8001":"Failed to cut the filament of the right extruder. Please check the cutter.","18FF_8002":"The cutter of the right extruder is stuck. Please pull out the cutter handle.","18FF_8003":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder. (Connect a PTFE tube if you are a...","18FF_8004":"Failed to pull back the filament from the right extruder. Please check whether the filament is stuck inside the extruder.","18FF_8005":"Failed to feed the filament outside the AMS-HT. Please clip the end of the filament flat and check to see if the spool is stuck.","18FF_8006":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","18FF_8007":"Please observe the nozzle of the right extruder. If the filament has been extruded, select 'Continue'; if it has not, please push the filament forward slightly, and then select 'Retry'.","18FF_8011":"The external filament connected to the right extruder has run out; please load a new filament.","18FF_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","18FF_8013":"Timeout purging old filament of the right extruder: Please check if the filament is stuck or the extruder is clogged.","18FF_8020":"Extruder change failed; please refer to the assistant.","18FF_8021":"AMS setup failed; please refer to the assistant.","18FF_8024":"Extruder position calibration failed; please refer to the assistant.","18FF_C003":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube ...","18FF_C006":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","18FF_C008":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube ...","18FF_C009":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","18FF_C00A":"Please observe the nozzle of the right extruder. If the filament has been extruded, select 'Continue'; if not, please push the filament forward slightly and then select 'Retry'."};function gMe(t){switch(t){case 1:return{label:"Fatal",color:"text-red-500",bgColor:"bg-red-500/20",Icon:jn};case 2:return{label:"Serious",color:"text-red-400",bgColor:"bg-red-500/15",Icon:jn};case 3:return{label:"Warning",color:"text-orange-400",bgColor:"bg-orange-500/20",Icon:Li};default:return{label:"Info",color:"text-blue-400",bgColor:"bg-blue-500/20",Icon:Hs}}}function RR(t,e){const n=t>>16&65535||(t>>8&255)<<8|t&255,r=e&65535;return`${n.toString(16).padStart(4,"0").toUpperCase()}_${r.toString(16).padStart(4,"0").toUpperCase()}`}function nk(t){return t.filter(e=>{const n=parseInt(e.code.replace("0x",""),16)||0,r=RR(e.attr,n);return DR[r]!==void 0})}function bMe(){return"https://wiki.bambulab.com/en/hms/home"}function xMe({printerName:t,errors:e,onClose:n,printerId:r,hasPermission:a}){const{t:s}=Dt(),{showToast:o}=bn(),l=gt({mutationFn:()=>ge.clearHMSErrors(r),onSuccess:()=>{o(s("hmsErrors.clearSuccess"),"success"),n()},onError:()=>{o(s("hmsErrors.clearFailed"),"error")}}),c=e.filter(u=>{const d=parseInt(u.code.replace("0x",""),16)||0,m=RR(u.attr,d);return DR[m]!==void 0});return w.useEffect(()=>{const u=d=>{d.key==="Escape"&&n()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n]),i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg shadow-xl max-w-lg w-full max-h-[80vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(jn,{className:"w-5 h-5 text-orange-400"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:s("hmsErrors.title",{name:t})})]}),i.jsx("button",{onClick:n,className:"p-1 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:c.length===0?i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(Li,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),i.jsx("p",{children:s("hmsErrors.noErrors")})]}):i.jsx("div",{className:"space-y-3",children:c.map((u,d)=>{const{label:m,color:p,bgColor:f,Icon:y}=gMe(u.severity),v=parseInt(u.code.replace("0x",""),16)||0,b=RR(u.attr,v),g=DR[b],_=bMe(),N=b.replace("_","-");return i.jsx("div",{className:`p-4 rounded-lg ${f} border border-white/10`,children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(y,{className:`w-5 h-5 ${p} flex-shrink-0 mt-0.5`}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsxs("span",{className:`font-mono text-sm ${p}`,children:["[",N,"]"]}),i.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${f} ${p}`,children:m})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:g}),i.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-bambu-green hover:underline",children:[i.jsx(ni,{className:"w-3 h-3"}),s("hmsErrors.viewOnWiki")]})]})]})},`${u.code}-${d}`)})})}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex items-center justify-between gap-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:s("hmsErrors.clearInstructions")}),c.length>0&&i.jsxs("button",{onClick:()=>l.mutate(),disabled:!a("printers:control")||l.isPending,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-lg bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex-shrink-0",children:[l.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(nn,{className:"w-4 h-4"}),s("hmsErrors.clearErrors")]})]})]})})}function IZ(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("h2dpro")||e.includes("h2d-pro")?"/img/printers/h2dpro.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 zZ(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 UZ(t,e,n){return t.filter(r=>{if(r.required_filament_types&&r.required_filament_types.length>0&&e!==void 0&&!r.required_filament_types.every(a=>e.has(a.toUpperCase())))return!1;if(r.filament_overrides&&r.filament_overrides.length>0&&n!==void 0){const a=r.filament_overrides.filter(o=>o.force_color_match===!0),s=r.filament_overrides.filter(o=>o.force_color_match!==!0);if(a.length>0&&!a.every(l=>{const c=(l.type||"").toUpperCase(),u=(l.color||"").replace("#","").toLowerCase().slice(0,6);return n.has(`${c}:${u}`)})||s.length>0&&a.length===0&&!s.some(l=>{const c=(l.type||"").toUpperCase(),u=(l.color||"").replace("#","").toLowerCase().slice(0,6);return n.has(`${c}:${u}`)}))return!1}return!0})}function yMe({printerId:t,printerModel:e,printerState:n,plateCleared:r,loadedFilamentTypes:a,loadedFilaments:s}){const{t:o}=Dt(),l=sn(),{showToast:c}=bn(),{hasPermission:u}=Ar(),{data:d}=et({queryKey:["queue",t,"pending",e],queryFn:()=>ge.getQueue(t,"pending",e||void 0),refetchInterval:3e4}),m=gt({mutationFn:()=>ge.clearPlate(t),onSuccess:()=>{l.invalidateQueries({queryKey:["queue",t]}),l.invalidateQueries({queryKey:["printerStatus",t]}),c(o("queue.clearPlateSuccess"),"success")},onError:_=>{c(_.message,"error")}}),p=d?UZ(d,a,s):void 0,f=p?.filter(_=>!_.manual_start)??[],y=p?.length||0;if(y===0)return null;const v=f[0],b=p?.[0];if((n==="FINISH"||n==="FAILED")&&!r&&f.length>0){const _=v||b;return i.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-yellow-400/30",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[i.jsx(Xr,{className:"w-5 h-5 text-yellow-400 flex-shrink-0"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:o("queue.nextInQueue")}),i.jsx("p",{className:"text-sm text-white truncate",children:_?.archive_name||_?.library_file_name||`File #${_?.archive_id||_?.library_file_id}`})]}),y>1&&i.jsxs("span",{className:"text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded flex-shrink-0",children:["+",y-1]})]}),m.isSuccess?i.jsxs("div",{className:"w-full py-2 px-3 rounded-lg bg-bambu-green/10 border border-bambu-green/20 text-bambu-green text-sm flex items-center justify-center gap-2",children:[i.jsx(vc,{className:"w-4 h-4"}),o("queue.plateReady")]}):i.jsxs("button",{onClick:()=>m.mutate(),disabled:m.isPending||!u("printers:clear_plate"),className:"w-full py-2 px-3 rounded-lg bg-bambu-green/20 border border-bambu-green/40 text-bambu-green hover:bg-bambu-green/30 transition-colors text-sm font-medium flex items-center justify-center gap-2 disabled:opacity-50",children:[m.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(vc,{className:"w-4 h-4"}),o("queue.clearPlate")]})]})}return i.jsx(fo,{to:"/queue",className:"block mb-3 p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx(Xr,{className:"w-5 h-5 text-yellow-400 flex-shrink-0"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:o("queue.nextInQueue")}),i.jsx("p",{className:"text-sm text-white truncate",children:b?.archive_name||b?.library_file_name||`File #${b?.archive_id||b?.library_file_id}`})]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(Zn,{className:"w-3 h-3"}),b?.scheduled_time?C0(b.scheduled_time,"system",o):o("time.waiting")]}),y>1&&i.jsxs("span",{className:"text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded",children:["+",y-1]}),i.jsx(fa,{className:"w-4 h-4 text-bambu-gray"})]})]})})}function BZ(t){var e,n,r="";if(typeof t=="string"||typeof t=="number")r+=t;else if(typeof t=="object")if(Array.isArray(t)){var a=t.length;for(e=0;e{var{children:n,width:r,height:a,viewBox:s,className:o,style:l,title:c,desc:u}=t,d=kMe(t,NMe),m=s||{width:r,height:a,x:0,y:0},p=hr("recharts-surface",o);return w.createElement("svg",FR({},ls(d),{className:p,width:r,height:a,style:l,viewBox:"".concat(m.x," ").concat(m.y," ").concat(m.width," ").concat(m.height),ref:e}),w.createElement("title",null,c),w.createElement("desc",null,u),n)}),TMe=["children","className"];function LR(){return LR=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{children:n,className:r}=t,a=AMe(t,TMe),s=hr("recharts-layer",r);return w.createElement("g",LR({className:s},ls(a),{ref:e}),n)}),qZ=w.createContext(null),MMe=()=>w.useContext(qZ);function ti(t){return function(){return t}}const VZ=Math.cos,rk=Math.sin,Rc=Math.sqrt,ik=Math.PI,kT=2*ik,OR=Math.PI,IR=2*OR,Up=1e-6,EMe=IR-Up;function GZ(t){this._+=t[0];for(let e=1,n=t.length;e=0))throw new Error(`invalid digits: ${t}`);if(e>15)return GZ;const n=10**e;return function(r){this._+=r[0];for(let a=1,s=r.length;aUp)if(!(Math.abs(m*c-u*d)>Up)||!s)this._append`L${this._x1=e},${this._y1=n}`;else{let f=r-o,y=a-l,v=c*c+u*u,b=f*f+y*y,g=Math.sqrt(v),_=Math.sqrt(p),N=s*Math.tan((OR-Math.acos((v+p-b)/(2*g*_)))/2),C=N/_,k=N/g;Math.abs(C-1)>Up&&this._append`L${e+C*d},${n+C*m}`,this._append`A${s},${s},0,0,${+(m*f>d*y)},${this._x1=e+k*c},${this._y1=n+k*u}`}}arc(e,n,r,a,s,o){if(e=+e,n=+n,r=+r,o=!!o,r<0)throw new Error(`negative radius: ${r}`);let l=r*Math.cos(a),c=r*Math.sin(a),u=e+l,d=n+c,m=1^o,p=o?a-s:s-a;this._x1===null?this._append`M${u},${d}`:(Math.abs(this._x1-u)>Up||Math.abs(this._y1-d)>Up)&&this._append`L${u},${d}`,r&&(p<0&&(p=p%IR+IR),p>EMe?this._append`A${r},${r},0,1,${m},${e-l},${n-c}A${r},${r},0,1,${m},${this._x1=u},${this._y1=d}`:p>Up&&this._append`A${r},${r},0,${+(p>=OR)},${m},${this._x1=e+r*Math.cos(s)},${this._y1=n+r*Math.sin(s)}`)}rect(e,n,r,a){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+n}h${r=+r}v${+a}h${-r}Z`}toString(){return this._}}function DO(t){let e=3;return t.digits=function(n){if(!arguments.length)return e;if(n==null)e=null;else{const r=Math.floor(n);if(!(r>=0))throw new RangeError(`invalid digits: ${n}`);e=r}return t},()=>new DMe(e)}function RO(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function WZ(t){this._context=t}WZ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e);break}}};function CT(t){return new WZ(t)}function KZ(t){return t[0]}function YZ(t){return t[1]}function XZ(t,e){var n=ti(!0),r=null,a=CT,s=null,o=DO(l);t=typeof t=="function"?t:t===void 0?KZ:ti(t),e=typeof e=="function"?e:e===void 0?YZ:ti(e);function l(c){var u,d=(c=RO(c)).length,m,p=!1,f;for(r==null&&(s=a(f=o())),u=0;u<=d;++u)!(u=f;--y)l.point(N[y],C[y]);l.lineEnd(),l.areaEnd()}g&&(N[p]=+t(b,p,m),C[p]=+e(b,p,m),l.point(r?+r(b,p,m):N[p],n?+n(b,p,m):C[p]))}if(_)return l=null,_+""||null}function d(){return XZ().defined(a).curve(o).context(s)}return u.x=function(m){return arguments.length?(t=typeof m=="function"?m:ti(+m),r=null,u):t},u.x0=function(m){return arguments.length?(t=typeof m=="function"?m:ti(+m),u):t},u.x1=function(m){return arguments.length?(r=m==null?null:typeof m=="function"?m:ti(+m),u):r},u.y=function(m){return arguments.length?(e=typeof m=="function"?m:ti(+m),n=null,u):e},u.y0=function(m){return arguments.length?(e=typeof m=="function"?m:ti(+m),u):e},u.y1=function(m){return arguments.length?(n=m==null?null:typeof m=="function"?m:ti(+m),u):n},u.lineX0=u.lineY0=function(){return d().x(t).y(e)},u.lineY1=function(){return d().x(t).y(n)},u.lineX1=function(){return d().x(r).y(e)},u.defined=function(m){return arguments.length?(a=typeof m=="function"?m:ti(!!m),u):a},u.curve=function(m){return arguments.length?(o=m,s!=null&&(l=o(s)),u):o},u.context=function(m){return arguments.length?(m==null?s=l=null:l=o(s=m),u):s},u}class QZ{constructor(e,n){this._context=e,this._x=n}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,n){switch(e=+e,n=+n,this._point){case 0:{this._point=1,this._line?this._context.lineTo(e,n):this._context.moveTo(e,n);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,n,e,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,e,this._y0,e,n);break}}this._x0=e,this._y0=n}}function RMe(t){return new QZ(t,!0)}function FMe(t){return new QZ(t,!1)}const FO={draw(t,e){const n=Rc(e/ik);t.moveTo(n,0),t.arc(0,0,n,0,kT)}},LMe={draw(t,e){const n=Rc(e/5)/2;t.moveTo(-3*n,-n),t.lineTo(-n,-n),t.lineTo(-n,-3*n),t.lineTo(n,-3*n),t.lineTo(n,-n),t.lineTo(3*n,-n),t.lineTo(3*n,n),t.lineTo(n,n),t.lineTo(n,3*n),t.lineTo(-n,3*n),t.lineTo(-n,n),t.lineTo(-3*n,n),t.closePath()}},ZZ=Rc(1/3),OMe=ZZ*2,IMe={draw(t,e){const n=Rc(e/OMe),r=n*ZZ;t.moveTo(0,-n),t.lineTo(r,0),t.lineTo(0,n),t.lineTo(-r,0),t.closePath()}},zMe={draw(t,e){const n=Rc(e),r=-n/2;t.rect(r,r,n,n)}},UMe=.8908130915292852,JZ=rk(ik/10)/rk(7*ik/10),BMe=rk(kT/10)*JZ,HMe=-VZ(kT/10)*JZ,$Me={draw(t,e){const n=Rc(e*UMe),r=BMe*n,a=HMe*n;t.moveTo(0,-n),t.lineTo(r,a);for(let s=1;s<5;++s){const o=kT*s/5,l=VZ(o),c=rk(o);t.lineTo(c*n,-l*n),t.lineTo(l*r-c*a,c*r+l*a)}t.closePath()}},yj=Rc(3),qMe={draw(t,e){const n=-Rc(e/(yj*3));t.moveTo(0,n*2),t.lineTo(-yj*n,-n),t.lineTo(yj*n,-n),t.closePath()}},_l=-.5,Nl=Rc(3)/2,zR=1/Rc(12),VMe=(zR/2+1)*3,GMe={draw(t,e){const n=Rc(e/VMe),r=n/2,a=n*zR,s=r,o=n*zR+n,l=-s,c=o;t.moveTo(r,a),t.lineTo(s,o),t.lineTo(l,c),t.lineTo(_l*r-Nl*a,Nl*r+_l*a),t.lineTo(_l*s-Nl*o,Nl*s+_l*o),t.lineTo(_l*l-Nl*c,Nl*l+_l*c),t.lineTo(_l*r+Nl*a,_l*a-Nl*r),t.lineTo(_l*s+Nl*o,_l*o-Nl*s),t.lineTo(_l*l+Nl*c,_l*c-Nl*l),t.closePath()}};function WMe(t,e){let n=null,r=DO(a);t=typeof t=="function"?t:ti(t||FO),e=typeof e=="function"?e:ti(e===void 0?64:+e);function a(){let s;if(n||(n=s=r()),t.apply(this,arguments).draw(n,+e.apply(this,arguments)),s)return n=null,s+""||null}return a.type=function(s){return arguments.length?(t=typeof s=="function"?s:ti(s),a):t},a.size=function(s){return arguments.length?(e=typeof s=="function"?s:ti(+s),a):e},a.context=function(s){return arguments.length?(n=s??null,a):n},a}function ak(){}function sk(t,e,n){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+n)/6)}function eJ(t){this._context=t}eJ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:sk(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:sk(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function KMe(t){return new eJ(t)}function tJ(t){this._context=t}tJ.prototype={areaStart:ak,areaEnd:ak,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:sk(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function YMe(t){return new tJ(t)}function nJ(t){this._context=t}nJ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:sk(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function XMe(t){return new nJ(t)}function rJ(t){this._context=t}rJ.prototype={areaStart:ak,areaEnd:ak,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}};function QMe(t){return new rJ(t)}function lq(t){return t<0?-1:1}function cq(t,e,n){var r=t._x1-t._x0,a=e-t._x1,s=(t._y1-t._y0)/(r||a<0&&-0),o=(n-t._y1)/(a||r<0&&-0),l=(s*a+o*r)/(r+a);return(lq(s)+lq(o))*Math.min(Math.abs(s),Math.abs(o),.5*Math.abs(l))||0}function uq(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function vj(t,e,n){var r=t._x0,a=t._y0,s=t._x1,o=t._y1,l=(s-r)/3;t._context.bezierCurveTo(r+l,a+l*e,s-l,o-l*n,s,o)}function ok(t){this._context=t}ok.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:vj(this,this._t0,uq(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var n=NaN;if(t=+t,e=+e,!(t===this._x1&&e===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,vj(this,uq(this,n=cq(this,t,e)),n);break;default:vj(this,this._t0,n=cq(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n}}};function iJ(t){this._context=new aJ(t)}(iJ.prototype=Object.create(ok.prototype)).point=function(t,e){ok.prototype.point.call(this,e,t)};function aJ(t){this._context=t}aJ.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,n,r,a,s){this._context.bezierCurveTo(e,t,r,n,s,a)}};function ZMe(t){return new ok(t)}function JMe(t){return new iJ(t)}function sJ(t){this._context=t}sJ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,n=t.length;if(n)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),n===2)this._context.lineTo(t[1],e[1]);else for(var r=dq(t),a=dq(e),s=0,o=1;o=0;--e)a[e]=(o[e]-a[e+1])/s[e];for(s[n-1]=(t[n]+a[n-1])/2,e=0;e=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var n=this._x*(1-this._t)+t*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,e)}break}}this._x=t,this._y=e}};function tEe(t){return new TT(t,.5)}function nEe(t){return new TT(t,0)}function rEe(t){return new TT(t,1)}function Uf(t,e){if((o=t.length)>1)for(var n=1,r,a,s=t[e[0]],o,l=s.length;n=0;)n[e]=e;return n}function iEe(t,e){return t[e]}function aEe(t){const e=[];return e.key=t,e}function sEe(){var t=ti([]),e=UR,n=Uf,r=iEe;function a(s){var o=Array.from(t.apply(this,arguments),aEe),l,c=o.length,u=-1,d;for(const m of s)for(l=0,++u;l0){for(var n,r,a=0,s=t[0].length,o;a0){for(var n=0,r=t[e[0]],a,s=r.length;n0)||!((s=(a=t[e[0]]).length)>0))){for(var n=0,r=1,a,s,o;r1&&arguments[1]!==void 0?arguments[1]:pEe,n=10**e,r=Math.round(t*n)/n;return Object.is(r,-0)?0:r}function Mi(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r{var l=n[o-1];return typeof l=="string"?a+l+s:l!==void 0?a+gh(l)+s:a+s},"")}var Fa=t=>t===0?0:t>0?1:-1,Mc=t=>typeof t=="number"&&t!=+t,Hf=t=>typeof t=="string"&&t.indexOf("%")===t.length-1,Yt=t=>(typeof t=="number"||t instanceof Number)&&!Mc(t),Kl=t=>Yt(t)||typeof t=="string",fEe=0,O0=t=>{var e=++fEe;return"".concat(t||"").concat(e)},ws=function(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!Yt(e)&&typeof e!="string")return r;var s;if(Hf(e)){if(n==null)return r;var o=e.indexOf("%");s=n*parseFloat(e.slice(0,o))/100}else s=+e;return Mc(s)&&(s=r),a&&n!=null&&s>n&&(s=n),s},lJ=t=>{if(!Array.isArray(t))return!1;for(var e=t.length,n={},r=0;rr&&(typeof e=="function"?e(r):Bf(r,e))===n)}var gi=t=>t===null||typeof t>"u",Tw=t=>gi(t)?t:"".concat(t.charAt(0).toUpperCase()).concat(t.slice(1));function yo(t){return t!=null}function Yh(){}var gEe=["type","size","sizeType"];function BR(){return BR=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var e="symbol".concat(Tw(t));return uJ[e]||FO},NEe=(t,e,n)=>{if(e==="area")return t;switch(n){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var r=18*SEe;return 1.25*t*t*(Math.tan(r)-Math.tan(r*2)*Math.tan(r)**2)}case"triangle":return Math.sqrt(3)*t*t/4;case"wye":return(21-10*Math.sqrt(3))*t*t/8;default:return Math.PI*t*t/4}},kEe=(t,e)=>{uJ["symbol".concat(Tw(t))]=e},zO=t=>{var{type:e="circle",size:n=64,sizeType:r="area"}=t,a=vEe(t,gEe),s=vq(vq({},a),{},{type:e,size:n,sizeType:r}),o="circle";typeof e=="string"&&(o=e);var l=()=>{var p=_Ee(o),f=WMe().type(p).size(NEe(n,r,o)),y=f();if(y!==null)return y},{className:c,cx:u,cy:d}=s,m=ls(s);return Yt(u)&&Yt(d)&&Yt(n)?w.createElement("path",BR({},m,{className:hr("recharts-symbols",c),transform:"translate(".concat(u,", ").concat(d,")"),d:l()})):null};zO.registerSymbol=kEe;var dJ=t=>"radius"in t&&"startAngle"in t&&"endAngle"in t,UO=(t,e)=>{if(!t||typeof t=="function"||typeof t=="boolean")return null;var n=t;if(w.isValidElement(t)&&(n=t.props),typeof n!="object"&&typeof n!="function")return null;var r={};return Object.keys(n).forEach(a=>{EO(a)&&(r[a]=(s=>n[a](n,s)))}),r},CEe=(t,e,n)=>r=>(t(e,n,r),null),Aw=(t,e,n)=>{if(t===null||typeof t!="object"&&typeof t!="function")return null;var r=null;return Object.keys(t).forEach(a=>{var s=t[a];EO(a)&&typeof s=="function"&&(r||(r={}),r[a]=CEe(s,e,n))}),r};function wq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function TEe(t){for(var e=1;e(o[l]===void 0&&r[l]!==void 0&&(o[l]=r[l]),o),n);return s}function lk(){return lk=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var p=d.formatter||a,f=hr({"recharts-legend-item":!0,["legend-item-".concat(m)]:!0,inactive:d.inactive});if(d.type==="none")return null;var y=d.inactive?s:d.color,v=p?p(d.value,d,m):d.value;return w.createElement("li",lk({className:f,style:c,key:"legend-item-".concat(m)},Aw(t,d,m)),w.createElement(jO,{width:n,height:n,viewBox:l,style:u,"aria-label":"".concat(v," legend icon")},w.createElement(LEe,{data:d,iconType:o,inactiveColor:s})),w.createElement("span",{className:"recharts-legend-item-text",style:{color:y}},v))})}var IEe=t=>{var e=wi(t,FEe),{payload:n,layout:r,align:a}=e;if(!n||!n.length)return null;var s={padding:0,margin:0,textAlign:r==="horizontal"?a:"left"};return w.createElement("ul",{className:"recharts-default-legend",style:s},w.createElement(OEe,lk({},e,{payload:n})))},A2={},P2={},_q;function zEe(){return _q||(_q=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r){const a=new Map;for(let s=0;s=0}t.isLength=e})(R2)),R2}var Tq;function BO(){return Tq||(Tq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=BEe();function n(r){return r!=null&&typeof r!="function"&&e.isLength(r.length)}t.isArrayLike=n})(D2)),D2}var F2={},Aq;function HEe(){return Aq||(Aq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="object"&&n!==null}t.isObjectLike=e})(F2)),F2}var Pq;function $Ee(){return Pq||(Pq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=BO(),n=HEe();function r(a){return n.isObjectLike(a)&&e.isArrayLike(a)}t.isArrayLikeObject=r})(j2)),j2}var L2={},O2={},Mq;function qEe(){return Mq||(Mq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=IO();function n(r){return function(a){return e.get(a,r)}}t.property=n})(O2)),O2}var I2={},z2={},U2={},B2={},Eq;function hJ(){return Eq||(Eq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n!==null&&(typeof n=="object"||typeof n=="function")}t.isObject=e})(B2)),B2}var H2={},jq;function pJ(){return jq||(jq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n==null||typeof n!="object"&&typeof n!="function"}t.isPrimitive=e})(H2)),H2}var $2={},Dq;function fJ(){return Dq||(Dq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r){return n===r||Number.isNaN(n)&&Number.isNaN(r)}t.isEqualsSameValueZero=e})($2)),$2}var Rq;function VEe(){return Rq||(Rq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=hJ(),n=pJ(),r=fJ();function a(d,m,p){return typeof p!="function"?a(d,m,()=>{}):s(d,m,function f(y,v,b,g,_,N){const C=p(y,v,b,g,_,N);return C!==void 0?!!C:s(y,v,f,N)},new Map)}function s(d,m,p,f){if(m===d)return!0;switch(typeof m){case"object":return o(d,m,p,f);case"function":return Object.keys(m).length>0?s(d,{...m},p,f):r.isEqualsSameValueZero(d,m);default:return e.isObject(d)?typeof m=="string"?m==="":!0:r.isEqualsSameValueZero(d,m)}}function o(d,m,p,f){if(m==null)return!0;if(Array.isArray(m))return c(d,m,p,f);if(m instanceof Map)return l(d,m,p,f);if(m instanceof Set)return u(d,m,p,f);const y=Object.keys(m);if(d==null||n.isPrimitive(d))return y.length===0;if(y.length===0)return!0;if(f?.has(m))return f.get(m)===d;f?.set(m,d);try{for(let v=0;v{})}t.isMatch=n})(z2)),z2}var q2={},V2={},G2={},Lq;function GEe(){return Lq||(Lq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Object.getOwnPropertySymbols(n).filter(r=>Object.prototype.propertyIsEnumerable.call(n,r))}t.getSymbols=e})(G2)),G2}var W2={},Oq;function HO(){return Oq||(Oq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n==null?n===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(n)}t.getTag=e})(W2)),W2}var K2={},Iq;function bJ(){return Iq||(Iq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e="[object RegExp]",n="[object String]",r="[object Number]",a="[object Boolean]",s="[object Arguments]",o="[object Symbol]",l="[object Date]",c="[object Map]",u="[object Set]",d="[object Array]",m="[object Function]",p="[object ArrayBuffer]",f="[object Object]",y="[object Error]",v="[object DataView]",b="[object Uint8Array]",g="[object Uint8ClampedArray]",_="[object Uint16Array]",N="[object Uint32Array]",C="[object BigUint64Array]",k="[object Int8Array]",P="[object Int16Array]",T="[object Int32Array]",D="[object BigInt64Array]",A="[object Float32Array]",R="[object Float64Array]";t.argumentsTag=s,t.arrayBufferTag=p,t.arrayTag=d,t.bigInt64ArrayTag=D,t.bigUint64ArrayTag=C,t.booleanTag=a,t.dataViewTag=v,t.dateTag=l,t.errorTag=y,t.float32ArrayTag=A,t.float64ArrayTag=R,t.functionTag=m,t.int16ArrayTag=P,t.int32ArrayTag=T,t.int8ArrayTag=k,t.mapTag=c,t.numberTag=r,t.objectTag=f,t.regexpTag=e,t.setTag=u,t.stringTag=n,t.symbolTag=o,t.uint16ArrayTag=_,t.uint32ArrayTag=N,t.uint8ArrayTag=b,t.uint8ClampedArrayTag=g})(K2)),K2}var Y2={},zq;function WEe(){return zq||(zq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}t.isTypedArray=e})(Y2)),Y2}var Uq;function xJ(){return Uq||(Uq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=GEe(),n=HO(),r=bJ(),a=pJ(),s=WEe();function o(d,m){return l(d,void 0,d,new Map,m)}function l(d,m,p,f=new Map,y=void 0){const v=y?.(d,m,p,f);if(v!==void 0)return v;if(a.isPrimitive(d))return d;if(f.has(d))return f.get(d);if(Array.isArray(d)){const b=new Array(d.length);f.set(d,b);for(let g=0;ge.isMatch(s,a)}t.matches=r})(I2)),I2}var X2={},Q2={},Z2={},$q;function XEe(){return $q||($q=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=xJ(),n=HO(),r=bJ();function a(s,o){return e.cloneDeepWith(s,(l,c,u,d)=>{const m=o?.(l,c,u,d);if(m!==void 0)return m;if(typeof s=="object"){if(n.getTag(s)===r.objectTag&&typeof s.constructor!="function"){const p={};return d.set(s,p),e.copyProperties(p,s,u,d),p}switch(Object.prototype.toString.call(s)){case r.numberTag:case r.stringTag:case r.booleanTag:{const p=new s.constructor(s?.valueOf());return e.copyProperties(p,s),p}case r.argumentsTag:{const p={};return e.copyProperties(p,s),p.length=s.length,p[Symbol.iterator]=s[Symbol.iterator],p}default:return}}})}t.cloneDeepWith=a})(Z2)),Z2}var qq;function QEe(){return qq||(qq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=XEe();function n(r){return e.cloneDeepWith(r)}t.cloneDeep=n})(Q2)),Q2}var J2={},ej={},Vq;function yJ(){return Vq||(Vq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=/^(?:0|[1-9]\d*)$/;function n(r,a=Number.MAX_SAFE_INTEGER){switch(typeof r){case"number":return Number.isInteger(r)&&r>=0&&rt,Jr=()=>{var t=w.useContext($O);return t?t.store.dispatch:o2e},mN=()=>{},l2e=()=>mN,c2e=(t,e)=>t===e;function en(t){var e=w.useContext($O),n=w.useMemo(()=>e?r=>{if(r!=null)return t(r)}:mN,[e,t]);return wJ.useSyncExternalStoreWithSelector(e?e.subscription.addNestedSub:l2e,e?e.store.getState:mN,e?e.store.getState:mN,n,c2e)}function u2e(t,e=`expected a function, instead received ${typeof t}`){if(typeof t!="function")throw new TypeError(e)}function d2e(t,e=`expected an object, instead received ${typeof t}`){if(typeof t!="object")throw new TypeError(e)}function m2e(t,e="expected all items to be functions, instead received the following types: "){if(!t.every(n=>typeof n=="function")){const n=t.map(r=>typeof r=="function"?`function ${r.name||"unnamed"}()`:typeof r).join(", ");throw new TypeError(`${e}[${n}]`)}}var tV=t=>Array.isArray(t)?t:[t];function h2e(t){const e=Array.isArray(t[0])?t[0]:t;return m2e(e,"createSelector expects all input-selectors to be functions, but received the following types: "),e}function p2e(t,e){const n=[],{length:r}=t;for(let a=0;a{n=f1(),o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function x2e(t,...e){const n=typeof t=="function"?{memoize:t,memoizeOptions:e}:t,r=(...a)=>{let s=0,o=0,l,c={},u=a.pop();typeof u=="object"&&(c=u,u=a.pop()),u2e(u,`createSelector expects an output function after the inputs, but received: [${typeof u}]`);const d={...n,...c},{memoize:m,memoizeOptions:p=[],argsMemoize:f=SJ,argsMemoizeOptions:y=[]}=d,v=tV(p),b=tV(y),g=h2e(a),_=m(function(){return s++,u.apply(null,arguments)},...v),N=f(function(){o++;const k=p2e(g,arguments);return l=_.apply(null,k),l},...b);return Object.assign(N,{resultFunc:u,memoizedResultFunc:_,dependencies:g,dependencyRecomputations:()=>o,resetDependencyRecomputations:()=>{o=0},lastResult:()=>l,recomputations:()=>s,resetRecomputations:()=>{s=0},memoize:m,argsMemoize:f})};return Object.assign(r,{withTypes:()=>r}),r}var yt=x2e(SJ),y2e=Object.assign((t,e=yt)=>{d2e(t,`createStructuredSelector expects first argument to be an object where each property is a selector, instead received a ${typeof t}`);const n=Object.keys(t),r=n.map(s=>t[s]);return e(r,(...s)=>s.reduce((o,l,c)=>(o[n[c]]=l,o),{}))},{withTypes:()=>y2e}),aj={},sj={},oj={},rV;function v2e(){return rV||(rV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(r){return typeof r=="symbol"?1:r===null?2:r===void 0?3:r!==r?4:0}const n=(r,a,s)=>{if(r!==a){const o=e(r),l=e(a);if(o===l&&o===0){if(ra)return s==="desc"?-1:1}return s==="desc"?l-o:o-l}return 0};t.compareValues=n})(oj)),oj}var lj={},cj={},iV;function _J(){return iV||(iV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="symbol"||n instanceof Symbol}t.isSymbol=e})(cj)),cj}var aV;function w2e(){return aV||(aV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=_J(),n=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,r=/^\w*$/;function a(s,o){return Array.isArray(s)?!1:typeof s=="number"||typeof s=="boolean"||s==null||e.isSymbol(s)?!0:typeof s=="string"&&(r.test(s)||!n.test(s))||o!=null&&Object.hasOwn(o,s)}t.isKey=a})(lj)),lj}var sV;function S2e(){return sV||(sV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=v2e(),n=w2e(),r=OO();function a(s,o,l,c){if(s==null)return[];l=c?void 0:l,Array.isArray(s)||(s=Object.values(s)),Array.isArray(o)||(o=o==null?[null]:[o]),o.length===0&&(o=[null]),Array.isArray(l)||(l=l==null?[]:[l]),l=l.map(f=>String(f));const u=(f,y)=>{let v=f;for(let b=0;by==null||f==null?y:typeof f=="object"&&"key"in f?Object.hasOwn(y,f.key)?y[f.key]:u(y,f.path):typeof f=="function"?f(y):Array.isArray(f)?u(y,f):typeof y=="object"?y[f]:y,m=o.map(f=>(Array.isArray(f)&&f.length===1&&(f=f[0]),f==null||typeof f=="function"||Array.isArray(f)||n.isKey(f)?f:{key:f,path:r.toPath(f)}));return s.map(f=>({original:f,criteria:m.map(y=>d(y,f))})).slice().sort((f,y)=>{for(let v=0;vf.original)}t.orderBy=a})(sj)),sj}var uj={},oV;function _2e(){return oV||(oV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r=1){const a=[],s=Math.floor(r),o=(l,c)=>{for(let u=0;u1&&r.isIterateeCall(s,o[0],o[1])?o=[]:l>2&&r.isIterateeCall(o[0],o[1],o[2])&&(o=[o[0]]),e.orderBy(s,n.flatten(o),["asc"])}t.sortBy=a})(aj)),aj}var mj,uV;function k2e(){return uV||(uV=1,mj=N2e().sortBy),mj}var C2e=k2e();const AT=Zl(C2e);var kJ=t=>t.legend.settings,T2e=t=>t.legend.size,A2e=t=>t.legend.payload,P2e=yt([A2e,kJ],(t,e)=>{var{itemSorter:n}=e,r=t.flat(1);return n?AT(r,n):r});function M2e(){return en(P2e)}var g1=1;function CJ(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],[e,n]=w.useState({height:0,left:0,top:0,width:0}),r=w.useCallback(a=>{if(a!=null){var s=a.getBoundingClientRect(),o={height:s.height,left:s.left,top:s.top,width:s.width};(Math.abs(o.height-e.height)>g1||Math.abs(o.left-e.left)>g1||Math.abs(o.top-e.top)>g1||Math.abs(o.width-e.width)>g1)&&n({height:o.height,left:o.left,top:o.top,width:o.width})}},[e.width,e.height,e.top,e.left,...t]);return[e,r]}function Qa(t){return`Minified Redux error #${t}; visit https://redux.js.org/Errors?code=${t} for the full message or use the non-minified dev environment for full errors. `}var E2e=typeof Symbol=="function"&&Symbol.observable||"@@observable",dV=E2e,hj=()=>Math.random().toString(36).substring(7).split("").join("."),j2e={INIT:`@@redux/INIT${hj()}`,REPLACE:`@@redux/REPLACE${hj()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${hj()}`},ck=j2e;function qO(t){if(typeof t!="object"||t===null)return!1;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e||Object.getPrototypeOf(t)===null}function TJ(t,e,n){if(typeof t!="function")throw new Error(Qa(2));if(typeof e=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(Qa(0));if(typeof e=="function"&&typeof n>"u"&&(n=e,e=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(Qa(1));return n(TJ)(t,e)}let r=t,a=e,s=new Map,o=s,l=0,c=!1;function u(){o===s&&(o=new Map,s.forEach((b,g)=>{o.set(g,b)}))}function d(){if(c)throw new Error(Qa(3));return a}function m(b){if(typeof b!="function")throw new Error(Qa(4));if(c)throw new Error(Qa(5));let g=!0;u();const _=l++;return o.set(_,b),function(){if(g){if(c)throw new Error(Qa(6));g=!1,u(),o.delete(_),s=null}}}function p(b){if(!qO(b))throw new Error(Qa(7));if(typeof b.type>"u")throw new Error(Qa(8));if(typeof b.type!="string")throw new Error(Qa(17));if(c)throw new Error(Qa(9));try{c=!0,a=r(a,b)}finally{c=!1}return(s=o).forEach(_=>{_()}),b}function f(b){if(typeof b!="function")throw new Error(Qa(10));r=b,p({type:ck.REPLACE})}function y(){const b=m;return{subscribe(g){if(typeof g!="object"||g===null)throw new Error(Qa(11));function _(){const C=g;C.next&&C.next(d())}return _(),{unsubscribe:b(_)}},[dV](){return this}}}return p({type:ck.INIT}),{dispatch:p,subscribe:m,getState:d,replaceReducer:f,[dV]:y}}function D2e(t){Object.keys(t).forEach(e=>{const n=t[e];if(typeof n(void 0,{type:ck.INIT})>"u")throw new Error(Qa(12));if(typeof n(void 0,{type:ck.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(Qa(13))})}function AJ(t){const e=Object.keys(t),n={};for(let s=0;s"u")throw l&&l.type,new Error(Qa(14));u[m]=y,c=c||y!==f}return c=c||r.length!==Object.keys(o).length,c?u:o}}function uk(...t){return t.length===0?e=>e:t.length===1?t[0]:t.reduce((e,n)=>(...r)=>e(n(...r)))}function R2e(...t){return e=>(n,r)=>{const a=e(n,r);let s=()=>{throw new Error(Qa(15))};const o={getState:a.getState,dispatch:(c,...u)=>s(c,...u)},l=t.map(c=>c(o));return s=uk(...l)(a.dispatch),{...a,dispatch:s}}}function PJ(t){return qO(t)&&"type"in t&&typeof t.type=="string"}var MJ=Symbol.for("immer-nothing"),mV=Symbol.for("immer-draftable"),Xs=Symbol.for("immer-state");function gc(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var Qo=Object,_x=Qo.getPrototypeOf,dk="constructor",PT="prototype",HR="configurable",mk="enumerable",hN="writable",I0="value",Wd=t=>!!t&&!!t[Xs];function Ec(t){return t?EJ(t)||ET(t)||!!t[mV]||!!t[dk]?.[mV]||jT(t)||DT(t):!1}var F2e=Qo[PT][dk].toString(),hV=new WeakMap;function EJ(t){if(!t||!VO(t))return!1;const e=_x(t);if(e===null||e===Qo[PT])return!0;const n=Qo.hasOwnProperty.call(e,dk)&&e[dk];if(n===Object)return!0;if(!Db(n))return!1;let r=hV.get(n);return r===void 0&&(r=Function.toString.call(n),hV.set(n,r)),r===F2e}function MT(t,e,n=!0){Pw(t)===0?(n?Reflect.ownKeys(t):Qo.keys(t)).forEach(a=>{e(a,t[a],t)}):t.forEach((r,a)=>e(a,r,t))}function Pw(t){const e=t[Xs];return e?e.type_:ET(t)?1:jT(t)?2:DT(t)?3:0}var pV=(t,e,n=Pw(t))=>n===2?t.has(e):Qo[PT].hasOwnProperty.call(t,e),$R=(t,e,n=Pw(t))=>n===2?t.get(e):t[e],hk=(t,e,n,r=Pw(t))=>{r===2?t.set(e,n):r===3?t.add(n):t[e]=n};function L2e(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}var ET=Array.isArray,jT=t=>t instanceof Map,DT=t=>t instanceof Set,VO=t=>typeof t=="object",Db=t=>typeof t=="function",pj=t=>typeof t=="boolean";function O2e(t){const e=+t;return Number.isInteger(e)&&String(e)===t}var xd=t=>t.copy_||t.base_,GO=t=>t.modified_?t.copy_:t.base_;function qR(t,e){if(jT(t))return new Map(t);if(DT(t))return new Set(t);if(ET(t))return Array[PT].slice.call(t);const n=EJ(t);if(e===!0||e==="class_only"&&!n){const r=Qo.getOwnPropertyDescriptors(t);delete r[Xs];let a=Reflect.ownKeys(r);for(let s=0;s1&&Qo.defineProperties(t,{set:b1,add:b1,clear:b1,delete:b1}),Qo.freeze(t),e&&MT(t,(n,r)=>{WO(r,!0)},!1)),t}function I2e(){gc(2)}var b1={[I0]:I2e};function RT(t){return t===null||!VO(t)?!0:Qo.isFrozen(t)}var pk="MapSet",VR="Patches",fV="ArrayMethods",jJ={};function $f(t){const e=jJ[t];return e||gc(0,t),e}var gV=t=>!!jJ[t],z0,DJ=()=>z0,z2e=(t,e)=>({drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:gV(pk)?$f(pk):void 0,arrayMethodsPlugin_:gV(fV)?$f(fV):void 0});function bV(t,e){e&&(t.patchPlugin_=$f(VR),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function GR(t){WR(t),t.drafts_.forEach(U2e),t.drafts_=null}function WR(t){t===z0&&(z0=t.parent_)}var xV=t=>z0=z2e(z0,t);function U2e(t){const e=t[Xs];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function yV(t,e){e.unfinalizedDrafts_=e.drafts_.length;const n=e.drafts_[0];if(t!==void 0&&t!==n){n[Xs].modified_&&(GR(e),gc(4)),Ec(t)&&(t=vV(e,t));const{patchPlugin_:a}=e;a&&a.generateReplacementPatches_(n[Xs].base_,t,e)}else t=vV(e,n);return B2e(e,t,!0),GR(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==MJ?t:void 0}function vV(t,e){if(RT(e))return e;const n=e[Xs];if(!n)return fk(e,t.handledSet_,t);if(!FT(n,t))return e;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:r}=n;if(r)for(;r.length>0;)r.pop()(t);LJ(n,t)}return n.copy_}function B2e(t,e,n=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&WO(e,n)}function RJ(t){t.finalized_=!0,t.scope_.unfinalizedDrafts_--}var FT=(t,e)=>t.scope_===e,H2e=[];function FJ(t,e,n,r){const a=xd(t),s=t.type_;if(r!==void 0&&$R(a,r,s)===e){hk(a,r,n,s);return}if(!t.draftLocations_){const l=t.draftLocations_=new Map;MT(a,(c,u)=>{if(Wd(u)){const d=l.get(u)||[];d.push(c),l.set(u,d)}})}const o=t.draftLocations_.get(e)??H2e;for(const l of o)hk(a,l,n,s)}function $2e(t,e,n){t.callbacks_.push(function(a){const s=e;if(!s||!FT(s,a))return;a.mapSetPlugin_?.fixSetContents(s);const o=GO(s);FJ(t,s.draft_??s,o,n),LJ(s,a)})}function LJ(t,e){if(t.modified_&&!t.finalized_&&(t.type_===3||t.type_===1&&t.allIndicesReassigned_||(t.assigned_?.size??0)>0)){const{patchPlugin_:r}=e;if(r){const a=r.getPath(t);a&&r.generatePatches_(t,a,e)}RJ(t)}}function q2e(t,e,n){const{scope_:r}=t;if(Wd(n)){const a=n[Xs];FT(a,r)&&a.callbacks_.push(function(){pN(t);const o=GO(a);FJ(t,n,o,e)})}else Ec(n)&&t.callbacks_.push(function(){const s=xd(t);t.type_===3?s.has(n)&&fk(n,r.handledSet_,r):$R(s,e,t.type_)===n&&r.drafts_.length>1&&(t.assigned_.get(e)??!1)===!0&&t.copy_&&fk($R(t.copy_,e,t.type_),r.handledSet_,r)})}function fk(t,e,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||Wd(t)||e.has(t)||!Ec(t)||RT(t)||(e.add(t),MT(t,(r,a)=>{if(Wd(a)){const s=a[Xs];if(FT(s,n)){const o=GO(s);hk(t,r,o,t.type_),RJ(s)}}else Ec(a)&&fk(a,e,n)})),t}function V2e(t,e){const n=ET(t),r={type_:n?1:0,scope_:e?e.scope_:DJ(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let a=r,s=gk;n&&(a=[r],s=U0);const{revoke:o,proxy:l}=Proxy.revocable(a,s);return r.draft_=l,r.revoke_=o,[l,r]}var gk={get(t,e){if(e===Xs)return t;let n=t.scope_.arrayMethodsPlugin_;const r=t.type_===1&&typeof e=="string";if(r&&n?.isArrayOperationMethod(e))return n.createMethodInterceptor(t,e);const a=xd(t);if(!pV(a,e,t.type_))return G2e(t,a,e);const s=a[e];if(t.finalized_||!Ec(s)||r&&t.operationMethod&&n?.isMutatingArrayMethod(t.operationMethod)&&O2e(e))return s;if(s===fj(t.base_,e)){pN(t);const o=t.type_===1?+e:e,l=YR(t.scope_,s,t,o);return t.copy_[o]=l}return s},has(t,e){return e in xd(t)},ownKeys(t){return Reflect.ownKeys(xd(t))},set(t,e,n){const r=OJ(xd(t),e);if(r?.set)return r.set.call(t.draft_,n),!0;if(!t.modified_){const a=fj(xd(t),e),s=a?.[Xs];if(s&&s.base_===n)return t.copy_[e]=n,t.assigned_.set(e,!1),!0;if(L2e(n,a)&&(n!==void 0||pV(t.base_,e,t.type_)))return!0;pN(t),KR(t)}return t.copy_[e]===n&&(n!==void 0||e in t.copy_)||Number.isNaN(n)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=n,t.assigned_.set(e,!0),q2e(t,e,n)),!0},deleteProperty(t,e){return pN(t),fj(t.base_,e)!==void 0||e in t.base_?(t.assigned_.set(e,!1),KR(t)):t.assigned_.delete(e),t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){const n=xd(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{[hN]:!0,[HR]:t.type_!==1||e!=="length",[mk]:r[mk],[I0]:n[e]}},defineProperty(){gc(11)},getPrototypeOf(t){return _x(t.base_)},setPrototypeOf(){gc(12)}},U0={};for(let t in gk){let e=gk[t];U0[t]=function(){const n=arguments;return n[0]=n[0][0],e.apply(this,n)}}U0.deleteProperty=function(t,e){return U0.set.call(this,t,e,void 0)};U0.set=function(t,e,n){return gk.set.call(this,t[0],e,n,t[0])};function fj(t,e){const n=t[Xs];return(n?xd(n):t)[e]}function G2e(t,e,n){const r=OJ(e,n);return r?I0 in r?r[I0]:r.get?.call(t.draft_):void 0}function OJ(t,e){if(!(e in t))return;let n=_x(t);for(;n;){const r=Object.getOwnPropertyDescriptor(n,e);if(r)return r;n=_x(n)}}function KR(t){t.modified_||(t.modified_=!0,t.parent_&&KR(t.parent_))}function pN(t){t.copy_||(t.assigned_=new Map,t.copy_=qR(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var W2e=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(n,r,a)=>{if(Db(n)&&!Db(r)){const o=r;r=n;const l=this;return function(u=o,...d){return l.produce(u,m=>r.call(this,m,...d))}}Db(r)||gc(6),a!==void 0&&!Db(a)&&gc(7);let s;if(Ec(n)){const o=xV(this),l=YR(o,n,void 0);let c=!0;try{s=r(l),c=!1}finally{c?GR(o):WR(o)}return bV(o,a),yV(s,o)}else if(!n||!VO(n)){if(s=r(n),s===void 0&&(s=n),s===MJ&&(s=void 0),this.autoFreeze_&&WO(s,!0),a){const o=[],l=[];$f(VR).generateReplacementPatches_(n,s,{patches_:o,inversePatches_:l}),a(o,l)}return s}else gc(1,n)},this.produceWithPatches=(n,r)=>{if(Db(n))return(l,...c)=>this.produceWithPatches(l,u=>n(u,...c));let a,s;return[this.produce(n,r,(l,c)=>{a=l,s=c}),a,s]},pj(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),pj(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),pj(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){Ec(e)||gc(8),Wd(e)&&(e=Nc(e));const n=xV(this),r=YR(n,e,void 0);return r[Xs].isManual_=!0,WR(n),r}finishDraft(e,n){const r=e&&e[Xs];(!r||!r.isManual_)&&gc(9);const{scope_:a}=r;return bV(a,n),yV(void 0,a)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,n){let r;for(r=n.length-1;r>=0;r--){const s=n[r];if(s.path.length===0&&s.op==="replace"){e=s.value;break}}r>-1&&(n=n.slice(r+1));const a=$f(VR).applyPatches_;return Wd(e)?a(e,n):this.produce(e,s=>a(s,n))}};function YR(t,e,n,r){const[a,s]=jT(e)?$f(pk).proxyMap_(e,n):DT(e)?$f(pk).proxySet_(e,n):V2e(e,n);return(n?.scope_??DJ()).drafts_.push(a),s.callbacks_=n?.callbacks_??[],s.key_=r,n&&r!==void 0?$2e(n,s,r):s.callbacks_.push(function(c){c.mapSetPlugin_?.fixSetContents(s);const{patchPlugin_:u}=c;s.modified_&&u&&u.generatePatches_(s,[],c)}),a}function Nc(t){return Wd(t)||gc(10,t),IJ(t)}function IJ(t){if(!Ec(t)||RT(t))return t;const e=t[Xs];let n,r=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,n=qR(t,e.scope_.immer_.useStrictShallowCopy_),r=e.scope_.immer_.shouldUseStrictIteration()}else n=qR(t,!0);return MT(n,(a,s)=>{hk(n,a,IJ(s))},r),e&&(e.finalized_=!1),n}var K2e=new W2e,zJ=K2e.produce;function UJ(t){return({dispatch:n,getState:r})=>a=>s=>typeof s=="function"?s(n,r,t):a(s)}var Y2e=UJ(),X2e=UJ,Q2e=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]=="object"?uk:uk.apply(null,arguments)};function Yl(t,e){function n(...r){if(e){let a=e(...r);if(!a)throw new Error(tl(0));return{type:t,payload:a.payload,..."meta"in a&&{meta:a.meta},..."error"in a&&{error:a.error}}}return{type:t,payload:r[0]}}return n.toString=()=>`${t}`,n.type=t,n.match=r=>PJ(r)&&r.type===t,n}var BJ=class Fv extends Array{constructor(...e){super(...e),Object.setPrototypeOf(this,Fv.prototype)}static get[Symbol.species](){return Fv}concat(...e){return super.concat.apply(this,e)}prepend(...e){return e.length===1&&Array.isArray(e[0])?new Fv(...e[0].concat(this)):new Fv(...e.concat(this))}};function wV(t){return Ec(t)?zJ(t,()=>{}):t}function x1(t,e,n){return t.has(e)?t.get(e):t.set(e,n(e)).get(e)}function Z2e(t){return typeof t=="boolean"}var J2e=()=>function(e){const{thunk:n=!0,immutableCheck:r=!0,serializableCheck:a=!0,actionCreatorCheck:s=!0}=e??{};let o=new BJ;return n&&(Z2e(n)?o.push(Y2e):o.push(X2e(n.extraArgument))),o},HJ="RTK_autoBatch",mi=()=>t=>({payload:t,meta:{[HJ]:!0}}),SV=t=>e=>{setTimeout(e,t)},$J=(t={type:"raf"})=>e=>(...n)=>{const r=e(...n);let a=!0,s=!1,o=!1;const l=new Set,c=t.type==="tick"?queueMicrotask:t.type==="raf"?typeof window<"u"&&window.requestAnimationFrame?window.requestAnimationFrame:SV(10):t.type==="callback"?t.queueNotification:SV(t.timeout),u=()=>{o=!1,s&&(s=!1,l.forEach(d=>d()))};return Object.assign({},r,{subscribe(d){const m=()=>a&&d(),p=r.subscribe(m);return l.add(d),()=>{p(),l.delete(d)}},dispatch(d){try{return a=!d?.meta?.[HJ],s=!a,s&&(o||(o=!0,c(u))),r.dispatch(d)}finally{a=!0}}})},eje=t=>function(n){const{autoBatch:r=!0}=n??{};let a=new BJ(t);return r&&a.push($J(typeof r=="object"?r:void 0)),a};function tje(t){const e=J2e(),{reducer:n=void 0,middleware:r,devTools:a=!0,preloadedState:s=void 0,enhancers:o=void 0}=t||{};let l;if(typeof n=="function")l=n;else if(qO(n))l=AJ(n);else throw new Error(tl(1));let c;typeof r=="function"?c=r(e):c=e();let u=uk;a&&(u=Q2e({trace:!1,...typeof a=="object"&&a}));const d=R2e(...c),m=eje(d);let p=typeof o=="function"?o(m):m();const f=u(...p);return TJ(l,s,f)}function qJ(t){const e={},n=[];let r;const a={addCase(s,o){const l=typeof s=="string"?s:s.type;if(!l)throw new Error(tl(28));if(l in e)throw new Error(tl(29));return e[l]=o,a},addAsyncThunk(s,o){return o.pending&&(e[s.pending.type]=o.pending),o.rejected&&(e[s.rejected.type]=o.rejected),o.fulfilled&&(e[s.fulfilled.type]=o.fulfilled),o.settled&&n.push({matcher:s.settled,reducer:o.settled}),a},addMatcher(s,o){return n.push({matcher:s,reducer:o}),a},addDefaultCase(s){return r=s,a}};return t(a),[e,n,r]}function nje(t){return typeof t=="function"}function rje(t,e){let[n,r,a]=qJ(e),s;if(nje(t))s=()=>wV(t());else{const l=wV(t);s=()=>l}function o(l=s(),c){let u=[n[c.type],...r.filter(({matcher:d})=>d(c)).map(({reducer:d})=>d)];return u.filter(d=>!!d).length===0&&(u=[a]),u.reduce((d,m)=>{if(m)if(Wd(d)){const f=m(d,c);return f===void 0?d:f}else{if(Ec(d))return zJ(d,p=>m(p,c));{const p=m(d,c);if(p===void 0){if(d===null)return d;throw Error("A case reducer on a non-draftable value must not return undefined")}return p}}return d},l)}return o.getInitialState=s,o}var ije="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW",aje=(t=21)=>{let e="",n=t;for(;n--;)e+=ije[Math.random()*64|0];return e},sje=Symbol.for("rtk-slice-createasyncthunk");function oje(t,e){return`${t}/${e}`}function lje({creators:t}={}){const e=t?.asyncThunk?.[sje];return function(r){const{name:a,reducerPath:s=a}=r;if(!a)throw new Error(tl(11));const o=(typeof r.reducers=="function"?r.reducers(uje()):r.reducers)||{},l=Object.keys(o),c={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},u={addCase(N,C){const k=typeof N=="string"?N:N.type;if(!k)throw new Error(tl(12));if(k in c.sliceCaseReducersByType)throw new Error(tl(13));return c.sliceCaseReducersByType[k]=C,u},addMatcher(N,C){return c.sliceMatchers.push({matcher:N,reducer:C}),u},exposeAction(N,C){return c.actionCreators[N]=C,u},exposeCaseReducer(N,C){return c.sliceCaseReducersByName[N]=C,u}};l.forEach(N=>{const C=o[N],k={reducerName:N,type:oje(a,N),createNotation:typeof r.reducers=="function"};mje(C)?pje(k,C,u,e):dje(k,C,u)});function d(){const[N={},C=[],k=void 0]=typeof r.extraReducers=="function"?qJ(r.extraReducers):[r.extraReducers],P={...N,...c.sliceCaseReducersByType};return rje(r.initialState,T=>{for(let D in P)T.addCase(D,P[D]);for(let D of c.sliceMatchers)T.addMatcher(D.matcher,D.reducer);for(let D of C)T.addMatcher(D.matcher,D.reducer);k&&T.addDefaultCase(k)})}const m=N=>N,p=new Map,f=new WeakMap;let y;function v(N,C){return y||(y=d()),y(N,C)}function b(){return y||(y=d()),y.getInitialState()}function g(N,C=!1){function k(T){let D=T[N];return typeof D>"u"&&C&&(D=x1(f,k,b)),D}function P(T=m){const D=x1(p,C,()=>new WeakMap);return x1(D,T,()=>{const A={};for(const[R,G]of Object.entries(r.selectors??{}))A[R]=cje(G,T,()=>x1(f,T,b),C);return A})}return{reducerPath:N,getSelectors:P,get selectors(){return P(k)},selectSlice:k}}const _={name:a,reducer:v,actions:c.actionCreators,caseReducers:c.sliceCaseReducersByName,getInitialState:b,...g(s),injectInto(N,{reducerPath:C,...k}={}){const P=C??s;return N.inject({reducerPath:P,reducer:v},k),{..._,...g(P,!0)}}};return _}}function cje(t,e,n,r){function a(s,...o){let l=e(s);return typeof l>"u"&&r&&(l=n()),t(l,...o)}return a.unwrapped=t,a}var Ao=lje();function uje(){function t(e,n){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...n}}return t.withTypes=()=>t,{reducer(e){return Object.assign({[e.name](...n){return e(...n)}}[e.name],{_reducerDefinitionType:"reducer"})},preparedReducer(e,n){return{_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:n}},asyncThunk:t}}function dje({type:t,reducerName:e,createNotation:n},r,a){let s,o;if("reducer"in r){if(n&&!hje(r))throw new Error(tl(17));s=r.reducer,o=r.prepare}else s=r;a.addCase(t,s).exposeCaseReducer(e,s).exposeAction(e,o?Yl(t,o):Yl(t))}function mje(t){return t._reducerDefinitionType==="asyncThunk"}function hje(t){return t._reducerDefinitionType==="reducerWithPrepare"}function pje({type:t,reducerName:e},n,r,a){if(!a)throw new Error(tl(18));const{payloadCreator:s,fulfilled:o,pending:l,rejected:c,settled:u,options:d}=n,m=a(t,s,d);r.exposeAction(e,m),o&&r.addCase(m.fulfilled,o),l&&r.addCase(m.pending,l),c&&r.addCase(m.rejected,c),u&&r.addMatcher(m.settled,u),r.exposeCaseReducer(e,{fulfilled:o||y1,pending:l||y1,rejected:c||y1,settled:u||y1})}function y1(){}var fje="task",VJ="listener",GJ="completed",KO="cancelled",gje=`task-${KO}`,bje=`task-${GJ}`,XR=`${VJ}-${KO}`,xje=`${VJ}-${GJ}`,LT=class{constructor(t){this.code=t,this.message=`${fje} ${KO} (reason: ${t})`}name="TaskAbortError";message},YO=(t,e)=>{if(typeof t!="function")throw new TypeError(tl(32))},bk=()=>{},WJ=(t,e=bk)=>(t.catch(e),t),KJ=(t,e)=>(t.addEventListener("abort",e,{once:!0}),()=>t.removeEventListener("abort",e)),gf=t=>{if(t.aborted)throw new LT(t.reason)};function YJ(t,e){let n=bk;return new Promise((r,a)=>{const s=()=>a(new LT(t.reason));if(t.aborted){s();return}n=KJ(t,s),e.finally(()=>n()).then(r,a)}).finally(()=>{n=bk})}var yje=async(t,e)=>{try{return await Promise.resolve(),{status:"ok",value:await t()}}catch(n){return{status:n instanceof LT?"cancelled":"rejected",error:n}}finally{e?.()}},xk=t=>e=>WJ(YJ(t,e).then(n=>(gf(t),n))),XJ=t=>{const e=xk(t);return n=>e(new Promise(r=>setTimeout(r,n)))},{assign:tx}=Object,_V={},OT="listenerMiddleware",vje=(t,e)=>{const n=r=>KJ(t,()=>r.abort(t.reason));return(r,a)=>{YO(r);const s=new AbortController;n(s);const o=yje(async()=>{gf(t),gf(s.signal);const l=await r({pause:xk(s.signal),delay:XJ(s.signal),signal:s.signal});return gf(s.signal),l},()=>s.abort(bje));return a?.autoJoin&&e.push(o.catch(bk)),{result:xk(t)(o),cancel(){s.abort(gje)}}}},wje=(t,e)=>{const n=async(r,a)=>{gf(e);let s=()=>{};const l=[new Promise((c,u)=>{let d=t({predicate:r,effect:(m,p)=>{p.unsubscribe(),c([m,p.getState(),p.getOriginalState()])}});s=()=>{d(),u()}})];a!=null&&l.push(new Promise(c=>setTimeout(c,a,null)));try{const c=await YJ(e,Promise.race(l));return gf(e),c}finally{s()}};return(r,a)=>WJ(n(r,a))},QJ=t=>{let{type:e,actionCreator:n,matcher:r,predicate:a,effect:s}=t;if(e)a=Yl(e).match;else if(n)e=n.type,a=n.match;else if(r)a=r;else if(!a)throw new Error(tl(21));return YO(s),{predicate:a,type:e,effect:s}},ZJ=tx(t=>{const{type:e,predicate:n,effect:r}=QJ(t);return{id:aje(),effect:r,type:e,predicate:n,pending:new Set,unsubscribe:()=>{throw new Error(tl(22))}}},{withTypes:()=>ZJ}),NV=(t,e)=>{const{type:n,effect:r,predicate:a}=QJ(e);return Array.from(t.values()).find(s=>(typeof n=="string"?s.type===n:s.predicate===a)&&s.effect===r)},QR=t=>{t.pending.forEach(e=>{e.abort(XR)})},Sje=(t,e)=>()=>{for(const n of e.keys())QR(n);t.clear()},kV=(t,e,n)=>{try{t(e,n)}catch(r){setTimeout(()=>{throw r},0)}},JJ=tx(Yl(`${OT}/add`),{withTypes:()=>JJ}),_je=Yl(`${OT}/removeAll`),eee=tx(Yl(`${OT}/remove`),{withTypes:()=>eee}),Nje=(...t)=>{console.error(`${OT}/error`,...t)},Mw=(t={})=>{const e=new Map,n=new Map,r=f=>{const y=n.get(f)??0;n.set(f,y+1)},a=f=>{const y=n.get(f)??1;y===1?n.delete(f):n.set(f,y-1)},{extra:s,onError:o=Nje}=t;YO(o);const l=f=>(f.unsubscribe=()=>e.delete(f.id),e.set(f.id,f),y=>{f.unsubscribe(),y?.cancelActive&&QR(f)}),c=f=>{const y=NV(e,f)??ZJ(f);return l(y)};tx(c,{withTypes:()=>c});const u=f=>{const y=NV(e,f);return y&&(y.unsubscribe(),f.cancelActive&&QR(y)),!!y};tx(u,{withTypes:()=>u});const d=async(f,y,v,b)=>{const g=new AbortController,_=wje(c,g.signal),N=[];try{f.pending.add(g),r(f),await Promise.resolve(f.effect(y,tx({},v,{getOriginalState:b,condition:(C,k)=>_(C,k).then(Boolean),take:_,delay:XJ(g.signal),pause:xk(g.signal),extra:s,signal:g.signal,fork:vje(g.signal,N),unsubscribe:f.unsubscribe,subscribe:()=>{e.set(f.id,f)},cancelActiveListeners:()=>{f.pending.forEach((C,k,P)=>{C!==g&&(C.abort(XR),P.delete(C))})},cancel:()=>{g.abort(XR),f.pending.delete(g)},throwIfCancelled:()=>{gf(g.signal)}})))}catch(C){C instanceof LT||kV(o,C,{raisedBy:"effect"})}finally{await Promise.all(N),g.abort(xje),a(f),f.pending.delete(g)}},m=Sje(e,n);return{middleware:f=>y=>v=>{if(!PJ(v))return y(v);if(JJ.match(v))return c(v.payload);if(_je.match(v)){m();return}if(eee.match(v))return u(v.payload);let b=f.getState();const g=()=>{if(b===_V)throw new Error(tl(23));return b};let _;try{if(_=y(v),e.size>0){const N=f.getState(),C=Array.from(e.values());for(const k of C){let P=!1;try{P=k.predicate(v,N,b)}catch(T){P=!1,kV(o,T,{raisedBy:"predicate"})}P&&d(k,v,f,g)}}}finally{b=_V}return _},startListening:c,stopListening:u,clearListeners:m}};function tl(t){return`Minified Redux Toolkit error #${t}; visit https://redux-toolkit.js.org/Errors?code=${t} for the full message or use the non-minified dev environment for full errors. `}var kje={layoutType:"horizontal",width:0,height:0,margin:{top:5,right:5,bottom:5,left:5},scale:1},tee=Ao({name:"chartLayout",initialState:kje,reducers:{setLayout(t,e){t.layoutType=e.payload},setChartSize(t,e){t.width=e.payload.width,t.height=e.payload.height},setMargin(t,e){var n,r,a,s;t.margin.top=(n=e.payload.top)!==null&&n!==void 0?n:0,t.margin.right=(r=e.payload.right)!==null&&r!==void 0?r:0,t.margin.bottom=(a=e.payload.bottom)!==null&&a!==void 0?a:0,t.margin.left=(s=e.payload.left)!==null&&s!==void 0?s:0},setScale(t,e){t.scale=e.payload}}}),{setMargin:Cje,setLayout:Tje,setChartSize:Aje,setScale:Pje}=tee.actions,Mje=tee.reducer;function nee(t,e,n){return Array.isArray(t)&&t&&e+n!==0?t.slice(e,n+1):t}function Ln(t){return Number.isFinite(t)}function vu(t){return typeof t=="number"&&t>0&&Number.isFinite(t)}function CV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Hb(t){for(var e=1;e{if(e&&n){var{width:r,height:a}=n,{align:s,verticalAlign:o,layout:l}=e;if((l==="vertical"||l==="horizontal"&&o==="middle")&&s!=="center"&&Yt(t[s]))return Hb(Hb({},t),{},{[s]:t[s]+(r||0)});if((l==="horizontal"||l==="vertical"&&s==="center")&&o!=="middle"&&Yt(t[o]))return Hb(Hb({},t),{},{[o]:t[o]+(a||0)})}return t},Fc=(t,e)=>t==="horizontal"&&e==="xAxis"||t==="vertical"&&e==="yAxis"||t==="centric"&&e==="angleAxis"||t==="radial"&&e==="radiusAxis",ree=(t,e,n,r)=>{if(r)return t.map(l=>l.coordinate);var a,s,o=t.map(l=>(l.coordinate===e&&(a=!0),l.coordinate===n&&(s=!0),l.coordinate));return a||o.push(e),s||o.push(n),o},iee=(t,e,n)=>{if(!t)return null;var{duplicateDomain:r,type:a,range:s,scale:o,realScaleType:l,isCategorical:c,categoricalDomain:u,tickCount:d,ticks:m,niceTicks:p,axisType:f}=t;if(!o)return null;var y=l==="scaleBand"&&o.bandwidth?o.bandwidth()/2:2,v=a==="category"&&o.bandwidth?o.bandwidth()/y:0;if(v=f==="angleAxis"&&s&&s.length>=2?Fa(s[0]-s[1])*2*v:v,m||p){var b=(m||p||[]).map((g,_)=>{var N=r?r.indexOf(g):g,C=o.map(N);return Ln(C)?{coordinate:C+v,value:g,offset:v,index:_}:null}).filter(yo);return b}return c&&u?u.map((g,_)=>{var N=o.map(g);return Ln(N)?{coordinate:N+v,value:g,index:_,offset:v}:null}).filter(yo):o.ticks&&d!=null?o.ticks(d).map((g,_)=>{var N=o.map(g);return Ln(N)?{coordinate:N+v,value:g,index:_,offset:v}:null}).filter(yo):o.domain().map((g,_)=>{var N=o.map(g);return Ln(N)?{coordinate:N+v,value:r?r[g]:g,index:_,offset:v}:null}).filter(yo)},Fje=(t,e)=>{if(!e||e.length!==2||!Yt(e[0])||!Yt(e[1]))return t;var n=Math.min(e[0],e[1]),r=Math.max(e[0],e[1]),a=[t[0],t[1]];return(!Yt(t[0])||t[0]r)&&(a[1]=r),a[0]>r&&(a[0]=r),a[1]{var e,n=t.length;if(!(n<=0)){var r=(e=t[0])===null||e===void 0?void 0:e.length;if(!(r==null||r<=0))for(var a=0;a=0?(u[0]=s,s+=p,u[1]=s):(u[0]=o,o+=p,u[1]=o)}}}},Oje=t=>{var e,n=t.length;if(!(n<=0)){var r=(e=t[0])===null||e===void 0?void 0:e.length;if(!(r==null||r<=0))for(var a=0;a=0?(c[0]=s,s+=u,c[1]=s):(c[0]=0,c[1]=0)}}}},Ije={sign:Lje,expand:oEe,none:Uf,silhouette:lEe,wiggle:cEe,positive:Oje},zje=(t,e,n)=>{var r,a=(r=Ije[n])!==null&&r!==void 0?r:Uf,s=sEe().keys(e).value((l,c)=>Number(Tr(l,c,0))).order(UR).offset(a),o=s(t);return o.forEach((l,c)=>{l.forEach((u,d)=>{var m=Tr(t[d],e[c],0);Array.isArray(m)&&m.length===2&&Yt(m[0])&&Yt(m[1])&&(u[0]=m[0],u[1]=m[1])})}),o};function aee(t){return t==null?void 0:String(t)}function yk(t){var{axis:e,ticks:n,bandSize:r,entry:a,index:s,dataKey:o}=t;if(e.type==="category"){if(!e.allowDuplicatedCategory&&e.dataKey&&!gi(a[e.dataKey])){var l=cJ(n,"value",a[e.dataKey]);if(l)return l.coordinate+r/2}return n!=null&&n[s]?n[s].coordinate+r/2:null}var c=Tr(a,gi(o)?e.dataKey:o),u=e.scale.map(c);return Yt(u)?u:null}var TV=t=>{var{axis:e,ticks:n,offset:r,bandSize:a,entry:s,index:o}=t;if(e.type==="category")return n[o]?n[o].coordinate+r:null;var l=Tr(s,e.dataKey,e.scale.domain()[o]);if(gi(l))return null;var c=e.scale.map(l);return Yt(c)?c-a/2+r:null},Uje=t=>{var{numericAxis:e}=t,n=e.scale.domain();if(e.type==="number"){var r=Math.min(n[0],n[1]),a=Math.max(n[0],n[1]);return r<=0&&a>=0?0:a<0?a:r}return n[0]},Bje=t=>{var e=t.flat(2).filter(Yt);return[Math.min(...e),Math.max(...e)]},Hje=t=>[t[0]===1/0?0:t[0],t[1]===-1/0?0:t[1]],$je=(t,e,n)=>{if(t!=null)return Hje(Object.keys(t).reduce((r,a)=>{var s=t[a];if(!s)return r;var{stackedData:o}=s,l=o.reduce((c,u)=>{var d=nee(u,e,n),m=Bje(d);return!Ln(m[0])||!Ln(m[1])?c:[Math.min(c[0],m[0]),Math.max(c[1],m[1])]},[1/0,-1/0]);return[Math.min(l[0],r[0]),Math.max(l[1],r[1])]},[1/0,-1/0]))},AV=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,PV=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,qh=(t,e,n)=>{if(t&&t.scale&&t.scale.bandwidth){var r=t.scale.bandwidth();if(!n||r>0)return r}if(t&&e&&e.length>=2){for(var a=AT(e,d=>d.coordinate),s=1/0,o=1,l=a.length;o{if(e==="horizontal")return t.chartX;if(e==="vertical")return t.chartY},Vje=(t,e)=>e==="centric"?t.angle:t.radius,tm=t=>t.layout.width,nm=t=>t.layout.height,Gje=t=>t.layout.scale,see=t=>t.layout.margin,IT=yt(t=>t.cartesianAxis.xAxis,t=>Object.values(t)),zT=yt(t=>t.cartesianAxis.yAxis,t=>Object.values(t)),oee="data-recharts-item-index",lee="data-recharts-item-id",Ew=60;function EV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function v1(t){for(var e=1;et.brush.height;function Qje(t){var e=zT(t);return e.reduce((n,r)=>{if(r.orientation==="left"&&!r.mirror&&!r.hide){var a=typeof r.width=="number"?r.width:Ew;return n+a}return n},0)}function Zje(t){var e=zT(t);return e.reduce((n,r)=>{if(r.orientation==="right"&&!r.mirror&&!r.hide){var a=typeof r.width=="number"?r.width:Ew;return n+a}return n},0)}function Jje(t){var e=IT(t);return e.reduce((n,r)=>r.orientation==="top"&&!r.mirror&&!r.hide?n+r.height:n,0)}function eDe(t){var e=IT(t);return e.reduce((n,r)=>r.orientation==="bottom"&&!r.mirror&&!r.hide?n+r.height:n,0)}var va=yt([tm,nm,see,Xje,Qje,Zje,Jje,eDe,kJ,T2e],(t,e,n,r,a,s,o,l,c,u)=>{var d={left:(n.left||0)+a,right:(n.right||0)+s},m={top:(n.top||0)+o,bottom:(n.bottom||0)+l},p=v1(v1({},m),d),f=p.bottom;p.bottom+=r,p=Rje(p,c,u);var y=t-p.left-p.right,v=e-p.top-p.bottom;return v1(v1({brushBottom:f},p),{},{width:Math.max(y,0),height:Math.max(v,0)})}),tDe=yt(va,t=>({x:t.left,y:t.top,width:t.width,height:t.height})),XO=yt(tm,nm,(t,e)=>({x:0,y:0,width:t,height:e})),nDe=w.createContext(null),wa=()=>w.useContext(nDe)!=null,UT=t=>t.brush,BT=yt([UT,va,see],(t,e,n)=>({height:t.height,x:Yt(t.x)?t.x:e.left,y:Yt(t.y)?t.y:e.top+e.height+e.brushBottom-(n?.bottom||0),width:Yt(t.width)?t.width:e.width})),gj={},bj={},xj={},jV;function rDe(){return jV||(jV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r,{signal:a,edges:s}={}){let o,l=null;const c=s!=null&&s.includes("leading"),u=s==null||s.includes("trailing"),d=()=>{l!==null&&(n.apply(o,l),o=void 0,l=null)},m=()=>{u&&d(),v()};let p=null;const f=()=>{p!=null&&clearTimeout(p),p=setTimeout(()=>{p=null,m()},r)},y=()=>{p!==null&&(clearTimeout(p),p=null)},v=()=>{y(),o=void 0,l=null},b=()=>{d()},g=function(..._){if(a?.aborted)return;o=this,l=_;const N=p==null;f(),c&&N&&d()};return g.schedule=f,g.cancel=v,g.flush=b,a?.addEventListener("abort",v,{once:!0}),g}t.debounce=e})(xj)),xj}var DV;function iDe(){return DV||(DV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=rDe();function n(r,a=0,s={}){typeof s!="object"&&(s={});const{leading:o=!1,trailing:l=!0,maxWait:c}=s,u=Array(2);o&&(u[0]="leading"),l&&(u[1]="trailing");let d,m=null;const p=e.debounce(function(...v){d=r.apply(this,v),m=null},a,{edges:u}),f=function(...v){return c!=null&&(m===null&&(m=Date.now()),Date.now()-m>=c)?(d=r.apply(this,v),m=Date.now(),p.cancel(),p.schedule(),d):(p.apply(this,v),d)},y=()=>(p.flush(),d);return f.cancel=p.cancel,f.flush=y,f}t.debounce=n})(bj)),bj}var RV;function aDe(){return RV||(RV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=iDe();function n(r,a=0,s={}){const{leading:o=!0,trailing:l=!0}=s;return e.debounce(r,a,{leading:o,maxWait:a,trailing:l})}t.throttle=n})(gj)),gj}var yj,FV;function sDe(){return FV||(FV=1,yj=aDe().throttle),yj}var oDe=sDe();const lDe=Zl(oDe);var vk=function(e,n){for(var r=arguments.length,a=new Array(r>2?r-2:0),s=2;sa[o++]))}},uu={width:"100%",height:"100%",debounce:0,minWidth:0,initialDimension:{width:-1,height:-1}},cee=(t,e,n)=>{var{width:r=uu.width,height:a=uu.height,aspect:s,maxHeight:o}=n,l=Hf(r)?t:Number(r),c=Hf(a)?e:Number(a);return s&&s>0&&(l?c=l/s:c&&(l=c*s),o&&c!=null&&c>o&&(c=o)),{calculatedWidth:l,calculatedHeight:c}},cDe={width:0,height:0,overflow:"visible"},uDe={width:0,overflowX:"visible"},dDe={height:0,overflowY:"visible"},mDe={},hDe=t=>{var{width:e,height:n}=t,r=Hf(e),a=Hf(n);return r&&a?cDe:r?uDe:a?dDe:mDe};function pDe(t){var{width:e,height:n,aspect:r}=t,a=e,s=n;return a===void 0&&s===void 0?(a=uu.width,s=uu.height):a===void 0?a=r&&r>0?void 0:uu.width:s===void 0&&(s=r&&r>0?void 0:uu.height),{width:a,height:s}}function ZR(){return ZR=Object.assign?Object.assign.bind():function(t){for(var e=1;e({width:n,height:r}),[n,r]);return xDe(a)?w.createElement(uee.Provider,{value:a},e):null}var QO=()=>w.useContext(uee),yDe=w.forwardRef((t,e)=>{var{aspect:n,initialDimension:r=uu.initialDimension,width:a,height:s,minWidth:o=uu.minWidth,minHeight:l,maxHeight:c,children:u,debounce:d=uu.debounce,id:m,className:p,onResize:f,style:y={}}=t,v=w.useRef(null),b=w.useRef();b.current=f,w.useImperativeHandle(e,()=>v.current);var[g,_]=w.useState({containerWidth:r.width,containerHeight:r.height}),N=w.useCallback((D,A)=>{_(R=>{var G=Math.round(D),z=Math.round(A);return R.containerWidth===G&&R.containerHeight===z?R:{containerWidth:G,containerHeight:z}})},[]);w.useEffect(()=>{if(v.current==null||typeof ResizeObserver>"u")return Yh;var D=z=>{var Z,I=z[0];if(I!=null){var{width:J,height:ae}=I.contentRect;N(J,ae),(Z=b.current)===null||Z===void 0||Z.call(b,J,ae)}};d>0&&(D=lDe(D,d,{trailing:!0,leading:!1}));var A=new ResizeObserver(D),{width:R,height:G}=v.current.getBoundingClientRect();return N(R,G),A.observe(v.current),()=>{A.disconnect()}},[N,d]);var{containerWidth:C,containerHeight:k}=g;vk(!n||n>0,"The aspect(%s) must be greater than zero.",n);var{calculatedWidth:P,calculatedHeight:T}=cee(C,k,{width:a,height:s,aspect:n,maxHeight:c});return vk(P!=null&&P>0||T!=null&&T>0,`The width(%s) and height(%s) of chart should be greater than 0, + A`).concat(s,",").concat(s,",0,1,1,").concat(o,",").concat(a),className:"recharts-legend-icon"});if(c==="rect")return w.createElement("path",{stroke:"none",fill:l,d:"M0,".concat(Tl/8,"h").concat(Tl,"v").concat(Tl*3/4,"h").concat(-Tl,"z"),className:"recharts-legend-icon"});if(w.isValidElement(e.legendIcon)){var d=EEe({},e);return delete d.legendIcon,w.cloneElement(e.legendIcon,d)}return w.createElement(zO,{fill:l,cx:a,cy:a,size:Tl,sizeType:"diameter",type:c})}function OEe(t){var{payload:e,iconSize:n,layout:r,formatter:a,inactiveColor:s,iconType:o}=t,l={x:0,y:0,width:Tl,height:Tl},c={display:r==="horizontal"?"inline-block":"block",marginRight:10},u={display:"inline-block",verticalAlign:"middle",marginRight:4};return e.map((d,m)=>{var p=d.formatter||a,f=hr({"recharts-legend-item":!0,["legend-item-".concat(m)]:!0,inactive:d.inactive});if(d.type==="none")return null;var y=d.inactive?s:d.color,v=p?p(d.value,d,m):d.value;return w.createElement("li",lk({className:f,style:c,key:"legend-item-".concat(m)},Aw(t,d,m)),w.createElement(jO,{width:n,height:n,viewBox:l,style:u,"aria-label":"".concat(v," legend icon")},w.createElement(LEe,{data:d,iconType:o,inactiveColor:s})),w.createElement("span",{className:"recharts-legend-item-text",style:{color:y}},v))})}var IEe=t=>{var e=wi(t,FEe),{payload:n,layout:r,align:a}=e;if(!n||!n.length)return null;var s={padding:0,margin:0,textAlign:r==="horizontal"?a:"left"};return w.createElement("ul",{className:"recharts-default-legend",style:s},w.createElement(OEe,lk({},e,{payload:n})))},Aj={},Pj={},_q;function zEe(){return _q||(_q=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r){const a=new Map;for(let s=0;s=0}t.isLength=e})(Rj)),Rj}var Tq;function BO(){return Tq||(Tq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=BEe();function n(r){return r!=null&&typeof r!="function"&&e.isLength(r.length)}t.isArrayLike=n})(Dj)),Dj}var Fj={},Aq;function HEe(){return Aq||(Aq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="object"&&n!==null}t.isObjectLike=e})(Fj)),Fj}var Pq;function $Ee(){return Pq||(Pq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=BO(),n=HEe();function r(a){return n.isObjectLike(a)&&e.isArrayLike(a)}t.isArrayLikeObject=r})(jj)),jj}var Lj={},Oj={},Mq;function qEe(){return Mq||(Mq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=IO();function n(r){return function(a){return e.get(a,r)}}t.property=n})(Oj)),Oj}var Ij={},zj={},Uj={},Bj={},Eq;function hJ(){return Eq||(Eq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n!==null&&(typeof n=="object"||typeof n=="function")}t.isObject=e})(Bj)),Bj}var Hj={},jq;function pJ(){return jq||(jq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n==null||typeof n!="object"&&typeof n!="function"}t.isPrimitive=e})(Hj)),Hj}var $j={},Dq;function fJ(){return Dq||(Dq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r){return n===r||Number.isNaN(n)&&Number.isNaN(r)}t.isEqualsSameValueZero=e})($j)),$j}var Rq;function VEe(){return Rq||(Rq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=hJ(),n=pJ(),r=fJ();function a(d,m,p){return typeof p!="function"?a(d,m,()=>{}):s(d,m,function f(y,v,b,g,_,N){const C=p(y,v,b,g,_,N);return C!==void 0?!!C:s(y,v,f,N)},new Map)}function s(d,m,p,f){if(m===d)return!0;switch(typeof m){case"object":return o(d,m,p,f);case"function":return Object.keys(m).length>0?s(d,{...m},p,f):r.isEqualsSameValueZero(d,m);default:return e.isObject(d)?typeof m=="string"?m==="":!0:r.isEqualsSameValueZero(d,m)}}function o(d,m,p,f){if(m==null)return!0;if(Array.isArray(m))return c(d,m,p,f);if(m instanceof Map)return l(d,m,p,f);if(m instanceof Set)return u(d,m,p,f);const y=Object.keys(m);if(d==null||n.isPrimitive(d))return y.length===0;if(y.length===0)return!0;if(f?.has(m))return f.get(m)===d;f?.set(m,d);try{for(let v=0;v{})}t.isMatch=n})(zj)),zj}var qj={},Vj={},Gj={},Lq;function GEe(){return Lq||(Lq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Object.getOwnPropertySymbols(n).filter(r=>Object.prototype.propertyIsEnumerable.call(n,r))}t.getSymbols=e})(Gj)),Gj}var Wj={},Oq;function HO(){return Oq||(Oq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n==null?n===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(n)}t.getTag=e})(Wj)),Wj}var Kj={},Iq;function bJ(){return Iq||(Iq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e="[object RegExp]",n="[object String]",r="[object Number]",a="[object Boolean]",s="[object Arguments]",o="[object Symbol]",l="[object Date]",c="[object Map]",u="[object Set]",d="[object Array]",m="[object Function]",p="[object ArrayBuffer]",f="[object Object]",y="[object Error]",v="[object DataView]",b="[object Uint8Array]",g="[object Uint8ClampedArray]",_="[object Uint16Array]",N="[object Uint32Array]",C="[object BigUint64Array]",k="[object Int8Array]",P="[object Int16Array]",T="[object Int32Array]",D="[object BigInt64Array]",A="[object Float32Array]",R="[object Float64Array]";t.argumentsTag=s,t.arrayBufferTag=p,t.arrayTag=d,t.bigInt64ArrayTag=D,t.bigUint64ArrayTag=C,t.booleanTag=a,t.dataViewTag=v,t.dateTag=l,t.errorTag=y,t.float32ArrayTag=A,t.float64ArrayTag=R,t.functionTag=m,t.int16ArrayTag=P,t.int32ArrayTag=T,t.int8ArrayTag=k,t.mapTag=c,t.numberTag=r,t.objectTag=f,t.regexpTag=e,t.setTag=u,t.stringTag=n,t.symbolTag=o,t.uint16ArrayTag=_,t.uint32ArrayTag=N,t.uint8ArrayTag=b,t.uint8ClampedArrayTag=g})(Kj)),Kj}var Yj={},zq;function WEe(){return zq||(zq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}t.isTypedArray=e})(Yj)),Yj}var Uq;function xJ(){return Uq||(Uq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=GEe(),n=HO(),r=bJ(),a=pJ(),s=WEe();function o(d,m){return l(d,void 0,d,new Map,m)}function l(d,m,p,f=new Map,y=void 0){const v=y?.(d,m,p,f);if(v!==void 0)return v;if(a.isPrimitive(d))return d;if(f.has(d))return f.get(d);if(Array.isArray(d)){const b=new Array(d.length);f.set(d,b);for(let g=0;ge.isMatch(s,a)}t.matches=r})(Ij)),Ij}var Xj={},Qj={},Zj={},$q;function XEe(){return $q||($q=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=xJ(),n=HO(),r=bJ();function a(s,o){return e.cloneDeepWith(s,(l,c,u,d)=>{const m=o?.(l,c,u,d);if(m!==void 0)return m;if(typeof s=="object"){if(n.getTag(s)===r.objectTag&&typeof s.constructor!="function"){const p={};return d.set(s,p),e.copyProperties(p,s,u,d),p}switch(Object.prototype.toString.call(s)){case r.numberTag:case r.stringTag:case r.booleanTag:{const p=new s.constructor(s?.valueOf());return e.copyProperties(p,s),p}case r.argumentsTag:{const p={};return e.copyProperties(p,s),p.length=s.length,p[Symbol.iterator]=s[Symbol.iterator],p}default:return}}})}t.cloneDeepWith=a})(Zj)),Zj}var qq;function QEe(){return qq||(qq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=XEe();function n(r){return e.cloneDeepWith(r)}t.cloneDeep=n})(Qj)),Qj}var Jj={},e2={},Vq;function yJ(){return Vq||(Vq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=/^(?:0|[1-9]\d*)$/;function n(r,a=Number.MAX_SAFE_INTEGER){switch(typeof r){case"number":return Number.isInteger(r)&&r>=0&&rt,Jr=()=>{var t=w.useContext($O);return t?t.store.dispatch:oje},mN=()=>{},lje=()=>mN,cje=(t,e)=>t===e;function en(t){var e=w.useContext($O),n=w.useMemo(()=>e?r=>{if(r!=null)return t(r)}:mN,[e,t]);return wJ.useSyncExternalStoreWithSelector(e?e.subscription.addNestedSub:lje,e?e.store.getState:mN,e?e.store.getState:mN,n,cje)}function uje(t,e=`expected a function, instead received ${typeof t}`){if(typeof t!="function")throw new TypeError(e)}function dje(t,e=`expected an object, instead received ${typeof t}`){if(typeof t!="object")throw new TypeError(e)}function mje(t,e="expected all items to be functions, instead received the following types: "){if(!t.every(n=>typeof n=="function")){const n=t.map(r=>typeof r=="function"?`function ${r.name||"unnamed"}()`:typeof r).join(", ");throw new TypeError(`${e}[${n}]`)}}var tV=t=>Array.isArray(t)?t:[t];function hje(t){const e=Array.isArray(t[0])?t[0]:t;return mje(e,"createSelector expects all input-selectors to be functions, but received the following types: "),e}function pje(t,e){const n=[],{length:r}=t;for(let a=0;a{n=f1(),o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function xje(t,...e){const n=typeof t=="function"?{memoize:t,memoizeOptions:e}:t,r=(...a)=>{let s=0,o=0,l,c={},u=a.pop();typeof u=="object"&&(c=u,u=a.pop()),uje(u,`createSelector expects an output function after the inputs, but received: [${typeof u}]`);const d={...n,...c},{memoize:m,memoizeOptions:p=[],argsMemoize:f=SJ,argsMemoizeOptions:y=[]}=d,v=tV(p),b=tV(y),g=hje(a),_=m(function(){return s++,u.apply(null,arguments)},...v),N=f(function(){o++;const k=pje(g,arguments);return l=_.apply(null,k),l},...b);return Object.assign(N,{resultFunc:u,memoizedResultFunc:_,dependencies:g,dependencyRecomputations:()=>o,resetDependencyRecomputations:()=>{o=0},lastResult:()=>l,recomputations:()=>s,resetRecomputations:()=>{s=0},memoize:m,argsMemoize:f})};return Object.assign(r,{withTypes:()=>r}),r}var yt=xje(SJ),yje=Object.assign((t,e=yt)=>{dje(t,`createStructuredSelector expects first argument to be an object where each property is a selector, instead received a ${typeof t}`);const n=Object.keys(t),r=n.map(s=>t[s]);return e(r,(...s)=>s.reduce((o,l,c)=>(o[n[c]]=l,o),{}))},{withTypes:()=>yje}),a2={},s2={},o2={},rV;function vje(){return rV||(rV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(r){return typeof r=="symbol"?1:r===null?2:r===void 0?3:r!==r?4:0}const n=(r,a,s)=>{if(r!==a){const o=e(r),l=e(a);if(o===l&&o===0){if(ra)return s==="desc"?-1:1}return s==="desc"?l-o:o-l}return 0};t.compareValues=n})(o2)),o2}var l2={},c2={},iV;function _J(){return iV||(iV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="symbol"||n instanceof Symbol}t.isSymbol=e})(c2)),c2}var aV;function wje(){return aV||(aV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=_J(),n=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,r=/^\w*$/;function a(s,o){return Array.isArray(s)?!1:typeof s=="number"||typeof s=="boolean"||s==null||e.isSymbol(s)?!0:typeof s=="string"&&(r.test(s)||!n.test(s))||o!=null&&Object.hasOwn(o,s)}t.isKey=a})(l2)),l2}var sV;function Sje(){return sV||(sV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=vje(),n=wje(),r=OO();function a(s,o,l,c){if(s==null)return[];l=c?void 0:l,Array.isArray(s)||(s=Object.values(s)),Array.isArray(o)||(o=o==null?[null]:[o]),o.length===0&&(o=[null]),Array.isArray(l)||(l=l==null?[]:[l]),l=l.map(f=>String(f));const u=(f,y)=>{let v=f;for(let b=0;by==null||f==null?y:typeof f=="object"&&"key"in f?Object.hasOwn(y,f.key)?y[f.key]:u(y,f.path):typeof f=="function"?f(y):Array.isArray(f)?u(y,f):typeof y=="object"?y[f]:y,m=o.map(f=>(Array.isArray(f)&&f.length===1&&(f=f[0]),f==null||typeof f=="function"||Array.isArray(f)||n.isKey(f)?f:{key:f,path:r.toPath(f)}));return s.map(f=>({original:f,criteria:m.map(y=>d(y,f))})).slice().sort((f,y)=>{for(let v=0;vf.original)}t.orderBy=a})(s2)),s2}var u2={},oV;function _je(){return oV||(oV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r=1){const a=[],s=Math.floor(r),o=(l,c)=>{for(let u=0;u1&&r.isIterateeCall(s,o[0],o[1])?o=[]:l>2&&r.isIterateeCall(o[0],o[1],o[2])&&(o=[o[0]]),e.orderBy(s,n.flatten(o),["asc"])}t.sortBy=a})(a2)),a2}var m2,uV;function kje(){return uV||(uV=1,m2=Nje().sortBy),m2}var Cje=kje();const AT=Zl(Cje);var kJ=t=>t.legend.settings,Tje=t=>t.legend.size,Aje=t=>t.legend.payload,Pje=yt([Aje,kJ],(t,e)=>{var{itemSorter:n}=e,r=t.flat(1);return n?AT(r,n):r});function Mje(){return en(Pje)}var g1=1;function CJ(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],[e,n]=w.useState({height:0,left:0,top:0,width:0}),r=w.useCallback(a=>{if(a!=null){var s=a.getBoundingClientRect(),o={height:s.height,left:s.left,top:s.top,width:s.width};(Math.abs(o.height-e.height)>g1||Math.abs(o.left-e.left)>g1||Math.abs(o.top-e.top)>g1||Math.abs(o.width-e.width)>g1)&&n({height:o.height,left:o.left,top:o.top,width:o.width})}},[e.width,e.height,e.top,e.left,...t]);return[e,r]}function Qa(t){return`Minified Redux error #${t}; visit https://redux.js.org/Errors?code=${t} for the full message or use the non-minified dev environment for full errors. `}var Eje=typeof Symbol=="function"&&Symbol.observable||"@@observable",dV=Eje,h2=()=>Math.random().toString(36).substring(7).split("").join("."),jje={INIT:`@@redux/INIT${h2()}`,REPLACE:`@@redux/REPLACE${h2()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${h2()}`},ck=jje;function qO(t){if(typeof t!="object"||t===null)return!1;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e||Object.getPrototypeOf(t)===null}function TJ(t,e,n){if(typeof t!="function")throw new Error(Qa(2));if(typeof e=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(Qa(0));if(typeof e=="function"&&typeof n>"u"&&(n=e,e=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(Qa(1));return n(TJ)(t,e)}let r=t,a=e,s=new Map,o=s,l=0,c=!1;function u(){o===s&&(o=new Map,s.forEach((b,g)=>{o.set(g,b)}))}function d(){if(c)throw new Error(Qa(3));return a}function m(b){if(typeof b!="function")throw new Error(Qa(4));if(c)throw new Error(Qa(5));let g=!0;u();const _=l++;return o.set(_,b),function(){if(g){if(c)throw new Error(Qa(6));g=!1,u(),o.delete(_),s=null}}}function p(b){if(!qO(b))throw new Error(Qa(7));if(typeof b.type>"u")throw new Error(Qa(8));if(typeof b.type!="string")throw new Error(Qa(17));if(c)throw new Error(Qa(9));try{c=!0,a=r(a,b)}finally{c=!1}return(s=o).forEach(_=>{_()}),b}function f(b){if(typeof b!="function")throw new Error(Qa(10));r=b,p({type:ck.REPLACE})}function y(){const b=m;return{subscribe(g){if(typeof g!="object"||g===null)throw new Error(Qa(11));function _(){const C=g;C.next&&C.next(d())}return _(),{unsubscribe:b(_)}},[dV](){return this}}}return p({type:ck.INIT}),{dispatch:p,subscribe:m,getState:d,replaceReducer:f,[dV]:y}}function Dje(t){Object.keys(t).forEach(e=>{const n=t[e];if(typeof n(void 0,{type:ck.INIT})>"u")throw new Error(Qa(12));if(typeof n(void 0,{type:ck.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(Qa(13))})}function AJ(t){const e=Object.keys(t),n={};for(let s=0;s"u")throw l&&l.type,new Error(Qa(14));u[m]=y,c=c||y!==f}return c=c||r.length!==Object.keys(o).length,c?u:o}}function uk(...t){return t.length===0?e=>e:t.length===1?t[0]:t.reduce((e,n)=>(...r)=>e(n(...r)))}function Rje(...t){return e=>(n,r)=>{const a=e(n,r);let s=()=>{throw new Error(Qa(15))};const o={getState:a.getState,dispatch:(c,...u)=>s(c,...u)},l=t.map(c=>c(o));return s=uk(...l)(a.dispatch),{...a,dispatch:s}}}function PJ(t){return qO(t)&&"type"in t&&typeof t.type=="string"}var MJ=Symbol.for("immer-nothing"),mV=Symbol.for("immer-draftable"),Xs=Symbol.for("immer-state");function gc(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var Qo=Object,_x=Qo.getPrototypeOf,dk="constructor",PT="prototype",HR="configurable",mk="enumerable",hN="writable",I0="value",Wd=t=>!!t&&!!t[Xs];function Ec(t){return t?EJ(t)||ET(t)||!!t[mV]||!!t[dk]?.[mV]||jT(t)||DT(t):!1}var Fje=Qo[PT][dk].toString(),hV=new WeakMap;function EJ(t){if(!t||!VO(t))return!1;const e=_x(t);if(e===null||e===Qo[PT])return!0;const n=Qo.hasOwnProperty.call(e,dk)&&e[dk];if(n===Object)return!0;if(!Db(n))return!1;let r=hV.get(n);return r===void 0&&(r=Function.toString.call(n),hV.set(n,r)),r===Fje}function MT(t,e,n=!0){Pw(t)===0?(n?Reflect.ownKeys(t):Qo.keys(t)).forEach(a=>{e(a,t[a],t)}):t.forEach((r,a)=>e(a,r,t))}function Pw(t){const e=t[Xs];return e?e.type_:ET(t)?1:jT(t)?2:DT(t)?3:0}var pV=(t,e,n=Pw(t))=>n===2?t.has(e):Qo[PT].hasOwnProperty.call(t,e),$R=(t,e,n=Pw(t))=>n===2?t.get(e):t[e],hk=(t,e,n,r=Pw(t))=>{r===2?t.set(e,n):r===3?t.add(n):t[e]=n};function Lje(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}var ET=Array.isArray,jT=t=>t instanceof Map,DT=t=>t instanceof Set,VO=t=>typeof t=="object",Db=t=>typeof t=="function",p2=t=>typeof t=="boolean";function Oje(t){const e=+t;return Number.isInteger(e)&&String(e)===t}var xd=t=>t.copy_||t.base_,GO=t=>t.modified_?t.copy_:t.base_;function qR(t,e){if(jT(t))return new Map(t);if(DT(t))return new Set(t);if(ET(t))return Array[PT].slice.call(t);const n=EJ(t);if(e===!0||e==="class_only"&&!n){const r=Qo.getOwnPropertyDescriptors(t);delete r[Xs];let a=Reflect.ownKeys(r);for(let s=0;s1&&Qo.defineProperties(t,{set:b1,add:b1,clear:b1,delete:b1}),Qo.freeze(t),e&&MT(t,(n,r)=>{WO(r,!0)},!1)),t}function Ije(){gc(2)}var b1={[I0]:Ije};function RT(t){return t===null||!VO(t)?!0:Qo.isFrozen(t)}var pk="MapSet",VR="Patches",fV="ArrayMethods",jJ={};function $f(t){const e=jJ[t];return e||gc(0,t),e}var gV=t=>!!jJ[t],z0,DJ=()=>z0,zje=(t,e)=>({drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:gV(pk)?$f(pk):void 0,arrayMethodsPlugin_:gV(fV)?$f(fV):void 0});function bV(t,e){e&&(t.patchPlugin_=$f(VR),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function GR(t){WR(t),t.drafts_.forEach(Uje),t.drafts_=null}function WR(t){t===z0&&(z0=t.parent_)}var xV=t=>z0=zje(z0,t);function Uje(t){const e=t[Xs];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function yV(t,e){e.unfinalizedDrafts_=e.drafts_.length;const n=e.drafts_[0];if(t!==void 0&&t!==n){n[Xs].modified_&&(GR(e),gc(4)),Ec(t)&&(t=vV(e,t));const{patchPlugin_:a}=e;a&&a.generateReplacementPatches_(n[Xs].base_,t,e)}else t=vV(e,n);return Bje(e,t,!0),GR(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==MJ?t:void 0}function vV(t,e){if(RT(e))return e;const n=e[Xs];if(!n)return fk(e,t.handledSet_,t);if(!FT(n,t))return e;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:r}=n;if(r)for(;r.length>0;)r.pop()(t);LJ(n,t)}return n.copy_}function Bje(t,e,n=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&WO(e,n)}function RJ(t){t.finalized_=!0,t.scope_.unfinalizedDrafts_--}var FT=(t,e)=>t.scope_===e,Hje=[];function FJ(t,e,n,r){const a=xd(t),s=t.type_;if(r!==void 0&&$R(a,r,s)===e){hk(a,r,n,s);return}if(!t.draftLocations_){const l=t.draftLocations_=new Map;MT(a,(c,u)=>{if(Wd(u)){const d=l.get(u)||[];d.push(c),l.set(u,d)}})}const o=t.draftLocations_.get(e)??Hje;for(const l of o)hk(a,l,n,s)}function $je(t,e,n){t.callbacks_.push(function(a){const s=e;if(!s||!FT(s,a))return;a.mapSetPlugin_?.fixSetContents(s);const o=GO(s);FJ(t,s.draft_??s,o,n),LJ(s,a)})}function LJ(t,e){if(t.modified_&&!t.finalized_&&(t.type_===3||t.type_===1&&t.allIndicesReassigned_||(t.assigned_?.size??0)>0)){const{patchPlugin_:r}=e;if(r){const a=r.getPath(t);a&&r.generatePatches_(t,a,e)}RJ(t)}}function qje(t,e,n){const{scope_:r}=t;if(Wd(n)){const a=n[Xs];FT(a,r)&&a.callbacks_.push(function(){pN(t);const o=GO(a);FJ(t,n,o,e)})}else Ec(n)&&t.callbacks_.push(function(){const s=xd(t);t.type_===3?s.has(n)&&fk(n,r.handledSet_,r):$R(s,e,t.type_)===n&&r.drafts_.length>1&&(t.assigned_.get(e)??!1)===!0&&t.copy_&&fk($R(t.copy_,e,t.type_),r.handledSet_,r)})}function fk(t,e,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||Wd(t)||e.has(t)||!Ec(t)||RT(t)||(e.add(t),MT(t,(r,a)=>{if(Wd(a)){const s=a[Xs];if(FT(s,n)){const o=GO(s);hk(t,r,o,t.type_),RJ(s)}}else Ec(a)&&fk(a,e,n)})),t}function Vje(t,e){const n=ET(t),r={type_:n?1:0,scope_:e?e.scope_:DJ(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let a=r,s=gk;n&&(a=[r],s=U0);const{revoke:o,proxy:l}=Proxy.revocable(a,s);return r.draft_=l,r.revoke_=o,[l,r]}var gk={get(t,e){if(e===Xs)return t;let n=t.scope_.arrayMethodsPlugin_;const r=t.type_===1&&typeof e=="string";if(r&&n?.isArrayOperationMethod(e))return n.createMethodInterceptor(t,e);const a=xd(t);if(!pV(a,e,t.type_))return Gje(t,a,e);const s=a[e];if(t.finalized_||!Ec(s)||r&&t.operationMethod&&n?.isMutatingArrayMethod(t.operationMethod)&&Oje(e))return s;if(s===f2(t.base_,e)){pN(t);const o=t.type_===1?+e:e,l=YR(t.scope_,s,t,o);return t.copy_[o]=l}return s},has(t,e){return e in xd(t)},ownKeys(t){return Reflect.ownKeys(xd(t))},set(t,e,n){const r=OJ(xd(t),e);if(r?.set)return r.set.call(t.draft_,n),!0;if(!t.modified_){const a=f2(xd(t),e),s=a?.[Xs];if(s&&s.base_===n)return t.copy_[e]=n,t.assigned_.set(e,!1),!0;if(Lje(n,a)&&(n!==void 0||pV(t.base_,e,t.type_)))return!0;pN(t),KR(t)}return t.copy_[e]===n&&(n!==void 0||e in t.copy_)||Number.isNaN(n)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=n,t.assigned_.set(e,!0),qje(t,e,n)),!0},deleteProperty(t,e){return pN(t),f2(t.base_,e)!==void 0||e in t.base_?(t.assigned_.set(e,!1),KR(t)):t.assigned_.delete(e),t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){const n=xd(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{[hN]:!0,[HR]:t.type_!==1||e!=="length",[mk]:r[mk],[I0]:n[e]}},defineProperty(){gc(11)},getPrototypeOf(t){return _x(t.base_)},setPrototypeOf(){gc(12)}},U0={};for(let t in gk){let e=gk[t];U0[t]=function(){const n=arguments;return n[0]=n[0][0],e.apply(this,n)}}U0.deleteProperty=function(t,e){return U0.set.call(this,t,e,void 0)};U0.set=function(t,e,n){return gk.set.call(this,t[0],e,n,t[0])};function f2(t,e){const n=t[Xs];return(n?xd(n):t)[e]}function Gje(t,e,n){const r=OJ(e,n);return r?I0 in r?r[I0]:r.get?.call(t.draft_):void 0}function OJ(t,e){if(!(e in t))return;let n=_x(t);for(;n;){const r=Object.getOwnPropertyDescriptor(n,e);if(r)return r;n=_x(n)}}function KR(t){t.modified_||(t.modified_=!0,t.parent_&&KR(t.parent_))}function pN(t){t.copy_||(t.assigned_=new Map,t.copy_=qR(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var Wje=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(n,r,a)=>{if(Db(n)&&!Db(r)){const o=r;r=n;const l=this;return function(u=o,...d){return l.produce(u,m=>r.call(this,m,...d))}}Db(r)||gc(6),a!==void 0&&!Db(a)&&gc(7);let s;if(Ec(n)){const o=xV(this),l=YR(o,n,void 0);let c=!0;try{s=r(l),c=!1}finally{c?GR(o):WR(o)}return bV(o,a),yV(s,o)}else if(!n||!VO(n)){if(s=r(n),s===void 0&&(s=n),s===MJ&&(s=void 0),this.autoFreeze_&&WO(s,!0),a){const o=[],l=[];$f(VR).generateReplacementPatches_(n,s,{patches_:o,inversePatches_:l}),a(o,l)}return s}else gc(1,n)},this.produceWithPatches=(n,r)=>{if(Db(n))return(l,...c)=>this.produceWithPatches(l,u=>n(u,...c));let a,s;return[this.produce(n,r,(l,c)=>{a=l,s=c}),a,s]},p2(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),p2(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),p2(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){Ec(e)||gc(8),Wd(e)&&(e=Nc(e));const n=xV(this),r=YR(n,e,void 0);return r[Xs].isManual_=!0,WR(n),r}finishDraft(e,n){const r=e&&e[Xs];(!r||!r.isManual_)&&gc(9);const{scope_:a}=r;return bV(a,n),yV(void 0,a)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,n){let r;for(r=n.length-1;r>=0;r--){const s=n[r];if(s.path.length===0&&s.op==="replace"){e=s.value;break}}r>-1&&(n=n.slice(r+1));const a=$f(VR).applyPatches_;return Wd(e)?a(e,n):this.produce(e,s=>a(s,n))}};function YR(t,e,n,r){const[a,s]=jT(e)?$f(pk).proxyMap_(e,n):DT(e)?$f(pk).proxySet_(e,n):Vje(e,n);return(n?.scope_??DJ()).drafts_.push(a),s.callbacks_=n?.callbacks_??[],s.key_=r,n&&r!==void 0?$je(n,s,r):s.callbacks_.push(function(c){c.mapSetPlugin_?.fixSetContents(s);const{patchPlugin_:u}=c;s.modified_&&u&&u.generatePatches_(s,[],c)}),a}function Nc(t){return Wd(t)||gc(10,t),IJ(t)}function IJ(t){if(!Ec(t)||RT(t))return t;const e=t[Xs];let n,r=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,n=qR(t,e.scope_.immer_.useStrictShallowCopy_),r=e.scope_.immer_.shouldUseStrictIteration()}else n=qR(t,!0);return MT(n,(a,s)=>{hk(n,a,IJ(s))},r),e&&(e.finalized_=!1),n}var Kje=new Wje,zJ=Kje.produce;function UJ(t){return({dispatch:n,getState:r})=>a=>s=>typeof s=="function"?s(n,r,t):a(s)}var Yje=UJ(),Xje=UJ,Qje=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]=="object"?uk:uk.apply(null,arguments)};function Yl(t,e){function n(...r){if(e){let a=e(...r);if(!a)throw new Error(tl(0));return{type:t,payload:a.payload,..."meta"in a&&{meta:a.meta},..."error"in a&&{error:a.error}}}return{type:t,payload:r[0]}}return n.toString=()=>`${t}`,n.type=t,n.match=r=>PJ(r)&&r.type===t,n}var BJ=class Fv extends Array{constructor(...e){super(...e),Object.setPrototypeOf(this,Fv.prototype)}static get[Symbol.species](){return Fv}concat(...e){return super.concat.apply(this,e)}prepend(...e){return e.length===1&&Array.isArray(e[0])?new Fv(...e[0].concat(this)):new Fv(...e.concat(this))}};function wV(t){return Ec(t)?zJ(t,()=>{}):t}function x1(t,e,n){return t.has(e)?t.get(e):t.set(e,n(e)).get(e)}function Zje(t){return typeof t=="boolean"}var Jje=()=>function(e){const{thunk:n=!0,immutableCheck:r=!0,serializableCheck:a=!0,actionCreatorCheck:s=!0}=e??{};let o=new BJ;return n&&(Zje(n)?o.push(Yje):o.push(Xje(n.extraArgument))),o},HJ="RTK_autoBatch",mi=()=>t=>({payload:t,meta:{[HJ]:!0}}),SV=t=>e=>{setTimeout(e,t)},$J=(t={type:"raf"})=>e=>(...n)=>{const r=e(...n);let a=!0,s=!1,o=!1;const l=new Set,c=t.type==="tick"?queueMicrotask:t.type==="raf"?typeof window<"u"&&window.requestAnimationFrame?window.requestAnimationFrame:SV(10):t.type==="callback"?t.queueNotification:SV(t.timeout),u=()=>{o=!1,s&&(s=!1,l.forEach(d=>d()))};return Object.assign({},r,{subscribe(d){const m=()=>a&&d(),p=r.subscribe(m);return l.add(d),()=>{p(),l.delete(d)}},dispatch(d){try{return a=!d?.meta?.[HJ],s=!a,s&&(o||(o=!0,c(u))),r.dispatch(d)}finally{a=!0}}})},e2e=t=>function(n){const{autoBatch:r=!0}=n??{};let a=new BJ(t);return r&&a.push($J(typeof r=="object"?r:void 0)),a};function t2e(t){const e=Jje(),{reducer:n=void 0,middleware:r,devTools:a=!0,preloadedState:s=void 0,enhancers:o=void 0}=t||{};let l;if(typeof n=="function")l=n;else if(qO(n))l=AJ(n);else throw new Error(tl(1));let c;typeof r=="function"?c=r(e):c=e();let u=uk;a&&(u=Qje({trace:!1,...typeof a=="object"&&a}));const d=Rje(...c),m=e2e(d);let p=typeof o=="function"?o(m):m();const f=u(...p);return TJ(l,s,f)}function qJ(t){const e={},n=[];let r;const a={addCase(s,o){const l=typeof s=="string"?s:s.type;if(!l)throw new Error(tl(28));if(l in e)throw new Error(tl(29));return e[l]=o,a},addAsyncThunk(s,o){return o.pending&&(e[s.pending.type]=o.pending),o.rejected&&(e[s.rejected.type]=o.rejected),o.fulfilled&&(e[s.fulfilled.type]=o.fulfilled),o.settled&&n.push({matcher:s.settled,reducer:o.settled}),a},addMatcher(s,o){return n.push({matcher:s,reducer:o}),a},addDefaultCase(s){return r=s,a}};return t(a),[e,n,r]}function n2e(t){return typeof t=="function"}function r2e(t,e){let[n,r,a]=qJ(e),s;if(n2e(t))s=()=>wV(t());else{const l=wV(t);s=()=>l}function o(l=s(),c){let u=[n[c.type],...r.filter(({matcher:d})=>d(c)).map(({reducer:d})=>d)];return u.filter(d=>!!d).length===0&&(u=[a]),u.reduce((d,m)=>{if(m)if(Wd(d)){const f=m(d,c);return f===void 0?d:f}else{if(Ec(d))return zJ(d,p=>m(p,c));{const p=m(d,c);if(p===void 0){if(d===null)return d;throw Error("A case reducer on a non-draftable value must not return undefined")}return p}}return d},l)}return o.getInitialState=s,o}var i2e="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW",a2e=(t=21)=>{let e="",n=t;for(;n--;)e+=i2e[Math.random()*64|0];return e},s2e=Symbol.for("rtk-slice-createasyncthunk");function o2e(t,e){return`${t}/${e}`}function l2e({creators:t}={}){const e=t?.asyncThunk?.[s2e];return function(r){const{name:a,reducerPath:s=a}=r;if(!a)throw new Error(tl(11));const o=(typeof r.reducers=="function"?r.reducers(u2e()):r.reducers)||{},l=Object.keys(o),c={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},u={addCase(N,C){const k=typeof N=="string"?N:N.type;if(!k)throw new Error(tl(12));if(k in c.sliceCaseReducersByType)throw new Error(tl(13));return c.sliceCaseReducersByType[k]=C,u},addMatcher(N,C){return c.sliceMatchers.push({matcher:N,reducer:C}),u},exposeAction(N,C){return c.actionCreators[N]=C,u},exposeCaseReducer(N,C){return c.sliceCaseReducersByName[N]=C,u}};l.forEach(N=>{const C=o[N],k={reducerName:N,type:o2e(a,N),createNotation:typeof r.reducers=="function"};m2e(C)?p2e(k,C,u,e):d2e(k,C,u)});function d(){const[N={},C=[],k=void 0]=typeof r.extraReducers=="function"?qJ(r.extraReducers):[r.extraReducers],P={...N,...c.sliceCaseReducersByType};return r2e(r.initialState,T=>{for(let D in P)T.addCase(D,P[D]);for(let D of c.sliceMatchers)T.addMatcher(D.matcher,D.reducer);for(let D of C)T.addMatcher(D.matcher,D.reducer);k&&T.addDefaultCase(k)})}const m=N=>N,p=new Map,f=new WeakMap;let y;function v(N,C){return y||(y=d()),y(N,C)}function b(){return y||(y=d()),y.getInitialState()}function g(N,C=!1){function k(T){let D=T[N];return typeof D>"u"&&C&&(D=x1(f,k,b)),D}function P(T=m){const D=x1(p,C,()=>new WeakMap);return x1(D,T,()=>{const A={};for(const[R,G]of Object.entries(r.selectors??{}))A[R]=c2e(G,T,()=>x1(f,T,b),C);return A})}return{reducerPath:N,getSelectors:P,get selectors(){return P(k)},selectSlice:k}}const _={name:a,reducer:v,actions:c.actionCreators,caseReducers:c.sliceCaseReducersByName,getInitialState:b,...g(s),injectInto(N,{reducerPath:C,...k}={}){const P=C??s;return N.inject({reducerPath:P,reducer:v},k),{..._,...g(P,!0)}}};return _}}function c2e(t,e,n,r){function a(s,...o){let l=e(s);return typeof l>"u"&&r&&(l=n()),t(l,...o)}return a.unwrapped=t,a}var Ao=l2e();function u2e(){function t(e,n){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...n}}return t.withTypes=()=>t,{reducer(e){return Object.assign({[e.name](...n){return e(...n)}}[e.name],{_reducerDefinitionType:"reducer"})},preparedReducer(e,n){return{_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:n}},asyncThunk:t}}function d2e({type:t,reducerName:e,createNotation:n},r,a){let s,o;if("reducer"in r){if(n&&!h2e(r))throw new Error(tl(17));s=r.reducer,o=r.prepare}else s=r;a.addCase(t,s).exposeCaseReducer(e,s).exposeAction(e,o?Yl(t,o):Yl(t))}function m2e(t){return t._reducerDefinitionType==="asyncThunk"}function h2e(t){return t._reducerDefinitionType==="reducerWithPrepare"}function p2e({type:t,reducerName:e},n,r,a){if(!a)throw new Error(tl(18));const{payloadCreator:s,fulfilled:o,pending:l,rejected:c,settled:u,options:d}=n,m=a(t,s,d);r.exposeAction(e,m),o&&r.addCase(m.fulfilled,o),l&&r.addCase(m.pending,l),c&&r.addCase(m.rejected,c),u&&r.addMatcher(m.settled,u),r.exposeCaseReducer(e,{fulfilled:o||y1,pending:l||y1,rejected:c||y1,settled:u||y1})}function y1(){}var f2e="task",VJ="listener",GJ="completed",KO="cancelled",g2e=`task-${KO}`,b2e=`task-${GJ}`,XR=`${VJ}-${KO}`,x2e=`${VJ}-${GJ}`,LT=class{constructor(t){this.code=t,this.message=`${f2e} ${KO} (reason: ${t})`}name="TaskAbortError";message},YO=(t,e)=>{if(typeof t!="function")throw new TypeError(tl(32))},bk=()=>{},WJ=(t,e=bk)=>(t.catch(e),t),KJ=(t,e)=>(t.addEventListener("abort",e,{once:!0}),()=>t.removeEventListener("abort",e)),gf=t=>{if(t.aborted)throw new LT(t.reason)};function YJ(t,e){let n=bk;return new Promise((r,a)=>{const s=()=>a(new LT(t.reason));if(t.aborted){s();return}n=KJ(t,s),e.finally(()=>n()).then(r,a)}).finally(()=>{n=bk})}var y2e=async(t,e)=>{try{return await Promise.resolve(),{status:"ok",value:await t()}}catch(n){return{status:n instanceof LT?"cancelled":"rejected",error:n}}finally{e?.()}},xk=t=>e=>WJ(YJ(t,e).then(n=>(gf(t),n))),XJ=t=>{const e=xk(t);return n=>e(new Promise(r=>setTimeout(r,n)))},{assign:tx}=Object,_V={},OT="listenerMiddleware",v2e=(t,e)=>{const n=r=>KJ(t,()=>r.abort(t.reason));return(r,a)=>{YO(r);const s=new AbortController;n(s);const o=y2e(async()=>{gf(t),gf(s.signal);const l=await r({pause:xk(s.signal),delay:XJ(s.signal),signal:s.signal});return gf(s.signal),l},()=>s.abort(b2e));return a?.autoJoin&&e.push(o.catch(bk)),{result:xk(t)(o),cancel(){s.abort(g2e)}}}},w2e=(t,e)=>{const n=async(r,a)=>{gf(e);let s=()=>{};const l=[new Promise((c,u)=>{let d=t({predicate:r,effect:(m,p)=>{p.unsubscribe(),c([m,p.getState(),p.getOriginalState()])}});s=()=>{d(),u()}})];a!=null&&l.push(new Promise(c=>setTimeout(c,a,null)));try{const c=await YJ(e,Promise.race(l));return gf(e),c}finally{s()}};return(r,a)=>WJ(n(r,a))},QJ=t=>{let{type:e,actionCreator:n,matcher:r,predicate:a,effect:s}=t;if(e)a=Yl(e).match;else if(n)e=n.type,a=n.match;else if(r)a=r;else if(!a)throw new Error(tl(21));return YO(s),{predicate:a,type:e,effect:s}},ZJ=tx(t=>{const{type:e,predicate:n,effect:r}=QJ(t);return{id:a2e(),effect:r,type:e,predicate:n,pending:new Set,unsubscribe:()=>{throw new Error(tl(22))}}},{withTypes:()=>ZJ}),NV=(t,e)=>{const{type:n,effect:r,predicate:a}=QJ(e);return Array.from(t.values()).find(s=>(typeof n=="string"?s.type===n:s.predicate===a)&&s.effect===r)},QR=t=>{t.pending.forEach(e=>{e.abort(XR)})},S2e=(t,e)=>()=>{for(const n of e.keys())QR(n);t.clear()},kV=(t,e,n)=>{try{t(e,n)}catch(r){setTimeout(()=>{throw r},0)}},JJ=tx(Yl(`${OT}/add`),{withTypes:()=>JJ}),_2e=Yl(`${OT}/removeAll`),eee=tx(Yl(`${OT}/remove`),{withTypes:()=>eee}),N2e=(...t)=>{console.error(`${OT}/error`,...t)},Mw=(t={})=>{const e=new Map,n=new Map,r=f=>{const y=n.get(f)??0;n.set(f,y+1)},a=f=>{const y=n.get(f)??1;y===1?n.delete(f):n.set(f,y-1)},{extra:s,onError:o=N2e}=t;YO(o);const l=f=>(f.unsubscribe=()=>e.delete(f.id),e.set(f.id,f),y=>{f.unsubscribe(),y?.cancelActive&&QR(f)}),c=f=>{const y=NV(e,f)??ZJ(f);return l(y)};tx(c,{withTypes:()=>c});const u=f=>{const y=NV(e,f);return y&&(y.unsubscribe(),f.cancelActive&&QR(y)),!!y};tx(u,{withTypes:()=>u});const d=async(f,y,v,b)=>{const g=new AbortController,_=w2e(c,g.signal),N=[];try{f.pending.add(g),r(f),await Promise.resolve(f.effect(y,tx({},v,{getOriginalState:b,condition:(C,k)=>_(C,k).then(Boolean),take:_,delay:XJ(g.signal),pause:xk(g.signal),extra:s,signal:g.signal,fork:v2e(g.signal,N),unsubscribe:f.unsubscribe,subscribe:()=>{e.set(f.id,f)},cancelActiveListeners:()=>{f.pending.forEach((C,k,P)=>{C!==g&&(C.abort(XR),P.delete(C))})},cancel:()=>{g.abort(XR),f.pending.delete(g)},throwIfCancelled:()=>{gf(g.signal)}})))}catch(C){C instanceof LT||kV(o,C,{raisedBy:"effect"})}finally{await Promise.all(N),g.abort(x2e),a(f),f.pending.delete(g)}},m=S2e(e,n);return{middleware:f=>y=>v=>{if(!PJ(v))return y(v);if(JJ.match(v))return c(v.payload);if(_2e.match(v)){m();return}if(eee.match(v))return u(v.payload);let b=f.getState();const g=()=>{if(b===_V)throw new Error(tl(23));return b};let _;try{if(_=y(v),e.size>0){const N=f.getState(),C=Array.from(e.values());for(const k of C){let P=!1;try{P=k.predicate(v,N,b)}catch(T){P=!1,kV(o,T,{raisedBy:"predicate"})}P&&d(k,v,f,g)}}}finally{b=_V}return _},startListening:c,stopListening:u,clearListeners:m}};function tl(t){return`Minified Redux Toolkit error #${t}; visit https://redux-toolkit.js.org/Errors?code=${t} for the full message or use the non-minified dev environment for full errors. `}var k2e={layoutType:"horizontal",width:0,height:0,margin:{top:5,right:5,bottom:5,left:5},scale:1},tee=Ao({name:"chartLayout",initialState:k2e,reducers:{setLayout(t,e){t.layoutType=e.payload},setChartSize(t,e){t.width=e.payload.width,t.height=e.payload.height},setMargin(t,e){var n,r,a,s;t.margin.top=(n=e.payload.top)!==null&&n!==void 0?n:0,t.margin.right=(r=e.payload.right)!==null&&r!==void 0?r:0,t.margin.bottom=(a=e.payload.bottom)!==null&&a!==void 0?a:0,t.margin.left=(s=e.payload.left)!==null&&s!==void 0?s:0},setScale(t,e){t.scale=e.payload}}}),{setMargin:C2e,setLayout:T2e,setChartSize:A2e,setScale:P2e}=tee.actions,M2e=tee.reducer;function nee(t,e,n){return Array.isArray(t)&&t&&e+n!==0?t.slice(e,n+1):t}function Ln(t){return Number.isFinite(t)}function vu(t){return typeof t=="number"&&t>0&&Number.isFinite(t)}function CV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Hb(t){for(var e=1;e{if(e&&n){var{width:r,height:a}=n,{align:s,verticalAlign:o,layout:l}=e;if((l==="vertical"||l==="horizontal"&&o==="middle")&&s!=="center"&&Yt(t[s]))return Hb(Hb({},t),{},{[s]:t[s]+(r||0)});if((l==="horizontal"||l==="vertical"&&s==="center")&&o!=="middle"&&Yt(t[o]))return Hb(Hb({},t),{},{[o]:t[o]+(a||0)})}return t},Fc=(t,e)=>t==="horizontal"&&e==="xAxis"||t==="vertical"&&e==="yAxis"||t==="centric"&&e==="angleAxis"||t==="radial"&&e==="radiusAxis",ree=(t,e,n,r)=>{if(r)return t.map(l=>l.coordinate);var a,s,o=t.map(l=>(l.coordinate===e&&(a=!0),l.coordinate===n&&(s=!0),l.coordinate));return a||o.push(e),s||o.push(n),o},iee=(t,e,n)=>{if(!t)return null;var{duplicateDomain:r,type:a,range:s,scale:o,realScaleType:l,isCategorical:c,categoricalDomain:u,tickCount:d,ticks:m,niceTicks:p,axisType:f}=t;if(!o)return null;var y=l==="scaleBand"&&o.bandwidth?o.bandwidth()/2:2,v=a==="category"&&o.bandwidth?o.bandwidth()/y:0;if(v=f==="angleAxis"&&s&&s.length>=2?Fa(s[0]-s[1])*2*v:v,m||p){var b=(m||p||[]).map((g,_)=>{var N=r?r.indexOf(g):g,C=o.map(N);return Ln(C)?{coordinate:C+v,value:g,offset:v,index:_}:null}).filter(yo);return b}return c&&u?u.map((g,_)=>{var N=o.map(g);return Ln(N)?{coordinate:N+v,value:g,index:_,offset:v}:null}).filter(yo):o.ticks&&d!=null?o.ticks(d).map((g,_)=>{var N=o.map(g);return Ln(N)?{coordinate:N+v,value:g,index:_,offset:v}:null}).filter(yo):o.domain().map((g,_)=>{var N=o.map(g);return Ln(N)?{coordinate:N+v,value:r?r[g]:g,index:_,offset:v}:null}).filter(yo)},F2e=(t,e)=>{if(!e||e.length!==2||!Yt(e[0])||!Yt(e[1]))return t;var n=Math.min(e[0],e[1]),r=Math.max(e[0],e[1]),a=[t[0],t[1]];return(!Yt(t[0])||t[0]r)&&(a[1]=r),a[0]>r&&(a[0]=r),a[1]{var e,n=t.length;if(!(n<=0)){var r=(e=t[0])===null||e===void 0?void 0:e.length;if(!(r==null||r<=0))for(var a=0;a=0?(u[0]=s,s+=p,u[1]=s):(u[0]=o,o+=p,u[1]=o)}}}},O2e=t=>{var e,n=t.length;if(!(n<=0)){var r=(e=t[0])===null||e===void 0?void 0:e.length;if(!(r==null||r<=0))for(var a=0;a=0?(c[0]=s,s+=u,c[1]=s):(c[0]=0,c[1]=0)}}}},I2e={sign:L2e,expand:oEe,none:Uf,silhouette:lEe,wiggle:cEe,positive:O2e},z2e=(t,e,n)=>{var r,a=(r=I2e[n])!==null&&r!==void 0?r:Uf,s=sEe().keys(e).value((l,c)=>Number(Tr(l,c,0))).order(UR).offset(a),o=s(t);return o.forEach((l,c)=>{l.forEach((u,d)=>{var m=Tr(t[d],e[c],0);Array.isArray(m)&&m.length===2&&Yt(m[0])&&Yt(m[1])&&(u[0]=m[0],u[1]=m[1])})}),o};function aee(t){return t==null?void 0:String(t)}function yk(t){var{axis:e,ticks:n,bandSize:r,entry:a,index:s,dataKey:o}=t;if(e.type==="category"){if(!e.allowDuplicatedCategory&&e.dataKey&&!gi(a[e.dataKey])){var l=cJ(n,"value",a[e.dataKey]);if(l)return l.coordinate+r/2}return n!=null&&n[s]?n[s].coordinate+r/2:null}var c=Tr(a,gi(o)?e.dataKey:o),u=e.scale.map(c);return Yt(u)?u:null}var TV=t=>{var{axis:e,ticks:n,offset:r,bandSize:a,entry:s,index:o}=t;if(e.type==="category")return n[o]?n[o].coordinate+r:null;var l=Tr(s,e.dataKey,e.scale.domain()[o]);if(gi(l))return null;var c=e.scale.map(l);return Yt(c)?c-a/2+r:null},U2e=t=>{var{numericAxis:e}=t,n=e.scale.domain();if(e.type==="number"){var r=Math.min(n[0],n[1]),a=Math.max(n[0],n[1]);return r<=0&&a>=0?0:a<0?a:r}return n[0]},B2e=t=>{var e=t.flat(2).filter(Yt);return[Math.min(...e),Math.max(...e)]},H2e=t=>[t[0]===1/0?0:t[0],t[1]===-1/0?0:t[1]],$2e=(t,e,n)=>{if(t!=null)return H2e(Object.keys(t).reduce((r,a)=>{var s=t[a];if(!s)return r;var{stackedData:o}=s,l=o.reduce((c,u)=>{var d=nee(u,e,n),m=B2e(d);return!Ln(m[0])||!Ln(m[1])?c:[Math.min(c[0],m[0]),Math.max(c[1],m[1])]},[1/0,-1/0]);return[Math.min(l[0],r[0]),Math.max(l[1],r[1])]},[1/0,-1/0]))},AV=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,PV=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,qh=(t,e,n)=>{if(t&&t.scale&&t.scale.bandwidth){var r=t.scale.bandwidth();if(!n||r>0)return r}if(t&&e&&e.length>=2){for(var a=AT(e,d=>d.coordinate),s=1/0,o=1,l=a.length;o{if(e==="horizontal")return t.chartX;if(e==="vertical")return t.chartY},V2e=(t,e)=>e==="centric"?t.angle:t.radius,tm=t=>t.layout.width,nm=t=>t.layout.height,G2e=t=>t.layout.scale,see=t=>t.layout.margin,IT=yt(t=>t.cartesianAxis.xAxis,t=>Object.values(t)),zT=yt(t=>t.cartesianAxis.yAxis,t=>Object.values(t)),oee="data-recharts-item-index",lee="data-recharts-item-id",Ew=60;function EV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function v1(t){for(var e=1;et.brush.height;function Q2e(t){var e=zT(t);return e.reduce((n,r)=>{if(r.orientation==="left"&&!r.mirror&&!r.hide){var a=typeof r.width=="number"?r.width:Ew;return n+a}return n},0)}function Z2e(t){var e=zT(t);return e.reduce((n,r)=>{if(r.orientation==="right"&&!r.mirror&&!r.hide){var a=typeof r.width=="number"?r.width:Ew;return n+a}return n},0)}function J2e(t){var e=IT(t);return e.reduce((n,r)=>r.orientation==="top"&&!r.mirror&&!r.hide?n+r.height:n,0)}function eDe(t){var e=IT(t);return e.reduce((n,r)=>r.orientation==="bottom"&&!r.mirror&&!r.hide?n+r.height:n,0)}var va=yt([tm,nm,see,X2e,Q2e,Z2e,J2e,eDe,kJ,Tje],(t,e,n,r,a,s,o,l,c,u)=>{var d={left:(n.left||0)+a,right:(n.right||0)+s},m={top:(n.top||0)+o,bottom:(n.bottom||0)+l},p=v1(v1({},m),d),f=p.bottom;p.bottom+=r,p=R2e(p,c,u);var y=t-p.left-p.right,v=e-p.top-p.bottom;return v1(v1({brushBottom:f},p),{},{width:Math.max(y,0),height:Math.max(v,0)})}),tDe=yt(va,t=>({x:t.left,y:t.top,width:t.width,height:t.height})),XO=yt(tm,nm,(t,e)=>({x:0,y:0,width:t,height:e})),nDe=w.createContext(null),wa=()=>w.useContext(nDe)!=null,UT=t=>t.brush,BT=yt([UT,va,see],(t,e,n)=>({height:t.height,x:Yt(t.x)?t.x:e.left,y:Yt(t.y)?t.y:e.top+e.height+e.brushBottom-(n?.bottom||0),width:Yt(t.width)?t.width:e.width})),g2={},b2={},x2={},jV;function rDe(){return jV||(jV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r,{signal:a,edges:s}={}){let o,l=null;const c=s!=null&&s.includes("leading"),u=s==null||s.includes("trailing"),d=()=>{l!==null&&(n.apply(o,l),o=void 0,l=null)},m=()=>{u&&d(),v()};let p=null;const f=()=>{p!=null&&clearTimeout(p),p=setTimeout(()=>{p=null,m()},r)},y=()=>{p!==null&&(clearTimeout(p),p=null)},v=()=>{y(),o=void 0,l=null},b=()=>{d()},g=function(..._){if(a?.aborted)return;o=this,l=_;const N=p==null;f(),c&&N&&d()};return g.schedule=f,g.cancel=v,g.flush=b,a?.addEventListener("abort",v,{once:!0}),g}t.debounce=e})(x2)),x2}var DV;function iDe(){return DV||(DV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=rDe();function n(r,a=0,s={}){typeof s!="object"&&(s={});const{leading:o=!1,trailing:l=!0,maxWait:c}=s,u=Array(2);o&&(u[0]="leading"),l&&(u[1]="trailing");let d,m=null;const p=e.debounce(function(...v){d=r.apply(this,v),m=null},a,{edges:u}),f=function(...v){return c!=null&&(m===null&&(m=Date.now()),Date.now()-m>=c)?(d=r.apply(this,v),m=Date.now(),p.cancel(),p.schedule(),d):(p.apply(this,v),d)},y=()=>(p.flush(),d);return f.cancel=p.cancel,f.flush=y,f}t.debounce=n})(b2)),b2}var RV;function aDe(){return RV||(RV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=iDe();function n(r,a=0,s={}){const{leading:o=!0,trailing:l=!0}=s;return e.debounce(r,a,{leading:o,maxWait:a,trailing:l})}t.throttle=n})(g2)),g2}var y2,FV;function sDe(){return FV||(FV=1,y2=aDe().throttle),y2}var oDe=sDe();const lDe=Zl(oDe);var vk=function(e,n){for(var r=arguments.length,a=new Array(r>2?r-2:0),s=2;sa[o++]))}},uu={width:"100%",height:"100%",debounce:0,minWidth:0,initialDimension:{width:-1,height:-1}},cee=(t,e,n)=>{var{width:r=uu.width,height:a=uu.height,aspect:s,maxHeight:o}=n,l=Hf(r)?t:Number(r),c=Hf(a)?e:Number(a);return s&&s>0&&(l?c=l/s:c&&(l=c*s),o&&c!=null&&c>o&&(c=o)),{calculatedWidth:l,calculatedHeight:c}},cDe={width:0,height:0,overflow:"visible"},uDe={width:0,overflowX:"visible"},dDe={height:0,overflowY:"visible"},mDe={},hDe=t=>{var{width:e,height:n}=t,r=Hf(e),a=Hf(n);return r&&a?cDe:r?uDe:a?dDe:mDe};function pDe(t){var{width:e,height:n,aspect:r}=t,a=e,s=n;return a===void 0&&s===void 0?(a=uu.width,s=uu.height):a===void 0?a=r&&r>0?void 0:uu.width:s===void 0&&(s=r&&r>0?void 0:uu.height),{width:a,height:s}}function ZR(){return ZR=Object.assign?Object.assign.bind():function(t){for(var e=1;e({width:n,height:r}),[n,r]);return xDe(a)?w.createElement(uee.Provider,{value:a},e):null}var QO=()=>w.useContext(uee),yDe=w.forwardRef((t,e)=>{var{aspect:n,initialDimension:r=uu.initialDimension,width:a,height:s,minWidth:o=uu.minWidth,minHeight:l,maxHeight:c,children:u,debounce:d=uu.debounce,id:m,className:p,onResize:f,style:y={}}=t,v=w.useRef(null),b=w.useRef();b.current=f,w.useImperativeHandle(e,()=>v.current);var[g,_]=w.useState({containerWidth:r.width,containerHeight:r.height}),N=w.useCallback((D,A)=>{_(R=>{var G=Math.round(D),z=Math.round(A);return R.containerWidth===G&&R.containerHeight===z?R:{containerWidth:G,containerHeight:z}})},[]);w.useEffect(()=>{if(v.current==null||typeof ResizeObserver>"u")return Yh;var D=z=>{var Z,I=z[0];if(I!=null){var{width:J,height:ae}=I.contentRect;N(J,ae),(Z=b.current)===null||Z===void 0||Z.call(b,J,ae)}};d>0&&(D=lDe(D,d,{trailing:!0,leading:!1}));var A=new ResizeObserver(D),{width:R,height:G}=v.current.getBoundingClientRect();return N(R,G),A.observe(v.current),()=>{A.disconnect()}},[N,d]);var{containerWidth:C,containerHeight:k}=g;vk(!n||n>0,"The aspect(%s) must be greater than zero.",n);var{calculatedWidth:P,calculatedHeight:T}=cee(C,k,{width:a,height:s,aspect:n,maxHeight:c});return vk(P!=null&&P>0||T!=null&&T>0,`The width(%s) and height(%s) of chart should be greater than 0, please check the style of container, or the props width(%s) and height(%s), or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the - height and width.`,P,T,a,s,o,l,n),w.createElement("div",{id:m?"".concat(m):void 0,className:hr("recharts-responsive-container",p),style:OV(OV({},y),{},{width:a,height:s,minWidth:o,minHeight:l,maxHeight:c}),ref:v},w.createElement("div",{style:hDe({width:a,height:s})},w.createElement(dee,{width:P,height:T},u)))}),bh=w.forwardRef((t,e)=>{var n=QO();if(vu(n.width)&&vu(n.height))return t.children;var{width:r,height:a}=pDe({width:t.width,height:t.height,aspect:t.aspect}),{calculatedWidth:s,calculatedHeight:o}=cee(void 0,void 0,{width:r,height:a,aspect:t.aspect,maxHeight:t.maxHeight});return Yt(s)&&Yt(o)?w.createElement(dee,{width:s,height:o},t.children):w.createElement(yDe,ZR({},t,{width:r,height:a,ref:e}))});function ZO(t){if(t)return{x:t.x,y:t.y,upperWidth:"upperWidth"in t?t.upperWidth:t.width,lowerWidth:"lowerWidth"in t?t.lowerWidth:t.width,width:t.width,height:t.height}}var jw=()=>{var t,e=wa(),n=en(tDe),r=en(BT),a=(t=en(UT))===null||t===void 0?void 0:t.padding;return!e||!r||!a?n:{width:r.width-a.left-a.right,height:r.height-a.top-a.bottom,x:a.left,y:a.top}},vDe={top:0,bottom:0,left:0,right:0,width:0,height:0,brushBottom:0},mee=()=>{var t;return(t=en(va))!==null&&t!==void 0?t:vDe},JO=()=>en(tm),e4=()=>en(nm),wDe=()=>en(t=>t.layout.margin),dr=t=>t.layout.layoutType,Qh=()=>en(dr),t4=()=>{var t=Qh();if(t==="horizontal"||t==="vertical")return t},hee=t=>{var e=t.layout.layoutType;if(e==="centric"||e==="radial")return e},SDe=()=>{var t=Qh();return t!==void 0},Dw=t=>{var e=Jr(),n=wa(),{width:r,height:a}=t,s=QO(),o=r,l=a;return s&&(o=s.width>0?s.width:r,l=s.height>0?s.height:a),w.useEffect(()=>{!n&&vu(o)&&vu(l)&&e(Aje({width:o,height:l}))},[e,n,o,l]),null},pee=Symbol.for("immer-nothing"),IV=Symbol.for("immer-draftable"),al=Symbol.for("immer-state");function bc(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var B0=Object.getPrototypeOf;function Nx(t){return!!t&&!!t[al]}function qf(t){return t?fee(t)||Array.isArray(t)||!!t[IV]||!!t.constructor?.[IV]||Rw(t)||$T(t):!1}var _De=Object.prototype.constructor.toString(),zV=new WeakMap;function fee(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);if(e===null||e===Object.prototype)return!0;const n=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;if(n===Object)return!0;if(typeof n!="function")return!1;let r=zV.get(n);return r===void 0&&(r=Function.toString.call(n),zV.set(n,r)),r===_De}function wk(t,e,n=!0){HT(t)===0?(n?Reflect.ownKeys(t):Object.keys(t)).forEach(a=>{e(a,t[a],t)}):t.forEach((r,a)=>e(a,r,t))}function HT(t){const e=t[al];return e?e.type_:Array.isArray(t)?1:Rw(t)?2:$T(t)?3:0}function JR(t,e){return HT(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function gee(t,e,n){const r=HT(t);r===2?t.set(e,n):r===3?t.add(n):t[e]=n}function NDe(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function Rw(t){return t instanceof Map}function $T(t){return t instanceof Set}function Bp(t){return t.copy_||t.base_}function eF(t,e){if(Rw(t))return new Map(t);if($T(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);const n=fee(t);if(e===!0||e==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(t);delete r[al];let a=Reflect.ownKeys(r);for(let s=0;s1&&Object.defineProperties(t,{set:w1,add:w1,clear:w1,delete:w1}),Object.freeze(t),e&&Object.values(t).forEach(n=>n4(n,!0))),t}function kDe(){bc(2)}var w1={value:kDe};function qT(t){return t===null||typeof t!="object"?!0:Object.isFrozen(t)}var CDe={};function Vf(t){const e=CDe[t];return e||bc(0,t),e}var H0;function bee(){return H0}function TDe(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function UV(t,e){e&&(Vf("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function tF(t){nF(t),t.drafts_.forEach(ADe),t.drafts_=null}function nF(t){t===H0&&(H0=t.parent_)}function BV(t){return H0=TDe(H0,t)}function ADe(t){const e=t[al];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function HV(t,e){e.unfinalizedDrafts_=e.drafts_.length;const n=e.drafts_[0];return t!==void 0&&t!==n?(n[al].modified_&&(tF(e),bc(4)),qf(t)&&(t=Sk(e,t),e.parent_||_k(e,t)),e.patches_&&Vf("Patches").generateReplacementPatches_(n[al].base_,t,e.patches_,e.inversePatches_)):t=Sk(e,n,[]),tF(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==pee?t:void 0}function Sk(t,e,n){if(qT(e))return e;const r=t.immer_.shouldUseStrictIteration(),a=e[al];if(!a)return wk(e,(s,o)=>$V(t,a,e,s,o,n),r),e;if(a.scope_!==t)return e;if(!a.modified_)return _k(t,a.base_,!0),a.base_;if(!a.finalized_){a.finalized_=!0,a.scope_.unfinalizedDrafts_--;const s=a.copy_;let o=s,l=!1;a.type_===3&&(o=new Set(s),s.clear(),l=!0),wk(o,(c,u)=>$V(t,a,s,c,u,n,l),r),_k(t,s,!1),n&&t.patches_&&Vf("Patches").generatePatches_(a,n,t.patches_,t.inversePatches_)}return a.copy_}function $V(t,e,n,r,a,s,o){if(a==null||typeof a!="object"&&!o)return;const l=qT(a);if(!(l&&!o)){if(Nx(a)){const c=s&&e&&e.type_!==3&&!JR(e.assigned_,r)?s.concat(r):void 0,u=Sk(t,a,c);if(gee(n,r,u),Nx(u))t.canAutoFreeze_=!1;else return}else o&&n.add(a);if(qf(a)&&!l){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1||e&&e.base_&&e.base_[r]===a&&l)return;Sk(t,a),(!e||!e.scope_.parent_)&&typeof r!="symbol"&&(Rw(n)?n.has(r):Object.prototype.propertyIsEnumerable.call(n,r))&&_k(t,a)}}}function _k(t,e,n=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&n4(e,n)}function PDe(t,e){const n=Array.isArray(t),r={type_:n?1:0,scope_:e?e.scope_:bee(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1};let a=r,s=r4;n&&(a=[r],s=$0);const{revoke:o,proxy:l}=Proxy.revocable(a,s);return r.draft_=l,r.revoke_=o,l}var r4={get(t,e){if(e===al)return t;const n=Bp(t);if(!JR(n,e))return MDe(t,n,e);const r=n[e];return t.finalized_||!qf(r)?r:r===vj(t.base_,e)?(wj(t),t.copy_[e]=iF(r,t)):r},has(t,e){return e in Bp(t)},ownKeys(t){return Reflect.ownKeys(Bp(t))},set(t,e,n){const r=xee(Bp(t),e);if(r?.set)return r.set.call(t.draft_,n),!0;if(!t.modified_){const a=vj(Bp(t),e),s=a?.[al];if(s&&s.base_===n)return t.copy_[e]=n,t.assigned_[e]=!1,!0;if(NDe(n,a)&&(n!==void 0||JR(t.base_,e)))return!0;wj(t),rF(t)}return t.copy_[e]===n&&(n!==void 0||e in t.copy_)||Number.isNaN(n)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=n,t.assigned_[e]=!0),!0},deleteProperty(t,e){return vj(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,wj(t),rF(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){const n=Bp(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:r.enumerable,value:n[e]}},defineProperty(){bc(11)},getPrototypeOf(t){return B0(t.base_)},setPrototypeOf(){bc(12)}},$0={};wk(r4,(t,e)=>{$0[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});$0.deleteProperty=function(t,e){return $0.set.call(this,t,e,void 0)};$0.set=function(t,e,n){return r4.set.call(this,t[0],e,n,t[0])};function vj(t,e){const n=t[al];return(n?Bp(n):t)[e]}function MDe(t,e,n){const r=xee(e,n);return r?"value"in r?r.value:r.get?.call(t.draft_):void 0}function xee(t,e){if(!(e in t))return;let n=B0(t);for(;n;){const r=Object.getOwnPropertyDescriptor(n,e);if(r)return r;n=B0(n)}}function rF(t){t.modified_||(t.modified_=!0,t.parent_&&rF(t.parent_))}function wj(t){t.copy_||(t.copy_=eF(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var EDe=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(e,n,r)=>{if(typeof e=="function"&&typeof n!="function"){const s=n;n=e;const o=this;return function(c=s,...u){return o.produce(c,d=>n.call(this,d,...u))}}typeof n!="function"&&bc(6),r!==void 0&&typeof r!="function"&&bc(7);let a;if(qf(e)){const s=BV(this),o=iF(e,void 0);let l=!0;try{a=n(o),l=!1}finally{l?tF(s):nF(s)}return UV(s,r),HV(a,s)}else if(!e||typeof e!="object"){if(a=n(e),a===void 0&&(a=e),a===pee&&(a=void 0),this.autoFreeze_&&n4(a,!0),r){const s=[],o=[];Vf("Patches").generateReplacementPatches_(e,a,s,o),r(s,o)}return a}else bc(1,e)},this.produceWithPatches=(e,n)=>{if(typeof e=="function")return(o,...l)=>this.produceWithPatches(o,c=>e(c,...l));let r,a;return[this.produce(e,n,(o,l)=>{r=o,a=l}),r,a]},typeof t?.autoFreeze=="boolean"&&this.setAutoFreeze(t.autoFreeze),typeof t?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(t.useStrictShallowCopy),typeof t?.useStrictIteration=="boolean"&&this.setUseStrictIteration(t.useStrictIteration)}createDraft(t){qf(t)||bc(8),Nx(t)&&(t=jDe(t));const e=BV(this),n=iF(t,void 0);return n[al].isManual_=!0,nF(e),n}finishDraft(t,e){const n=t&&t[al];(!n||!n.isManual_)&&bc(9);const{scope_:r}=n;return UV(r,e),HV(void 0,r)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}setUseStrictIteration(t){this.useStrictIteration_=t}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(t,e){let n;for(n=e.length-1;n>=0;n--){const a=e[n];if(a.path.length===0&&a.op==="replace"){t=a.value;break}}n>-1&&(e=e.slice(n+1));const r=Vf("Patches").applyPatches_;return Nx(t)?r(t,e):this.produce(t,a=>r(a,e))}};function iF(t,e){const n=Rw(t)?Vf("MapSet").proxyMap_(t,e):$T(t)?Vf("MapSet").proxySet_(t,e):PDe(t,e);return(e?e.scope_:bee()).drafts_.push(n),n}function jDe(t){return Nx(t)||bc(10,t),yee(t)}function yee(t){if(!qf(t)||qT(t))return t;const e=t[al];let n,r=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,n=eF(t,e.scope_.immer_.useStrictShallowCopy_),r=e.scope_.immer_.shouldUseStrictIteration()}else n=eF(t,!0);return wk(n,(a,s)=>{gee(n,a,yee(s))},r),e&&(e.finalized_=!1),n}var DDe=new EDe;DDe.produce;var RDe={settings:{layout:"horizontal",align:"center",verticalAlign:"middle",itemSorter:"value"},size:{width:0,height:0},payload:[]},vee=Ao({name:"legend",initialState:RDe,reducers:{setLegendSize(t,e){t.size.width=e.payload.width,t.size.height=e.payload.height},setLegendSettings(t,e){t.settings.align=e.payload.align,t.settings.layout=e.payload.layout,t.settings.verticalAlign=e.payload.verticalAlign,t.settings.itemSorter=e.payload.itemSorter},addLegendPayload:{reducer(t,e){t.payload.push(e.payload)},prepare:mi()},replaceLegendPayload:{reducer(t,e){var{prev:n,next:r}=e.payload,a=Nc(t).payload.indexOf(n);a>-1&&(t.payload[a]=r)},prepare:mi()},removeLegendPayload:{reducer(t,e){var n=Nc(t).payload.indexOf(e.payload);n>-1&&t.payload.splice(n,1)},prepare:mi()}}}),{setLegendSize:qV,setLegendSettings:FDe,addLegendPayload:wee,replaceLegendPayload:See,removeLegendPayload:_ee}=vee.actions,LDe=vee.reducer,ODe=["contextPayload"];function aF(){return aF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{e(FDe(t))},[e,t]),null}function WDe(t){var e=Jr();return w.useEffect(()=>(e(qV(t)),()=>{e(qV({width:0,height:0}))}),[e,t]),null}function KDe(t,e,n,r){return t==="vertical"&&e!=null?{height:e}:t==="horizontal"?{width:n||r}:null}var YDe={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",layout:"horizontal",verticalAlign:"bottom"};function Nee(t){var e=wi(t,YDe),n=M2e(),r=MMe(),a=wDe(),{width:s,height:o,wrapperStyle:l,portal:c}=e,[u,d]=CJ([n]),m=JO(),p=e4();if(m==null||p==null)return null;var f=m-(a?.left||0)-(a?.right||0),y=KDe(e.layout,o,s,f),v=c?l:kx(kx({position:"absolute",width:y?.width||s||"auto",height:y?.height||o||"auto"},VDe(l,e,a,m,p,u)),l),b=c??r;if(b==null||n==null)return null;var g=w.createElement("div",{className:"recharts-legend-wrapper",style:v,ref:d},w.createElement(GDe,{layout:e.layout,align:e.align,verticalAlign:e.verticalAlign,itemSorter:e.itemSorter}),!c&&w.createElement(WDe,{width:u.width,height:u.height}),w.createElement(qDe,aF({},e,y,{margin:a,chartWidth:m,chartHeight:p,contextPayload:n})));return wd.createPortal(g,b)}Nee.displayName="Legend";function sF(){return sF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{separator:e=vb.separator,contentStyle:n,itemStyle:r,labelStyle:a=vb.labelStyle,payload:s,formatter:o,itemSorter:l,wrapperClassName:c,labelClassName:u,label:d,labelFormatter:m,accessibilityLayer:p=vb.accessibilityLayer}=t,f=()=>{if(s&&s.length){var k={padding:0,margin:0},P=(l?AT(s,l):s).map((T,D)=>{if(T.type==="none")return null;var A=T.formatter||o||JDe,{value:R,name:G}=T,z=R,Z=G;if(A){var I=A(R,G,T,D,s);if(Array.isArray(I))[z,Z]=I;else if(I!=null)z=I;else return null}var J=pv(pv({},vb.itemStyle),{},{color:T.color||vb.itemStyle.color},r);return w.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(D),style:J},Kl(Z)?w.createElement("span",{className:"recharts-tooltip-item-name"},Z):null,Kl(Z)?w.createElement("span",{className:"recharts-tooltip-item-separator"},e):null,w.createElement("span",{className:"recharts-tooltip-item-value"},z),w.createElement("span",{className:"recharts-tooltip-item-unit"},T.unit||""))});return w.createElement("ul",{className:"recharts-tooltip-item-list",style:k},P)}return null},y=pv(pv({},vb.contentStyle),n),v=pv({margin:0},a),b=!gi(d),g=b?d:"",_=hr("recharts-default-tooltip",c),N=hr("recharts-tooltip-label",u);b&&m&&s!==void 0&&s!==null&&(g=m(d,s));var C=p?{role:"status","aria-live":"assertive"}:{};return w.createElement("div",sF({className:_,style:y},C),w.createElement("p",{className:N,style:v},w.isValidElement(g)?g:"".concat(g)),f())},fv="recharts-tooltip-wrapper",t3e={visibility:"hidden"};function n3e(t){var{coordinate:e,translateX:n,translateY:r}=t;return hr(fv,{["".concat(fv,"-right")]:Yt(n)&&e&&Yt(e.x)&&n>=e.x,["".concat(fv,"-left")]:Yt(n)&&e&&Yt(e.x)&&n=e.y,["".concat(fv,"-top")]:Yt(r)&&e&&Yt(e.y)&&r0?a:0),m=n[r]+a;if(e[r])return o[r]?d:m;var p=c[r];if(p==null)return 0;if(o[r]){var f=d,y=p;return fb?Math.max(d,p):Math.max(m,p)}function r3e(t){var{translateX:e,translateY:n,useTranslate3d:r}=t;return{transform:r?"translate3d(".concat(e,"px, ").concat(n,"px, 0)"):"translate(".concat(e,"px, ").concat(n,"px)")}}function i3e(t){var{allowEscapeViewBox:e,coordinate:n,offsetTop:r,offsetLeft:a,position:s,reverseDirection:o,tooltipBox:l,useTranslate3d:c,viewBox:u}=t,d,m,p;return l.height>0&&l.width>0&&n?(m=WV({allowEscapeViewBox:e,coordinate:n,key:"x",offset:a,position:s,reverseDirection:o,tooltipDimension:l.width,viewBox:u,viewBoxDimension:u.width}),p=WV({allowEscapeViewBox:e,coordinate:n,key:"y",offset:r,position:s,reverseDirection:o,tooltipDimension:l.height,viewBox:u,viewBoxDimension:u.height}),d=r3e({translateX:m,translateY:p,useTranslate3d:c})):d=t3e,{cssProperties:d,cssClasses:n3e({translateX:m,translateY:p,coordinate:n})}}function KV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function S1(t){for(var e=1;e{if(e.key==="Escape"){var n,r,a,s;this.setState({dismissed:!0,dismissedAtCoordinate:{x:(n=(r=this.props.coordinate)===null||r===void 0?void 0:r.x)!==null&&n!==void 0?n:0,y:(a=(s=this.props.coordinate)===null||s===void 0?void 0:s.y)!==null&&a!==void 0?a:0}})}})}componentDidMount(){document.addEventListener("keydown",this.handleKeyDown)}componentWillUnmount(){document.removeEventListener("keydown",this.handleKeyDown)}componentDidUpdate(){var e,n;this.state.dismissed&&(((e=this.props.coordinate)===null||e===void 0?void 0:e.x)!==this.state.dismissedAtCoordinate.x||((n=this.props.coordinate)===null||n===void 0?void 0:n.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}render(){var{active:e,allowEscapeViewBox:n,animationDuration:r,animationEasing:a,children:s,coordinate:o,hasPayload:l,isAnimationActive:c,offset:u,position:d,reverseDirection:m,useTranslate3d:p,viewBox:f,wrapperStyle:y,lastBoundingBox:v,innerRef:b,hasPortalFromProps:g}=this.props,_=typeof u=="number"?u:u.x,N=typeof u=="number"?u:u.y,{cssClasses:C,cssProperties:k}=i3e({allowEscapeViewBox:n,coordinate:o,offsetLeft:_,offsetTop:N,position:d,reverseDirection:m,tooltipBox:{height:v.height,width:v.width},useTranslate3d:p,viewBox:f}),P=g?{}:S1(S1({transition:c&&e?"transform ".concat(r,"ms ").concat(a):void 0},k),{},{pointerEvents:"none",visibility:!this.state.dismissed&&e&&l?"visible":"hidden",position:"absolute",top:0,left:0}),T=S1(S1({},P),{},{visibility:!this.state.dismissed&&e&&l?"visible":"hidden"},y);return w.createElement("div",{xmlns:"http://www.w3.org/1999/xhtml",tabIndex:-1,className:C,style:T,ref:b},s)}}var kee=()=>{var t;return(t=en(e=>e.rootProps.accessibilityLayer))!==null&&t!==void 0?t:!0};function lF(){return lF=Object.assign?Object.assign.bind():function(t){for(var e=1;eLn(t.x)&&Ln(t.y),ZV=t=>t.base!=null&&Nk(t.base)&&Nk(t),gv=t=>t.x,bv=t=>t.y,d3e=(t,e)=>{if(typeof t=="function")return t;var n="curve".concat(Tw(t));if((n==="curveMonotone"||n==="curveBump")&&e){var r=QV["".concat(n).concat(e==="vertical"?"Y":"X")];if(r)return r}return QV[n]||CT},JV={connectNulls:!1,type:"linear"},m3e=t=>{var{type:e=JV.type,points:n=[],baseLine:r,layout:a,connectNulls:s=JV.connectNulls}=t,o=d3e(e,a),l=s?n.filter(Nk):n;if(Array.isArray(r)){var c,u=n.map((y,v)=>XV(XV({},y),{},{base:r[v]}));a==="vertical"?c=p1().y(bv).x1(gv).x0(y=>y.base.x):c=p1().x(gv).y1(bv).y0(y=>y.base.y);var d=c.defined(ZV).curve(o),m=s?u.filter(ZV):u;return d(m)}var p;a==="vertical"&&Yt(r)?p=p1().y(bv).x1(gv).x0(r):Yt(r)?p=p1().x(gv).y1(bv).y0(r):p=XZ().x(gv).y(bv);var f=p.defined(Nk).curve(o);return f(l)},nx=t=>{var{className:e,points:n,path:r,pathRef:a}=t,s=Qh();if((!n||!n.length)&&!r)return null;var o={type:t.type,points:t.points,baseLine:t.baseLine,layout:t.layout||s,connectNulls:t.connectNulls},l=n&&n.length?m3e(o):r;return w.createElement("path",lF({},Ys(t),UO(t),{className:hr("recharts-curve",e),d:l===null?void 0:l,ref:a}))},h3e=["x","y","top","left","width","height","className"];function cF(){return cF=Object.assign?Object.assign.bind():function(t){for(var e=1;e"M".concat(t,",").concat(a,"v").concat(r,"M").concat(s,",").concat(e,"h").concat(n),w3e=t=>{var{x:e=0,y:n=0,top:r=0,left:a=0,width:s=0,height:o=0,className:l}=t,c=x3e(t,h3e),u=p3e({x:e,y:n,top:r,left:a,width:s,height:o},c);return!Yt(e)||!Yt(n)||!Yt(s)||!Yt(o)||!Yt(r)||!Yt(a)?null:w.createElement("path",cF({},ls(u),{className:hr("recharts-cross",l),d:v3e(e,n,s,o,r,a)}))};function S3e(t,e,n,r){var a=r/2;return{stroke:"none",fill:"#ccc",x:t==="horizontal"?e.x-a:n.left+.5,y:t==="horizontal"?n.top+.5:e.y-a,width:t==="horizontal"?r:n.width-1,height:t==="horizontal"?n.height-1:r}}function t7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function n7(t){for(var e=1;et.replace(/([A-Z])/g,e=>"-".concat(e.toLowerCase())),Cee=(t,e,n)=>t.map(r=>"".concat(C3e(r)," ").concat(e,"ms ").concat(n)).join(","),T3e=(t,e)=>[Object.keys(t),Object.keys(e)].reduce((n,r)=>n.filter(a=>r.includes(a))),q0=(t,e)=>Object.keys(e).reduce((n,r)=>n7(n7({},n),{},{[r]:t(r,e[r])}),{});function r7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function ma(t){for(var e=1;et+(e-t)*n,uF=t=>{var{from:e,to:n}=t;return e!==n},Tee=(t,e,n)=>{var r=q0((a,s)=>{if(uF(s)){var[o,l]=t(s.from,s.to,s.velocity);return ma(ma({},s),{},{from:o,velocity:l})}return s},e);return n<1?q0((a,s)=>uF(s)&&r[a]!=null?ma(ma({},s),{},{velocity:kk(s.velocity,r[a].velocity,n),from:kk(s.from,r[a].from,n)}):s,e):Tee(t,r,n-1)};function E3e(t,e,n,r,a,s){var o,l=r.reduce((p,f)=>ma(ma({},p),{},{[f]:{from:t[f],velocity:0,to:e[f]}}),{}),c=()=>q0((p,f)=>f.from,l),u=()=>!Object.values(l).filter(uF).length,d=null,m=p=>{o||(o=p);var f=p-o,y=f/n.dt;l=Tee(n,l,y),a(ma(ma(ma({},t),e),c())),o=p,u()||(d=s.setTimeout(m))};return()=>(d=s.setTimeout(m),()=>{var p;(p=d)===null||p===void 0||p()})}function j3e(t,e,n,r,a,s,o){var l=null,c=a.reduce((m,p)=>{var f=t[p],y=e[p];return f==null||y==null?m:ma(ma({},m),{},{[p]:[f,y]})},{}),u,d=m=>{u||(u=m);var p=(m-u)/r,f=q0((v,b)=>kk(...b,n(p)),c);if(s(ma(ma(ma({},t),e),f)),p<1)l=o.setTimeout(d);else{var y=q0((v,b)=>kk(...b,n(1)),c);s(ma(ma(ma({},t),e),y))}};return()=>(l=o.setTimeout(d),()=>{var m;(m=l)===null||m===void 0||m()})}const D3e=(t,e,n,r,a,s)=>{var o=T3e(t,e);return n==null?()=>(a(ma(ma({},t),e)),()=>{}):n.isStepper===!0?E3e(t,e,n,o,a,s):j3e(t,e,n,r,o,a,s)};var Ck=1e-4,Aee=(t,e)=>[0,3*t,3*e-6*t,3*t-3*e+1],Pee=(t,e)=>t.map((n,r)=>n*e**r).reduce((n,r)=>n+r),i7=(t,e)=>n=>{var r=Aee(t,e);return Pee(r,n)},R3e=(t,e)=>n=>{var r=Aee(t,e),a=[...r.map((s,o)=>s*o).slice(1),0];return Pee(a,n)},F3e=t=>{var e,n=t.split("(");if(n.length!==2||n[0]!=="cubic-bezier")return null;var r=(e=n[1])===null||e===void 0||(e=e.split(")")[0])===null||e===void 0?void 0:e.split(",");if(r==null||r.length!==4)return null;var a=r.map(s=>parseFloat(s));return[a[0],a[1],a[2],a[3]]},L3e=function(){for(var e=arguments.length,n=new Array(e),r=0;r{var a=i7(t,n),s=i7(e,r),o=R3e(t,n),l=u=>u>1?1:u<0?0:u,c=u=>{for(var d=u>1?1:u,m=d,p=0;p<8;++p){var f=a(m)-d,y=o(m);if(Math.abs(f-d)0&&arguments[0]!==void 0?arguments[0]:{},{stiff:n=100,damping:r=8,dt:a=17}=e,s=(o,l,c)=>{var u=-(o-l)*n,d=c*r,m=c+(u-d)*a/1e3,p=c*a/1e3+o;return Math.abs(p-l){if(typeof t=="string")switch(t){case"ease":case"ease-in-out":case"ease-out":case"ease-in":case"linear":return a7(t);case"spring":return I3e();default:if(t.split("(")[0]==="cubic-bezier")return a7(t)}return typeof t=="function"?t:null};function U3e(t){var e,n=()=>null,r=!1,a=null,s=o=>{if(!r){if(Array.isArray(o)){if(!o.length)return;var l=o,[c,...u]=l;if(typeof c=="number"){a=t.setTimeout(s.bind(null,u),c);return}s(c),a=t.setTimeout(s.bind(null,u));return}typeof o=="string"&&(e=o,n(e)),typeof o=="object"&&(e=o,n(e)),typeof o=="function"&&o()}};return{stop:()=>{r=!0},start:o=>{r=!1,a&&(a(),a=null),s(o)},subscribe:o=>(n=o,()=>{n=()=>null}),getTimeoutController:()=>t}}class B3e{setTimeout(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=performance.now(),a=null,s=o=>{o-r>=n?e(o):typeof requestAnimationFrame=="function"&&(a=requestAnimationFrame(s))};return a=requestAnimationFrame(s),()=>{a!=null&&cancelAnimationFrame(a)}}}function H3e(){return U3e(new B3e)}var $3e=w.createContext(H3e);function q3e(t,e){var n=w.useContext($3e);return w.useMemo(()=>e??n(t),[t,e,n])}var V3e=()=>!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout),Fw={isSsr:V3e()},G3e={begin:0,duration:1e3,easing:"ease",isActive:!0,canBegin:!0,onAnimationEnd:()=>{},onAnimationStart:()=>{}},s7={t:0},Sj={t:1};function Zx(t){var e=wi(t,G3e),{isActive:n,canBegin:r,duration:a,easing:s,begin:o,onAnimationEnd:l,onAnimationStart:c,children:u}=e,d=n==="auto"?!Fw.isSsr:n,m=q3e(e.animationId,e.animationManager),[p,f]=w.useState(d?s7:Sj),y=w.useRef(null);return w.useEffect(()=>{d||f(Sj)},[d]),w.useEffect(()=>{if(!d||!r)return Yh;var v=D3e(s7,Sj,z3e(s),a,f,m.getTimeoutController()),b=()=>{y.current=v()};return m.start([c,o,b,a,l]),()=>{m.stop(),y.current&&y.current(),l()}},[d,r,a,s,o,c,l,m]),u(p.t)}function Jx(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"animation-",n=w.useRef(O0(e)),r=w.useRef(t);return r.current!==t&&(n.current=O0(e),r.current=t),n.current}var W3e=["radius"],K3e=["radius"],o7,l7,c7,u7,d7,m7,h7,p7,f7,g7;function b7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function x7(t){for(var e=1;e{var s=gh(n),o=gh(r),l=Math.min(Math.abs(s)/2,Math.abs(o)/2),c=o>=0?1:-1,u=s>=0?1:-1,d=o>=0&&s>=0||o<0&&s<0?1:0,m;if(l>0&&Array.isArray(a)){for(var p=[0,0,0,0],f=0,y=4;fl?l:b}m=Mi(o7||(o7=Yc(["M",",",""])),t,e+c*p[0]),p[0]>0&&(m+=Mi(l7||(l7=Yc(["A ",",",",0,0,",",",",",""])),p[0],p[0],d,t+u*p[0],e)),m+=Mi(c7||(c7=Yc(["L ",",",""])),t+n-u*p[1],e),p[1]>0&&(m+=Mi(u7||(u7=Yc(["A ",",",",0,0,",`, + height and width.`,P,T,a,s,o,l,n),w.createElement("div",{id:m?"".concat(m):void 0,className:hr("recharts-responsive-container",p),style:OV(OV({},y),{},{width:a,height:s,minWidth:o,minHeight:l,maxHeight:c}),ref:v},w.createElement("div",{style:hDe({width:a,height:s})},w.createElement(dee,{width:P,height:T},u)))}),bh=w.forwardRef((t,e)=>{var n=QO();if(vu(n.width)&&vu(n.height))return t.children;var{width:r,height:a}=pDe({width:t.width,height:t.height,aspect:t.aspect}),{calculatedWidth:s,calculatedHeight:o}=cee(void 0,void 0,{width:r,height:a,aspect:t.aspect,maxHeight:t.maxHeight});return Yt(s)&&Yt(o)?w.createElement(dee,{width:s,height:o},t.children):w.createElement(yDe,ZR({},t,{width:r,height:a,ref:e}))});function ZO(t){if(t)return{x:t.x,y:t.y,upperWidth:"upperWidth"in t?t.upperWidth:t.width,lowerWidth:"lowerWidth"in t?t.lowerWidth:t.width,width:t.width,height:t.height}}var jw=()=>{var t,e=wa(),n=en(tDe),r=en(BT),a=(t=en(UT))===null||t===void 0?void 0:t.padding;return!e||!r||!a?n:{width:r.width-a.left-a.right,height:r.height-a.top-a.bottom,x:a.left,y:a.top}},vDe={top:0,bottom:0,left:0,right:0,width:0,height:0,brushBottom:0},mee=()=>{var t;return(t=en(va))!==null&&t!==void 0?t:vDe},JO=()=>en(tm),eI=()=>en(nm),wDe=()=>en(t=>t.layout.margin),dr=t=>t.layout.layoutType,Qh=()=>en(dr),tI=()=>{var t=Qh();if(t==="horizontal"||t==="vertical")return t},hee=t=>{var e=t.layout.layoutType;if(e==="centric"||e==="radial")return e},SDe=()=>{var t=Qh();return t!==void 0},Dw=t=>{var e=Jr(),n=wa(),{width:r,height:a}=t,s=QO(),o=r,l=a;return s&&(o=s.width>0?s.width:r,l=s.height>0?s.height:a),w.useEffect(()=>{!n&&vu(o)&&vu(l)&&e(A2e({width:o,height:l}))},[e,n,o,l]),null},pee=Symbol.for("immer-nothing"),IV=Symbol.for("immer-draftable"),al=Symbol.for("immer-state");function bc(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var B0=Object.getPrototypeOf;function Nx(t){return!!t&&!!t[al]}function qf(t){return t?fee(t)||Array.isArray(t)||!!t[IV]||!!t.constructor?.[IV]||Rw(t)||$T(t):!1}var _De=Object.prototype.constructor.toString(),zV=new WeakMap;function fee(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);if(e===null||e===Object.prototype)return!0;const n=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;if(n===Object)return!0;if(typeof n!="function")return!1;let r=zV.get(n);return r===void 0&&(r=Function.toString.call(n),zV.set(n,r)),r===_De}function wk(t,e,n=!0){HT(t)===0?(n?Reflect.ownKeys(t):Object.keys(t)).forEach(a=>{e(a,t[a],t)}):t.forEach((r,a)=>e(a,r,t))}function HT(t){const e=t[al];return e?e.type_:Array.isArray(t)?1:Rw(t)?2:$T(t)?3:0}function JR(t,e){return HT(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function gee(t,e,n){const r=HT(t);r===2?t.set(e,n):r===3?t.add(n):t[e]=n}function NDe(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function Rw(t){return t instanceof Map}function $T(t){return t instanceof Set}function Bp(t){return t.copy_||t.base_}function eF(t,e){if(Rw(t))return new Map(t);if($T(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);const n=fee(t);if(e===!0||e==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(t);delete r[al];let a=Reflect.ownKeys(r);for(let s=0;s1&&Object.defineProperties(t,{set:w1,add:w1,clear:w1,delete:w1}),Object.freeze(t),e&&Object.values(t).forEach(n=>nI(n,!0))),t}function kDe(){bc(2)}var w1={value:kDe};function qT(t){return t===null||typeof t!="object"?!0:Object.isFrozen(t)}var CDe={};function Vf(t){const e=CDe[t];return e||bc(0,t),e}var H0;function bee(){return H0}function TDe(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function UV(t,e){e&&(Vf("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function tF(t){nF(t),t.drafts_.forEach(ADe),t.drafts_=null}function nF(t){t===H0&&(H0=t.parent_)}function BV(t){return H0=TDe(H0,t)}function ADe(t){const e=t[al];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function HV(t,e){e.unfinalizedDrafts_=e.drafts_.length;const n=e.drafts_[0];return t!==void 0&&t!==n?(n[al].modified_&&(tF(e),bc(4)),qf(t)&&(t=Sk(e,t),e.parent_||_k(e,t)),e.patches_&&Vf("Patches").generateReplacementPatches_(n[al].base_,t,e.patches_,e.inversePatches_)):t=Sk(e,n,[]),tF(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==pee?t:void 0}function Sk(t,e,n){if(qT(e))return e;const r=t.immer_.shouldUseStrictIteration(),a=e[al];if(!a)return wk(e,(s,o)=>$V(t,a,e,s,o,n),r),e;if(a.scope_!==t)return e;if(!a.modified_)return _k(t,a.base_,!0),a.base_;if(!a.finalized_){a.finalized_=!0,a.scope_.unfinalizedDrafts_--;const s=a.copy_;let o=s,l=!1;a.type_===3&&(o=new Set(s),s.clear(),l=!0),wk(o,(c,u)=>$V(t,a,s,c,u,n,l),r),_k(t,s,!1),n&&t.patches_&&Vf("Patches").generatePatches_(a,n,t.patches_,t.inversePatches_)}return a.copy_}function $V(t,e,n,r,a,s,o){if(a==null||typeof a!="object"&&!o)return;const l=qT(a);if(!(l&&!o)){if(Nx(a)){const c=s&&e&&e.type_!==3&&!JR(e.assigned_,r)?s.concat(r):void 0,u=Sk(t,a,c);if(gee(n,r,u),Nx(u))t.canAutoFreeze_=!1;else return}else o&&n.add(a);if(qf(a)&&!l){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1||e&&e.base_&&e.base_[r]===a&&l)return;Sk(t,a),(!e||!e.scope_.parent_)&&typeof r!="symbol"&&(Rw(n)?n.has(r):Object.prototype.propertyIsEnumerable.call(n,r))&&_k(t,a)}}}function _k(t,e,n=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&nI(e,n)}function PDe(t,e){const n=Array.isArray(t),r={type_:n?1:0,scope_:e?e.scope_:bee(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1};let a=r,s=rI;n&&(a=[r],s=$0);const{revoke:o,proxy:l}=Proxy.revocable(a,s);return r.draft_=l,r.revoke_=o,l}var rI={get(t,e){if(e===al)return t;const n=Bp(t);if(!JR(n,e))return MDe(t,n,e);const r=n[e];return t.finalized_||!qf(r)?r:r===v2(t.base_,e)?(w2(t),t.copy_[e]=iF(r,t)):r},has(t,e){return e in Bp(t)},ownKeys(t){return Reflect.ownKeys(Bp(t))},set(t,e,n){const r=xee(Bp(t),e);if(r?.set)return r.set.call(t.draft_,n),!0;if(!t.modified_){const a=v2(Bp(t),e),s=a?.[al];if(s&&s.base_===n)return t.copy_[e]=n,t.assigned_[e]=!1,!0;if(NDe(n,a)&&(n!==void 0||JR(t.base_,e)))return!0;w2(t),rF(t)}return t.copy_[e]===n&&(n!==void 0||e in t.copy_)||Number.isNaN(n)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=n,t.assigned_[e]=!0),!0},deleteProperty(t,e){return v2(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,w2(t),rF(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){const n=Bp(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:r.enumerable,value:n[e]}},defineProperty(){bc(11)},getPrototypeOf(t){return B0(t.base_)},setPrototypeOf(){bc(12)}},$0={};wk(rI,(t,e)=>{$0[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});$0.deleteProperty=function(t,e){return $0.set.call(this,t,e,void 0)};$0.set=function(t,e,n){return rI.set.call(this,t[0],e,n,t[0])};function v2(t,e){const n=t[al];return(n?Bp(n):t)[e]}function MDe(t,e,n){const r=xee(e,n);return r?"value"in r?r.value:r.get?.call(t.draft_):void 0}function xee(t,e){if(!(e in t))return;let n=B0(t);for(;n;){const r=Object.getOwnPropertyDescriptor(n,e);if(r)return r;n=B0(n)}}function rF(t){t.modified_||(t.modified_=!0,t.parent_&&rF(t.parent_))}function w2(t){t.copy_||(t.copy_=eF(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var EDe=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(e,n,r)=>{if(typeof e=="function"&&typeof n!="function"){const s=n;n=e;const o=this;return function(c=s,...u){return o.produce(c,d=>n.call(this,d,...u))}}typeof n!="function"&&bc(6),r!==void 0&&typeof r!="function"&&bc(7);let a;if(qf(e)){const s=BV(this),o=iF(e,void 0);let l=!0;try{a=n(o),l=!1}finally{l?tF(s):nF(s)}return UV(s,r),HV(a,s)}else if(!e||typeof e!="object"){if(a=n(e),a===void 0&&(a=e),a===pee&&(a=void 0),this.autoFreeze_&&nI(a,!0),r){const s=[],o=[];Vf("Patches").generateReplacementPatches_(e,a,s,o),r(s,o)}return a}else bc(1,e)},this.produceWithPatches=(e,n)=>{if(typeof e=="function")return(o,...l)=>this.produceWithPatches(o,c=>e(c,...l));let r,a;return[this.produce(e,n,(o,l)=>{r=o,a=l}),r,a]},typeof t?.autoFreeze=="boolean"&&this.setAutoFreeze(t.autoFreeze),typeof t?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(t.useStrictShallowCopy),typeof t?.useStrictIteration=="boolean"&&this.setUseStrictIteration(t.useStrictIteration)}createDraft(t){qf(t)||bc(8),Nx(t)&&(t=jDe(t));const e=BV(this),n=iF(t,void 0);return n[al].isManual_=!0,nF(e),n}finishDraft(t,e){const n=t&&t[al];(!n||!n.isManual_)&&bc(9);const{scope_:r}=n;return UV(r,e),HV(void 0,r)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}setUseStrictIteration(t){this.useStrictIteration_=t}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(t,e){let n;for(n=e.length-1;n>=0;n--){const a=e[n];if(a.path.length===0&&a.op==="replace"){t=a.value;break}}n>-1&&(e=e.slice(n+1));const r=Vf("Patches").applyPatches_;return Nx(t)?r(t,e):this.produce(t,a=>r(a,e))}};function iF(t,e){const n=Rw(t)?Vf("MapSet").proxyMap_(t,e):$T(t)?Vf("MapSet").proxySet_(t,e):PDe(t,e);return(e?e.scope_:bee()).drafts_.push(n),n}function jDe(t){return Nx(t)||bc(10,t),yee(t)}function yee(t){if(!qf(t)||qT(t))return t;const e=t[al];let n,r=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,n=eF(t,e.scope_.immer_.useStrictShallowCopy_),r=e.scope_.immer_.shouldUseStrictIteration()}else n=eF(t,!0);return wk(n,(a,s)=>{gee(n,a,yee(s))},r),e&&(e.finalized_=!1),n}var DDe=new EDe;DDe.produce;var RDe={settings:{layout:"horizontal",align:"center",verticalAlign:"middle",itemSorter:"value"},size:{width:0,height:0},payload:[]},vee=Ao({name:"legend",initialState:RDe,reducers:{setLegendSize(t,e){t.size.width=e.payload.width,t.size.height=e.payload.height},setLegendSettings(t,e){t.settings.align=e.payload.align,t.settings.layout=e.payload.layout,t.settings.verticalAlign=e.payload.verticalAlign,t.settings.itemSorter=e.payload.itemSorter},addLegendPayload:{reducer(t,e){t.payload.push(e.payload)},prepare:mi()},replaceLegendPayload:{reducer(t,e){var{prev:n,next:r}=e.payload,a=Nc(t).payload.indexOf(n);a>-1&&(t.payload[a]=r)},prepare:mi()},removeLegendPayload:{reducer(t,e){var n=Nc(t).payload.indexOf(e.payload);n>-1&&t.payload.splice(n,1)},prepare:mi()}}}),{setLegendSize:qV,setLegendSettings:FDe,addLegendPayload:wee,replaceLegendPayload:See,removeLegendPayload:_ee}=vee.actions,LDe=vee.reducer,ODe=["contextPayload"];function aF(){return aF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{e(FDe(t))},[e,t]),null}function WDe(t){var e=Jr();return w.useEffect(()=>(e(qV(t)),()=>{e(qV({width:0,height:0}))}),[e,t]),null}function KDe(t,e,n,r){return t==="vertical"&&e!=null?{height:e}:t==="horizontal"?{width:n||r}:null}var YDe={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",layout:"horizontal",verticalAlign:"bottom"};function Nee(t){var e=wi(t,YDe),n=Mje(),r=MMe(),a=wDe(),{width:s,height:o,wrapperStyle:l,portal:c}=e,[u,d]=CJ([n]),m=JO(),p=eI();if(m==null||p==null)return null;var f=m-(a?.left||0)-(a?.right||0),y=KDe(e.layout,o,s,f),v=c?l:kx(kx({position:"absolute",width:y?.width||s||"auto",height:y?.height||o||"auto"},VDe(l,e,a,m,p,u)),l),b=c??r;if(b==null||n==null)return null;var g=w.createElement("div",{className:"recharts-legend-wrapper",style:v,ref:d},w.createElement(GDe,{layout:e.layout,align:e.align,verticalAlign:e.verticalAlign,itemSorter:e.itemSorter}),!c&&w.createElement(WDe,{width:u.width,height:u.height}),w.createElement(qDe,aF({},e,y,{margin:a,chartWidth:m,chartHeight:p,contextPayload:n})));return wd.createPortal(g,b)}Nee.displayName="Legend";function sF(){return sF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{separator:e=vb.separator,contentStyle:n,itemStyle:r,labelStyle:a=vb.labelStyle,payload:s,formatter:o,itemSorter:l,wrapperClassName:c,labelClassName:u,label:d,labelFormatter:m,accessibilityLayer:p=vb.accessibilityLayer}=t,f=()=>{if(s&&s.length){var k={padding:0,margin:0},P=(l?AT(s,l):s).map((T,D)=>{if(T.type==="none")return null;var A=T.formatter||o||JDe,{value:R,name:G}=T,z=R,Z=G;if(A){var I=A(R,G,T,D,s);if(Array.isArray(I))[z,Z]=I;else if(I!=null)z=I;else return null}var J=pv(pv({},vb.itemStyle),{},{color:T.color||vb.itemStyle.color},r);return w.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(D),style:J},Kl(Z)?w.createElement("span",{className:"recharts-tooltip-item-name"},Z):null,Kl(Z)?w.createElement("span",{className:"recharts-tooltip-item-separator"},e):null,w.createElement("span",{className:"recharts-tooltip-item-value"},z),w.createElement("span",{className:"recharts-tooltip-item-unit"},T.unit||""))});return w.createElement("ul",{className:"recharts-tooltip-item-list",style:k},P)}return null},y=pv(pv({},vb.contentStyle),n),v=pv({margin:0},a),b=!gi(d),g=b?d:"",_=hr("recharts-default-tooltip",c),N=hr("recharts-tooltip-label",u);b&&m&&s!==void 0&&s!==null&&(g=m(d,s));var C=p?{role:"status","aria-live":"assertive"}:{};return w.createElement("div",sF({className:_,style:y},C),w.createElement("p",{className:N,style:v},w.isValidElement(g)?g:"".concat(g)),f())},fv="recharts-tooltip-wrapper",t3e={visibility:"hidden"};function n3e(t){var{coordinate:e,translateX:n,translateY:r}=t;return hr(fv,{["".concat(fv,"-right")]:Yt(n)&&e&&Yt(e.x)&&n>=e.x,["".concat(fv,"-left")]:Yt(n)&&e&&Yt(e.x)&&n=e.y,["".concat(fv,"-top")]:Yt(r)&&e&&Yt(e.y)&&r0?a:0),m=n[r]+a;if(e[r])return o[r]?d:m;var p=c[r];if(p==null)return 0;if(o[r]){var f=d,y=p;return fb?Math.max(d,p):Math.max(m,p)}function r3e(t){var{translateX:e,translateY:n,useTranslate3d:r}=t;return{transform:r?"translate3d(".concat(e,"px, ").concat(n,"px, 0)"):"translate(".concat(e,"px, ").concat(n,"px)")}}function i3e(t){var{allowEscapeViewBox:e,coordinate:n,offsetTop:r,offsetLeft:a,position:s,reverseDirection:o,tooltipBox:l,useTranslate3d:c,viewBox:u}=t,d,m,p;return l.height>0&&l.width>0&&n?(m=WV({allowEscapeViewBox:e,coordinate:n,key:"x",offset:a,position:s,reverseDirection:o,tooltipDimension:l.width,viewBox:u,viewBoxDimension:u.width}),p=WV({allowEscapeViewBox:e,coordinate:n,key:"y",offset:r,position:s,reverseDirection:o,tooltipDimension:l.height,viewBox:u,viewBoxDimension:u.height}),d=r3e({translateX:m,translateY:p,useTranslate3d:c})):d=t3e,{cssProperties:d,cssClasses:n3e({translateX:m,translateY:p,coordinate:n})}}function KV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function S1(t){for(var e=1;e{if(e.key==="Escape"){var n,r,a,s;this.setState({dismissed:!0,dismissedAtCoordinate:{x:(n=(r=this.props.coordinate)===null||r===void 0?void 0:r.x)!==null&&n!==void 0?n:0,y:(a=(s=this.props.coordinate)===null||s===void 0?void 0:s.y)!==null&&a!==void 0?a:0}})}})}componentDidMount(){document.addEventListener("keydown",this.handleKeyDown)}componentWillUnmount(){document.removeEventListener("keydown",this.handleKeyDown)}componentDidUpdate(){var e,n;this.state.dismissed&&(((e=this.props.coordinate)===null||e===void 0?void 0:e.x)!==this.state.dismissedAtCoordinate.x||((n=this.props.coordinate)===null||n===void 0?void 0:n.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}render(){var{active:e,allowEscapeViewBox:n,animationDuration:r,animationEasing:a,children:s,coordinate:o,hasPayload:l,isAnimationActive:c,offset:u,position:d,reverseDirection:m,useTranslate3d:p,viewBox:f,wrapperStyle:y,lastBoundingBox:v,innerRef:b,hasPortalFromProps:g}=this.props,_=typeof u=="number"?u:u.x,N=typeof u=="number"?u:u.y,{cssClasses:C,cssProperties:k}=i3e({allowEscapeViewBox:n,coordinate:o,offsetLeft:_,offsetTop:N,position:d,reverseDirection:m,tooltipBox:{height:v.height,width:v.width},useTranslate3d:p,viewBox:f}),P=g?{}:S1(S1({transition:c&&e?"transform ".concat(r,"ms ").concat(a):void 0},k),{},{pointerEvents:"none",visibility:!this.state.dismissed&&e&&l?"visible":"hidden",position:"absolute",top:0,left:0}),T=S1(S1({},P),{},{visibility:!this.state.dismissed&&e&&l?"visible":"hidden"},y);return w.createElement("div",{xmlns:"http://www.w3.org/1999/xhtml",tabIndex:-1,className:C,style:T,ref:b},s)}}var kee=()=>{var t;return(t=en(e=>e.rootProps.accessibilityLayer))!==null&&t!==void 0?t:!0};function lF(){return lF=Object.assign?Object.assign.bind():function(t){for(var e=1;eLn(t.x)&&Ln(t.y),ZV=t=>t.base!=null&&Nk(t.base)&&Nk(t),gv=t=>t.x,bv=t=>t.y,d3e=(t,e)=>{if(typeof t=="function")return t;var n="curve".concat(Tw(t));if((n==="curveMonotone"||n==="curveBump")&&e){var r=QV["".concat(n).concat(e==="vertical"?"Y":"X")];if(r)return r}return QV[n]||CT},JV={connectNulls:!1,type:"linear"},m3e=t=>{var{type:e=JV.type,points:n=[],baseLine:r,layout:a,connectNulls:s=JV.connectNulls}=t,o=d3e(e,a),l=s?n.filter(Nk):n;if(Array.isArray(r)){var c,u=n.map((y,v)=>XV(XV({},y),{},{base:r[v]}));a==="vertical"?c=p1().y(bv).x1(gv).x0(y=>y.base.x):c=p1().x(gv).y1(bv).y0(y=>y.base.y);var d=c.defined(ZV).curve(o),m=s?u.filter(ZV):u;return d(m)}var p;a==="vertical"&&Yt(r)?p=p1().y(bv).x1(gv).x0(r):Yt(r)?p=p1().x(gv).y1(bv).y0(r):p=XZ().x(gv).y(bv);var f=p.defined(Nk).curve(o);return f(l)},nx=t=>{var{className:e,points:n,path:r,pathRef:a}=t,s=Qh();if((!n||!n.length)&&!r)return null;var o={type:t.type,points:t.points,baseLine:t.baseLine,layout:t.layout||s,connectNulls:t.connectNulls},l=n&&n.length?m3e(o):r;return w.createElement("path",lF({},Ys(t),UO(t),{className:hr("recharts-curve",e),d:l===null?void 0:l,ref:a}))},h3e=["x","y","top","left","width","height","className"];function cF(){return cF=Object.assign?Object.assign.bind():function(t){for(var e=1;e"M".concat(t,",").concat(a,"v").concat(r,"M").concat(s,",").concat(e,"h").concat(n),w3e=t=>{var{x:e=0,y:n=0,top:r=0,left:a=0,width:s=0,height:o=0,className:l}=t,c=x3e(t,h3e),u=p3e({x:e,y:n,top:r,left:a,width:s,height:o},c);return!Yt(e)||!Yt(n)||!Yt(s)||!Yt(o)||!Yt(r)||!Yt(a)?null:w.createElement("path",cF({},ls(u),{className:hr("recharts-cross",l),d:v3e(e,n,s,o,r,a)}))};function S3e(t,e,n,r){var a=r/2;return{stroke:"none",fill:"#ccc",x:t==="horizontal"?e.x-a:n.left+.5,y:t==="horizontal"?n.top+.5:e.y-a,width:t==="horizontal"?r:n.width-1,height:t==="horizontal"?n.height-1:r}}function t7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function n7(t){for(var e=1;et.replace(/([A-Z])/g,e=>"-".concat(e.toLowerCase())),Cee=(t,e,n)=>t.map(r=>"".concat(C3e(r)," ").concat(e,"ms ").concat(n)).join(","),T3e=(t,e)=>[Object.keys(t),Object.keys(e)].reduce((n,r)=>n.filter(a=>r.includes(a))),q0=(t,e)=>Object.keys(e).reduce((n,r)=>n7(n7({},n),{},{[r]:t(r,e[r])}),{});function r7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function ma(t){for(var e=1;et+(e-t)*n,uF=t=>{var{from:e,to:n}=t;return e!==n},Tee=(t,e,n)=>{var r=q0((a,s)=>{if(uF(s)){var[o,l]=t(s.from,s.to,s.velocity);return ma(ma({},s),{},{from:o,velocity:l})}return s},e);return n<1?q0((a,s)=>uF(s)&&r[a]!=null?ma(ma({},s),{},{velocity:kk(s.velocity,r[a].velocity,n),from:kk(s.from,r[a].from,n)}):s,e):Tee(t,r,n-1)};function E3e(t,e,n,r,a,s){var o,l=r.reduce((p,f)=>ma(ma({},p),{},{[f]:{from:t[f],velocity:0,to:e[f]}}),{}),c=()=>q0((p,f)=>f.from,l),u=()=>!Object.values(l).filter(uF).length,d=null,m=p=>{o||(o=p);var f=p-o,y=f/n.dt;l=Tee(n,l,y),a(ma(ma(ma({},t),e),c())),o=p,u()||(d=s.setTimeout(m))};return()=>(d=s.setTimeout(m),()=>{var p;(p=d)===null||p===void 0||p()})}function j3e(t,e,n,r,a,s,o){var l=null,c=a.reduce((m,p)=>{var f=t[p],y=e[p];return f==null||y==null?m:ma(ma({},m),{},{[p]:[f,y]})},{}),u,d=m=>{u||(u=m);var p=(m-u)/r,f=q0((v,b)=>kk(...b,n(p)),c);if(s(ma(ma(ma({},t),e),f)),p<1)l=o.setTimeout(d);else{var y=q0((v,b)=>kk(...b,n(1)),c);s(ma(ma(ma({},t),e),y))}};return()=>(l=o.setTimeout(d),()=>{var m;(m=l)===null||m===void 0||m()})}const D3e=(t,e,n,r,a,s)=>{var o=T3e(t,e);return n==null?()=>(a(ma(ma({},t),e)),()=>{}):n.isStepper===!0?E3e(t,e,n,o,a,s):j3e(t,e,n,r,o,a,s)};var Ck=1e-4,Aee=(t,e)=>[0,3*t,3*e-6*t,3*t-3*e+1],Pee=(t,e)=>t.map((n,r)=>n*e**r).reduce((n,r)=>n+r),i7=(t,e)=>n=>{var r=Aee(t,e);return Pee(r,n)},R3e=(t,e)=>n=>{var r=Aee(t,e),a=[...r.map((s,o)=>s*o).slice(1),0];return Pee(a,n)},F3e=t=>{var e,n=t.split("(");if(n.length!==2||n[0]!=="cubic-bezier")return null;var r=(e=n[1])===null||e===void 0||(e=e.split(")")[0])===null||e===void 0?void 0:e.split(",");if(r==null||r.length!==4)return null;var a=r.map(s=>parseFloat(s));return[a[0],a[1],a[2],a[3]]},L3e=function(){for(var e=arguments.length,n=new Array(e),r=0;r{var a=i7(t,n),s=i7(e,r),o=R3e(t,n),l=u=>u>1?1:u<0?0:u,c=u=>{for(var d=u>1?1:u,m=d,p=0;p<8;++p){var f=a(m)-d,y=o(m);if(Math.abs(f-d)0&&arguments[0]!==void 0?arguments[0]:{},{stiff:n=100,damping:r=8,dt:a=17}=e,s=(o,l,c)=>{var u=-(o-l)*n,d=c*r,m=c+(u-d)*a/1e3,p=c*a/1e3+o;return Math.abs(p-l){if(typeof t=="string")switch(t){case"ease":case"ease-in-out":case"ease-out":case"ease-in":case"linear":return a7(t);case"spring":return I3e();default:if(t.split("(")[0]==="cubic-bezier")return a7(t)}return typeof t=="function"?t:null};function U3e(t){var e,n=()=>null,r=!1,a=null,s=o=>{if(!r){if(Array.isArray(o)){if(!o.length)return;var l=o,[c,...u]=l;if(typeof c=="number"){a=t.setTimeout(s.bind(null,u),c);return}s(c),a=t.setTimeout(s.bind(null,u));return}typeof o=="string"&&(e=o,n(e)),typeof o=="object"&&(e=o,n(e)),typeof o=="function"&&o()}};return{stop:()=>{r=!0},start:o=>{r=!1,a&&(a(),a=null),s(o)},subscribe:o=>(n=o,()=>{n=()=>null}),getTimeoutController:()=>t}}class B3e{setTimeout(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=performance.now(),a=null,s=o=>{o-r>=n?e(o):typeof requestAnimationFrame=="function"&&(a=requestAnimationFrame(s))};return a=requestAnimationFrame(s),()=>{a!=null&&cancelAnimationFrame(a)}}}function H3e(){return U3e(new B3e)}var $3e=w.createContext(H3e);function q3e(t,e){var n=w.useContext($3e);return w.useMemo(()=>e??n(t),[t,e,n])}var V3e=()=>!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout),Fw={isSsr:V3e()},G3e={begin:0,duration:1e3,easing:"ease",isActive:!0,canBegin:!0,onAnimationEnd:()=>{},onAnimationStart:()=>{}},s7={t:0},S2={t:1};function Zx(t){var e=wi(t,G3e),{isActive:n,canBegin:r,duration:a,easing:s,begin:o,onAnimationEnd:l,onAnimationStart:c,children:u}=e,d=n==="auto"?!Fw.isSsr:n,m=q3e(e.animationId,e.animationManager),[p,f]=w.useState(d?s7:S2),y=w.useRef(null);return w.useEffect(()=>{d||f(S2)},[d]),w.useEffect(()=>{if(!d||!r)return Yh;var v=D3e(s7,S2,z3e(s),a,f,m.getTimeoutController()),b=()=>{y.current=v()};return m.start([c,o,b,a,l]),()=>{m.stop(),y.current&&y.current(),l()}},[d,r,a,s,o,c,l,m]),u(p.t)}function Jx(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"animation-",n=w.useRef(O0(e)),r=w.useRef(t);return r.current!==t&&(n.current=O0(e),r.current=t),n.current}var W3e=["radius"],K3e=["radius"],o7,l7,c7,u7,d7,m7,h7,p7,f7,g7;function b7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function x7(t){for(var e=1;e{var s=gh(n),o=gh(r),l=Math.min(Math.abs(s)/2,Math.abs(o)/2),c=o>=0?1:-1,u=s>=0?1:-1,d=o>=0&&s>=0||o<0&&s<0?1:0,m;if(l>0&&Array.isArray(a)){for(var p=[0,0,0,0],f=0,y=4;fl?l:b}m=Mi(o7||(o7=Yc(["M",",",""])),t,e+c*p[0]),p[0]>0&&(m+=Mi(l7||(l7=Yc(["A ",",",",0,0,",",",",",""])),p[0],p[0],d,t+u*p[0],e)),m+=Mi(c7||(c7=Yc(["L ",",",""])),t+n-u*p[1],e),p[1]>0&&(m+=Mi(u7||(u7=Yc(["A ",",",",0,0,",`, `,",",""])),p[1],p[1],d,t+n,e+c*p[1])),m+=Mi(d7||(d7=Yc(["L ",",",""])),t+n,e+r-c*p[2]),p[2]>0&&(m+=Mi(m7||(m7=Yc(["A ",",",",0,0,",`, `,",",""])),p[2],p[2],d,t+n-u*p[2],e+r)),m+=Mi(h7||(h7=Yc(["L ",",",""])),t+u*p[3],e+r),p[3]>0&&(m+=Mi(p7||(p7=Yc(["A ",",",",0,0,",`, `,",",""])),p[3],p[3],d,t,e+r-c*p[3])),m+="Z"}else if(l>0&&a===+a&&a>0){var g=Math.min(l,a);m=Mi(f7||(f7=Yc(["M ",",",` @@ -8470,9 +8470,9 @@ void main() { `])),p.x,p.y,s,s,+(d<0),m.x,m.y,a,a,+(g>180),+(d<0),y.x,y.y,s,s,+(d<0),v.x,v.y);if(r>0){var{circleTangency:N,lineTangency:C,theta:k}=_1({cx:e,cy:n,radius:r,angle:c,sign:d,isExternal:!0,cornerRadius:s,cornerIsExternal:l}),{circleTangency:P,lineTangency:T,theta:D}=_1({cx:e,cy:n,radius:r,angle:u,sign:-d,isExternal:!0,cornerRadius:s,cornerIsExternal:l}),A=l?Math.abs(c-u):Math.abs(c-u)-k-D;if(A<0&&s===0)return"".concat(_,"L").concat(e,",").concat(n,"Z");_+=Mi(P7||(P7=Jp(["L",",",` A`,",",",0,0,",",",",",` A`,",",",0,",",",",",",",` - A`,",",",0,0,",",",",","Z"])),T.x,T.y,s,s,+(d<0),P.x,P.y,r,r,+(A>180),+(d>0),N.x,N.y,s,s,+(d<0),C.x,C.y)}else _+=Mi(M7||(M7=Jp(["L",",","Z"])),e,n);return _},uRe={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},Ree=t=>{var e=wi(t,uRe),{cx:n,cy:r,innerRadius:a,outerRadius:s,cornerRadius:o,forceCornerRadius:l,cornerIsExternal:c,startAngle:u,endAngle:d,className:m}=e;if(s0&&Math.abs(u-d)<360?v=cRe({cx:n,cy:r,innerRadius:a,outerRadius:s,cornerRadius:Math.min(y,f/2),forceCornerRadius:l,cornerIsExternal:c,startAngle:u,endAngle:d}):v=Dee({cx:n,cy:r,innerRadius:a,outerRadius:s,startAngle:u,endAngle:d}),w.createElement("path",dF({},ls(e),{className:p,d:v}))};function dRe(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(dJ(e)){if(t==="centric"){var{cx:r,cy:a,innerRadius:s,outerRadius:o,angle:l}=e,c=aa(r,a,s,l),u=aa(r,a,o,l);return[{x:c.x,y:c.y},{x:u.x,y:u.y}]}return jee(e)}}var _j={},Nj={},kj={},E7;function mRe(){return E7||(E7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=_J();function n(r){return e.isSymbol(r)?NaN:Number(r)}t.toNumber=n})(kj)),kj}var j7;function hRe(){return j7||(j7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=mRe();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})(Nj)),Nj}var D7;function pRe(){return D7||(D7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=NJ(),n=hRe();function r(a,s,o){o&&typeof o!="number"&&e.isIterateeCall(a,s,o)&&(s=o=void 0),a=n.toFinite(a),s===void 0?(s=a,a=0):s=n.toFinite(s),o=o===void 0?ae?1:t>=e?0:NaN}function bRe(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}function i4(t){let e,n,r;t.length!==2?(e=Rh,n=(l,c)=>Rh(t(l),c),r=(l,c)=>t(l)-c):(e=t===Rh||t===bRe?t:xRe,n=t,r=t);function a(l,c,u=0,d=l.length){if(u>>1;n(l[m],c)<0?u=m+1:d=m}while(u>>1;n(l[m],c)<=0?u=m+1:d=m}while(uu&&r(l[m-1],c)>-r(l[m],c)?m-1:m}return{left:a,center:o,right:s}}function xRe(){return 0}function Lee(t){return t===null?NaN:+t}function*yRe(t,e){for(let n of t)n!=null&&(n=+n)>=n&&(yield n)}const vRe=i4(Rh),Lw=vRe.right;i4(Lee).center;class F7 extends Map{constructor(e,n=_Re){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),e!=null)for(const[r,a]of e)this.set(r,a)}get(e){return super.get(L7(this,e))}has(e){return super.has(L7(this,e))}set(e,n){return super.set(wRe(this,e),n)}delete(e){return super.delete(SRe(this,e))}}function L7({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):n}function wRe({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}function SRe({_intern:t,_key:e},n){const r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}function _Re(t){return t!==null&&typeof t=="object"?t.valueOf():t}function NRe(t=Rh){if(t===Rh)return Oee;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 Oee(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(te?1:0)}const kRe=Math.sqrt(50),CRe=Math.sqrt(10),TRe=Math.sqrt(2);function Pk(t,e,n){const r=(e-t)/Math.max(0,n),a=Math.floor(Math.log10(r)),s=r/Math.pow(10,a),o=s>=kRe?10:s>=CRe?5:s>=TRe?2:1;let l,c,u;return a<0?(u=Math.pow(10,-a)/o,l=Math.round(t*u),c=Math.round(e*u),l/ue&&--c,u=-u):(u=Math.pow(10,a)*o,l=Math.round(t/u),c=Math.round(e/u),l*ue&&--c),c0))return[];if(t===e)return[t];const r=e=a))return[];const l=s-a+1,c=new Array(l);if(r)if(o<0)for(let u=0;u=r)&&(n=r);return n}function I7(t,e){let n;for(const r of t)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function Iee(t,e,n=0,r=1/0,a){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(a=a===void 0?Oee:NRe(a);r>n;){if(r-n>600){const c=r-n+1,u=e-n+1,d=Math.log(c),m=.5*Math.exp(2*d/3),p=.5*Math.sqrt(d*m*(c-m)/c)*(u-c/2<0?-1:1),f=Math.max(n,Math.floor(e-u*m/c+p)),y=Math.min(r,Math.floor(e+(c-u)*m/c+p));Iee(t,e,f,y,a)}const s=t[e];let o=n,l=r;for(xv(t,n,e),a(t[r],s)>0&&xv(t,n,r);o0;)--l}a(t[n],s)===0?xv(t,n,l):(++l,xv(t,l,r)),l<=e&&(n=l+1),e<=l&&(r=l-1)}return t}function xv(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}function ARe(t,e,n){if(t=Float64Array.from(yRe(t)),!(!(r=t.length)||isNaN(e=+e))){if(e<=0||r<2)return I7(t);if(e>=1)return O7(t);var r,a=(r-1)*e,s=Math.floor(a),o=O7(Iee(t,s).subarray(0,s+1)),l=I7(t.subarray(s+1));return o+(l-o)*(a-s)}}function PRe(t,e,n=Lee){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,a=(r-1)*e,s=Math.floor(a),o=+n(t[s],s,t),l=+n(t[s+1],s+1,t);return o+(l-o)*(a-s)}}function MRe(t,e,n){t=+t,e=+e,n=(a=arguments.length)<2?(e=t,t=0,1):a<3?1:+n;for(var r=-1,a=Math.max(0,Math.ceil((e-t)/n))|0,s=new Array(a);++r>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):n===8?N1(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):n===4?N1(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=DRe.exec(t))?new vo(e[1],e[2],e[3],1):(e=RRe.exec(t))?new vo(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=FRe.exec(t))?N1(e[1],e[2],e[3],e[4]):(e=LRe.exec(t))?N1(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=ORe.exec(t))?V7(e[1],e[2]/100,e[3]/100,1):(e=IRe.exec(t))?V7(e[1],e[2]/100,e[3]/100,e[4]):z7.hasOwnProperty(t)?H7(z7[t]):t==="transparent"?new vo(NaN,NaN,NaN,0):null}function H7(t){return new vo(t>>16&255,t>>8&255,t&255,1)}function N1(t,e,n,r){return r<=0&&(t=e=n=NaN),new vo(t,e,n,r)}function BRe(t){return t instanceof Ow||(t=W0(t)),t?(t=t.rgb(),new vo(t.r,t.g,t.b,t.opacity)):new vo}function gF(t,e,n,r){return arguments.length===1?BRe(t):new vo(t,e,n,r??1)}function vo(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}o4(vo,gF,Uee(Ow,{brighter(t){return t=t==null?Mk:Math.pow(Mk,t),new vo(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?V0:Math.pow(V0,t),new vo(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new vo(bf(this.r),bf(this.g),bf(this.b),Ek(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:$7,formatHex:$7,formatHex8:HRe,formatRgb:q7,toString:q7}));function $7(){return`#${ef(this.r)}${ef(this.g)}${ef(this.b)}`}function HRe(){return`#${ef(this.r)}${ef(this.g)}${ef(this.b)}${ef((isNaN(this.opacity)?1:this.opacity)*255)}`}function q7(){const t=Ek(this.opacity);return`${t===1?"rgb(":"rgba("}${bf(this.r)}, ${bf(this.g)}, ${bf(this.b)}${t===1?")":`, ${t})`}`}function Ek(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function bf(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function ef(t){return t=bf(t),(t<16?"0":"")+t.toString(16)}function V7(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new xc(t,e,n,r)}function Bee(t){if(t instanceof xc)return new xc(t.h,t.s,t.l,t.opacity);if(t instanceof Ow||(t=W0(t)),!t)return new xc;if(t instanceof xc)return t;t=t.rgb();var e=t.r/255,n=t.g/255,r=t.b/255,a=Math.min(e,n,r),s=Math.max(e,n,r),o=NaN,l=s-a,c=(s+a)/2;return l?(e===s?o=(n-r)/l+(n0&&c<1?0:o,new xc(o,l,c,t.opacity)}function $Re(t,e,n,r){return arguments.length===1?Bee(t):new xc(t,e,n,r??1)}function xc(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}o4(xc,$Re,Uee(Ow,{brighter(t){return t=t==null?Mk:Math.pow(Mk,t),new xc(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?V0:Math.pow(V0,t),new xc(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,a=2*n-r;return new vo(Tj(t>=240?t-240:t+120,a,r),Tj(t,a,r),Tj(t<120?t+240:t-120,a,r),this.opacity)},clamp(){return new xc(G7(this.h),k1(this.s),k1(this.l),Ek(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=Ek(this.opacity);return`${t===1?"hsl(":"hsla("}${G7(this.h)}, ${k1(this.s)*100}%, ${k1(this.l)*100}%${t===1?")":`, ${t})`}`}}));function G7(t){return t=(t||0)%360,t<0?t+360:t}function k1(t){return Math.max(0,Math.min(1,t||0))}function Tj(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 l4=t=>()=>t;function qRe(t,e){return function(n){return t+n*e}}function VRe(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 GRe(t){return(t=+t)==1?Hee:function(e,n){return n-e?VRe(e,n,t):l4(isNaN(e)?n:e)}}function Hee(t,e){var n=e-t;return n?qRe(t,n):l4(isNaN(t)?e:t)}const W7=(function t(e){var n=GRe(e);function r(a,s){var o=n((a=gF(a)).r,(s=gF(s)).r),l=n(a.g,s.g),c=n(a.b,s.b),u=Hee(a.opacity,s.opacity);return function(d){return a.r=o(d),a.g=l(d),a.b=c(d),a.opacity=u(d),a+""}}return r.gamma=t,r})(1);function WRe(t,e){e||(e=[]);var n=t?Math.min(e.length,t.length):0,r=e.slice(),a;return function(s){for(a=0;an&&(s=e.slice(n,s),l[o]?l[o]+=s:l[++o]=s),(r=r[0])===(a=a[0])?l[o]?l[o]+=a:l[++o]=a:(l[++o]=null,c.push({i:o,x:jk(r,a)})),n=Aj.lastIndex;return ne&&(n=t,t=e,e=n),function(r){return Math.max(t,Math.min(e,r))}}function iFe(t,e,n){var r=t[0],a=t[1],s=e[0],o=e[1];return a2?aFe:iFe,c=u=null,m}function m(p){return p==null||isNaN(p=+p)?s:(c||(c=l(t.map(r),e,n)))(r(o(p)))}return m.invert=function(p){return o(a((u||(u=l(e,t.map(r),jk)))(p)))},m.domain=function(p){return arguments.length?(t=Array.from(p,Dk),d()):t.slice()},m.range=function(p){return arguments.length?(e=Array.from(p),d()):e.slice()},m.rangeRound=function(p){return e=Array.from(p),n=c4,d()},m.clamp=function(p){return arguments.length?(o=p?!0:$s,d()):o!==$s},m.interpolate=function(p){return arguments.length?(n=p,d()):n},m.unknown=function(p){return arguments.length?(s=p,m):s},function(p,f){return r=p,a=f,d()}}function u4(){return VT()($s,$s)}function sFe(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function Rk(t,e){if(!isFinite(t)||t===0)return null;var n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"),r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}function Cx(t){return t=Rk(Math.abs(t)),t?t[1]:NaN}function oFe(t,e){return function(n,r){for(var a=n.length,s=[],o=0,l=t[0],c=0;a>0&&l>0&&(c+l+1>r&&(l=Math.max(1,r-c)),s.push(n.substring(a-=l,a+l)),!((c+=l+1)>r));)l=t[o=(o+1)%t.length];return s.reverse().join(e)}}function lFe(t){return function(e){return e.replace(/[0-9]/g,function(n){return t[+n]})}}var cFe=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function K0(t){if(!(e=cFe.exec(t)))throw new Error("invalid format: "+t);var e;return new d4({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]})}K0.prototype=d4.prototype;function d4(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+""}d4.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 uFe(t){e:for(var e=t.length,n=1,r=-1,a;n0&&(r=0);break}return r>0?t.slice(0,r)+t.slice(a+1):t}var Fk;function dFe(t,e){var n=Rk(t,e);if(!n)return Fk=void 0,t.toPrecision(e);var r=n[0],a=n[1],s=a-(Fk=Math.max(-8,Math.min(8,Math.floor(a/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")+Rk(t,Math.max(0,e+s-1))[0]}function Y7(t,e){var n=Rk(t,e);if(!n)return t+"";var r=n[0],a=n[1];return a<0?"0."+new Array(-a).join("0")+r:r.length>a+1?r.slice(0,a+1)+"."+r.slice(a+1):r+new Array(a-r.length+2).join("0")}const X7={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:sFe,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)=>Y7(t*100,e),r:Y7,s:dFe,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function Q7(t){return t}var Z7=Array.prototype.map,J7=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function mFe(t){var e=t.grouping===void 0||t.thousands===void 0?Q7:oFe(Z7.call(t.grouping,Number),t.thousands+""),n=t.currency===void 0?"":t.currency[0]+"",r=t.currency===void 0?"":t.currency[1]+"",a=t.decimal===void 0?".":t.decimal+"",s=t.numerals===void 0?Q7:lFe(Z7.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(m,p){m=K0(m);var f=m.fill,y=m.align,v=m.sign,b=m.symbol,g=m.zero,_=m.width,N=m.comma,C=m.precision,k=m.trim,P=m.type;P==="n"?(N=!0,P="g"):X7[P]||(C===void 0&&(C=12),k=!0,P="g"),(g||f==="0"&&y==="=")&&(g=!0,f="0",y="=");var T=(p&&p.prefix!==void 0?p.prefix:"")+(b==="$"?n:b==="#"&&/[boxX]/.test(P)?"0"+P.toLowerCase():""),D=(b==="$"?r:/[%p]/.test(P)?o:"")+(p&&p.suffix!==void 0?p.suffix:""),A=X7[P],R=/[defgprs%]/.test(P);C=C===void 0?6:/[gprs]/.test(P)?Math.max(1,Math.min(21,C)):Math.max(0,Math.min(20,C));function G(z){var Z=T,I=D,J,ae,Y;if(P==="c")I=A(z)+I,z="";else{z=+z;var ue=z<0||1/z<0;if(z=isNaN(z)?c:A(Math.abs(z),C),k&&(z=uFe(z)),ue&&+z==0&&v!=="+"&&(ue=!1),Z=(ue?v==="("?v:l:v==="-"||v==="("?"":v)+Z,I=(P==="s"&&!isNaN(z)&&Fk!==void 0?J7[8+Fk/3]:"")+I+(ue&&v==="("?")":""),R){for(J=-1,ae=z.length;++JY||Y>57){I=(Y===46?a+z.slice(J+1):z.slice(J))+I,z=z.slice(0,J);break}}}N&&!g&&(z=e(z,1/0));var de=Z.length+z.length+I.length,he=de<_?new Array(_-de+1).join(f):"";switch(N&&g&&(z=e(he+z,he.length?_-I.length:1/0),he=""),y){case"<":z=Z+z+I+he;break;case"=":z=Z+he+z+I;break;case"^":z=he.slice(0,de=he.length>>1)+Z+z+I+he.slice(de);break;default:z=he+Z+z+I;break}return s(z)}return G.toString=function(){return m+""},G}function d(m,p){var f=Math.max(-8,Math.min(8,Math.floor(Cx(p)/3)))*3,y=Math.pow(10,-f),v=u((m=K0(m),m.type="f",m),{suffix:J7[8+f/3]});return function(b){return v(y*b)}}return{format:u,formatPrefix:d}}var C1,m4,$ee;hFe({thousands:",",grouping:[3],currency:["$",""]});function hFe(t){return C1=mFe(t),m4=C1.format,$ee=C1.formatPrefix,C1}function pFe(t){return Math.max(0,-Cx(Math.abs(t)))}function fFe(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Cx(e)/3)))*3-Cx(Math.abs(t)))}function gFe(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,Cx(e)-Cx(t))+1}function qee(t,e,n,r){var a=pF(t,e,n),s;switch(r=K0(r??",f"),r.type){case"s":{var o=Math.max(Math.abs(t),Math.abs(e));return r.precision==null&&!isNaN(s=fFe(a,o))&&(r.precision=s),$ee(r,o)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(s=gFe(a,Math.max(Math.abs(t),Math.abs(e))))&&(r.precision=s-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(s=pFe(a))&&(r.precision=s-(r.type==="%")*2);break}}return m4(r)}function Zh(t){var e=t.domain;return t.ticks=function(n){var r=e();return mF(r[0],r[r.length-1],n??10)},t.tickFormat=function(n,r){var a=e();return qee(a[0],a[a.length-1],n??10,r)},t.nice=function(n){n==null&&(n=10);var r=e(),a=0,s=r.length-1,o=r[a],l=r[s],c,u,d=10;for(l0;){if(u=hF(o,l,n),u===c)return r[a]=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 Vee(){var t=u4();return t.copy=function(){return Iw(t,Vee())},ec.apply(t,arguments),Zh(t)}function Gee(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,Dk),n):t.slice()},n.unknown=function(r){return arguments.length?(e=r,n):e},n.copy=function(){return Gee(t).unknown(e)},t=arguments.length?Array.from(t,Dk):[0,1],Zh(n)}function Wee(t,e){t=t.slice();var n=0,r=t.length-1,a=t[n],s=t[r],o;return sMath.pow(t,e)}function wFe(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 nG(t){return(e,n)=>-t(-e,n)}function h4(t){const e=t(eG,tG),n=e.domain;let r=10,a,s;function o(){return a=wFe(r),s=vFe(r),n()[0]<0?(a=nG(a),s=nG(s),t(bFe,xFe)):t(eG,tG),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 m=d0){for(;p<=f;++p)for(y=1;yd)break;g.push(v)}}else for(;p<=f;++p)for(y=r-1;y>=1;--y)if(v=p>0?y/s(-p):y*s(p),!(vd)break;g.push(v)}g.length*2{if(l==null&&(l=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=K0(c)).precision==null&&(c.trim=!0),c=m4(c)),l===1/0)return c;const u=Math.max(1,r*l/e.ticks().length);return d=>{let m=d/s(Math.round(a(d)));return m*rn(Wee(n(),{floor:l=>s(Math.floor(a(l))),ceil:l=>s(Math.ceil(a(l)))})),e}function Kee(){const t=h4(VT()).domain([1,10]);return t.copy=()=>Iw(t,Kee()).base(t.base()),ec.apply(t,arguments),t}function rG(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function iG(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function p4(t){var e=1,n=t(rG(e),iG(e));return n.constant=function(r){return arguments.length?t(rG(e=+r),iG(e)):e},Zh(n)}function Yee(){var t=p4(VT());return t.copy=function(){return Iw(t,Yee()).constant(t.constant())},ec.apply(t,arguments)}function aG(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function SFe(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function _Fe(t){return t<0?-t*t:t*t}function f4(t){var e=t($s,$s),n=1;function r(){return n===1?t($s,$s):n===.5?t(SFe,_Fe):t(aG(n),aG(1/n))}return e.exponent=function(a){return arguments.length?(n=+a,r()):n},Zh(e)}function g4(){var t=f4(VT());return t.copy=function(){return Iw(t,g4()).exponent(t.exponent())},ec.apply(t,arguments),t}function NFe(){return g4.apply(null,arguments).exponent(.5)}function sG(t){return Math.sign(t)*t*t}function kFe(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function Xee(){var t=u4(),e=[0,1],n=!1,r;function a(s){var o=kFe(t(s));return isNaN(o)?r:n?Math.round(o):o}return a.invert=function(s){return t.invert(sG(s))},a.domain=function(s){return arguments.length?(t.domain(s),a):t.domain()},a.range=function(s){return arguments.length?(t.range((e=Array.from(s,Dk)).map(sG)),a):e.slice()},a.rangeRound=function(s){return a.range(s).round(!0)},a.round=function(s){return arguments.length?(n=!!s,a):n},a.clamp=function(s){return arguments.length?(t.clamp(s),a):t.clamp()},a.unknown=function(s){return arguments.length?(r=s,a):r},a.copy=function(){return Xee(t.domain(),e).round(n).clamp(t.clamp()).unknown(r)},ec.apply(a,arguments),Zh(a)}function Qee(){var t=[],e=[],n=[],r;function a(){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 Zee().domain([t,e]).range(a).unknown(s)},ec.apply(Zh(o),arguments)}function Jee(){var t=[.5],e=[0,1],n,r=1;function a(s){return s!=null&&s<=s?e[Lw(t,s,0,r)]:n}return a.domain=function(s){return arguments.length?(t=Array.from(s),r=Math.min(t.length,e.length-1),a):t.slice()},a.range=function(s){return arguments.length?(e=Array.from(s),r=Math.min(t.length,e.length-1),a):e.slice()},a.invertExtent=function(s){var o=e.indexOf(s);return[t[o-1],t[o]]},a.unknown=function(s){return arguments.length?(n=s,a):n},a.copy=function(){return Jee().domain(t).range(e).unknown(n)},ec.apply(a,arguments)}const Pj=new Date,Mj=new Date;function Sa(t,e,n,r){function a(s){return t(s=arguments.length===0?new Date:new Date(+s)),s}return a.floor=s=>(t(s=new Date(+s)),s),a.ceil=s=>(t(s=new Date(s-1)),e(s,1),t(s),s),a.round=s=>{const o=a(s),l=a.ceil(s);return s-o(e(s=new Date(+s),o==null?1:Math.floor(o)),s),a.range=(s,o,l)=>{const c=[];if(s=a.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&&(a.count=(s,o)=>(Pj.setTime(+s),Mj.setTime(+o),t(Pj),t(Mj),Math.floor(n(Pj,Mj))),a.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?a.filter(r?o=>r(o)%s===0:o=>a.count(0,o)%s===0):a)),a}const Lk=Sa(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);Lk.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):Lk);Lk.range;const Td=1e3,zl=Td*60,Ad=zl*60,Kd=Ad*24,b4=Kd*7,oG=Kd*30,Ej=Kd*365,tf=Sa(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*Td)},(t,e)=>(e-t)/Td,t=>t.getUTCSeconds());tf.range;const x4=Sa(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Td)},(t,e)=>{t.setTime(+t+e*zl)},(t,e)=>(e-t)/zl,t=>t.getMinutes());x4.range;const y4=Sa(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*zl)},(t,e)=>(e-t)/zl,t=>t.getUTCMinutes());y4.range;const v4=Sa(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Td-t.getMinutes()*zl)},(t,e)=>{t.setTime(+t+e*Ad)},(t,e)=>(e-t)/Ad,t=>t.getHours());v4.range;const w4=Sa(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*Ad)},(t,e)=>(e-t)/Ad,t=>t.getUTCHours());w4.range;const zw=Sa(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*zl)/Kd,t=>t.getDate()-1);zw.range;const GT=Sa(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Kd,t=>t.getUTCDate()-1);GT.range;const ete=Sa(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Kd,t=>Math.floor(t/Kd));ete.range;function ag(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())*zl)/b4)}const WT=ag(0),Ok=ag(1),CFe=ag(2),TFe=ag(3),Tx=ag(4),AFe=ag(5),PFe=ag(6);WT.range;Ok.range;CFe.range;TFe.range;Tx.range;AFe.range;PFe.range;function sg(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)/b4)}const KT=sg(0),Ik=sg(1),MFe=sg(2),EFe=sg(3),Ax=sg(4),jFe=sg(5),DFe=sg(6);KT.range;Ik.range;MFe.range;EFe.range;Ax.range;jFe.range;DFe.range;const S4=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());S4.range;const _4=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());_4.range;const Yd=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());Yd.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)});Yd.range;const Xd=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());Xd.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)});Xd.range;function tte(t,e,n,r,a,s){const o=[[tf,1,Td],[tf,5,5*Td],[tf,15,15*Td],[tf,30,30*Td],[s,1,zl],[s,5,5*zl],[s,15,15*zl],[s,30,30*zl],[a,1,Ad],[a,3,3*Ad],[a,6,6*Ad],[a,12,12*Ad],[r,1,Kd],[r,2,2*Kd],[n,1,b4],[e,1,oG],[e,3,3*oG],[t,1,Ej]];function l(u,d,m){const p=db).right(o,p);if(f===o.length)return t.every(pF(u/Ej,d/Ej,m));if(f===0)return Lk.every(Math.max(pF(u,d,m),1));const[y,v]=o[p/o[f-1][2]53)return null;"w"in H||(H.w=1),"Z"in H?(O=Dj(yv(H.y,0,1)),$=O.getUTCDay(),O=$>4||$===0?Ik.ceil(O):Ik(O),O=GT.offset(O,(H.V-1)*7),H.y=O.getUTCFullYear(),H.m=O.getUTCMonth(),H.d=O.getUTCDate()+(H.w+6)%7):(O=jj(yv(H.y,0,1)),$=O.getDay(),O=$>4||$===0?Ok.ceil(O):Ok(O),O=zw.offset(O,(H.V-1)*7),H.y=O.getFullYear(),H.m=O.getMonth(),H.d=O.getDate()+(H.w+6)%7)}else("W"in H||"U"in H)&&("w"in H||(H.w="u"in H?H.u%7:"W"in H?1:0),$="Z"in H?Dj(yv(H.y,0,1)).getUTCDay():jj(yv(H.y,0,1)).getDay(),H.m=0,H.d="W"in H?(H.w+6)%7+H.W*7-($+5)%7:H.w+H.U*7-($+6)%7);return"Z"in H?(H.H+=H.Z/100|0,H.M+=H.Z%100,Dj(H)):jj(H)}}function D(E,U,K,H){for(var re=0,O=U.length,$=K.length,ee,W;re=$)return-1;if(ee=U.charCodeAt(re++),ee===37){if(ee=U.charAt(re++),W=k[ee in lG?U.charAt(re++):ee],!W||(H=W(E,K,H))<0)return-1}else if(ee!=K.charCodeAt(H++))return-1}return H}function A(E,U,K){var H=u.exec(U.slice(K));return H?(E.p=d.get(H[0].toLowerCase()),K+H[0].length):-1}function R(E,U,K){var H=f.exec(U.slice(K));return H?(E.w=y.get(H[0].toLowerCase()),K+H[0].length):-1}function G(E,U,K){var H=m.exec(U.slice(K));return H?(E.w=p.get(H[0].toLowerCase()),K+H[0].length):-1}function z(E,U,K){var H=g.exec(U.slice(K));return H?(E.m=_.get(H[0].toLowerCase()),K+H[0].length):-1}function Z(E,U,K){var H=v.exec(U.slice(K));return H?(E.m=b.get(H[0].toLowerCase()),K+H[0].length):-1}function I(E,U,K){return D(E,e,U,K)}function J(E,U,K){return D(E,n,U,K)}function ae(E,U,K){return D(E,r,U,K)}function Y(E){return o[E.getDay()]}function ue(E){return s[E.getDay()]}function de(E){return c[E.getMonth()]}function he(E){return l[E.getMonth()]}function V(E){return a[+(E.getHours()>=12)]}function ne(E){return 1+~~(E.getMonth()/3)}function se(E){return o[E.getUTCDay()]}function pe(E){return s[E.getUTCDay()]}function Te(E){return c[E.getUTCMonth()]}function q(E){return l[E.getUTCMonth()]}function X(E){return a[+(E.getUTCHours()>=12)]}function j(E){return 1+~~(E.getUTCMonth()/3)}return{format:function(E){var U=P(E+="",N);return U.toString=function(){return E},U},parse:function(E){var U=T(E+="",!1);return U.toString=function(){return E},U},utcFormat:function(E){var U=P(E+="",C);return U.toString=function(){return E},U},utcParse:function(E){var U=T(E+="",!0);return U.toString=function(){return E},U}}}var lG={"-":"",_:" ",0:"0"},Ia=/^\s*\d+/,zFe=/^%/,UFe=/[\\^$*+?|[\]().{}]/g;function vr(t,e,n){var r=t<0?"-":"",a=(r?-t:t)+"",s=a.length;return r+(s[e.toLowerCase(),n]))}function HFe(t,e,n){var r=Ia.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function $Fe(t,e,n){var r=Ia.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function qFe(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function VFe(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function GFe(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function cG(t,e,n){var r=Ia.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function uG(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function WFe(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 KFe(t,e,n){var r=Ia.exec(e.slice(n,n+1));return r?(t.q=r[0]*3-3,n+r[0].length):-1}function YFe(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function dG(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function XFe(t,e,n){var r=Ia.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function mG(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function QFe(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function ZFe(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function JFe(t,e,n){var r=Ia.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function eLe(t,e,n){var r=Ia.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function tLe(t,e,n){var r=zFe.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function nLe(t,e,n){var r=Ia.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function rLe(t,e,n){var r=Ia.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function hG(t,e){return vr(t.getDate(),e,2)}function iLe(t,e){return vr(t.getHours(),e,2)}function aLe(t,e){return vr(t.getHours()%12||12,e,2)}function sLe(t,e){return vr(1+zw.count(Yd(t),t),e,3)}function nte(t,e){return vr(t.getMilliseconds(),e,3)}function oLe(t,e){return nte(t,e)+"000"}function lLe(t,e){return vr(t.getMonth()+1,e,2)}function cLe(t,e){return vr(t.getMinutes(),e,2)}function uLe(t,e){return vr(t.getSeconds(),e,2)}function dLe(t){var e=t.getDay();return e===0?7:e}function mLe(t,e){return vr(WT.count(Yd(t)-1,t),e,2)}function rte(t){var e=t.getDay();return e>=4||e===0?Tx(t):Tx.ceil(t)}function hLe(t,e){return t=rte(t),vr(Tx.count(Yd(t),t)+(Yd(t).getDay()===4),e,2)}function pLe(t){return t.getDay()}function fLe(t,e){return vr(Ok.count(Yd(t)-1,t),e,2)}function gLe(t,e){return vr(t.getFullYear()%100,e,2)}function bLe(t,e){return t=rte(t),vr(t.getFullYear()%100,e,2)}function xLe(t,e){return vr(t.getFullYear()%1e4,e,4)}function yLe(t,e){var n=t.getDay();return t=n>=4||n===0?Tx(t):Tx.ceil(t),vr(t.getFullYear()%1e4,e,4)}function vLe(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+vr(e/60|0,"0",2)+vr(e%60,"0",2)}function pG(t,e){return vr(t.getUTCDate(),e,2)}function wLe(t,e){return vr(t.getUTCHours(),e,2)}function SLe(t,e){return vr(t.getUTCHours()%12||12,e,2)}function _Le(t,e){return vr(1+GT.count(Xd(t),t),e,3)}function ite(t,e){return vr(t.getUTCMilliseconds(),e,3)}function NLe(t,e){return ite(t,e)+"000"}function kLe(t,e){return vr(t.getUTCMonth()+1,e,2)}function CLe(t,e){return vr(t.getUTCMinutes(),e,2)}function TLe(t,e){return vr(t.getUTCSeconds(),e,2)}function ALe(t){var e=t.getUTCDay();return e===0?7:e}function PLe(t,e){return vr(KT.count(Xd(t)-1,t),e,2)}function ate(t){var e=t.getUTCDay();return e>=4||e===0?Ax(t):Ax.ceil(t)}function MLe(t,e){return t=ate(t),vr(Ax.count(Xd(t),t)+(Xd(t).getUTCDay()===4),e,2)}function ELe(t){return t.getUTCDay()}function jLe(t,e){return vr(Ik.count(Xd(t)-1,t),e,2)}function DLe(t,e){return vr(t.getUTCFullYear()%100,e,2)}function RLe(t,e){return t=ate(t),vr(t.getUTCFullYear()%100,e,2)}function FLe(t,e){return vr(t.getUTCFullYear()%1e4,e,4)}function LLe(t,e){var n=t.getUTCDay();return t=n>=4||n===0?Ax(t):Ax.ceil(t),vr(t.getUTCFullYear()%1e4,e,4)}function OLe(){return"+0000"}function fG(){return"%"}function gG(t){return+t}function bG(t){return Math.floor(+t/1e3)}var wb,ste,ote;ILe({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 ILe(t){return wb=IFe(t),ste=wb.format,wb.parse,ote=wb.utcFormat,wb.utcParse,wb}function zLe(t){return new Date(t)}function ULe(t){return t instanceof Date?+t:+new Date(+t)}function N4(t,e,n,r,a,s,o,l,c,u){var d=u4(),m=d.invert,p=d.domain,f=u(".%L"),y=u(":%S"),v=u("%I:%M"),b=u("%I %p"),g=u("%a %d"),_=u("%b %d"),N=u("%B"),C=u("%Y");function k(P){return(c(P)e(a/(t.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,s)=>ARe(t,s/r))},n.copy=function(){return dte(e).domain(t)},rm.apply(n,arguments)}function XT(){var t=0,e=.5,n=1,r=1,a,s,o,l,c,u=$s,d,m=!1,p;function f(v){return isNaN(v=+v)?p:(v=.5+((v=+d(v))-s)*(r*vt.chartData,QT=yt([im],t=>{var e=t.chartData!=null?t.chartData.length-1:0;return{chartData:t.chartData,computedData:t.computedData,dataEndIndex:e,dataStartIndex:0}}),T4=(t,e,n,r)=>r?QT(t):im(t),fte=(t,e,n)=>n?QT(t):im(t);function Qd(t){if(Array.isArray(t)&&t.length===2){var[e,n]=t;if(Ln(e)&&Ln(n))return!0}return!1}function xG(t,e,n){return n?t:[Math.min(t[0],e[0]),Math.max(t[1],e[1])]}function gte(t,e){if(e&&typeof t!="function"&&Array.isArray(t)&&t.length===2){var[n,r]=t,a,s;if(Ln(n))a=n;else if(typeof n=="function")return;if(Ln(r))s=r;else if(typeof r=="function")return;var o=[a,s];if(Qd(o))return o}}function VLe(t,e,n){if(!(!n&&e==null)){if(typeof t=="function"&&e!=null)try{var r=t(e,n);if(Qd(r))return xG(r,e,n)}catch{}if(Array.isArray(t)&&t.length===2){var[a,s]=t,o,l;if(a==="auto")e!=null&&(o=Math.min(...e));else if(Yt(a))o=a;else if(typeof a=="function")try{e!=null&&(o=a(e?.[0]))}catch{}else if(typeof a=="string"&&AV.test(a)){var c=AV.exec(a);if(c==null||c[1]==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(Yt(s))l=s;else if(typeof s=="function")try{e!=null&&(l=s(e?.[1]))}catch{}else if(typeof s=="string"&&PV.test(s)){var d=PV.exec(s);if(d==null||d[1]==null||e==null)l=void 0;else{var m=+d[1];l=e[1]+m}}else l=e?.[1];var p=[o,l];if(Qd(p))return e==null?p:xG(p,e,n)}}}var ty=1e9,GLe={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},P4,hi=!0,Xl="[DecimalError] ",xf=Xl+"Invalid argument: ",A4=Xl+"Exponent out of range: ",ny=Math.floor,Hp=Math.pow,WLe=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Yo,ja=1e7,ci=7,bte=9007199254740991,zk=ny(bte/ci),rn={};rn.absoluteValue=rn.abs=function(){var t=new this.constructor(this);return t.s&&(t.s=1),t};rn.comparedTo=rn.cmp=function(t){var e,n,r,a,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,a=t.d.length,e=0,n=rt.d[e]^s.s<0?1:-1;return r===a?0:r>a^s.s<0?1:-1};rn.decimalPlaces=rn.dp=function(){var t=this,e=t.d.length-1,n=(e-t.e)*ci;if(e=t.d[e],e)for(;e%10==0;e/=10)n--;return n<0?0:n};rn.dividedBy=rn.div=function(t){return Rd(this,new this.constructor(t))};rn.dividedToIntegerBy=rn.idiv=function(t){var e=this,n=e.constructor;return Qr(Rd(e,new n(t),0,1),n.precision)};rn.equals=rn.eq=function(t){return!this.cmp(t)};rn.exponent=function(){return la(this)};rn.greaterThan=rn.gt=function(t){return this.cmp(t)>0};rn.greaterThanOrEqualTo=rn.gte=function(t){return this.cmp(t)>=0};rn.isInteger=rn.isint=function(){return this.e>this.d.length-2};rn.isNegative=rn.isneg=function(){return this.s<0};rn.isPositive=rn.ispos=function(){return this.s>0};rn.isZero=function(){return this.s===0};rn.lessThan=rn.lt=function(t){return this.cmp(t)<0};rn.lessThanOrEqualTo=rn.lte=function(t){return this.cmp(t)<1};rn.logarithm=rn.log=function(t){var e,n=this,r=n.constructor,a=r.precision,s=a+5;if(t===void 0)t=new r(10);else if(t=new r(t),t.s<1||t.eq(Yo))throw Error(Xl+"NaN");if(n.s<1)throw Error(Xl+(n.s?"NaN":"-Infinity"));return n.eq(Yo)?new r(0):(hi=!1,e=Rd(Y0(n,s),Y0(t,s),s),hi=!0,Qr(e,a))};rn.minus=rn.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?vte(e,t):xte(e,(t.s=-t.s,t))};rn.modulo=rn.mod=function(t){var e,n=this,r=n.constructor,a=r.precision;if(t=new r(t),!t.s)throw Error(Xl+"NaN");return n.s?(hi=!1,e=Rd(n,t,0,1).times(t),hi=!0,n.minus(e)):Qr(new r(n),a)};rn.naturalExponential=rn.exp=function(){return yte(this)};rn.naturalLogarithm=rn.ln=function(){return Y0(this)};rn.negated=rn.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};rn.plus=rn.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?xte(e,t):vte(e,(t.s=-t.s,t))};rn.precision=rn.sd=function(t){var e,n,r,a=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(xf+t);if(e=la(a)+1,r=a.d.length-1,n=r*ci+1,r=a.d[r],r){for(;r%10==0;r/=10)n--;for(r=a.d[0];r>=10;r/=10)n++}return t&&e>n?e:n};rn.squareRoot=rn.sqrt=function(){var t,e,n,r,a,s,o,l=this,c=l.constructor;if(l.s<1){if(!l.s)return new c(0);throw Error(Xl+"NaN")}for(t=la(l),hi=!1,a=Math.sqrt(+l),a==0||a==1/0?(e=du(l.d),(e.length+t)%2==0&&(e+="0"),a=Math.sqrt(e),t=ny((t+1)/2)-(t<0||t%2),a==1/0?e="5e"+t:(e=a.toExponential(),e=e.slice(0,e.indexOf("e")+1)+t),r=new c(e)):r=new c(a.toString()),n=c.precision,a=o=n+3;;)if(s=r,r=s.plus(Rd(l,s,o+2)).times(.5),du(s.d).slice(0,o)===(e=du(r.d)).slice(0,o)){if(e=e.slice(o-3,o+1),a==o&&e=="4999"){if(Qr(s,n+1,0),s.times(s).eq(l)){r=s;break}}else if(e!="9999")break;o+=4}return hi=!0,Qr(r,n)};rn.times=rn.mul=function(t){var e,n,r,a,s,o,l,c,u,d=this,m=d.constructor,p=d.d,f=(t=new m(t)).d;if(!d.s||!t.s)return new m(0);for(t.s*=d.s,n=d.e+t.e,c=p.length,u=f.length,c=0;){for(e=0,a=c+r;a>r;)l=s[a]+f[r]*p[a-r-1]+e,s[a--]=l%ja|0,e=l/ja|0;s[a]=(s[a]+e)%ja|0}for(;!s[--o];)s.pop();return e?++n:s.shift(),t.d=s,t.e=n,hi?Qr(t,m.precision):t};rn.toDecimalPlaces=rn.todp=function(t,e){var n=this,r=n.constructor;return n=new r(n),t===void 0?n:(wu(t,0,ty),e===void 0?e=r.rounding:wu(e,0,8),Qr(n,t+la(n)+1,e))};rn.toExponential=function(t,e){var n,r=this,a=r.constructor;return t===void 0?n=Gf(r,!0):(wu(t,0,ty),e===void 0?e=a.rounding:wu(e,0,8),r=Qr(new a(r),t+1,e),n=Gf(r,!0,t+1)),n};rn.toFixed=function(t,e){var n,r,a=this,s=a.constructor;return t===void 0?Gf(a):(wu(t,0,ty),e===void 0?e=s.rounding:wu(e,0,8),r=Qr(new s(a),t+la(a)+1,e),n=Gf(r.abs(),!1,t+la(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};rn.toInteger=rn.toint=function(){var t=this,e=t.constructor;return Qr(new e(t),la(t)+1,e.rounding)};rn.toNumber=function(){return+this};rn.toPower=rn.pow=function(t){var e,n,r,a,s,o,l=this,c=l.constructor,u=12,d=+(t=new c(t));if(!t.s)return new c(Yo);if(l=new c(l),!l.s){if(t.s<1)throw Error(Xl+"Infinity");return l}if(l.eq(Yo))return l;if(r=c.precision,t.eq(Yo))return Qr(l,r);if(e=t.e,n=t.d.length-1,o=e>=n,s=l.s,o){if((n=d<0?-d:d)<=bte){for(a=new c(Yo),e=Math.ceil(r/ci+4),hi=!1;n%2&&(a=a.times(l),vG(a.d,e)),n=ny(n/2),n!==0;)l=l.times(l),vG(l.d,e);return hi=!0,t.s<0?new c(Yo).div(a):Qr(a,r)}}else if(s<0)throw Error(Xl+"NaN");return s=s<0&&t.d[Math.max(e,n)]&1?-1:1,l.s=1,hi=!1,a=t.times(Y0(l,r+u)),hi=!0,a=yte(a),a.s=s,a};rn.toPrecision=function(t,e){var n,r,a=this,s=a.constructor;return t===void 0?(n=la(a),r=Gf(a,n<=s.toExpNeg||n>=s.toExpPos)):(wu(t,1,ty),e===void 0?e=s.rounding:wu(e,0,8),a=Qr(new s(a),t,e),n=la(a),r=Gf(a,t<=n||n<=s.toExpNeg,t)),r};rn.toSignificantDigits=rn.tosd=function(t,e){var n=this,r=n.constructor;return t===void 0?(t=r.precision,e=r.rounding):(wu(t,1,ty),e===void 0?e=r.rounding:wu(e,0,8)),Qr(new r(n),t,e)};rn.toString=rn.valueOf=rn.val=rn.toJSON=rn[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=la(t),n=t.constructor;return Gf(t,e<=n.toExpNeg||e>=n.toExpPos)};function xte(t,e){var n,r,a,s,o,l,c,u,d=t.constructor,m=d.precision;if(!t.s||!e.s)return e.s||(e=new d(t)),hi?Qr(e,m):e;if(c=t.d,u=e.d,o=t.e,a=e.e,c=c.slice(),s=o-a,s){for(s<0?(r=c,s=-s,l=u.length):(r=u,a=o,l=c.length),o=Math.ceil(m/ci),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)/ja|0,c[s]%=ja;for(n&&(c.unshift(n),++a),l=c.length;c[--l]==0;)c.pop();return e.d=c,e.e=a,hi?Qr(e,m):e}function wu(t,e,n){if(t!==~~t||tn)throw Error(xf+t)}function du(t){var e,n,r,a=t.length-1,s="",o=t[0];if(a>0){for(s+=o,e=1;eo?1:-1;else for(l=c=0;la[l]?1:-1;break}return c}function n(r,a,s){for(var o=0;s--;)r[s]-=o,o=r[s]1;)r.shift()}return function(r,a,s,o){var l,c,u,d,m,p,f,y,v,b,g,_,N,C,k,P,T,D,A=r.constructor,R=r.s==a.s?1:-1,G=r.d,z=a.d;if(!r.s)return new A(r);if(!a.s)throw Error(Xl+"Division by zero");for(c=r.e-a.e,T=z.length,k=G.length,f=new A(R),y=f.d=[],u=0;z[u]==(G[u]||0);)++u;if(z[u]>(G[u]||0)&&--c,s==null?_=s=A.precision:o?_=s+(la(r)-la(a))+1:_=s,_<0)return new A(0);if(_=_/ci+2|0,u=0,T==1)for(d=0,z=z[0],_++;(u1&&(z=t(z,d),G=t(G,d),T=z.length,k=G.length),C=T,v=G.slice(0,T),b=v.length;b=ja/2&&++P;do d=0,l=e(z,v,T,b),l<0?(g=v[0],T!=b&&(g=g*ja+(v[1]||0)),d=g/P|0,d>1?(d>=ja&&(d=ja-1),m=t(z,d),p=m.length,b=v.length,l=e(m,v,p,b),l==1&&(d--,n(m,T16)throw Error(A4+la(t));if(!t.s)return new d(Yo);for(hi=!1,l=m,o=new d(.03125);t.abs().gte(.1);)t=t.times(o),u+=5;for(r=Math.log(Hp(2,u))/Math.LN10*2+5|0,l+=r,n=a=s=new d(Yo),d.precision=l;;){if(a=Qr(a.times(t),l),n=n.times(++c),o=s.plus(Rd(a,n,l)),du(o.d).slice(0,l)===du(s.d).slice(0,l)){for(;u--;)s=Qr(s.times(s),l);return d.precision=m,e==null?(hi=!0,Qr(s,m)):s}s=o}}function la(t){for(var e=t.e*ci,n=t.d[0];n>=10;n/=10)e++;return e}function Rj(t,e,n){if(e>t.LN10.sd())throw hi=!0,n&&(t.precision=n),Error(Xl+"LN10 precision limit exceeded");return Qr(new t(t.LN10),e)}function Zm(t){for(var e="";t--;)e+="0";return e}function Y0(t,e){var n,r,a,s,o,l,c,u,d,m=1,p=10,f=t,y=f.d,v=f.constructor,b=v.precision;if(f.s<1)throw Error(Xl+(f.s?"NaN":"-Infinity"));if(f.eq(Yo))return new v(0);if(e==null?(hi=!1,u=b):u=e,f.eq(10))return e==null&&(hi=!0),Rj(v,u);if(u+=p,v.precision=u,n=du(y),r=n.charAt(0),s=la(f),Math.abs(s)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)f=f.times(t),n=du(f.d),r=n.charAt(0),m++;s=la(f),r>1?(f=new v("0."+n),s++):f=new v(r+"."+n.slice(1))}else return c=Rj(v,u+2,b).times(s+""),f=Y0(new v(r+"."+n.slice(1)),u-p).plus(c),v.precision=b,e==null?(hi=!0,Qr(f,b)):f;for(l=o=f=Rd(f.minus(Yo),f.plus(Yo),u),d=Qr(f.times(f),u),a=3;;){if(o=Qr(o.times(d),u),c=l.plus(Rd(o,new v(a),u)),du(c.d).slice(0,u)===du(l.d).slice(0,u))return l=l.times(2),s!==0&&(l=l.plus(Rj(v,u+2,b).times(s+""))),l=Rd(l,new v(m),u),v.precision=b,e==null?(hi=!0,Qr(l,b)):l;l=c,a+=2}}function yG(t,e){var n,r,a;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(a=e.length;e.charCodeAt(a-1)===48;)--a;if(e=e.slice(r,a),e){if(a-=r,n=n-r-1,t.e=ny(n/ci),t.d=[],r=(n+1)%ci,n<0&&(r+=ci),rzk||t.e<-zk))throw Error(A4+n)}else t.s=0,t.e=0,t.d=[0];return t}function Qr(t,e,n){var r,a,s,o,l,c,u,d,m=t.d;for(o=1,s=m[0];s>=10;s/=10)o++;if(r=e-o,r<0)r+=ci,a=e,u=m[d=0];else{if(d=Math.ceil((r+1)/ci),s=m.length,d>=s)return t;for(u=s=m[d],o=1;s>=10;s/=10)o++;r%=ci,a=r-ci+o}if(n!==void 0&&(s=Hp(10,o-a-1),l=u/s%10|0,c=e<0||m[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?a>0?u/Hp(10,o-a):0:m[d-1])%10&1||n==(t.s<0?8:7))),e<1||!m[0])return c?(s=la(t),m.length=1,e=e-s-1,m[0]=Hp(10,(ci-e%ci)%ci),t.e=ny(-e/ci)||0):(m.length=1,m[0]=t.e=t.s=0),t;if(r==0?(m.length=d,s=1,d--):(m.length=d+1,s=Hp(10,ci-r),m[d]=a>0?(u/Hp(10,o-a)%Hp(10,a)|0)*s:0),c)for(;;)if(d==0){(m[0]+=s)==ja&&(m[0]=1,++t.e);break}else{if(m[d]+=s,m[d]!=ja)break;m[d--]=0,s=1}for(r=m.length;m[--r]===0;)m.pop();if(hi&&(t.e>zk||t.e<-zk))throw Error(A4+la(t));return t}function vte(t,e){var n,r,a,s,o,l,c,u,d,m,p=t.constructor,f=p.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new p(t),hi?Qr(e,f):e;if(c=t.d,m=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=m.length):(n=m,r=u,l=c.length),a=Math.max(Math.ceil(f/ci),l)+2,o>a&&(o=a,n.length=1),n.reverse(),a=o;a--;)n.push(0);n.reverse()}else{for(a=c.length,l=m.length,d=a0;--a)c[l++]=0;for(a=m.length;a>o;){if(c[--a]0?s=s.charAt(0)+"."+s.slice(1)+Zm(r):o>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(a<0?"e":"e+")+a):a<0?(s="0."+Zm(-a-1)+s,n&&(r=n-o)>0&&(s+=Zm(r))):a>=o?(s+=Zm(a+1-o),n&&(r=n-a-1)>0&&(s=s+"."+Zm(r))):((r=a+1)0&&(a+1===o&&(s+="."),s+=Zm(r))),t.s<0?"-"+s:s}function vG(t,e){if(t.length>e)return t.length=e,!0}function wte(t){var e,n,r;function a(s){var o=this;if(!(o instanceof a))return new a(s);if(o.constructor=a,s instanceof a){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(xf+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 yG(o,s.toString())}else if(typeof s!="string")throw Error(xf+s);if(s.charCodeAt(0)===45?(s=s.slice(1),o.s=-1):o.s=1,WLe.test(s))yG(o,s);else throw Error(xf+s)}if(a.prototype=rn,a.ROUND_UP=0,a.ROUND_DOWN=1,a.ROUND_CEIL=2,a.ROUND_FLOOR=3,a.ROUND_HALF_UP=4,a.ROUND_HALF_DOWN=5,a.ROUND_HALF_EVEN=6,a.ROUND_HALF_CEIL=7,a.ROUND_HALF_FLOOR=8,a.clone=wte,a.config=a.set=KLe,t===void 0&&(t={}),t)for(r=["precision","rounding","toExpNeg","toExpPos","LN10"],e=0;e=a[e+1]&&r<=a[e+2])this[n]=r;else throw Error(xf+n+": "+r);if((r=t[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(xf+n+": "+r);return this}var P4=wte(GLe);Yo=new P4(1);const Dr=P4;function Ste(t){var e;return t===0?e=1:e=Math.floor(new Dr(t).abs().log(10).toNumber())+1,e}function _te(t,e,n){for(var r=new Dr(t),a=0,s=[];r.lt(e)&&a<1e5;)s.push(r.toNumber()),r=r.add(n),a++;return s}var Nte=t=>{var[e,n]=t,[r,a]=[e,n];return e>n&&([r,a]=[n,e]),[r,a]},kte=(t,e,n)=>{if(t.lte(0))return new Dr(0);var r=Ste(t.toNumber()),a=new Dr(10).pow(r),s=t.div(a),o=r!==1?.05:.1,l=new Dr(Math.ceil(s.div(o).toNumber())).add(n).mul(o),c=l.mul(a);return e?new Dr(c.toNumber()):new Dr(Math.ceil(c.toNumber()))},YLe=(t,e,n)=>{var r=new Dr(1),a=new Dr(t);if(!a.isint()&&n){var s=Math.abs(t);s<1?(r=new Dr(10).pow(Ste(t)-1),a=new Dr(Math.floor(a.div(r).toNumber())).mul(r)):s>1&&(a=new Dr(Math.floor(t)))}else t===0?a=new Dr(Math.floor((e-1)/2)):n||(a=new Dr(Math.floor(t)));for(var o=Math.floor((e-1)/2),l=[],c=0;c4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((n-e)/(r-1)))return{step:new Dr(0),tickMin:new Dr(0),tickMax:new Dr(0)};var o=kte(new Dr(n).sub(e).div(r-1),a,s),l;e<=0&&n>=0?l=new Dr(0):(l=new Dr(e).add(n).div(2),l=l.sub(new Dr(l).mod(o)));var c=Math.ceil(l.sub(e).div(o).toNumber()),u=Math.ceil(new Dr(n).sub(l).div(o).toNumber()),d=c+u+1;return d>r?Cte(e,n,r,a,s+1):(d0?u+(r-d):u,c=n>0?c:c+(r-d)),{step:o,tickMin:l.sub(new Dr(c).mul(o)),tickMax:l.add(new Dr(u).mul(o))})},XLe=function(e){var[n,r]=e,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=Math.max(a,2),[l,c]=Nte([n,r]);if(l===-1/0||c===1/0){var u=c===1/0?[l,...Array(a-1).fill(1/0)]:[...Array(a-1).fill(-1/0),c];return n>r?u.reverse():u}if(l===c)return YLe(l,a,s);var{step:d,tickMin:m,tickMax:p}=Cte(l,c,o,s,0),f=_te(m,p.add(new Dr(.1).mul(d)),d);return n>r?f.reverse():f},QLe=function(e,n){var[r,a]=e,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,[o,l]=Nte([r,a]);if(o===-1/0||l===1/0)return[r,a];if(o===l)return[o];var c=Math.max(n,2),u=kte(new Dr(l).sub(o).div(c-1),s,0),d=[..._te(new Dr(o),new Dr(l),u),l];return s===!1&&(d=d.map(m=>Math.round(m))),r>a?d.reverse():d},Tte=t=>t.rootProps.maxBarSize,ZLe=t=>t.rootProps.barGap,Ate=t=>t.rootProps.barCategoryGap,JLe=t=>t.rootProps.barSize,Uw=t=>t.rootProps.stackOffset,Pte=t=>t.rootProps.reverseStackOrder,M4=t=>t.options.chartName,E4=t=>t.rootProps.syncId,Mte=t=>t.rootProps.syncMethod,j4=t=>t.options.eventEmitter,eOe=t=>t.rootProps.baseValue,Fi={grid:-100,barBackground:-50,area:100,cursorRectangle:200,bar:300,line:400,axis:500,scatter:600,activeBar:1e3,cursorLine:1100,activeDot:1200,label:2e3},Rp={allowDecimals:!1,allowDataOverflow:!1,angleAxisId:0,reversed:!1,scale:"auto",tick:!0,type:"auto"},Xc={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:!0,includeHidden:!1,radiusAxisId:0,reversed:!1,scale:"auto",tick:!0,tickCount:5,type:"auto"},ZT=(t,e)=>{if(!(!t||!e))return t!=null&&t.reversed?[e[1],e[0]]:e};function JT(t,e,n){if(n!=="auto")return n;if(t!=null)return Fc(t,e)?"category":"number"}function wG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Uk(t){for(var e=1;e{if(e!=null)return t.polarAxis.angleAxis[e]},D4=yt([iOe,hee],(t,e)=>{var n;if(t!=null)return t;var r=(n=JT(e,"angleAxis",SG.type))!==null&&n!==void 0?n:"category";return Uk(Uk({},SG),{},{type:r})}),aOe=(t,e)=>t.polarAxis.radiusAxis[e],R4=yt([aOe,hee],(t,e)=>{var n;if(t!=null)return t;var r=(n=JT(e,"radiusAxis",_G.type))!==null&&n!==void 0?n:"category";return Uk(Uk({},_G),{},{type:r})}),eA=t=>t.polarOptions,F4=yt([tm,nm,va],Eee),Ete=yt([eA,F4],(t,e)=>{if(t!=null)return ws(t.innerRadius,e,0)}),jte=yt([eA,F4],(t,e)=>{if(t!=null)return ws(t.outerRadius,e,e*.8)}),sOe=t=>{if(t==null)return[0,0];var{startAngle:e,endAngle:n}=t;return[e,n]},Dte=yt([eA],sOe);yt([D4,Dte],ZT);var Rte=yt([F4,Ete,jte],(t,e,n)=>{if(!(t==null||e==null||n==null))return[e,n]});yt([R4,Rte],ZT);var Fte=yt([dr,eA,Ete,jte,tm,nm],(t,e,n,r,a,s)=>{if(!(t!=="centric"&&t!=="radial"||e==null||n==null||r==null)){var{cx:o,cy:l,startAngle:c,endAngle:u}=e;return{cx:ws(o,a,a/2),cy:ws(l,s,s/2),innerRadius:n,outerRadius:r,startAngle:c,endAngle:u,clockWise:!1}}}),Si=(t,e)=>e,Bw=(t,e,n)=>n;function tA(t){return t?.id}function Lte(t,e,n){var{chartData:r=[]}=e,{allowDuplicatedCategory:a,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=tA(l);u.forEach((m,p)=>{var f=s==null||a?p:String(Tr(m,s,null)),y=Tr(m,l.dataKey,0),v;o.has(f)?v=o.get(f):v={},Object.assign(v,{[d]:y}),o.set(f,v)})}}),Array.from(o.values())}function nA(t){return"stackId"in t&&t.stackId!=null&&t.dataKey!=null}var rA=(t,e)=>t===e?!0:t==null||e==null?!1:t[0]===e[0]&&t[1]===e[1];function iA(t,e){return Array.isArray(t)&&Array.isArray(e)&&t.length===0&&e.length===0?!0:t===e}function oOe(t,e){if(t.length===e.length){for(var n=0;n{var e=dr(t);return e==="horizontal"?"xAxis":e==="vertical"?"yAxis":e==="centric"?"angleAxis":"radiusAxis"},ry=t=>t.tooltip.settings.axisId;function lOe(t){if(t in Lv)return Lv[t]();var e="scale".concat(Tw(t));if(e in Lv)return Lv[e]()}function NG(t){var e=t.ticks,n=t.bandwidth,r=t.range(),a=[Math.min(...r),Math.max(...r)];return{domain:()=>t.domain(),range:(function(s){function o(){return s.apply(this,arguments)}return o.toString=function(){return s.toString()},o})(()=>a),rangeMin:()=>a[0],rangeMax:()=>a[1],isInRange(s){var o=a[0],l=a[1];return o<=l?s>=o&&s<=l:s>=l&&s<=o},bandwidth:n?()=>n.call(t):void 0,ticks:e?s=>e.call(t,s):void 0,map:(s,o)=>{var l=t(s);if(l!=null){if(t.bandwidth&&o!==null&&o!==void 0&&o.position){var c=t.bandwidth();switch(o.position){case"middle":l+=c/2;break;case"end":l+=c;break}}return l}}}}function kG(t,e,n){if(typeof t=="function")return NG(t.copy().domain(e).range(n));if(t!=null){var r=lOe(t);if(r!=null)return r.domain(e).range(n),NG(r)}}var Ote=(t,e)=>{if(e!=null)switch(t){case"linear":{if(!Qd(e)){for(var n,r,a=0;ar)&&(r=s))}return n!==void 0&&r!==void 0?[n,r]:void 0}return e}default:return e}};function CG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Bk(t){for(var e=1;et.cartesianAxis.xAxis[e],Au=(t,e)=>{var n=Ite(t,e);return n??Ma},Ea={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:yF,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:Ew},zte=(t,e)=>t.cartesianAxis.yAxis[e],Pu=(t,e)=>{var n=zte(t,e);return n??Ea},mOe={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:""},L4=(t,e)=>{var n=t.cartesianAxis.zAxis[e];return n??mOe},Ii=(t,e,n)=>{switch(e){case"xAxis":return Au(t,n);case"yAxis":return Pu(t,n);case"zAxis":return L4(t,n);case"angleAxis":return D4(t,n);case"radiusAxis":return R4(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},hOe=(t,e,n)=>{switch(e){case"xAxis":return Au(t,n);case"yAxis":return Pu(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},iy=(t,e,n)=>{switch(e){case"xAxis":return Au(t,n);case"yAxis":return Pu(t,n);case"angleAxis":return D4(t,n);case"radiusAxis":return R4(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},Ute=t=>t.graphicalItems.cartesianItems.some(e=>e.type==="bar")||t.graphicalItems.polarItems.some(e=>e.type==="radialBar");function O4(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 Hw=t=>t.graphicalItems.cartesianItems,pOe=yt([Si,Bw],O4),I4=(t,e,n)=>t.filter(n).filter(r=>e?.includeHidden===!0?!0:!r.hide),$w=yt([Hw,Ii,pOe],I4,{memoizeOptions:{resultEqualityCheck:iA}}),Bte=yt([$w],t=>t.filter(e=>e.type==="area"||e.type==="bar").filter(nA)),Hte=t=>t.filter(e=>!("stackId"in e)||e.stackId===void 0),fOe=yt([$w],Hte),z4=t=>t.map(e=>e.data).filter(Boolean).flat(1),gOe=yt([$w],z4,{memoizeOptions:{resultEqualityCheck:iA}}),U4=(t,e)=>{var{chartData:n=[],dataStartIndex:r,dataEndIndex:a}=e;return t.length>0?t:n.slice(r,a+1)},B4=yt([gOe,T4],U4),H4=(t,e,n)=>e?.dataKey!=null?t.map(r=>({value:Tr(r,e.dataKey)})):n.length>0?n.map(r=>r.dataKey).flatMap(r=>t.map(a=>({value:Tr(a,r)}))):t.map(r=>({value:r})),aA=yt([B4,Ii,$w],H4);function $te(t,e){switch(t){case"xAxis":return e.direction==="x";case"yAxis":return e.direction==="y";default:return!1}}function fN(t){if(Kl(t)||t instanceof Date){var e=Number(t);if(Ln(e))return e}}function TG(t){if(Array.isArray(t)){var e=[fN(t[0]),fN(t[1])];return Qd(e)?e:void 0}var n=fN(t);if(n!=null)return[n,n]}function Zd(t){return t.map(fN).filter(yo)}function bOe(t,e,n){return!n||typeof e!="number"||Mc(e)?[]:n.length?Zd(n.flatMap(r=>{var a=Tr(t,r.dataKey),s,o;if(Array.isArray(a)?[s,o]=a:s=o=a,!(!Ln(s)||!Ln(o)))return[e-s,e+o]})):[]}var _a=t=>{var e=za(t),n=ry(t);return iy(t,e,n)},qw=yt([_a],t=>t?.dataKey),xOe=yt([Bte,T4,_a],Lte),qte=(t,e,n,r)=>{var a={},s=e.reduce((o,l)=>{if(l.stackId==null)return o;var c=o[l.stackId];return c==null&&(c=[]),c.push(l),o[l.stackId]=c,o},a);return Object.fromEntries(Object.entries(s).map(o=>{var[l,c]=o,u=r?[...c].reverse():c,d=u.map(tA);return[l,{stackedData:zje(t,d,n),graphicalItems:u}]}))},Hk=yt([xOe,Bte,Uw,Pte],qte),Vte=(t,e,n,r)=>{var{dataStartIndex:a,dataEndIndex:s}=e;if(r==null&&n!=="zAxis"){var o=$je(t,a,s);if(!(o!=null&&o[0]===0&&o[1]===0))return o}},yOe=yt([Ii],t=>t.allowDataOverflow),$4=t=>{var e;if(t==null||!("domain"in t))return yF;if(t.domain!=null)return t.domain;if("ticks"in t&&t.ticks!=null){if(t.type==="number"){var n=Zd(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:yF},q4=yt([Ii],$4),V4=yt([q4,yOe],gte),vOe=yt([Hk,im,Si,V4],Vte,{memoizeOptions:{resultEqualityCheck:rA}}),sA=t=>t.errorBars,wOe=(t,e,n)=>t.flatMap(r=>e[r.id]).filter(Boolean).filter(r=>$te(n,r)),$k=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,m=(u=r[c.id])===null||u===void 0?void 0:u.filter(g=>$te(a,g)),p=Tr(l,(d=e.dataKey)!==null&&d!==void 0?d:c.dataKey),f=bOe(l,p,m);if(f.length>=2){var y=Math.min(...f),v=Math.max(...f);(s==null||yo)&&(o=v)}var b=TG(p);b!=null&&(s=s==null?b[0]:Math.min(s,b[0]),o=o==null?b[1]:Math.max(o,b[1]))})}),e?.dataKey!=null&&t.forEach(l=>{var c=TG(Tr(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]))}),Ln(s)&&Ln(o))return[s,o]},SOe=yt([B4,Ii,fOe,sA,Si],G4,{memoizeOptions:{resultEqualityCheck:rA}});function _Oe(t){var{value:e}=t;if(Kl(e)||e instanceof Date)return e}var NOe=(t,e,n)=>{var r=t.map(_Oe).filter(a=>a!=null);return n&&(e.dataKey==null||e.allowDuplicatedCategory&&lJ(r))?Fee(0,t.length):e.allowDuplicatedCategory?r:Array.from(new Set(r))},Gte=t=>t.referenceElements.dots,ay=(t,e,n)=>t.filter(r=>r.ifOverflow==="extendDomain").filter(r=>e==="xAxis"?r.xAxisId===n:r.yAxisId===n),kOe=yt([Gte,Si,Bw],ay),Wte=t=>t.referenceElements.areas,COe=yt([Wte,Si,Bw],ay),Kte=t=>t.referenceElements.lines,TOe=yt([Kte,Si,Bw],ay),Yte=(t,e)=>{if(t!=null){var n=Zd(t.map(r=>e==="xAxis"?r.x:r.y));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},AOe=yt(kOe,Si,Yte),Xte=(t,e)=>{if(t!=null){var n=Zd(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)]}},POe=yt([COe,Si],Xte);function MOe(t){var e;if(t.x!=null)return Zd([t.x]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.x);return n==null||n.length===0?[]:Zd(n)}function EOe(t){var e;if(t.y!=null)return Zd([t.y]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.y);return n==null||n.length===0?[]:Zd(n)}var Qte=(t,e)=>{if(t!=null){var n=t.flatMap(r=>e==="xAxis"?MOe(r):EOe(r));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},jOe=yt([TOe,Si],Qte),DOe=yt(AOe,jOe,POe,(t,e,n)=>$k(t,n,e)),W4=(t,e,n,r,a,s,o,l)=>{if(n!=null)return n;var c=o==="vertical"&&l==="xAxis"||o==="horizontal"&&l==="yAxis",u=c?$k(r,s,a):$k(s,a);return VLe(e,u,t.allowDataOverflow)},ROe=yt([Ii,q4,V4,vOe,SOe,DOe,dr,Si],W4,{memoizeOptions:{resultEqualityCheck:rA}}),FOe=[0,1],K4=(t,e,n,r,a,s,o)=>{if(!((t==null||n==null||n.length===0)&&o===void 0)){var{dataKey:l,type:c}=t,u=Fc(e,s);if(u&&l==null){var d;return Fee(0,(d=n?.length)!==null&&d!==void 0?d:0)}return c==="category"?NOe(r,t,u):a==="expand"?FOe:o}},Y4=yt([Ii,dr,B4,aA,Uw,Si,ROe],K4);function LOe(t){return t in Lv}var Zte=(t,e,n)=>{if(t!=null){var{scale:r,type:a}=t;if(r==="auto")return a==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!e)?"point":a==="category"?"band":"linear";if(typeof r=="string"){var s="scale".concat(Tw(r));return LOe(s)?s:"point"}}},ep=yt([Ii,Ute,M4],Zte);function X4(t,e,n,r){if(!(n==null||r==null))return typeof t.scale=="function"?kG(t.scale,n,r):kG(e,n,r)}var Q4=(t,e,n)=>{var r=$4(e);if(!(n!=="auto"&&n!=="linear")){if(e!=null&&e.tickCount&&Array.isArray(r)&&(r[0]==="auto"||r[1]==="auto")&&Qd(t))return XLe(t,e.tickCount,e.allowDecimals);if(e!=null&&e.tickCount&&e.type==="number"&&Qd(t))return QLe(t,e.tickCount,e.allowDecimals)}},Z4=yt([Y4,iy,ep],Q4),J4=(t,e,n,r)=>{if(r!=="angleAxis"&&t?.type==="number"&&Qd(e)&&Array.isArray(n)&&n.length>0){var a,s,o=e[0],l=(a=n[0])!==null&&a!==void 0?a:0,c=e[1],u=(s=n[n.length-1])!==null&&s!==void 0?s:0;return[Math.min(o,l),Math.max(c,u)]}return e},OOe=yt([Ii,Y4,Z4,Si],J4),IOe=yt(aA,Ii,(t,e)=>{if(!(!e||e.type!=="number")){var n=1/0,r=Array.from(Zd(t.map(m=>m.value))).sort((m,p)=>m-p),a=r[0],s=r[r.length-1];if(a==null||s==null)return 1/0;var o=s-a;if(o===0)return 1/0;for(var l=0;la,(t,e,n,r,a)=>{if(!Ln(t))return 0;var s=e==="vertical"?r.height:r.width;if(a==="gap")return t*s/2;if(a==="no-gap"){var o=ws(n,t*s),l=t*s/2;return l-o-(l-o)/s*o}return 0}),zOe=(t,e,n)=>{var r=Au(t,e);return r==null||typeof r.padding!="string"?0:Jte(t,"xAxis",e,n,r.padding)},UOe=(t,e,n)=>{var r=Pu(t,e);return r==null||typeof r.padding!="string"?0:Jte(t,"yAxis",e,n,r.padding)},BOe=yt(Au,zOe,(t,e)=>{var n,r;if(t==null)return{left:0,right:0};var{padding:a}=t;return typeof a=="string"?{left:e,right:e}:{left:((n=a.left)!==null&&n!==void 0?n:0)+e,right:((r=a.right)!==null&&r!==void 0?r:0)+e}}),HOe=yt(Pu,UOe,(t,e)=>{var n,r;if(t==null)return{top:0,bottom:0};var{padding:a}=t;return typeof a=="string"?{top:e,bottom:e}:{top:((n=a.top)!==null&&n!==void 0?n:0)+e,bottom:((r=a.bottom)!==null&&r!==void 0?r:0)+e}}),$Oe=yt([va,BOe,BT,UT,(t,e,n)=>n],(t,e,n,r,a)=>{var{padding:s}=r;return a?[s.left,n.width-s.right]:[t.left+e.left,t.left+t.width-e.right]}),qOe=yt([va,dr,HOe,BT,UT,(t,e,n)=>n],(t,e,n,r,a,s)=>{var{padding:o}=a;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]}),Vw=(t,e,n,r)=>{var a;switch(e){case"xAxis":return $Oe(t,n,r);case"yAxis":return qOe(t,n,r);case"zAxis":return(a=L4(t,n))===null||a===void 0?void 0:a.range;case"angleAxis":return Dte(t);case"radiusAxis":return Rte(t,n);default:return}},ene=yt([Ii,Vw],ZT),VOe=yt([ep,OOe],Ote),Px=yt([Ii,ep,VOe,ene],X4);yt([$w,sA,Si],wOe);function tne(t,e){return t.ide.id?1:0}var oA=(t,e)=>e,lA=(t,e,n)=>n,GOe=yt(IT,oA,lA,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(tne)),WOe=yt(zT,oA,lA,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(tne)),nne=(t,e)=>({width:t.width,height:e.height}),KOe=(t,e)=>{var n=typeof e.width=="number"?e.width:Ew;return{width:n,height:t.height}},rne=yt(va,Au,nne),YOe=(t,e,n)=>{switch(e){case"top":return t.top;case"bottom":return n-t.bottom;default:return 0}},XOe=(t,e,n)=>{switch(e){case"left":return t.left;case"right":return n-t.right;default:return 0}},QOe=yt(nm,va,GOe,oA,lA,(t,e,n,r,a)=>{var s={},o;return n.forEach(l=>{var c=nne(e,l);o==null&&(o=YOe(e,r,t));var u=r==="top"&&!a||r==="bottom"&&a;s[l.id]=o-Number(u)*c.height,o+=(u?-1:1)*c.height}),s}),ZOe=yt(tm,va,WOe,oA,lA,(t,e,n,r,a)=>{var s={},o;return n.forEach(l=>{var c=KOe(e,l);o==null&&(o=XOe(e,r,t));var u=r==="left"&&!a||r==="right"&&a;s[l.id]=o-Number(u)*c.width,o+=(u?-1:1)*c.width}),s}),JOe=(t,e)=>{var n=Au(t,e);if(n!=null)return QOe(t,n.orientation,n.mirror)},e4e=yt([va,Au,JOe,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var a=n?.[r];return a==null?{x:t.left,y:0}:{x:t.left,y:a}}}),t4e=(t,e)=>{var n=Pu(t,e);if(n!=null)return ZOe(t,n.orientation,n.mirror)},n4e=yt([va,Pu,t4e,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var a=n?.[r];return a==null?{x:0,y:t.top}:{x:a,y:t.top}}}),ine=yt(va,Pu,(t,e)=>{var n=typeof e.width=="number"?e.width:Ew;return{width:n,height:t.height}}),AG=(t,e,n)=>{switch(e){case"xAxis":return rne(t,n).width;case"yAxis":return ine(t,n).height;default:return}},ane=(t,e,n,r)=>{if(n!=null){var{allowDuplicatedCategory:a,type:s,dataKey:o}=n,l=Fc(t,r),c=e.map(u=>u.value);if(o&&l&&s==="category"&&a&&lJ(c))return c}},eI=yt([dr,aA,Ii,Si],ane),sne=(t,e,n,r)=>{if(!(n==null||n.dataKey==null)){var{type:a,scale:s}=n,o=Fc(t,r);if(o&&(a==="number"||s!=="auto"))return e.map(l=>l.value)}},tI=yt([dr,aA,iy,Si],sne),PG=yt([dr,hOe,ep,Px,eI,tI,Vw,Z4,Si],(t,e,n,r,a,s,o,l,c)=>{if(e!=null){var u=Fc(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:a,isCategorical:u,niceTicks:l,range:o,realScaleType:n,scale:r}}}),r4e=(t,e,n,r,a,s,o,l,c)=>{if(!(e==null||r==null)){var u=Fc(t,c),{type:d,ticks:m,tickCount:p}=e,f=n==="scaleBand"&&typeof r.bandwidth=="function"?r.bandwidth()/2:2,y=d==="category"&&r.bandwidth?r.bandwidth()/f:0;y=c==="angleAxis"&&s!=null&&s.length>=2?Fa(s[0]-s[1])*2*y:y;var v=m||a;return v?v.map((b,g)=>{var _=o?o.indexOf(b):b,N=r.map(_);return Ln(N)?{index:g,coordinate:N+y,value:b,offset:y}:null}).filter(yo):u&&l?l.map((b,g)=>{var _=r.map(b);return Ln(_)?{coordinate:_+y,value:b,index:g,offset:y}:null}).filter(yo):r.ticks?r.ticks(p).map((b,g)=>{var _=r.map(b);return Ln(_)?{coordinate:_+y,value:b,index:g,offset:y}:null}).filter(yo):r.domain().map((b,g)=>{var _=r.map(b);return Ln(_)?{coordinate:_+y,value:o?o[b]:b,index:g,offset:y}:null}).filter(yo)}},one=yt([dr,iy,ep,Px,Z4,Vw,eI,tI,Si],r4e),i4e=(t,e,n,r,a,s,o)=>{if(!(e==null||n==null||r==null||r[0]===r[1])){var l=Fc(t,o),{tickCount:c}=e,u=0;return u=o==="angleAxis"&&r?.length>=2?Fa(r[0]-r[1])*2*u:u,l&&s?s.map((d,m)=>{var p=n.map(d);return Ln(p)?{coordinate:p+u,value:d,index:m,offset:u}:null}).filter(yo):n.ticks?n.ticks(c).map((d,m)=>{var p=n.map(d);return Ln(p)?{coordinate:p+u,value:d,index:m,offset:u}:null}).filter(yo):n.domain().map((d,m)=>{var p=n.map(d);return Ln(p)?{coordinate:p+u,value:a?a[d]:d,index:m,offset:u}:null}).filter(yo)}},Su=yt([dr,iy,Px,Vw,eI,tI,Si],i4e),_u=yt(Ii,Px,(t,e)=>{if(!(t==null||e==null))return Bk(Bk({},t),{},{scale:e})}),a4e=yt([Ii,ep,Y4,ene],X4);yt((t,e,n)=>L4(t,n),a4e,(t,e)=>{if(!(t==null||e==null))return Bk(Bk({},t),{},{scale:e})});var s4e=yt([dr,IT,zT],(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}}),lne=t=>t.options.defaultTooltipEventType,cne=t=>t.options.validateTooltipEventTypes;function une(t,e,n){if(t==null)return e;var r=t?"axis":"item";return n==null?e:n.includes(r)?r:e}function nI(t,e){var n=lne(t),r=cne(t);return une(e,n,r)}function o4e(t){return en(e=>nI(e,t))}var dne=(t,e)=>{var n,r=Number(e);if(!(Mc(r)||e==null))return r>=0?t==null||(n=t[r])===null||n===void 0?void 0:n.value:void 0},l4e=t=>t.tooltip.settings,sh={active:!1,index:null,dataKey:void 0,graphicalItemId:void 0,coordinate:void 0},c4e={itemInteraction:{click:sh,hover:sh},axisInteraction:{click:sh,hover:sh},keyboardInteraction:sh,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}},mne=Ao({name:"tooltip",initialState:c4e,reducers:{addTooltipEntrySettings:{reducer(t,e){t.tooltipItemPayloads.push(e.payload)},prepare:mi()},replaceTooltipEntrySettings:{reducer(t,e){var{prev:n,next:r}=e.payload,a=Nc(t).tooltipItemPayloads.indexOf(n);a>-1&&(t.tooltipItemPayloads[a]=r)},prepare:mi()},removeTooltipEntrySettings:{reducer(t,e){var n=Nc(t).tooltipItemPayloads.indexOf(e.payload);n>-1&&t.tooltipItemPayloads.splice(n,1)},prepare:mi()},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}}}),{addTooltipEntrySettings:u4e,replaceTooltipEntrySettings:d4e,removeTooltipEntrySettings:m4e,setTooltipSettingsState:h4e,setActiveMouseOverItemIndex:hne,mouseLeaveItem:p4e,mouseLeaveChart:pne,setActiveClickItemIndex:f4e,setMouseOverAxisIndex:fne,setMouseClickAxisIndex:g4e,setSyncInteraction:vF,setKeyboardInteraction:wF}=mne.actions,b4e=mne.reducer;function MG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function T1(t){for(var e=1;e{if(e==null)return sh;var a=w4e(t,e,n);if(a==null)return sh;if(a.active)return a;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(S4e(a)){if(s)return T1(T1({},a),{},{active:!0})}else if(r!=null)return{active:!0,coordinate:void 0,dataKey:void 0,index:r,graphicalItemId:void 0};return T1(T1({},sh),{},{coordinate:a.coordinate})};function _4e(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 N4e(t,e){var n=_4e(t),r=e[0],a=e[1];if(n===void 0)return!1;var s=Math.min(r,a),o=Math.max(r,a);return n>=s&&n<=o}function k4e(t,e,n){if(n==null||e==null)return!0;var r=Tr(t,e);return r==null||!Qd(n)?!0:N4e(r,n)}var rI=(t,e,n,r)=>{var a=t?.index;if(a==null)return null;var s=Number(a);if(!Ln(s))return a;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||k4e(u,n,r)?String(c):null},bne=(t,e,n,r,a,s,o)=>{if(s!=null){var l=o[0],c=l?.getPosition(s);if(c!=null)return c;var u=a?.[Number(s)];if(u)return n==="horizontal"?{x:u.coordinate,y:(r.top+e)/2}:{x:(r.left+t)/2,y:u.coordinate}}},xne=(t,e,n,r)=>{if(e==="axis")return t.tooltipItemPayloads;if(t.tooltipItemPayloads.length===0)return[];var a;if(n==="hover"?a=t.itemInteraction.hover.graphicalItemId:a=t.itemInteraction.click.graphicalItemId,a==null&&r!=null){var s=t.tooltipItemPayloads[0];return s!=null?[s]:[]}return t.tooltipItemPayloads.filter(o=>{var l;return((l=o.settings)===null||l===void 0?void 0:l.graphicalItemId)===a})},yne=t=>t.options.tooltipPayloadSearcher,sy=t=>t.tooltip;function EG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function jG(t){for(var e=1;e{if(!(e==null||s==null)){var{chartData:l,computedData:c,dataStartIndex:u,dataEndIndex:d}=n,m=[];return t.reduce((p,f)=>{var y,{dataDefinedOnItem:v,settings:b}=f,g=P4e(v,l),_=Array.isArray(g)?nee(g,u,d):g,N=(y=b?.dataKey)!==null&&y!==void 0?y:r,C=b?.nameKey,k;if(r&&Array.isArray(_)&&!Array.isArray(_[0])&&o==="axis"?k=cJ(_,r,a):k=s(_,e,c,C),Array.isArray(k))k.forEach(T=>{var D=jG(jG({},b),{},{name:T.name,unit:T.unit,color:void 0,fill:void 0});p.push(MV({tooltipEntrySettings:D,dataKey:T.dataKey,payload:T.payload,value:Tr(T.payload,T.dataKey),name:T.name}))});else{var P;p.push(MV({tooltipEntrySettings:b,dataKey:N,payload:k,value:Tr(k,N),name:(P=Tr(k,C))!==null&&P!==void 0?P:b?.name}))}return p},m)}},iI=yt([_a,Ute,M4],Zte),M4e=yt([t=>t.graphicalItems.cartesianItems,t=>t.graphicalItems.polarItems],(t,e)=>[...t,...e]),E4e=yt([za,ry],O4),oy=yt([M4e,_a,E4e],I4,{memoizeOptions:{resultEqualityCheck:iA}}),j4e=yt([oy],t=>t.filter(nA)),D4e=yt([oy],z4,{memoizeOptions:{resultEqualityCheck:iA}}),ly=yt([D4e,im],U4),R4e=yt([j4e,im,_a],Lte),aI=yt([ly,_a,oy],H4),wne=yt([_a],$4),F4e=yt([_a],t=>t.allowDataOverflow),Sne=yt([wne,F4e],gte),L4e=yt([oy],t=>t.filter(nA)),O4e=yt([R4e,L4e,Uw,Pte],qte),I4e=yt([O4e,im,za,Sne],Vte),z4e=yt([oy],Hte),U4e=yt([ly,_a,z4e,sA,za],G4,{memoizeOptions:{resultEqualityCheck:rA}}),B4e=yt([Gte,za,ry],ay),H4e=yt([B4e,za],Yte),$4e=yt([Wte,za,ry],ay),q4e=yt([$4e,za],Xte),V4e=yt([Kte,za,ry],ay),G4e=yt([V4e,za],Qte),W4e=yt([H4e,G4e,q4e],$k),K4e=yt([_a,wne,Sne,I4e,U4e,W4e,dr,za],W4),Gw=yt([_a,dr,ly,aI,Uw,za,K4e],K4),Y4e=yt([Gw,_a,iI],Q4),X4e=yt([_a,Gw,Y4e,za],J4),_ne=t=>{var e=za(t),n=ry(t),r=!1;return Vw(t,e,n,r)},Nne=yt([_a,_ne],ZT),kne=yt([_a,iI,X4e,Nne],X4),Q4e=yt([dr,aI,_a,za],ane),Z4e=yt([dr,aI,_a,za],sne),J4e=(t,e,n,r,a,s,o,l)=>{if(e){var{type:c}=e,u=Fc(t,l);if(r){var d=n==="scaleBand"&&r.bandwidth?r.bandwidth()/2:2,m=c==="category"&&r.bandwidth?r.bandwidth()/d:0;return m=l==="angleAxis"&&a!=null&&a?.length>=2?Fa(a[0]-a[1])*2*m:m,u&&o?o.map((p,f)=>{var y=r.map(p);return Ln(y)?{coordinate:y+m,value:p,index:f,offset:m}:null}).filter(yo):r.domain().map((p,f)=>{var y=r.map(p);return Ln(y)?{coordinate:y+m,value:s?s[p]:p,index:f,offset:m}:null}).filter(yo)}}},am=yt([dr,_a,iI,kne,_ne,Q4e,Z4e,za],J4e),sI=yt([lne,cne,l4e],(t,e,n)=>une(n.shared,t,e)),Cne=t=>t.tooltip.settings.trigger,oI=t=>t.tooltip.settings.defaultIndex,Ww=yt([sy,sI,Cne,oI],gne),Vh=yt([Ww,ly,qw,Gw],rI),Tne=yt([am,Vh],dne),lI=yt([Ww],t=>{if(t)return t.dataKey}),eIe=yt([Ww],t=>{if(t)return t.graphicalItemId}),Ane=yt([sy,sI,Cne,oI],xne),tIe=yt([tm,nm,dr,va,am,oI,Ane],bne),nIe=yt([Ww,tIe],(t,e)=>t!=null&&t.coordinate?t.coordinate:e),rIe=yt([Ww],t=>{var e;return(e=t?.active)!==null&&e!==void 0?e:!1}),iIe=yt([Ane,Vh,im,qw,Tne,yne,sI],vne),aIe=yt([iIe],t=>{if(t!=null){var e=t.map(n=>n.payload).filter(n=>n!=null);return Array.from(new Set(e))}});function DG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function RG(t){for(var e=1;een(_a),uIe=()=>{var t=cIe(),e=en(am),n=en(kne);return qh(!t||!n?void 0:RG(RG({},t),{},{scale:n}),e)};function FG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Sb(t){for(var e=1;e{var a=e.find(s=>s&&s.index===n);if(a){if(t==="horizontal")return{x:a.coordinate,y:r.chartY};if(t==="vertical")return{x:r.chartX,y:a.coordinate}}return{x:0,y:0}},fIe=(t,e,n,r)=>{var a=e.find(u=>u&&u.index===n);if(a){if(t==="centric"){var s=a.coordinate,{radius:o}=r;return Sb(Sb(Sb({},r),aa(r.cx,r.cy,o,s)),{},{angle:s,radius:o})}var l=a.coordinate,{angle:c}=r;return Sb(Sb(Sb({},r),aa(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 gIe(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 Pne=(t,e,n,r,a)=>{var s,o=(s=e?.length)!==null&&s!==void 0?s:0;if(o<=1||t==null)return 0;if(r==="angleAxis"&&a!=null&&Math.abs(Math.abs(a[1]-a[0])-360)<=1e-6)for(var l=0;l0?(c=n[l-1])===null||c===void 0?void 0:c.coordinate:(u=n[o-1])===null||u===void 0?void 0:u.coordinate,y=(d=n[l])===null||d===void 0?void 0:d.coordinate,v=l>=o-1?(m=n[0])===null||m===void 0?void 0:m.coordinate:(p=n[l+1])===null||p===void 0?void 0:p.coordinate,b=void 0;if(!(f==null||y==null||v==null))if(Fa(y-f)!==Fa(v-y)){var g=[];if(Fa(v-y)===Fa(a[1]-a[0])){b=v;var _=y+a[1]-a[0];g[0]=Math.min(_,(_+f)/2),g[1]=Math.max(_,(_+f)/2)}else{b=f;var N=v+a[1]-a[0];g[0]=Math.min(y,(N+y)/2),g[1]=Math.max(y,(N+y)/2)}var C=[Math.min(y,(b+y)/2),Math.max(y,(b+y)/2)];if(t>C[0]&&t<=C[1]||t>=g[0]&&t<=g[1]){var k;return(k=n[l])===null||k===void 0?void 0:k.index}}else{var P=Math.min(f,v),T=Math.max(f,v);if(t>(P+y)/2&&t<=(T+y)/2){var D;return(D=n[l])===null||D===void 0?void 0:D.index}}}else if(e)for(var A=0;A(R.coordinate+z.coordinate)/2||A>0&&A(R.coordinate+z.coordinate)/2&&t<=(R.coordinate+G.coordinate)/2)return R.index}}return-1},Mne=()=>en(M4),cI=(t,e)=>e,Ene=(t,e,n)=>n,uI=(t,e,n,r)=>r,bIe=yt(am,t=>AT(t,e=>e.coordinate)),dI=yt([sy,cI,Ene,uI],gne),mI=yt([dI,ly,qw,Gw],rI),xIe=(t,e,n)=>{if(e!=null){var r=sy(t);return e==="axis"?n==="hover"?r.axisInteraction.hover.dataKey:r.axisInteraction.click.dataKey:n==="hover"?r.itemInteraction.hover.dataKey:r.itemInteraction.click.dataKey}},jne=yt([sy,cI,Ene,uI],xne),qk=yt([tm,nm,dr,va,am,uI,jne],bne),yIe=yt([dI,qk],(t,e)=>{var n;return(n=t.coordinate)!==null&&n!==void 0?n:e}),Dne=yt([am,mI],dne),vIe=yt([jne,mI,im,qw,Dne,yne,cI],vne),wIe=yt([dI,mI],(t,e)=>({isActive:t.active&&e!=null,activeIndex:e})),SIe=(t,e,n,r,a,s,o)=>{if(!(!t||!n||!r||!a)&&gIe(t,o)){var l=qje(t,e),c=Pne(l,s,a,n,r),u=pIe(e,a,c,t);return{activeIndex:String(c),activeCoordinate:u}}},_Ie=(t,e,n,r,a,s,o)=>{if(!(!t||!r||!a||!s||!n)){var l=oRe(t,n);if(l){var c=Vje(l,e),u=Pne(c,o,s,r,a),d=fIe(e,s,u,l);return{activeIndex:String(u),activeCoordinate:d}}}},NIe=(t,e,n,r,a,s,o,l)=>{if(!(!t||!e||!r||!a||!s))return e==="horizontal"||e==="vertical"?SIe(t,e,r,a,s,o,l):_Ie(t,e,n,r,a,s,o)},kIe=yt(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.panoramaElement:r.element}}),CIe=yt(t=>t.zIndex.zIndexMap,t=>{var e=Object.keys(t).map(r=>parseInt(r,10)).concat(Object.values(Fi)),n=Array.from(new Set(e));return n.sort((r,a)=>r-a)},{memoizeOptions:{resultEqualityCheck:oOe}});function LG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function OG(t){for(var e=1;eOG(OG({},t),{},{[e]:{element:void 0,panoramaElement:void 0,consumers:0}}),MIe)},jIe=new Set(Object.values(Fi));function DIe(t){return jIe.has(t)}var Rne=Ao({name:"zIndex",initialState:EIe,reducers:{registerZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]?t.zIndexMap[n].consumers+=1:t.zIndexMap[n]={consumers:1,element:void 0,panoramaElement:void 0}},prepare:mi()},unregisterZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(t.zIndexMap[n].consumers-=1,t.zIndexMap[n].consumers<=0&&!DIe(n)&&delete t.zIndexMap[n])},prepare:mi()},registerZIndexPortalElement:{reducer:(t,e)=>{var{zIndex:n,element:r,isPanorama:a}=e.payload;t.zIndexMap[n]?a?t.zIndexMap[n].panoramaElement=r:t.zIndexMap[n].element=r:t.zIndexMap[n]={consumers:0,element:a?void 0:r,panoramaElement:a?r:void 0}},prepare:mi()},unregisterZIndexPortalElement:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(e.payload.isPanorama?t.zIndexMap[n].panoramaElement=void 0:t.zIndexMap[n].element=void 0)},prepare:mi()}}}),{registerZIndexPortal:RIe,unregisterZIndexPortal:FIe,registerZIndexPortalElement:LIe,unregisterZIndexPortalElement:OIe}=Rne.actions,IIe=Rne.reducer;function Ns(t){var{zIndex:e,children:n}=t,r=SDe(),a=r&&e!==void 0&&e!==0,s=wa(),o=Jr();w.useLayoutEffect(()=>a?(o(RIe({zIndex:e})),()=>{o(FIe({zIndex:e}))}):Yh,[o,e,a]);var l=en(c=>kIe(c,e,s));return a?l?wd.createPortal(n,l):null:n}function SF(){return SF=Object.assign?Object.assign.bind():function(t){for(var e=1;ew.useContext(Fne),Fj={exports:{}},zG;function GIe(){return zG||(zG=1,(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function a(c,u,d){this.fn=c,this.context=u,this.once=d||!1}function s(c,u,d,m,p){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new a(d,m||c,p),y=n?n+u:u;return c._events[y]?c._events[y].fn?c._events[y]=[c._events[y],f]:c._events[y].push(f):(c._events[y]=f,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,m;if(this._eventsCount===0)return u;for(m in d=this._events)e.call(d,m)&&u.push(n?m.slice(1):m);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},l.prototype.listeners=function(u){var d=n?n+u:u,m=this._events[d];if(!m)return[];if(m.fn)return[m.fn];for(var p=0,f=m.length,y=new Array(f);p{if(e&&Array.isArray(t)){var n=Number.parseInt(e,10);if(!Mc(n))return t[n]}},YIe={chartName:"",tooltipPayloadSearcher:()=>{},eventEmitter:void 0,defaultTooltipEventType:"axis"},Lne=Ao({name:"options",initialState:YIe,reducers:{createEventEmitter:t=>{t.eventEmitter==null&&(t.eventEmitter=Symbol("rechartsEventEmitter"))}}}),XIe=Lne.reducer,{createEventEmitter:QIe}=Lne.actions;function ZIe(t){return t.tooltip.syncInteraction}var JIe={chartData:void 0,computedData:void 0,dataStartIndex:0,dataEndIndex:0},One=Ao({name:"chartData",initialState:JIe,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:BG,setDataStartEndIndexes:e5e,setComputedData:vit}=One.actions,t5e=One.reducer,n5e=["x","y"];function HG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function _b(t){for(var e=1;ec.rootProps.className);w.useEffect(()=>{if(t==null)return Yh;var c=(u,d,m)=>{if(e!==m&&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 f=d.payload.coordinate,{x:y,y:v}=f,b=s5e(f,n5e),{x:g,y:_,width:N,height:C}=d.payload.sourceViewBox,k=_b(_b({},b),{},{x:o.x+(N?(y-g)/N:0)*o.width,y:o.y+(C?(v-_)/C:0)*o.height});n(_b(_b({},d),{},{payload:_b(_b({},d.payload),{},{coordinate:k})}))}else n(d);return}if(a!=null){var P;if(typeof r=="function"){var T={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},D=r(a,T);P=a[D]}else r==="value"&&(P=a.find(ae=>String(ae.value)===d.payload.label));var{coordinate:A}=d.payload;if(P==null||d.payload.active===!1||A==null||o==null){n(vF({active:!1,coordinate:void 0,dataKey:void 0,index:null,label:void 0,sourceViewBox:void 0,graphicalItemId:void 0}));return}var{x:R,y:G}=A,z=Math.min(R,o.x+o.width),Z=Math.min(G,o.y+o.height),I={x:s==="horizontal"?P.coordinate:z,y:s==="horizontal"?Z:P.coordinate},J=vF({active:d.payload.active,coordinate:I,dataKey:d.payload.dataKey,index:String(P.index),label:d.payload.label,sourceViewBox:d.payload.sourceViewBox,graphicalItemId:d.payload.graphicalItemId});n(J)}}};return X0.on(_F,c),()=>{X0.off(_F,c)}},[l,n,e,t,r,a,s,o])}function c5e(){var t=en(E4),e=en(j4),n=Jr();w.useEffect(()=>{if(t==null)return Yh;var r=(a,s,o)=>{e!==o&&t===a&&n(e5e(s))};return X0.on(UG,r),()=>{X0.off(UG,r)}},[n,e,t])}function u5e(){var t=Jr();w.useEffect(()=>{t(QIe())},[t]),l5e(),c5e()}function d5e(t,e,n,r,a,s){var o=en(f=>xIe(f,t,e)),l=en(j4),c=en(E4),u=en(Mte),d=en(ZIe),m=d?.active,p=jw();w.useEffect(()=>{if(!m&&c!=null&&l!=null){var f=vF({active:s,coordinate:n,dataKey:o,index:a,label:typeof r=="number"?String(r):r,sourceViewBox:p,graphicalItemId:void 0});X0.emit(_F,c,f,l)}},[m,n,o,a,r,l,c,u,s,p])}function $G(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function qG(t){for(var e=1;e{T(h4e({shared:_,trigger:N,axisId:P,active:a,defaultIndex:D}))},[T,_,N,P,a,D]);var A=jw(),R=kee(),G=o4e(_),{activeIndex:z,isActive:Z}=(e=en(X=>wIe(X,G,N,D)))!==null&&e!==void 0?e:{},I=en(X=>vIe(X,G,N,D)),J=en(X=>Dne(X,G,N,D)),ae=en(X=>yIe(X,G,N,D)),Y=I,ue=VIe(),de=(n=a??Z)!==null&&n!==void 0?n:!1,[he,V]=CJ([Y,de]),ne=G==="axis"?J:void 0;d5e(G,N,ae,ne,z,de);var se=k??ue;if(se==null||A==null||G==null)return null;var pe=Y??VG;de||(pe=VG),u&&pe.length&&(pe=vJ(pe.filter(X=>X.value!=null&&(X.hide!==!0||r.includeHidden)),p,f5e));var Te=pe.length>0,q=w.createElement(o3e,{allowEscapeViewBox:s,animationDuration:o,animationEasing:l,isAnimationActive:d,active:de,coordinate:ae,hasPayload:Te,offset:m,position:f,reverseDirection:y,useTranslate3d:v,viewBox:A,wrapperStyle:b,lastBoundingBox:he,innerRef:V,hasPortalFromProps:!!k},g5e(c,qG(qG({},r),{},{payload:pe,label:ne,active:de,activeIndex:z,coordinate:ae,accessibilityLayer:R})));return w.createElement(w.Fragment,null,wd.createPortal(q,se),de&&w.createElement(qIe,{cursor:g,tooltipEventType:G,coordinate:ae,payload:pe,index:z}))}var Mx=t=>null;Mx.displayName="Cell";function x5e(t,e,n){return(e=y5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function y5e(t){var e=v5e(t,"string");return typeof e=="symbol"?e:e+""}function v5e(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 w5e{constructor(e){x5e(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 GG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function S5e(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,T5e,e),n.textContent="".concat(t);var r=n.getBoundingClientRect();return{width:r.width,height:r.height}}catch{return{width:0,height:0}}},Jv=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||Fw.isSsr)return{width:0,height:0};if(!Ine.enableCache)return YG(e,n);var r=A5e(e,n),a=WG.get(r);if(a)return a;var s=YG(e,n);return WG.set(r,s),s},zne;function P5e(t,e,n){return(e=M5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function M5e(t){var e=E5e(t,"string");return typeof e=="symbol"?e:e+""}function E5e(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)}var XG=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,QG=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,j5e=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,D5e=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,R5e={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},F5e=["cm","mm","pt","pc","in","Q","px"];function L5e(t){return F5e.includes(t)}var $b="NaN";function O5e(t,e){return t*R5e[e]}class Ja{static parse(e){var n,[,r,a]=(n=D5e.exec(e))!==null&&n!==void 0?n:[];return r==null?Ja.NaN:new Ja(parseFloat(r),a??"")}constructor(e,n){this.num=e,this.unit=n,this.num=e,this.unit=n,Mc(e)&&(this.unit=""),n!==""&&!j5e.test(n)&&(this.num=NaN,this.unit=""),L5e(n)&&(this.num=O5e(e,n),this.unit="px")}add(e){return this.unit!==e.unit?new Ja(NaN,""):new Ja(this.num+e.num,this.unit)}subtract(e){return this.unit!==e.unit?new Ja(NaN,""):new Ja(this.num-e.num,this.unit)}multiply(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new Ja(NaN,""):new Ja(this.num*e.num,this.unit||e.unit)}divide(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new Ja(NaN,""):new Ja(this.num/e.num,this.unit||e.unit)}toString(){return"".concat(this.num).concat(this.unit)}isNaN(){return Mc(this.num)}}zne=Ja;P5e(Ja,"NaN",new zne(NaN,""));function Une(t){if(t==null||t.includes($b))return $b;for(var e=t;e.includes("*")||e.includes("/");){var n,[,r,a,s]=(n=XG.exec(e))!==null&&n!==void 0?n:[],o=Ja.parse(r??""),l=Ja.parse(s??""),c=a==="*"?o.multiply(l):o.divide(l);if(c.isNaN())return $b;e=e.replace(XG,c.toString())}for(;e.includes("+")||/.-\d+(?:\.\d+)?/.test(e);){var u,[,d,m,p]=(u=QG.exec(e))!==null&&u!==void 0?u:[],f=Ja.parse(d??""),y=Ja.parse(p??""),v=m==="+"?f.add(y):f.subtract(y);if(v.isNaN())return $b;e=e.replace(QG,v.toString())}return e}var ZG=/\(([^()]*)\)/;function I5e(t){for(var e=t,n;(n=ZG.exec(e))!=null;){var[,r]=n;e=e.replace(ZG,Une(r))}return e}function z5e(t){var e=t.replace(/\s+/g,"");return e=I5e(e),e=Une(e),e}function U5e(t){try{return z5e(t)}catch{return $b}}function Lj(t){var e=U5e(t.slice(5,-1));return e===$b?"":e}var B5e=["x","y","lineHeight","capHeight","fill","scaleToFit","textAnchor","verticalAnchor"],H5e=["dx","dy","angle","className","breakAll"];function NF(){return NF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{children:e,breakAll:n,style:r}=t;try{var a=[];gi(e)||(n?a=e.toString().split(""):a=e.toString().split(Bne));var s=a.map(l=>({word:l,width:Jv(l,r).width})),o=n?0:Jv(" ",r).width;return{wordsWithComputedWidth:s,spaceWidth:o}}catch{return null}};function q5e(t){return t==="start"||t==="middle"||t==="end"||t==="inherit"}var $ne=(t,e,n,r)=>t.reduce((a,s)=>{var{word:o,width:l}=s,c=a[a.length-1];if(c&&l!=null&&(e==null||r||c.width+l+nt.reduce((e,n)=>e.width>n.width?e:n),V5e="…",e9=(t,e,n,r,a,s,o,l)=>{var c=t.slice(0,e),u=Hne({breakAll:n,style:r,children:c+V5e});if(!u)return[!1,[]];var d=$ne(u.wordsWithComputedWidth,s,o,l),m=d.length>a||qne(d).width>Number(s);return[m,d]},G5e=(t,e,n,r,a)=>{var{maxLines:s,children:o,style:l,breakAll:c}=t,u=Yt(s),d=String(o),m=$ne(e,r,n,a);if(!u||a)return m;var p=m.length>s||qne(m).width>Number(r);if(!p)return m;for(var f=0,y=d.length-1,v=0,b;f<=y&&v<=d.length-1;){var g=Math.floor((f+y)/2),_=g-1,[N,C]=e9(d,_,c,l,s,r,n,a),[k]=e9(d,g,c,l,s,r,n,a);if(!N&&!k&&(f=g+1),N&&k&&(y=g-1),!N&&k){b=C;break}v++}return b||m},t9=t=>{var e=gi(t)?[]:t.toString().split(Bne);return[{words:e,width:void 0}]},W5e=t=>{var{width:e,scaleToFit:n,children:r,style:a,breakAll:s,maxLines:o}=t;if((e||n)&&!Fw.isSsr){var l,c,u=Hne({breakAll:s,children:r,style:a});if(u){var{wordsWithComputedWidth:d,spaceWidth:m}=u;l=d,c=m}else return t9(r);return G5e({breakAll:s,children:r,maxLines:o,style:a},l,c,e,!!n)}return t9(r)},Vne="#808080",K5e={angle:0,breakAll:!1,capHeight:"0.71em",fill:Vne,lineHeight:"1em",scaleToFit:!1,textAnchor:"start",verticalAnchor:"end",x:0,y:0},uA=w.forwardRef((t,e)=>{var n=wi(t,K5e),{x:r,y:a,lineHeight:s,capHeight:o,fill:l,scaleToFit:c,textAnchor:u,verticalAnchor:d}=n,m=JG(n,B5e),p=w.useMemo(()=>W5e({breakAll:m.breakAll,children:m.children,maxLines:m.maxLines,scaleToFit:c,style:m.style,width:m.width}),[m.breakAll,m.children,m.maxLines,c,m.style,m.width]),{dx:f,dy:y,angle:v,className:b,breakAll:g}=m,_=JG(m,H5e);if(!Kl(r)||!Kl(a)||p.length===0)return null;var N=Number(r)+(Yt(f)?f:0),C=Number(a)+(Yt(y)?y:0);if(!Ln(N)||!Ln(C))return null;var k;switch(d){case"start":k=Lj("calc(".concat(o,")"));break;case"middle":k=Lj("calc(".concat((p.length-1)/2," * -").concat(s," + (").concat(o," / 2))"));break;default:k=Lj("calc(".concat(p.length-1," * -").concat(s,")"));break}var P=[],T=p[0];if(c&&T!=null){var D=T.width,{width:A}=m;P.push("scale(".concat(Yt(A)&&Yt(D)?A/D:1,")"))}return v&&P.push("rotate(".concat(v,", ").concat(N,", ").concat(C,")")),P.length&&(_.transform=P.join(" ")),w.createElement("text",NF({},ls(_),{ref:e,x:N,y:C,className:hr("recharts-text",b),textAnchor:u,fill:l.includes("url")?Vne:l}),p.map((R,G)=>{var z=R.words.join(g?"":" ");return w.createElement("tspan",{x:N,dy:G===0?k:s,key:"".concat(z,"-").concat(G)},z)}))});uA.displayName="Text";function n9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Qc(t){for(var e=1;e{var{viewBox:e,position:n,offset:r=0,parentViewBox:a}=t,{x:s,y:o,height:l,upperWidth:c,lowerWidth:u}=ZO(e),d=s,m=s+(c-u)/2,p=(d+m)/2,f=(c+u)/2,y=d+c/2,v=l>=0?1:-1,b=v*r,g=v>0?"end":"start",_=v>0?"start":"end",N=c>=0?1:-1,C=N*r,k=N>0?"end":"start",P=N>0?"start":"end",T=a;if(n==="top"){var D={x:d+c/2,y:o-b,horizontalAnchor:"middle",verticalAnchor:g};return T&&(D.height=Math.max(o-T.y,0),D.width=c),D}if(n==="bottom"){var A={x:m+u/2,y:o+l+b,horizontalAnchor:"middle",verticalAnchor:_};return T&&(A.height=Math.max(T.y+T.height-(o+l),0),A.width=u),A}if(n==="left"){var R={x:p-C,y:o+l/2,horizontalAnchor:k,verticalAnchor:"middle"};return T&&(R.width=Math.max(R.x-T.x,0),R.height=l),R}if(n==="right"){var G={x:p+f+C,y:o+l/2,horizontalAnchor:P,verticalAnchor:"middle"};return T&&(G.width=Math.max(T.x+T.width-G.x,0),G.height=l),G}var z=T?{width:f,height:l}:{};return n==="insideLeft"?Qc({x:p+C,y:o+l/2,horizontalAnchor:P,verticalAnchor:"middle"},z):n==="insideRight"?Qc({x:p+f-C,y:o+l/2,horizontalAnchor:k,verticalAnchor:"middle"},z):n==="insideTop"?Qc({x:d+c/2,y:o+b,horizontalAnchor:"middle",verticalAnchor:_},z):n==="insideBottom"?Qc({x:m+u/2,y:o+l-b,horizontalAnchor:"middle",verticalAnchor:g},z):n==="insideTopLeft"?Qc({x:d+C,y:o+b,horizontalAnchor:P,verticalAnchor:_},z):n==="insideTopRight"?Qc({x:d+c-C,y:o+b,horizontalAnchor:k,verticalAnchor:_},z):n==="insideBottomLeft"?Qc({x:m+C,y:o+l-b,horizontalAnchor:P,verticalAnchor:g},z):n==="insideBottomRight"?Qc({x:m+u-C,y:o+l-b,horizontalAnchor:k,verticalAnchor:g},z):n&&typeof n=="object"&&(Yt(n.x)||Hf(n.x))&&(Yt(n.y)||Hf(n.y))?Qc({x:s+ws(n.x,f),y:o+ws(n.y,l),horizontalAnchor:"end",verticalAnchor:"end"},z):Qc({x:y,y:o+l/2,horizontalAnchor:"middle",verticalAnchor:"middle"},z)},J5e=["labelRef"],eze=["content"];function r9(t,e){if(t==null)return{};var n,r,a=tze(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var{x:e,y:n,upperWidth:r,lowerWidth:a,width:s,height:o,children:l}=t,c=w.useMemo(()=>({x:e,y:n,upperWidth:r,lowerWidth:a,width:s,height:o}),[e,n,r,a,s,o]);return w.createElement(Gne.Provider,{value:c},l)},Kne=()=>{var t=w.useContext(Gne),e=jw();return t||(e?ZO(e):void 0)},aze=w.createContext(null),sze=()=>{var t=w.useContext(aze),e=en(Fte);return t||e},oze=t=>{var{value:e,formatter:n}=t,r=gi(t.children)?e:t.children;return typeof n=="function"?n(r):r},hI=t=>t!=null&&typeof t=="function",lze=(t,e)=>{var n=Fa(e-t),r=Math.min(Math.abs(e-t),360);return n*r},cze=(t,e,n,r,a)=>{var{offset:s,className:o}=t,{cx:l,cy:c,innerRadius:u,outerRadius:d,startAngle:m,endAngle:p,clockWise:f}=a,y=(u+d)/2,v=lze(m,p),b=v>=0?1:-1,g,_;switch(e){case"insideStart":g=m+b*s,_=f;break;case"insideEnd":g=p-b*s,_=!f;break;case"end":g=p+b*s,_=f;break;default:throw new Error("Unsupported position ".concat(e))}_=v<=0?_:!_;var N=aa(l,c,y,g),C=aa(l,c,y,g+(_?1:-1)*359),k="M".concat(N.x,",").concat(N.y,` + A`,",",",0,0,",",",",","Z"])),T.x,T.y,s,s,+(d<0),P.x,P.y,r,r,+(A>180),+(d>0),N.x,N.y,s,s,+(d<0),C.x,C.y)}else _+=Mi(M7||(M7=Jp(["L",",","Z"])),e,n);return _},uRe={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},Ree=t=>{var e=wi(t,uRe),{cx:n,cy:r,innerRadius:a,outerRadius:s,cornerRadius:o,forceCornerRadius:l,cornerIsExternal:c,startAngle:u,endAngle:d,className:m}=e;if(s0&&Math.abs(u-d)<360?v=cRe({cx:n,cy:r,innerRadius:a,outerRadius:s,cornerRadius:Math.min(y,f/2),forceCornerRadius:l,cornerIsExternal:c,startAngle:u,endAngle:d}):v=Dee({cx:n,cy:r,innerRadius:a,outerRadius:s,startAngle:u,endAngle:d}),w.createElement("path",dF({},ls(e),{className:p,d:v}))};function dRe(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(dJ(e)){if(t==="centric"){var{cx:r,cy:a,innerRadius:s,outerRadius:o,angle:l}=e,c=aa(r,a,s,l),u=aa(r,a,o,l);return[{x:c.x,y:c.y},{x:u.x,y:u.y}]}return jee(e)}}var _2={},N2={},k2={},E7;function mRe(){return E7||(E7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=_J();function n(r){return e.isSymbol(r)?NaN:Number(r)}t.toNumber=n})(k2)),k2}var j7;function hRe(){return j7||(j7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=mRe();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})(N2)),N2}var D7;function pRe(){return D7||(D7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=NJ(),n=hRe();function r(a,s,o){o&&typeof o!="number"&&e.isIterateeCall(a,s,o)&&(s=o=void 0),a=n.toFinite(a),s===void 0?(s=a,a=0):s=n.toFinite(s),o=o===void 0?ae?1:t>=e?0:NaN}function bRe(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}function iI(t){let e,n,r;t.length!==2?(e=Rh,n=(l,c)=>Rh(t(l),c),r=(l,c)=>t(l)-c):(e=t===Rh||t===bRe?t:xRe,n=t,r=t);function a(l,c,u=0,d=l.length){if(u>>1;n(l[m],c)<0?u=m+1:d=m}while(u>>1;n(l[m],c)<=0?u=m+1:d=m}while(uu&&r(l[m-1],c)>-r(l[m],c)?m-1:m}return{left:a,center:o,right:s}}function xRe(){return 0}function Lee(t){return t===null?NaN:+t}function*yRe(t,e){for(let n of t)n!=null&&(n=+n)>=n&&(yield n)}const vRe=iI(Rh),Lw=vRe.right;iI(Lee).center;class F7 extends Map{constructor(e,n=_Re){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),e!=null)for(const[r,a]of e)this.set(r,a)}get(e){return super.get(L7(this,e))}has(e){return super.has(L7(this,e))}set(e,n){return super.set(wRe(this,e),n)}delete(e){return super.delete(SRe(this,e))}}function L7({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):n}function wRe({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}function SRe({_intern:t,_key:e},n){const r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}function _Re(t){return t!==null&&typeof t=="object"?t.valueOf():t}function NRe(t=Rh){if(t===Rh)return Oee;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 Oee(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(te?1:0)}const kRe=Math.sqrt(50),CRe=Math.sqrt(10),TRe=Math.sqrt(2);function Pk(t,e,n){const r=(e-t)/Math.max(0,n),a=Math.floor(Math.log10(r)),s=r/Math.pow(10,a),o=s>=kRe?10:s>=CRe?5:s>=TRe?2:1;let l,c,u;return a<0?(u=Math.pow(10,-a)/o,l=Math.round(t*u),c=Math.round(e*u),l/ue&&--c,u=-u):(u=Math.pow(10,a)*o,l=Math.round(t/u),c=Math.round(e/u),l*ue&&--c),c0))return[];if(t===e)return[t];const r=e=a))return[];const l=s-a+1,c=new Array(l);if(r)if(o<0)for(let u=0;u=r)&&(n=r);return n}function I7(t,e){let n;for(const r of t)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function Iee(t,e,n=0,r=1/0,a){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(a=a===void 0?Oee:NRe(a);r>n;){if(r-n>600){const c=r-n+1,u=e-n+1,d=Math.log(c),m=.5*Math.exp(2*d/3),p=.5*Math.sqrt(d*m*(c-m)/c)*(u-c/2<0?-1:1),f=Math.max(n,Math.floor(e-u*m/c+p)),y=Math.min(r,Math.floor(e+(c-u)*m/c+p));Iee(t,e,f,y,a)}const s=t[e];let o=n,l=r;for(xv(t,n,e),a(t[r],s)>0&&xv(t,n,r);o0;)--l}a(t[n],s)===0?xv(t,n,l):(++l,xv(t,l,r)),l<=e&&(n=l+1),e<=l&&(r=l-1)}return t}function xv(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}function ARe(t,e,n){if(t=Float64Array.from(yRe(t)),!(!(r=t.length)||isNaN(e=+e))){if(e<=0||r<2)return I7(t);if(e>=1)return O7(t);var r,a=(r-1)*e,s=Math.floor(a),o=O7(Iee(t,s).subarray(0,s+1)),l=I7(t.subarray(s+1));return o+(l-o)*(a-s)}}function PRe(t,e,n=Lee){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,a=(r-1)*e,s=Math.floor(a),o=+n(t[s],s,t),l=+n(t[s+1],s+1,t);return o+(l-o)*(a-s)}}function MRe(t,e,n){t=+t,e=+e,n=(a=arguments.length)<2?(e=t,t=0,1):a<3?1:+n;for(var r=-1,a=Math.max(0,Math.ceil((e-t)/n))|0,s=new Array(a);++r>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):n===8?N1(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):n===4?N1(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=DRe.exec(t))?new vo(e[1],e[2],e[3],1):(e=RRe.exec(t))?new vo(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=FRe.exec(t))?N1(e[1],e[2],e[3],e[4]):(e=LRe.exec(t))?N1(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=ORe.exec(t))?V7(e[1],e[2]/100,e[3]/100,1):(e=IRe.exec(t))?V7(e[1],e[2]/100,e[3]/100,e[4]):z7.hasOwnProperty(t)?H7(z7[t]):t==="transparent"?new vo(NaN,NaN,NaN,0):null}function H7(t){return new vo(t>>16&255,t>>8&255,t&255,1)}function N1(t,e,n,r){return r<=0&&(t=e=n=NaN),new vo(t,e,n,r)}function BRe(t){return t instanceof Ow||(t=W0(t)),t?(t=t.rgb(),new vo(t.r,t.g,t.b,t.opacity)):new vo}function gF(t,e,n,r){return arguments.length===1?BRe(t):new vo(t,e,n,r??1)}function vo(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}oI(vo,gF,Uee(Ow,{brighter(t){return t=t==null?Mk:Math.pow(Mk,t),new vo(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?V0:Math.pow(V0,t),new vo(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new vo(bf(this.r),bf(this.g),bf(this.b),Ek(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:$7,formatHex:$7,formatHex8:HRe,formatRgb:q7,toString:q7}));function $7(){return`#${ef(this.r)}${ef(this.g)}${ef(this.b)}`}function HRe(){return`#${ef(this.r)}${ef(this.g)}${ef(this.b)}${ef((isNaN(this.opacity)?1:this.opacity)*255)}`}function q7(){const t=Ek(this.opacity);return`${t===1?"rgb(":"rgba("}${bf(this.r)}, ${bf(this.g)}, ${bf(this.b)}${t===1?")":`, ${t})`}`}function Ek(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function bf(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function ef(t){return t=bf(t),(t<16?"0":"")+t.toString(16)}function V7(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new xc(t,e,n,r)}function Bee(t){if(t instanceof xc)return new xc(t.h,t.s,t.l,t.opacity);if(t instanceof Ow||(t=W0(t)),!t)return new xc;if(t instanceof xc)return t;t=t.rgb();var e=t.r/255,n=t.g/255,r=t.b/255,a=Math.min(e,n,r),s=Math.max(e,n,r),o=NaN,l=s-a,c=(s+a)/2;return l?(e===s?o=(n-r)/l+(n0&&c<1?0:o,new xc(o,l,c,t.opacity)}function $Re(t,e,n,r){return arguments.length===1?Bee(t):new xc(t,e,n,r??1)}function xc(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}oI(xc,$Re,Uee(Ow,{brighter(t){return t=t==null?Mk:Math.pow(Mk,t),new xc(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?V0:Math.pow(V0,t),new xc(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,a=2*n-r;return new vo(T2(t>=240?t-240:t+120,a,r),T2(t,a,r),T2(t<120?t+240:t-120,a,r),this.opacity)},clamp(){return new xc(G7(this.h),k1(this.s),k1(this.l),Ek(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=Ek(this.opacity);return`${t===1?"hsl(":"hsla("}${G7(this.h)}, ${k1(this.s)*100}%, ${k1(this.l)*100}%${t===1?")":`, ${t})`}`}}));function G7(t){return t=(t||0)%360,t<0?t+360:t}function k1(t){return Math.max(0,Math.min(1,t||0))}function T2(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 lI=t=>()=>t;function qRe(t,e){return function(n){return t+n*e}}function VRe(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 GRe(t){return(t=+t)==1?Hee:function(e,n){return n-e?VRe(e,n,t):lI(isNaN(e)?n:e)}}function Hee(t,e){var n=e-t;return n?qRe(t,n):lI(isNaN(t)?e:t)}const W7=(function t(e){var n=GRe(e);function r(a,s){var o=n((a=gF(a)).r,(s=gF(s)).r),l=n(a.g,s.g),c=n(a.b,s.b),u=Hee(a.opacity,s.opacity);return function(d){return a.r=o(d),a.g=l(d),a.b=c(d),a.opacity=u(d),a+""}}return r.gamma=t,r})(1);function WRe(t,e){e||(e=[]);var n=t?Math.min(e.length,t.length):0,r=e.slice(),a;return function(s){for(a=0;an&&(s=e.slice(n,s),l[o]?l[o]+=s:l[++o]=s),(r=r[0])===(a=a[0])?l[o]?l[o]+=a:l[++o]=a:(l[++o]=null,c.push({i:o,x:jk(r,a)})),n=A2.lastIndex;return ne&&(n=t,t=e,e=n),function(r){return Math.max(t,Math.min(e,r))}}function iFe(t,e,n){var r=t[0],a=t[1],s=e[0],o=e[1];return a2?aFe:iFe,c=u=null,m}function m(p){return p==null||isNaN(p=+p)?s:(c||(c=l(t.map(r),e,n)))(r(o(p)))}return m.invert=function(p){return o(a((u||(u=l(e,t.map(r),jk)))(p)))},m.domain=function(p){return arguments.length?(t=Array.from(p,Dk),d()):t.slice()},m.range=function(p){return arguments.length?(e=Array.from(p),d()):e.slice()},m.rangeRound=function(p){return e=Array.from(p),n=cI,d()},m.clamp=function(p){return arguments.length?(o=p?!0:$s,d()):o!==$s},m.interpolate=function(p){return arguments.length?(n=p,d()):n},m.unknown=function(p){return arguments.length?(s=p,m):s},function(p,f){return r=p,a=f,d()}}function uI(){return VT()($s,$s)}function sFe(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function Rk(t,e){if(!isFinite(t)||t===0)return null;var n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"),r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}function Cx(t){return t=Rk(Math.abs(t)),t?t[1]:NaN}function oFe(t,e){return function(n,r){for(var a=n.length,s=[],o=0,l=t[0],c=0;a>0&&l>0&&(c+l+1>r&&(l=Math.max(1,r-c)),s.push(n.substring(a-=l,a+l)),!((c+=l+1)>r));)l=t[o=(o+1)%t.length];return s.reverse().join(e)}}function lFe(t){return function(e){return e.replace(/[0-9]/g,function(n){return t[+n]})}}var cFe=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function K0(t){if(!(e=cFe.exec(t)))throw new Error("invalid format: "+t);var e;return new dI({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]})}K0.prototype=dI.prototype;function dI(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+""}dI.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 uFe(t){e:for(var e=t.length,n=1,r=-1,a;n0&&(r=0);break}return r>0?t.slice(0,r)+t.slice(a+1):t}var Fk;function dFe(t,e){var n=Rk(t,e);if(!n)return Fk=void 0,t.toPrecision(e);var r=n[0],a=n[1],s=a-(Fk=Math.max(-8,Math.min(8,Math.floor(a/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")+Rk(t,Math.max(0,e+s-1))[0]}function Y7(t,e){var n=Rk(t,e);if(!n)return t+"";var r=n[0],a=n[1];return a<0?"0."+new Array(-a).join("0")+r:r.length>a+1?r.slice(0,a+1)+"."+r.slice(a+1):r+new Array(a-r.length+2).join("0")}const X7={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:sFe,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)=>Y7(t*100,e),r:Y7,s:dFe,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function Q7(t){return t}var Z7=Array.prototype.map,J7=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function mFe(t){var e=t.grouping===void 0||t.thousands===void 0?Q7:oFe(Z7.call(t.grouping,Number),t.thousands+""),n=t.currency===void 0?"":t.currency[0]+"",r=t.currency===void 0?"":t.currency[1]+"",a=t.decimal===void 0?".":t.decimal+"",s=t.numerals===void 0?Q7:lFe(Z7.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(m,p){m=K0(m);var f=m.fill,y=m.align,v=m.sign,b=m.symbol,g=m.zero,_=m.width,N=m.comma,C=m.precision,k=m.trim,P=m.type;P==="n"?(N=!0,P="g"):X7[P]||(C===void 0&&(C=12),k=!0,P="g"),(g||f==="0"&&y==="=")&&(g=!0,f="0",y="=");var T=(p&&p.prefix!==void 0?p.prefix:"")+(b==="$"?n:b==="#"&&/[boxX]/.test(P)?"0"+P.toLowerCase():""),D=(b==="$"?r:/[%p]/.test(P)?o:"")+(p&&p.suffix!==void 0?p.suffix:""),A=X7[P],R=/[defgprs%]/.test(P);C=C===void 0?6:/[gprs]/.test(P)?Math.max(1,Math.min(21,C)):Math.max(0,Math.min(20,C));function G(z){var Z=T,I=D,J,ae,Y;if(P==="c")I=A(z)+I,z="";else{z=+z;var ue=z<0||1/z<0;if(z=isNaN(z)?c:A(Math.abs(z),C),k&&(z=uFe(z)),ue&&+z==0&&v!=="+"&&(ue=!1),Z=(ue?v==="("?v:l:v==="-"||v==="("?"":v)+Z,I=(P==="s"&&!isNaN(z)&&Fk!==void 0?J7[8+Fk/3]:"")+I+(ue&&v==="("?")":""),R){for(J=-1,ae=z.length;++JY||Y>57){I=(Y===46?a+z.slice(J+1):z.slice(J))+I,z=z.slice(0,J);break}}}N&&!g&&(z=e(z,1/0));var de=Z.length+z.length+I.length,he=de<_?new Array(_-de+1).join(f):"";switch(N&&g&&(z=e(he+z,he.length?_-I.length:1/0),he=""),y){case"<":z=Z+z+I+he;break;case"=":z=Z+he+z+I;break;case"^":z=he.slice(0,de=he.length>>1)+Z+z+I+he.slice(de);break;default:z=he+Z+z+I;break}return s(z)}return G.toString=function(){return m+""},G}function d(m,p){var f=Math.max(-8,Math.min(8,Math.floor(Cx(p)/3)))*3,y=Math.pow(10,-f),v=u((m=K0(m),m.type="f",m),{suffix:J7[8+f/3]});return function(b){return v(y*b)}}return{format:u,formatPrefix:d}}var C1,mI,$ee;hFe({thousands:",",grouping:[3],currency:["$",""]});function hFe(t){return C1=mFe(t),mI=C1.format,$ee=C1.formatPrefix,C1}function pFe(t){return Math.max(0,-Cx(Math.abs(t)))}function fFe(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Cx(e)/3)))*3-Cx(Math.abs(t)))}function gFe(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,Cx(e)-Cx(t))+1}function qee(t,e,n,r){var a=pF(t,e,n),s;switch(r=K0(r??",f"),r.type){case"s":{var o=Math.max(Math.abs(t),Math.abs(e));return r.precision==null&&!isNaN(s=fFe(a,o))&&(r.precision=s),$ee(r,o)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(s=gFe(a,Math.max(Math.abs(t),Math.abs(e))))&&(r.precision=s-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(s=pFe(a))&&(r.precision=s-(r.type==="%")*2);break}}return mI(r)}function Zh(t){var e=t.domain;return t.ticks=function(n){var r=e();return mF(r[0],r[r.length-1],n??10)},t.tickFormat=function(n,r){var a=e();return qee(a[0],a[a.length-1],n??10,r)},t.nice=function(n){n==null&&(n=10);var r=e(),a=0,s=r.length-1,o=r[a],l=r[s],c,u,d=10;for(l0;){if(u=hF(o,l,n),u===c)return r[a]=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 Vee(){var t=uI();return t.copy=function(){return Iw(t,Vee())},ec.apply(t,arguments),Zh(t)}function Gee(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,Dk),n):t.slice()},n.unknown=function(r){return arguments.length?(e=r,n):e},n.copy=function(){return Gee(t).unknown(e)},t=arguments.length?Array.from(t,Dk):[0,1],Zh(n)}function Wee(t,e){t=t.slice();var n=0,r=t.length-1,a=t[n],s=t[r],o;return sMath.pow(t,e)}function wFe(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 nG(t){return(e,n)=>-t(-e,n)}function hI(t){const e=t(eG,tG),n=e.domain;let r=10,a,s;function o(){return a=wFe(r),s=vFe(r),n()[0]<0?(a=nG(a),s=nG(s),t(bFe,xFe)):t(eG,tG),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 m=d0){for(;p<=f;++p)for(y=1;yd)break;g.push(v)}}else for(;p<=f;++p)for(y=r-1;y>=1;--y)if(v=p>0?y/s(-p):y*s(p),!(vd)break;g.push(v)}g.length*2{if(l==null&&(l=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=K0(c)).precision==null&&(c.trim=!0),c=mI(c)),l===1/0)return c;const u=Math.max(1,r*l/e.ticks().length);return d=>{let m=d/s(Math.round(a(d)));return m*rn(Wee(n(),{floor:l=>s(Math.floor(a(l))),ceil:l=>s(Math.ceil(a(l)))})),e}function Kee(){const t=hI(VT()).domain([1,10]);return t.copy=()=>Iw(t,Kee()).base(t.base()),ec.apply(t,arguments),t}function rG(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function iG(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function pI(t){var e=1,n=t(rG(e),iG(e));return n.constant=function(r){return arguments.length?t(rG(e=+r),iG(e)):e},Zh(n)}function Yee(){var t=pI(VT());return t.copy=function(){return Iw(t,Yee()).constant(t.constant())},ec.apply(t,arguments)}function aG(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function SFe(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function _Fe(t){return t<0?-t*t:t*t}function fI(t){var e=t($s,$s),n=1;function r(){return n===1?t($s,$s):n===.5?t(SFe,_Fe):t(aG(n),aG(1/n))}return e.exponent=function(a){return arguments.length?(n=+a,r()):n},Zh(e)}function gI(){var t=fI(VT());return t.copy=function(){return Iw(t,gI()).exponent(t.exponent())},ec.apply(t,arguments),t}function NFe(){return gI.apply(null,arguments).exponent(.5)}function sG(t){return Math.sign(t)*t*t}function kFe(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function Xee(){var t=uI(),e=[0,1],n=!1,r;function a(s){var o=kFe(t(s));return isNaN(o)?r:n?Math.round(o):o}return a.invert=function(s){return t.invert(sG(s))},a.domain=function(s){return arguments.length?(t.domain(s),a):t.domain()},a.range=function(s){return arguments.length?(t.range((e=Array.from(s,Dk)).map(sG)),a):e.slice()},a.rangeRound=function(s){return a.range(s).round(!0)},a.round=function(s){return arguments.length?(n=!!s,a):n},a.clamp=function(s){return arguments.length?(t.clamp(s),a):t.clamp()},a.unknown=function(s){return arguments.length?(r=s,a):r},a.copy=function(){return Xee(t.domain(),e).round(n).clamp(t.clamp()).unknown(r)},ec.apply(a,arguments),Zh(a)}function Qee(){var t=[],e=[],n=[],r;function a(){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 Zee().domain([t,e]).range(a).unknown(s)},ec.apply(Zh(o),arguments)}function Jee(){var t=[.5],e=[0,1],n,r=1;function a(s){return s!=null&&s<=s?e[Lw(t,s,0,r)]:n}return a.domain=function(s){return arguments.length?(t=Array.from(s),r=Math.min(t.length,e.length-1),a):t.slice()},a.range=function(s){return arguments.length?(e=Array.from(s),r=Math.min(t.length,e.length-1),a):e.slice()},a.invertExtent=function(s){var o=e.indexOf(s);return[t[o-1],t[o]]},a.unknown=function(s){return arguments.length?(n=s,a):n},a.copy=function(){return Jee().domain(t).range(e).unknown(n)},ec.apply(a,arguments)}const P2=new Date,M2=new Date;function Sa(t,e,n,r){function a(s){return t(s=arguments.length===0?new Date:new Date(+s)),s}return a.floor=s=>(t(s=new Date(+s)),s),a.ceil=s=>(t(s=new Date(s-1)),e(s,1),t(s),s),a.round=s=>{const o=a(s),l=a.ceil(s);return s-o(e(s=new Date(+s),o==null?1:Math.floor(o)),s),a.range=(s,o,l)=>{const c=[];if(s=a.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&&(a.count=(s,o)=>(P2.setTime(+s),M2.setTime(+o),t(P2),t(M2),Math.floor(n(P2,M2))),a.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?a.filter(r?o=>r(o)%s===0:o=>a.count(0,o)%s===0):a)),a}const Lk=Sa(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);Lk.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):Lk);Lk.range;const Td=1e3,zl=Td*60,Ad=zl*60,Kd=Ad*24,bI=Kd*7,oG=Kd*30,E2=Kd*365,tf=Sa(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*Td)},(t,e)=>(e-t)/Td,t=>t.getUTCSeconds());tf.range;const xI=Sa(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Td)},(t,e)=>{t.setTime(+t+e*zl)},(t,e)=>(e-t)/zl,t=>t.getMinutes());xI.range;const yI=Sa(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*zl)},(t,e)=>(e-t)/zl,t=>t.getUTCMinutes());yI.range;const vI=Sa(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Td-t.getMinutes()*zl)},(t,e)=>{t.setTime(+t+e*Ad)},(t,e)=>(e-t)/Ad,t=>t.getHours());vI.range;const wI=Sa(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*Ad)},(t,e)=>(e-t)/Ad,t=>t.getUTCHours());wI.range;const zw=Sa(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*zl)/Kd,t=>t.getDate()-1);zw.range;const GT=Sa(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Kd,t=>t.getUTCDate()-1);GT.range;const ete=Sa(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Kd,t=>Math.floor(t/Kd));ete.range;function ag(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())*zl)/bI)}const WT=ag(0),Ok=ag(1),CFe=ag(2),TFe=ag(3),Tx=ag(4),AFe=ag(5),PFe=ag(6);WT.range;Ok.range;CFe.range;TFe.range;Tx.range;AFe.range;PFe.range;function sg(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)/bI)}const KT=sg(0),Ik=sg(1),MFe=sg(2),EFe=sg(3),Ax=sg(4),jFe=sg(5),DFe=sg(6);KT.range;Ik.range;MFe.range;EFe.range;Ax.range;jFe.range;DFe.range;const SI=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());SI.range;const _I=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());_I.range;const Yd=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());Yd.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)});Yd.range;const Xd=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());Xd.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)});Xd.range;function tte(t,e,n,r,a,s){const o=[[tf,1,Td],[tf,5,5*Td],[tf,15,15*Td],[tf,30,30*Td],[s,1,zl],[s,5,5*zl],[s,15,15*zl],[s,30,30*zl],[a,1,Ad],[a,3,3*Ad],[a,6,6*Ad],[a,12,12*Ad],[r,1,Kd],[r,2,2*Kd],[n,1,bI],[e,1,oG],[e,3,3*oG],[t,1,E2]];function l(u,d,m){const p=db).right(o,p);if(f===o.length)return t.every(pF(u/E2,d/E2,m));if(f===0)return Lk.every(Math.max(pF(u,d,m),1));const[y,v]=o[p/o[f-1][2]53)return null;"w"in H||(H.w=1),"Z"in H?(O=D2(yv(H.y,0,1)),$=O.getUTCDay(),O=$>4||$===0?Ik.ceil(O):Ik(O),O=GT.offset(O,(H.V-1)*7),H.y=O.getUTCFullYear(),H.m=O.getUTCMonth(),H.d=O.getUTCDate()+(H.w+6)%7):(O=j2(yv(H.y,0,1)),$=O.getDay(),O=$>4||$===0?Ok.ceil(O):Ok(O),O=zw.offset(O,(H.V-1)*7),H.y=O.getFullYear(),H.m=O.getMonth(),H.d=O.getDate()+(H.w+6)%7)}else("W"in H||"U"in H)&&("w"in H||(H.w="u"in H?H.u%7:"W"in H?1:0),$="Z"in H?D2(yv(H.y,0,1)).getUTCDay():j2(yv(H.y,0,1)).getDay(),H.m=0,H.d="W"in H?(H.w+6)%7+H.W*7-($+5)%7:H.w+H.U*7-($+6)%7);return"Z"in H?(H.H+=H.Z/100|0,H.M+=H.Z%100,D2(H)):j2(H)}}function D(E,U,K,H){for(var re=0,O=U.length,$=K.length,ee,W;re=$)return-1;if(ee=U.charCodeAt(re++),ee===37){if(ee=U.charAt(re++),W=k[ee in lG?U.charAt(re++):ee],!W||(H=W(E,K,H))<0)return-1}else if(ee!=K.charCodeAt(H++))return-1}return H}function A(E,U,K){var H=u.exec(U.slice(K));return H?(E.p=d.get(H[0].toLowerCase()),K+H[0].length):-1}function R(E,U,K){var H=f.exec(U.slice(K));return H?(E.w=y.get(H[0].toLowerCase()),K+H[0].length):-1}function G(E,U,K){var H=m.exec(U.slice(K));return H?(E.w=p.get(H[0].toLowerCase()),K+H[0].length):-1}function z(E,U,K){var H=g.exec(U.slice(K));return H?(E.m=_.get(H[0].toLowerCase()),K+H[0].length):-1}function Z(E,U,K){var H=v.exec(U.slice(K));return H?(E.m=b.get(H[0].toLowerCase()),K+H[0].length):-1}function I(E,U,K){return D(E,e,U,K)}function J(E,U,K){return D(E,n,U,K)}function ae(E,U,K){return D(E,r,U,K)}function Y(E){return o[E.getDay()]}function ue(E){return s[E.getDay()]}function de(E){return c[E.getMonth()]}function he(E){return l[E.getMonth()]}function V(E){return a[+(E.getHours()>=12)]}function ne(E){return 1+~~(E.getMonth()/3)}function se(E){return o[E.getUTCDay()]}function pe(E){return s[E.getUTCDay()]}function Te(E){return c[E.getUTCMonth()]}function q(E){return l[E.getUTCMonth()]}function X(E){return a[+(E.getUTCHours()>=12)]}function j(E){return 1+~~(E.getUTCMonth()/3)}return{format:function(E){var U=P(E+="",N);return U.toString=function(){return E},U},parse:function(E){var U=T(E+="",!1);return U.toString=function(){return E},U},utcFormat:function(E){var U=P(E+="",C);return U.toString=function(){return E},U},utcParse:function(E){var U=T(E+="",!0);return U.toString=function(){return E},U}}}var lG={"-":"",_:" ",0:"0"},Ia=/^\s*\d+/,zFe=/^%/,UFe=/[\\^$*+?|[\]().{}]/g;function vr(t,e,n){var r=t<0?"-":"",a=(r?-t:t)+"",s=a.length;return r+(s[e.toLowerCase(),n]))}function HFe(t,e,n){var r=Ia.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function $Fe(t,e,n){var r=Ia.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function qFe(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function VFe(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function GFe(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function cG(t,e,n){var r=Ia.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function uG(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function WFe(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 KFe(t,e,n){var r=Ia.exec(e.slice(n,n+1));return r?(t.q=r[0]*3-3,n+r[0].length):-1}function YFe(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function dG(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function XFe(t,e,n){var r=Ia.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function mG(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function QFe(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function ZFe(t,e,n){var r=Ia.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function JFe(t,e,n){var r=Ia.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function eLe(t,e,n){var r=Ia.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function tLe(t,e,n){var r=zFe.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function nLe(t,e,n){var r=Ia.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function rLe(t,e,n){var r=Ia.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function hG(t,e){return vr(t.getDate(),e,2)}function iLe(t,e){return vr(t.getHours(),e,2)}function aLe(t,e){return vr(t.getHours()%12||12,e,2)}function sLe(t,e){return vr(1+zw.count(Yd(t),t),e,3)}function nte(t,e){return vr(t.getMilliseconds(),e,3)}function oLe(t,e){return nte(t,e)+"000"}function lLe(t,e){return vr(t.getMonth()+1,e,2)}function cLe(t,e){return vr(t.getMinutes(),e,2)}function uLe(t,e){return vr(t.getSeconds(),e,2)}function dLe(t){var e=t.getDay();return e===0?7:e}function mLe(t,e){return vr(WT.count(Yd(t)-1,t),e,2)}function rte(t){var e=t.getDay();return e>=4||e===0?Tx(t):Tx.ceil(t)}function hLe(t,e){return t=rte(t),vr(Tx.count(Yd(t),t)+(Yd(t).getDay()===4),e,2)}function pLe(t){return t.getDay()}function fLe(t,e){return vr(Ok.count(Yd(t)-1,t),e,2)}function gLe(t,e){return vr(t.getFullYear()%100,e,2)}function bLe(t,e){return t=rte(t),vr(t.getFullYear()%100,e,2)}function xLe(t,e){return vr(t.getFullYear()%1e4,e,4)}function yLe(t,e){var n=t.getDay();return t=n>=4||n===0?Tx(t):Tx.ceil(t),vr(t.getFullYear()%1e4,e,4)}function vLe(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+vr(e/60|0,"0",2)+vr(e%60,"0",2)}function pG(t,e){return vr(t.getUTCDate(),e,2)}function wLe(t,e){return vr(t.getUTCHours(),e,2)}function SLe(t,e){return vr(t.getUTCHours()%12||12,e,2)}function _Le(t,e){return vr(1+GT.count(Xd(t),t),e,3)}function ite(t,e){return vr(t.getUTCMilliseconds(),e,3)}function NLe(t,e){return ite(t,e)+"000"}function kLe(t,e){return vr(t.getUTCMonth()+1,e,2)}function CLe(t,e){return vr(t.getUTCMinutes(),e,2)}function TLe(t,e){return vr(t.getUTCSeconds(),e,2)}function ALe(t){var e=t.getUTCDay();return e===0?7:e}function PLe(t,e){return vr(KT.count(Xd(t)-1,t),e,2)}function ate(t){var e=t.getUTCDay();return e>=4||e===0?Ax(t):Ax.ceil(t)}function MLe(t,e){return t=ate(t),vr(Ax.count(Xd(t),t)+(Xd(t).getUTCDay()===4),e,2)}function ELe(t){return t.getUTCDay()}function jLe(t,e){return vr(Ik.count(Xd(t)-1,t),e,2)}function DLe(t,e){return vr(t.getUTCFullYear()%100,e,2)}function RLe(t,e){return t=ate(t),vr(t.getUTCFullYear()%100,e,2)}function FLe(t,e){return vr(t.getUTCFullYear()%1e4,e,4)}function LLe(t,e){var n=t.getUTCDay();return t=n>=4||n===0?Ax(t):Ax.ceil(t),vr(t.getUTCFullYear()%1e4,e,4)}function OLe(){return"+0000"}function fG(){return"%"}function gG(t){return+t}function bG(t){return Math.floor(+t/1e3)}var wb,ste,ote;ILe({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 ILe(t){return wb=IFe(t),ste=wb.format,wb.parse,ote=wb.utcFormat,wb.utcParse,wb}function zLe(t){return new Date(t)}function ULe(t){return t instanceof Date?+t:+new Date(+t)}function NI(t,e,n,r,a,s,o,l,c,u){var d=uI(),m=d.invert,p=d.domain,f=u(".%L"),y=u(":%S"),v=u("%I:%M"),b=u("%I %p"),g=u("%a %d"),_=u("%b %d"),N=u("%B"),C=u("%Y");function k(P){return(c(P)e(a/(t.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,s)=>ARe(t,s/r))},n.copy=function(){return dte(e).domain(t)},rm.apply(n,arguments)}function XT(){var t=0,e=.5,n=1,r=1,a,s,o,l,c,u=$s,d,m=!1,p;function f(v){return isNaN(v=+v)?p:(v=.5+((v=+d(v))-s)*(r*vt.chartData,QT=yt([im],t=>{var e=t.chartData!=null?t.chartData.length-1:0;return{chartData:t.chartData,computedData:t.computedData,dataEndIndex:e,dataStartIndex:0}}),TI=(t,e,n,r)=>r?QT(t):im(t),fte=(t,e,n)=>n?QT(t):im(t);function Qd(t){if(Array.isArray(t)&&t.length===2){var[e,n]=t;if(Ln(e)&&Ln(n))return!0}return!1}function xG(t,e,n){return n?t:[Math.min(t[0],e[0]),Math.max(t[1],e[1])]}function gte(t,e){if(e&&typeof t!="function"&&Array.isArray(t)&&t.length===2){var[n,r]=t,a,s;if(Ln(n))a=n;else if(typeof n=="function")return;if(Ln(r))s=r;else if(typeof r=="function")return;var o=[a,s];if(Qd(o))return o}}function VLe(t,e,n){if(!(!n&&e==null)){if(typeof t=="function"&&e!=null)try{var r=t(e,n);if(Qd(r))return xG(r,e,n)}catch{}if(Array.isArray(t)&&t.length===2){var[a,s]=t,o,l;if(a==="auto")e!=null&&(o=Math.min(...e));else if(Yt(a))o=a;else if(typeof a=="function")try{e!=null&&(o=a(e?.[0]))}catch{}else if(typeof a=="string"&&AV.test(a)){var c=AV.exec(a);if(c==null||c[1]==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(Yt(s))l=s;else if(typeof s=="function")try{e!=null&&(l=s(e?.[1]))}catch{}else if(typeof s=="string"&&PV.test(s)){var d=PV.exec(s);if(d==null||d[1]==null||e==null)l=void 0;else{var m=+d[1];l=e[1]+m}}else l=e?.[1];var p=[o,l];if(Qd(p))return e==null?p:xG(p,e,n)}}}var ty=1e9,GLe={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},PI,hi=!0,Xl="[DecimalError] ",xf=Xl+"Invalid argument: ",AI=Xl+"Exponent out of range: ",ny=Math.floor,Hp=Math.pow,WLe=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Yo,ja=1e7,ci=7,bte=9007199254740991,zk=ny(bte/ci),rn={};rn.absoluteValue=rn.abs=function(){var t=new this.constructor(this);return t.s&&(t.s=1),t};rn.comparedTo=rn.cmp=function(t){var e,n,r,a,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,a=t.d.length,e=0,n=rt.d[e]^s.s<0?1:-1;return r===a?0:r>a^s.s<0?1:-1};rn.decimalPlaces=rn.dp=function(){var t=this,e=t.d.length-1,n=(e-t.e)*ci;if(e=t.d[e],e)for(;e%10==0;e/=10)n--;return n<0?0:n};rn.dividedBy=rn.div=function(t){return Rd(this,new this.constructor(t))};rn.dividedToIntegerBy=rn.idiv=function(t){var e=this,n=e.constructor;return Qr(Rd(e,new n(t),0,1),n.precision)};rn.equals=rn.eq=function(t){return!this.cmp(t)};rn.exponent=function(){return la(this)};rn.greaterThan=rn.gt=function(t){return this.cmp(t)>0};rn.greaterThanOrEqualTo=rn.gte=function(t){return this.cmp(t)>=0};rn.isInteger=rn.isint=function(){return this.e>this.d.length-2};rn.isNegative=rn.isneg=function(){return this.s<0};rn.isPositive=rn.ispos=function(){return this.s>0};rn.isZero=function(){return this.s===0};rn.lessThan=rn.lt=function(t){return this.cmp(t)<0};rn.lessThanOrEqualTo=rn.lte=function(t){return this.cmp(t)<1};rn.logarithm=rn.log=function(t){var e,n=this,r=n.constructor,a=r.precision,s=a+5;if(t===void 0)t=new r(10);else if(t=new r(t),t.s<1||t.eq(Yo))throw Error(Xl+"NaN");if(n.s<1)throw Error(Xl+(n.s?"NaN":"-Infinity"));return n.eq(Yo)?new r(0):(hi=!1,e=Rd(Y0(n,s),Y0(t,s),s),hi=!0,Qr(e,a))};rn.minus=rn.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?vte(e,t):xte(e,(t.s=-t.s,t))};rn.modulo=rn.mod=function(t){var e,n=this,r=n.constructor,a=r.precision;if(t=new r(t),!t.s)throw Error(Xl+"NaN");return n.s?(hi=!1,e=Rd(n,t,0,1).times(t),hi=!0,n.minus(e)):Qr(new r(n),a)};rn.naturalExponential=rn.exp=function(){return yte(this)};rn.naturalLogarithm=rn.ln=function(){return Y0(this)};rn.negated=rn.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};rn.plus=rn.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?xte(e,t):vte(e,(t.s=-t.s,t))};rn.precision=rn.sd=function(t){var e,n,r,a=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(xf+t);if(e=la(a)+1,r=a.d.length-1,n=r*ci+1,r=a.d[r],r){for(;r%10==0;r/=10)n--;for(r=a.d[0];r>=10;r/=10)n++}return t&&e>n?e:n};rn.squareRoot=rn.sqrt=function(){var t,e,n,r,a,s,o,l=this,c=l.constructor;if(l.s<1){if(!l.s)return new c(0);throw Error(Xl+"NaN")}for(t=la(l),hi=!1,a=Math.sqrt(+l),a==0||a==1/0?(e=du(l.d),(e.length+t)%2==0&&(e+="0"),a=Math.sqrt(e),t=ny((t+1)/2)-(t<0||t%2),a==1/0?e="5e"+t:(e=a.toExponential(),e=e.slice(0,e.indexOf("e")+1)+t),r=new c(e)):r=new c(a.toString()),n=c.precision,a=o=n+3;;)if(s=r,r=s.plus(Rd(l,s,o+2)).times(.5),du(s.d).slice(0,o)===(e=du(r.d)).slice(0,o)){if(e=e.slice(o-3,o+1),a==o&&e=="4999"){if(Qr(s,n+1,0),s.times(s).eq(l)){r=s;break}}else if(e!="9999")break;o+=4}return hi=!0,Qr(r,n)};rn.times=rn.mul=function(t){var e,n,r,a,s,o,l,c,u,d=this,m=d.constructor,p=d.d,f=(t=new m(t)).d;if(!d.s||!t.s)return new m(0);for(t.s*=d.s,n=d.e+t.e,c=p.length,u=f.length,c=0;){for(e=0,a=c+r;a>r;)l=s[a]+f[r]*p[a-r-1]+e,s[a--]=l%ja|0,e=l/ja|0;s[a]=(s[a]+e)%ja|0}for(;!s[--o];)s.pop();return e?++n:s.shift(),t.d=s,t.e=n,hi?Qr(t,m.precision):t};rn.toDecimalPlaces=rn.todp=function(t,e){var n=this,r=n.constructor;return n=new r(n),t===void 0?n:(wu(t,0,ty),e===void 0?e=r.rounding:wu(e,0,8),Qr(n,t+la(n)+1,e))};rn.toExponential=function(t,e){var n,r=this,a=r.constructor;return t===void 0?n=Gf(r,!0):(wu(t,0,ty),e===void 0?e=a.rounding:wu(e,0,8),r=Qr(new a(r),t+1,e),n=Gf(r,!0,t+1)),n};rn.toFixed=function(t,e){var n,r,a=this,s=a.constructor;return t===void 0?Gf(a):(wu(t,0,ty),e===void 0?e=s.rounding:wu(e,0,8),r=Qr(new s(a),t+la(a)+1,e),n=Gf(r.abs(),!1,t+la(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};rn.toInteger=rn.toint=function(){var t=this,e=t.constructor;return Qr(new e(t),la(t)+1,e.rounding)};rn.toNumber=function(){return+this};rn.toPower=rn.pow=function(t){var e,n,r,a,s,o,l=this,c=l.constructor,u=12,d=+(t=new c(t));if(!t.s)return new c(Yo);if(l=new c(l),!l.s){if(t.s<1)throw Error(Xl+"Infinity");return l}if(l.eq(Yo))return l;if(r=c.precision,t.eq(Yo))return Qr(l,r);if(e=t.e,n=t.d.length-1,o=e>=n,s=l.s,o){if((n=d<0?-d:d)<=bte){for(a=new c(Yo),e=Math.ceil(r/ci+4),hi=!1;n%2&&(a=a.times(l),vG(a.d,e)),n=ny(n/2),n!==0;)l=l.times(l),vG(l.d,e);return hi=!0,t.s<0?new c(Yo).div(a):Qr(a,r)}}else if(s<0)throw Error(Xl+"NaN");return s=s<0&&t.d[Math.max(e,n)]&1?-1:1,l.s=1,hi=!1,a=t.times(Y0(l,r+u)),hi=!0,a=yte(a),a.s=s,a};rn.toPrecision=function(t,e){var n,r,a=this,s=a.constructor;return t===void 0?(n=la(a),r=Gf(a,n<=s.toExpNeg||n>=s.toExpPos)):(wu(t,1,ty),e===void 0?e=s.rounding:wu(e,0,8),a=Qr(new s(a),t,e),n=la(a),r=Gf(a,t<=n||n<=s.toExpNeg,t)),r};rn.toSignificantDigits=rn.tosd=function(t,e){var n=this,r=n.constructor;return t===void 0?(t=r.precision,e=r.rounding):(wu(t,1,ty),e===void 0?e=r.rounding:wu(e,0,8)),Qr(new r(n),t,e)};rn.toString=rn.valueOf=rn.val=rn.toJSON=rn[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=la(t),n=t.constructor;return Gf(t,e<=n.toExpNeg||e>=n.toExpPos)};function xte(t,e){var n,r,a,s,o,l,c,u,d=t.constructor,m=d.precision;if(!t.s||!e.s)return e.s||(e=new d(t)),hi?Qr(e,m):e;if(c=t.d,u=e.d,o=t.e,a=e.e,c=c.slice(),s=o-a,s){for(s<0?(r=c,s=-s,l=u.length):(r=u,a=o,l=c.length),o=Math.ceil(m/ci),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)/ja|0,c[s]%=ja;for(n&&(c.unshift(n),++a),l=c.length;c[--l]==0;)c.pop();return e.d=c,e.e=a,hi?Qr(e,m):e}function wu(t,e,n){if(t!==~~t||tn)throw Error(xf+t)}function du(t){var e,n,r,a=t.length-1,s="",o=t[0];if(a>0){for(s+=o,e=1;eo?1:-1;else for(l=c=0;la[l]?1:-1;break}return c}function n(r,a,s){for(var o=0;s--;)r[s]-=o,o=r[s]1;)r.shift()}return function(r,a,s,o){var l,c,u,d,m,p,f,y,v,b,g,_,N,C,k,P,T,D,A=r.constructor,R=r.s==a.s?1:-1,G=r.d,z=a.d;if(!r.s)return new A(r);if(!a.s)throw Error(Xl+"Division by zero");for(c=r.e-a.e,T=z.length,k=G.length,f=new A(R),y=f.d=[],u=0;z[u]==(G[u]||0);)++u;if(z[u]>(G[u]||0)&&--c,s==null?_=s=A.precision:o?_=s+(la(r)-la(a))+1:_=s,_<0)return new A(0);if(_=_/ci+2|0,u=0,T==1)for(d=0,z=z[0],_++;(u1&&(z=t(z,d),G=t(G,d),T=z.length,k=G.length),C=T,v=G.slice(0,T),b=v.length;b=ja/2&&++P;do d=0,l=e(z,v,T,b),l<0?(g=v[0],T!=b&&(g=g*ja+(v[1]||0)),d=g/P|0,d>1?(d>=ja&&(d=ja-1),m=t(z,d),p=m.length,b=v.length,l=e(m,v,p,b),l==1&&(d--,n(m,T16)throw Error(AI+la(t));if(!t.s)return new d(Yo);for(hi=!1,l=m,o=new d(.03125);t.abs().gte(.1);)t=t.times(o),u+=5;for(r=Math.log(Hp(2,u))/Math.LN10*2+5|0,l+=r,n=a=s=new d(Yo),d.precision=l;;){if(a=Qr(a.times(t),l),n=n.times(++c),o=s.plus(Rd(a,n,l)),du(o.d).slice(0,l)===du(s.d).slice(0,l)){for(;u--;)s=Qr(s.times(s),l);return d.precision=m,e==null?(hi=!0,Qr(s,m)):s}s=o}}function la(t){for(var e=t.e*ci,n=t.d[0];n>=10;n/=10)e++;return e}function R2(t,e,n){if(e>t.LN10.sd())throw hi=!0,n&&(t.precision=n),Error(Xl+"LN10 precision limit exceeded");return Qr(new t(t.LN10),e)}function Zm(t){for(var e="";t--;)e+="0";return e}function Y0(t,e){var n,r,a,s,o,l,c,u,d,m=1,p=10,f=t,y=f.d,v=f.constructor,b=v.precision;if(f.s<1)throw Error(Xl+(f.s?"NaN":"-Infinity"));if(f.eq(Yo))return new v(0);if(e==null?(hi=!1,u=b):u=e,f.eq(10))return e==null&&(hi=!0),R2(v,u);if(u+=p,v.precision=u,n=du(y),r=n.charAt(0),s=la(f),Math.abs(s)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)f=f.times(t),n=du(f.d),r=n.charAt(0),m++;s=la(f),r>1?(f=new v("0."+n),s++):f=new v(r+"."+n.slice(1))}else return c=R2(v,u+2,b).times(s+""),f=Y0(new v(r+"."+n.slice(1)),u-p).plus(c),v.precision=b,e==null?(hi=!0,Qr(f,b)):f;for(l=o=f=Rd(f.minus(Yo),f.plus(Yo),u),d=Qr(f.times(f),u),a=3;;){if(o=Qr(o.times(d),u),c=l.plus(Rd(o,new v(a),u)),du(c.d).slice(0,u)===du(l.d).slice(0,u))return l=l.times(2),s!==0&&(l=l.plus(R2(v,u+2,b).times(s+""))),l=Rd(l,new v(m),u),v.precision=b,e==null?(hi=!0,Qr(l,b)):l;l=c,a+=2}}function yG(t,e){var n,r,a;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(a=e.length;e.charCodeAt(a-1)===48;)--a;if(e=e.slice(r,a),e){if(a-=r,n=n-r-1,t.e=ny(n/ci),t.d=[],r=(n+1)%ci,n<0&&(r+=ci),rzk||t.e<-zk))throw Error(AI+n)}else t.s=0,t.e=0,t.d=[0];return t}function Qr(t,e,n){var r,a,s,o,l,c,u,d,m=t.d;for(o=1,s=m[0];s>=10;s/=10)o++;if(r=e-o,r<0)r+=ci,a=e,u=m[d=0];else{if(d=Math.ceil((r+1)/ci),s=m.length,d>=s)return t;for(u=s=m[d],o=1;s>=10;s/=10)o++;r%=ci,a=r-ci+o}if(n!==void 0&&(s=Hp(10,o-a-1),l=u/s%10|0,c=e<0||m[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?a>0?u/Hp(10,o-a):0:m[d-1])%10&1||n==(t.s<0?8:7))),e<1||!m[0])return c?(s=la(t),m.length=1,e=e-s-1,m[0]=Hp(10,(ci-e%ci)%ci),t.e=ny(-e/ci)||0):(m.length=1,m[0]=t.e=t.s=0),t;if(r==0?(m.length=d,s=1,d--):(m.length=d+1,s=Hp(10,ci-r),m[d]=a>0?(u/Hp(10,o-a)%Hp(10,a)|0)*s:0),c)for(;;)if(d==0){(m[0]+=s)==ja&&(m[0]=1,++t.e);break}else{if(m[d]+=s,m[d]!=ja)break;m[d--]=0,s=1}for(r=m.length;m[--r]===0;)m.pop();if(hi&&(t.e>zk||t.e<-zk))throw Error(AI+la(t));return t}function vte(t,e){var n,r,a,s,o,l,c,u,d,m,p=t.constructor,f=p.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new p(t),hi?Qr(e,f):e;if(c=t.d,m=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=m.length):(n=m,r=u,l=c.length),a=Math.max(Math.ceil(f/ci),l)+2,o>a&&(o=a,n.length=1),n.reverse(),a=o;a--;)n.push(0);n.reverse()}else{for(a=c.length,l=m.length,d=a0;--a)c[l++]=0;for(a=m.length;a>o;){if(c[--a]0?s=s.charAt(0)+"."+s.slice(1)+Zm(r):o>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(a<0?"e":"e+")+a):a<0?(s="0."+Zm(-a-1)+s,n&&(r=n-o)>0&&(s+=Zm(r))):a>=o?(s+=Zm(a+1-o),n&&(r=n-a-1)>0&&(s=s+"."+Zm(r))):((r=a+1)0&&(a+1===o&&(s+="."),s+=Zm(r))),t.s<0?"-"+s:s}function vG(t,e){if(t.length>e)return t.length=e,!0}function wte(t){var e,n,r;function a(s){var o=this;if(!(o instanceof a))return new a(s);if(o.constructor=a,s instanceof a){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(xf+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 yG(o,s.toString())}else if(typeof s!="string")throw Error(xf+s);if(s.charCodeAt(0)===45?(s=s.slice(1),o.s=-1):o.s=1,WLe.test(s))yG(o,s);else throw Error(xf+s)}if(a.prototype=rn,a.ROUND_UP=0,a.ROUND_DOWN=1,a.ROUND_CEIL=2,a.ROUND_FLOOR=3,a.ROUND_HALF_UP=4,a.ROUND_HALF_DOWN=5,a.ROUND_HALF_EVEN=6,a.ROUND_HALF_CEIL=7,a.ROUND_HALF_FLOOR=8,a.clone=wte,a.config=a.set=KLe,t===void 0&&(t={}),t)for(r=["precision","rounding","toExpNeg","toExpPos","LN10"],e=0;e=a[e+1]&&r<=a[e+2])this[n]=r;else throw Error(xf+n+": "+r);if((r=t[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(xf+n+": "+r);return this}var PI=wte(GLe);Yo=new PI(1);const Dr=PI;function Ste(t){var e;return t===0?e=1:e=Math.floor(new Dr(t).abs().log(10).toNumber())+1,e}function _te(t,e,n){for(var r=new Dr(t),a=0,s=[];r.lt(e)&&a<1e5;)s.push(r.toNumber()),r=r.add(n),a++;return s}var Nte=t=>{var[e,n]=t,[r,a]=[e,n];return e>n&&([r,a]=[n,e]),[r,a]},kte=(t,e,n)=>{if(t.lte(0))return new Dr(0);var r=Ste(t.toNumber()),a=new Dr(10).pow(r),s=t.div(a),o=r!==1?.05:.1,l=new Dr(Math.ceil(s.div(o).toNumber())).add(n).mul(o),c=l.mul(a);return e?new Dr(c.toNumber()):new Dr(Math.ceil(c.toNumber()))},YLe=(t,e,n)=>{var r=new Dr(1),a=new Dr(t);if(!a.isint()&&n){var s=Math.abs(t);s<1?(r=new Dr(10).pow(Ste(t)-1),a=new Dr(Math.floor(a.div(r).toNumber())).mul(r)):s>1&&(a=new Dr(Math.floor(t)))}else t===0?a=new Dr(Math.floor((e-1)/2)):n||(a=new Dr(Math.floor(t)));for(var o=Math.floor((e-1)/2),l=[],c=0;c4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((n-e)/(r-1)))return{step:new Dr(0),tickMin:new Dr(0),tickMax:new Dr(0)};var o=kte(new Dr(n).sub(e).div(r-1),a,s),l;e<=0&&n>=0?l=new Dr(0):(l=new Dr(e).add(n).div(2),l=l.sub(new Dr(l).mod(o)));var c=Math.ceil(l.sub(e).div(o).toNumber()),u=Math.ceil(new Dr(n).sub(l).div(o).toNumber()),d=c+u+1;return d>r?Cte(e,n,r,a,s+1):(d0?u+(r-d):u,c=n>0?c:c+(r-d)),{step:o,tickMin:l.sub(new Dr(c).mul(o)),tickMax:l.add(new Dr(u).mul(o))})},XLe=function(e){var[n,r]=e,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=Math.max(a,2),[l,c]=Nte([n,r]);if(l===-1/0||c===1/0){var u=c===1/0?[l,...Array(a-1).fill(1/0)]:[...Array(a-1).fill(-1/0),c];return n>r?u.reverse():u}if(l===c)return YLe(l,a,s);var{step:d,tickMin:m,tickMax:p}=Cte(l,c,o,s,0),f=_te(m,p.add(new Dr(.1).mul(d)),d);return n>r?f.reverse():f},QLe=function(e,n){var[r,a]=e,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,[o,l]=Nte([r,a]);if(o===-1/0||l===1/0)return[r,a];if(o===l)return[o];var c=Math.max(n,2),u=kte(new Dr(l).sub(o).div(c-1),s,0),d=[..._te(new Dr(o),new Dr(l),u),l];return s===!1&&(d=d.map(m=>Math.round(m))),r>a?d.reverse():d},Tte=t=>t.rootProps.maxBarSize,ZLe=t=>t.rootProps.barGap,Ate=t=>t.rootProps.barCategoryGap,JLe=t=>t.rootProps.barSize,Uw=t=>t.rootProps.stackOffset,Pte=t=>t.rootProps.reverseStackOrder,MI=t=>t.options.chartName,EI=t=>t.rootProps.syncId,Mte=t=>t.rootProps.syncMethod,jI=t=>t.options.eventEmitter,eOe=t=>t.rootProps.baseValue,Fi={grid:-100,barBackground:-50,area:100,cursorRectangle:200,bar:300,line:400,axis:500,scatter:600,activeBar:1e3,cursorLine:1100,activeDot:1200,label:2e3},Rp={allowDecimals:!1,allowDataOverflow:!1,angleAxisId:0,reversed:!1,scale:"auto",tick:!0,type:"auto"},Xc={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:!0,includeHidden:!1,radiusAxisId:0,reversed:!1,scale:"auto",tick:!0,tickCount:5,type:"auto"},ZT=(t,e)=>{if(!(!t||!e))return t!=null&&t.reversed?[e[1],e[0]]:e};function JT(t,e,n){if(n!=="auto")return n;if(t!=null)return Fc(t,e)?"category":"number"}function wG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Uk(t){for(var e=1;e{if(e!=null)return t.polarAxis.angleAxis[e]},DI=yt([iOe,hee],(t,e)=>{var n;if(t!=null)return t;var r=(n=JT(e,"angleAxis",SG.type))!==null&&n!==void 0?n:"category";return Uk(Uk({},SG),{},{type:r})}),aOe=(t,e)=>t.polarAxis.radiusAxis[e],RI=yt([aOe,hee],(t,e)=>{var n;if(t!=null)return t;var r=(n=JT(e,"radiusAxis",_G.type))!==null&&n!==void 0?n:"category";return Uk(Uk({},_G),{},{type:r})}),eA=t=>t.polarOptions,FI=yt([tm,nm,va],Eee),Ete=yt([eA,FI],(t,e)=>{if(t!=null)return ws(t.innerRadius,e,0)}),jte=yt([eA,FI],(t,e)=>{if(t!=null)return ws(t.outerRadius,e,e*.8)}),sOe=t=>{if(t==null)return[0,0];var{startAngle:e,endAngle:n}=t;return[e,n]},Dte=yt([eA],sOe);yt([DI,Dte],ZT);var Rte=yt([FI,Ete,jte],(t,e,n)=>{if(!(t==null||e==null||n==null))return[e,n]});yt([RI,Rte],ZT);var Fte=yt([dr,eA,Ete,jte,tm,nm],(t,e,n,r,a,s)=>{if(!(t!=="centric"&&t!=="radial"||e==null||n==null||r==null)){var{cx:o,cy:l,startAngle:c,endAngle:u}=e;return{cx:ws(o,a,a/2),cy:ws(l,s,s/2),innerRadius:n,outerRadius:r,startAngle:c,endAngle:u,clockWise:!1}}}),Si=(t,e)=>e,Bw=(t,e,n)=>n;function tA(t){return t?.id}function Lte(t,e,n){var{chartData:r=[]}=e,{allowDuplicatedCategory:a,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=tA(l);u.forEach((m,p)=>{var f=s==null||a?p:String(Tr(m,s,null)),y=Tr(m,l.dataKey,0),v;o.has(f)?v=o.get(f):v={},Object.assign(v,{[d]:y}),o.set(f,v)})}}),Array.from(o.values())}function nA(t){return"stackId"in t&&t.stackId!=null&&t.dataKey!=null}var rA=(t,e)=>t===e?!0:t==null||e==null?!1:t[0]===e[0]&&t[1]===e[1];function iA(t,e){return Array.isArray(t)&&Array.isArray(e)&&t.length===0&&e.length===0?!0:t===e}function oOe(t,e){if(t.length===e.length){for(var n=0;n{var e=dr(t);return e==="horizontal"?"xAxis":e==="vertical"?"yAxis":e==="centric"?"angleAxis":"radiusAxis"},ry=t=>t.tooltip.settings.axisId;function lOe(t){if(t in Lv)return Lv[t]();var e="scale".concat(Tw(t));if(e in Lv)return Lv[e]()}function NG(t){var e=t.ticks,n=t.bandwidth,r=t.range(),a=[Math.min(...r),Math.max(...r)];return{domain:()=>t.domain(),range:(function(s){function o(){return s.apply(this,arguments)}return o.toString=function(){return s.toString()},o})(()=>a),rangeMin:()=>a[0],rangeMax:()=>a[1],isInRange(s){var o=a[0],l=a[1];return o<=l?s>=o&&s<=l:s>=l&&s<=o},bandwidth:n?()=>n.call(t):void 0,ticks:e?s=>e.call(t,s):void 0,map:(s,o)=>{var l=t(s);if(l!=null){if(t.bandwidth&&o!==null&&o!==void 0&&o.position){var c=t.bandwidth();switch(o.position){case"middle":l+=c/2;break;case"end":l+=c;break}}return l}}}}function kG(t,e,n){if(typeof t=="function")return NG(t.copy().domain(e).range(n));if(t!=null){var r=lOe(t);if(r!=null)return r.domain(e).range(n),NG(r)}}var Ote=(t,e)=>{if(e!=null)switch(t){case"linear":{if(!Qd(e)){for(var n,r,a=0;ar)&&(r=s))}return n!==void 0&&r!==void 0?[n,r]:void 0}return e}default:return e}};function CG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Bk(t){for(var e=1;et.cartesianAxis.xAxis[e],Au=(t,e)=>{var n=Ite(t,e);return n??Ma},Ea={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:yF,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:Ew},zte=(t,e)=>t.cartesianAxis.yAxis[e],Pu=(t,e)=>{var n=zte(t,e);return n??Ea},mOe={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:""},LI=(t,e)=>{var n=t.cartesianAxis.zAxis[e];return n??mOe},Ii=(t,e,n)=>{switch(e){case"xAxis":return Au(t,n);case"yAxis":return Pu(t,n);case"zAxis":return LI(t,n);case"angleAxis":return DI(t,n);case"radiusAxis":return RI(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},hOe=(t,e,n)=>{switch(e){case"xAxis":return Au(t,n);case"yAxis":return Pu(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},iy=(t,e,n)=>{switch(e){case"xAxis":return Au(t,n);case"yAxis":return Pu(t,n);case"angleAxis":return DI(t,n);case"radiusAxis":return RI(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},Ute=t=>t.graphicalItems.cartesianItems.some(e=>e.type==="bar")||t.graphicalItems.polarItems.some(e=>e.type==="radialBar");function OI(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 Hw=t=>t.graphicalItems.cartesianItems,pOe=yt([Si,Bw],OI),II=(t,e,n)=>t.filter(n).filter(r=>e?.includeHidden===!0?!0:!r.hide),$w=yt([Hw,Ii,pOe],II,{memoizeOptions:{resultEqualityCheck:iA}}),Bte=yt([$w],t=>t.filter(e=>e.type==="area"||e.type==="bar").filter(nA)),Hte=t=>t.filter(e=>!("stackId"in e)||e.stackId===void 0),fOe=yt([$w],Hte),zI=t=>t.map(e=>e.data).filter(Boolean).flat(1),gOe=yt([$w],zI,{memoizeOptions:{resultEqualityCheck:iA}}),UI=(t,e)=>{var{chartData:n=[],dataStartIndex:r,dataEndIndex:a}=e;return t.length>0?t:n.slice(r,a+1)},BI=yt([gOe,TI],UI),HI=(t,e,n)=>e?.dataKey!=null?t.map(r=>({value:Tr(r,e.dataKey)})):n.length>0?n.map(r=>r.dataKey).flatMap(r=>t.map(a=>({value:Tr(a,r)}))):t.map(r=>({value:r})),aA=yt([BI,Ii,$w],HI);function $te(t,e){switch(t){case"xAxis":return e.direction==="x";case"yAxis":return e.direction==="y";default:return!1}}function fN(t){if(Kl(t)||t instanceof Date){var e=Number(t);if(Ln(e))return e}}function TG(t){if(Array.isArray(t)){var e=[fN(t[0]),fN(t[1])];return Qd(e)?e:void 0}var n=fN(t);if(n!=null)return[n,n]}function Zd(t){return t.map(fN).filter(yo)}function bOe(t,e,n){return!n||typeof e!="number"||Mc(e)?[]:n.length?Zd(n.flatMap(r=>{var a=Tr(t,r.dataKey),s,o;if(Array.isArray(a)?[s,o]=a:s=o=a,!(!Ln(s)||!Ln(o)))return[e-s,e+o]})):[]}var _a=t=>{var e=za(t),n=ry(t);return iy(t,e,n)},qw=yt([_a],t=>t?.dataKey),xOe=yt([Bte,TI,_a],Lte),qte=(t,e,n,r)=>{var a={},s=e.reduce((o,l)=>{if(l.stackId==null)return o;var c=o[l.stackId];return c==null&&(c=[]),c.push(l),o[l.stackId]=c,o},a);return Object.fromEntries(Object.entries(s).map(o=>{var[l,c]=o,u=r?[...c].reverse():c,d=u.map(tA);return[l,{stackedData:z2e(t,d,n),graphicalItems:u}]}))},Hk=yt([xOe,Bte,Uw,Pte],qte),Vte=(t,e,n,r)=>{var{dataStartIndex:a,dataEndIndex:s}=e;if(r==null&&n!=="zAxis"){var o=$2e(t,a,s);if(!(o!=null&&o[0]===0&&o[1]===0))return o}},yOe=yt([Ii],t=>t.allowDataOverflow),$I=t=>{var e;if(t==null||!("domain"in t))return yF;if(t.domain!=null)return t.domain;if("ticks"in t&&t.ticks!=null){if(t.type==="number"){var n=Zd(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:yF},qI=yt([Ii],$I),VI=yt([qI,yOe],gte),vOe=yt([Hk,im,Si,VI],Vte,{memoizeOptions:{resultEqualityCheck:rA}}),sA=t=>t.errorBars,wOe=(t,e,n)=>t.flatMap(r=>e[r.id]).filter(Boolean).filter(r=>$te(n,r)),$k=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,m=(u=r[c.id])===null||u===void 0?void 0:u.filter(g=>$te(a,g)),p=Tr(l,(d=e.dataKey)!==null&&d!==void 0?d:c.dataKey),f=bOe(l,p,m);if(f.length>=2){var y=Math.min(...f),v=Math.max(...f);(s==null||yo)&&(o=v)}var b=TG(p);b!=null&&(s=s==null?b[0]:Math.min(s,b[0]),o=o==null?b[1]:Math.max(o,b[1]))})}),e?.dataKey!=null&&t.forEach(l=>{var c=TG(Tr(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]))}),Ln(s)&&Ln(o))return[s,o]},SOe=yt([BI,Ii,fOe,sA,Si],GI,{memoizeOptions:{resultEqualityCheck:rA}});function _Oe(t){var{value:e}=t;if(Kl(e)||e instanceof Date)return e}var NOe=(t,e,n)=>{var r=t.map(_Oe).filter(a=>a!=null);return n&&(e.dataKey==null||e.allowDuplicatedCategory&&lJ(r))?Fee(0,t.length):e.allowDuplicatedCategory?r:Array.from(new Set(r))},Gte=t=>t.referenceElements.dots,ay=(t,e,n)=>t.filter(r=>r.ifOverflow==="extendDomain").filter(r=>e==="xAxis"?r.xAxisId===n:r.yAxisId===n),kOe=yt([Gte,Si,Bw],ay),Wte=t=>t.referenceElements.areas,COe=yt([Wte,Si,Bw],ay),Kte=t=>t.referenceElements.lines,TOe=yt([Kte,Si,Bw],ay),Yte=(t,e)=>{if(t!=null){var n=Zd(t.map(r=>e==="xAxis"?r.x:r.y));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},AOe=yt(kOe,Si,Yte),Xte=(t,e)=>{if(t!=null){var n=Zd(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)]}},POe=yt([COe,Si],Xte);function MOe(t){var e;if(t.x!=null)return Zd([t.x]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.x);return n==null||n.length===0?[]:Zd(n)}function EOe(t){var e;if(t.y!=null)return Zd([t.y]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.y);return n==null||n.length===0?[]:Zd(n)}var Qte=(t,e)=>{if(t!=null){var n=t.flatMap(r=>e==="xAxis"?MOe(r):EOe(r));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},jOe=yt([TOe,Si],Qte),DOe=yt(AOe,jOe,POe,(t,e,n)=>$k(t,n,e)),WI=(t,e,n,r,a,s,o,l)=>{if(n!=null)return n;var c=o==="vertical"&&l==="xAxis"||o==="horizontal"&&l==="yAxis",u=c?$k(r,s,a):$k(s,a);return VLe(e,u,t.allowDataOverflow)},ROe=yt([Ii,qI,VI,vOe,SOe,DOe,dr,Si],WI,{memoizeOptions:{resultEqualityCheck:rA}}),FOe=[0,1],KI=(t,e,n,r,a,s,o)=>{if(!((t==null||n==null||n.length===0)&&o===void 0)){var{dataKey:l,type:c}=t,u=Fc(e,s);if(u&&l==null){var d;return Fee(0,(d=n?.length)!==null&&d!==void 0?d:0)}return c==="category"?NOe(r,t,u):a==="expand"?FOe:o}},YI=yt([Ii,dr,BI,aA,Uw,Si,ROe],KI);function LOe(t){return t in Lv}var Zte=(t,e,n)=>{if(t!=null){var{scale:r,type:a}=t;if(r==="auto")return a==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!e)?"point":a==="category"?"band":"linear";if(typeof r=="string"){var s="scale".concat(Tw(r));return LOe(s)?s:"point"}}},ep=yt([Ii,Ute,MI],Zte);function XI(t,e,n,r){if(!(n==null||r==null))return typeof t.scale=="function"?kG(t.scale,n,r):kG(e,n,r)}var QI=(t,e,n)=>{var r=$I(e);if(!(n!=="auto"&&n!=="linear")){if(e!=null&&e.tickCount&&Array.isArray(r)&&(r[0]==="auto"||r[1]==="auto")&&Qd(t))return XLe(t,e.tickCount,e.allowDecimals);if(e!=null&&e.tickCount&&e.type==="number"&&Qd(t))return QLe(t,e.tickCount,e.allowDecimals)}},ZI=yt([YI,iy,ep],QI),JI=(t,e,n,r)=>{if(r!=="angleAxis"&&t?.type==="number"&&Qd(e)&&Array.isArray(n)&&n.length>0){var a,s,o=e[0],l=(a=n[0])!==null&&a!==void 0?a:0,c=e[1],u=(s=n[n.length-1])!==null&&s!==void 0?s:0;return[Math.min(o,l),Math.max(c,u)]}return e},OOe=yt([Ii,YI,ZI,Si],JI),IOe=yt(aA,Ii,(t,e)=>{if(!(!e||e.type!=="number")){var n=1/0,r=Array.from(Zd(t.map(m=>m.value))).sort((m,p)=>m-p),a=r[0],s=r[r.length-1];if(a==null||s==null)return 1/0;var o=s-a;if(o===0)return 1/0;for(var l=0;la,(t,e,n,r,a)=>{if(!Ln(t))return 0;var s=e==="vertical"?r.height:r.width;if(a==="gap")return t*s/2;if(a==="no-gap"){var o=ws(n,t*s),l=t*s/2;return l-o-(l-o)/s*o}return 0}),zOe=(t,e,n)=>{var r=Au(t,e);return r==null||typeof r.padding!="string"?0:Jte(t,"xAxis",e,n,r.padding)},UOe=(t,e,n)=>{var r=Pu(t,e);return r==null||typeof r.padding!="string"?0:Jte(t,"yAxis",e,n,r.padding)},BOe=yt(Au,zOe,(t,e)=>{var n,r;if(t==null)return{left:0,right:0};var{padding:a}=t;return typeof a=="string"?{left:e,right:e}:{left:((n=a.left)!==null&&n!==void 0?n:0)+e,right:((r=a.right)!==null&&r!==void 0?r:0)+e}}),HOe=yt(Pu,UOe,(t,e)=>{var n,r;if(t==null)return{top:0,bottom:0};var{padding:a}=t;return typeof a=="string"?{top:e,bottom:e}:{top:((n=a.top)!==null&&n!==void 0?n:0)+e,bottom:((r=a.bottom)!==null&&r!==void 0?r:0)+e}}),$Oe=yt([va,BOe,BT,UT,(t,e,n)=>n],(t,e,n,r,a)=>{var{padding:s}=r;return a?[s.left,n.width-s.right]:[t.left+e.left,t.left+t.width-e.right]}),qOe=yt([va,dr,HOe,BT,UT,(t,e,n)=>n],(t,e,n,r,a,s)=>{var{padding:o}=a;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]}),Vw=(t,e,n,r)=>{var a;switch(e){case"xAxis":return $Oe(t,n,r);case"yAxis":return qOe(t,n,r);case"zAxis":return(a=LI(t,n))===null||a===void 0?void 0:a.range;case"angleAxis":return Dte(t);case"radiusAxis":return Rte(t,n);default:return}},ene=yt([Ii,Vw],ZT),VOe=yt([ep,OOe],Ote),Px=yt([Ii,ep,VOe,ene],XI);yt([$w,sA,Si],wOe);function tne(t,e){return t.ide.id?1:0}var oA=(t,e)=>e,lA=(t,e,n)=>n,GOe=yt(IT,oA,lA,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(tne)),WOe=yt(zT,oA,lA,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(tne)),nne=(t,e)=>({width:t.width,height:e.height}),KOe=(t,e)=>{var n=typeof e.width=="number"?e.width:Ew;return{width:n,height:t.height}},rne=yt(va,Au,nne),YOe=(t,e,n)=>{switch(e){case"top":return t.top;case"bottom":return n-t.bottom;default:return 0}},XOe=(t,e,n)=>{switch(e){case"left":return t.left;case"right":return n-t.right;default:return 0}},QOe=yt(nm,va,GOe,oA,lA,(t,e,n,r,a)=>{var s={},o;return n.forEach(l=>{var c=nne(e,l);o==null&&(o=YOe(e,r,t));var u=r==="top"&&!a||r==="bottom"&&a;s[l.id]=o-Number(u)*c.height,o+=(u?-1:1)*c.height}),s}),ZOe=yt(tm,va,WOe,oA,lA,(t,e,n,r,a)=>{var s={},o;return n.forEach(l=>{var c=KOe(e,l);o==null&&(o=XOe(e,r,t));var u=r==="left"&&!a||r==="right"&&a;s[l.id]=o-Number(u)*c.width,o+=(u?-1:1)*c.width}),s}),JOe=(t,e)=>{var n=Au(t,e);if(n!=null)return QOe(t,n.orientation,n.mirror)},eIe=yt([va,Au,JOe,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var a=n?.[r];return a==null?{x:t.left,y:0}:{x:t.left,y:a}}}),tIe=(t,e)=>{var n=Pu(t,e);if(n!=null)return ZOe(t,n.orientation,n.mirror)},nIe=yt([va,Pu,tIe,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var a=n?.[r];return a==null?{x:0,y:t.top}:{x:a,y:t.top}}}),ine=yt(va,Pu,(t,e)=>{var n=typeof e.width=="number"?e.width:Ew;return{width:n,height:t.height}}),AG=(t,e,n)=>{switch(e){case"xAxis":return rne(t,n).width;case"yAxis":return ine(t,n).height;default:return}},ane=(t,e,n,r)=>{if(n!=null){var{allowDuplicatedCategory:a,type:s,dataKey:o}=n,l=Fc(t,r),c=e.map(u=>u.value);if(o&&l&&s==="category"&&a&&lJ(c))return c}},e4=yt([dr,aA,Ii,Si],ane),sne=(t,e,n,r)=>{if(!(n==null||n.dataKey==null)){var{type:a,scale:s}=n,o=Fc(t,r);if(o&&(a==="number"||s!=="auto"))return e.map(l=>l.value)}},t4=yt([dr,aA,iy,Si],sne),PG=yt([dr,hOe,ep,Px,e4,t4,Vw,ZI,Si],(t,e,n,r,a,s,o,l,c)=>{if(e!=null){var u=Fc(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:a,isCategorical:u,niceTicks:l,range:o,realScaleType:n,scale:r}}}),rIe=(t,e,n,r,a,s,o,l,c)=>{if(!(e==null||r==null)){var u=Fc(t,c),{type:d,ticks:m,tickCount:p}=e,f=n==="scaleBand"&&typeof r.bandwidth=="function"?r.bandwidth()/2:2,y=d==="category"&&r.bandwidth?r.bandwidth()/f:0;y=c==="angleAxis"&&s!=null&&s.length>=2?Fa(s[0]-s[1])*2*y:y;var v=m||a;return v?v.map((b,g)=>{var _=o?o.indexOf(b):b,N=r.map(_);return Ln(N)?{index:g,coordinate:N+y,value:b,offset:y}:null}).filter(yo):u&&l?l.map((b,g)=>{var _=r.map(b);return Ln(_)?{coordinate:_+y,value:b,index:g,offset:y}:null}).filter(yo):r.ticks?r.ticks(p).map((b,g)=>{var _=r.map(b);return Ln(_)?{coordinate:_+y,value:b,index:g,offset:y}:null}).filter(yo):r.domain().map((b,g)=>{var _=r.map(b);return Ln(_)?{coordinate:_+y,value:o?o[b]:b,index:g,offset:y}:null}).filter(yo)}},one=yt([dr,iy,ep,Px,ZI,Vw,e4,t4,Si],rIe),iIe=(t,e,n,r,a,s,o)=>{if(!(e==null||n==null||r==null||r[0]===r[1])){var l=Fc(t,o),{tickCount:c}=e,u=0;return u=o==="angleAxis"&&r?.length>=2?Fa(r[0]-r[1])*2*u:u,l&&s?s.map((d,m)=>{var p=n.map(d);return Ln(p)?{coordinate:p+u,value:d,index:m,offset:u}:null}).filter(yo):n.ticks?n.ticks(c).map((d,m)=>{var p=n.map(d);return Ln(p)?{coordinate:p+u,value:d,index:m,offset:u}:null}).filter(yo):n.domain().map((d,m)=>{var p=n.map(d);return Ln(p)?{coordinate:p+u,value:a?a[d]:d,index:m,offset:u}:null}).filter(yo)}},Su=yt([dr,iy,Px,Vw,e4,t4,Si],iIe),_u=yt(Ii,Px,(t,e)=>{if(!(t==null||e==null))return Bk(Bk({},t),{},{scale:e})}),aIe=yt([Ii,ep,YI,ene],XI);yt((t,e,n)=>LI(t,n),aIe,(t,e)=>{if(!(t==null||e==null))return Bk(Bk({},t),{},{scale:e})});var sIe=yt([dr,IT,zT],(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}}),lne=t=>t.options.defaultTooltipEventType,cne=t=>t.options.validateTooltipEventTypes;function une(t,e,n){if(t==null)return e;var r=t?"axis":"item";return n==null?e:n.includes(r)?r:e}function n4(t,e){var n=lne(t),r=cne(t);return une(e,n,r)}function oIe(t){return en(e=>n4(e,t))}var dne=(t,e)=>{var n,r=Number(e);if(!(Mc(r)||e==null))return r>=0?t==null||(n=t[r])===null||n===void 0?void 0:n.value:void 0},lIe=t=>t.tooltip.settings,sh={active:!1,index:null,dataKey:void 0,graphicalItemId:void 0,coordinate:void 0},cIe={itemInteraction:{click:sh,hover:sh},axisInteraction:{click:sh,hover:sh},keyboardInteraction:sh,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}},mne=Ao({name:"tooltip",initialState:cIe,reducers:{addTooltipEntrySettings:{reducer(t,e){t.tooltipItemPayloads.push(e.payload)},prepare:mi()},replaceTooltipEntrySettings:{reducer(t,e){var{prev:n,next:r}=e.payload,a=Nc(t).tooltipItemPayloads.indexOf(n);a>-1&&(t.tooltipItemPayloads[a]=r)},prepare:mi()},removeTooltipEntrySettings:{reducer(t,e){var n=Nc(t).tooltipItemPayloads.indexOf(e.payload);n>-1&&t.tooltipItemPayloads.splice(n,1)},prepare:mi()},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}}}),{addTooltipEntrySettings:uIe,replaceTooltipEntrySettings:dIe,removeTooltipEntrySettings:mIe,setTooltipSettingsState:hIe,setActiveMouseOverItemIndex:hne,mouseLeaveItem:pIe,mouseLeaveChart:pne,setActiveClickItemIndex:fIe,setMouseOverAxisIndex:fne,setMouseClickAxisIndex:gIe,setSyncInteraction:vF,setKeyboardInteraction:wF}=mne.actions,bIe=mne.reducer;function MG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function T1(t){for(var e=1;e{if(e==null)return sh;var a=wIe(t,e,n);if(a==null)return sh;if(a.active)return a;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(SIe(a)){if(s)return T1(T1({},a),{},{active:!0})}else if(r!=null)return{active:!0,coordinate:void 0,dataKey:void 0,index:r,graphicalItemId:void 0};return T1(T1({},sh),{},{coordinate:a.coordinate})};function _Ie(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 NIe(t,e){var n=_Ie(t),r=e[0],a=e[1];if(n===void 0)return!1;var s=Math.min(r,a),o=Math.max(r,a);return n>=s&&n<=o}function kIe(t,e,n){if(n==null||e==null)return!0;var r=Tr(t,e);return r==null||!Qd(n)?!0:NIe(r,n)}var r4=(t,e,n,r)=>{var a=t?.index;if(a==null)return null;var s=Number(a);if(!Ln(s))return a;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||kIe(u,n,r)?String(c):null},bne=(t,e,n,r,a,s,o)=>{if(s!=null){var l=o[0],c=l?.getPosition(s);if(c!=null)return c;var u=a?.[Number(s)];if(u)return n==="horizontal"?{x:u.coordinate,y:(r.top+e)/2}:{x:(r.left+t)/2,y:u.coordinate}}},xne=(t,e,n,r)=>{if(e==="axis")return t.tooltipItemPayloads;if(t.tooltipItemPayloads.length===0)return[];var a;if(n==="hover"?a=t.itemInteraction.hover.graphicalItemId:a=t.itemInteraction.click.graphicalItemId,a==null&&r!=null){var s=t.tooltipItemPayloads[0];return s!=null?[s]:[]}return t.tooltipItemPayloads.filter(o=>{var l;return((l=o.settings)===null||l===void 0?void 0:l.graphicalItemId)===a})},yne=t=>t.options.tooltipPayloadSearcher,sy=t=>t.tooltip;function EG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function jG(t){for(var e=1;e{if(!(e==null||s==null)){var{chartData:l,computedData:c,dataStartIndex:u,dataEndIndex:d}=n,m=[];return t.reduce((p,f)=>{var y,{dataDefinedOnItem:v,settings:b}=f,g=PIe(v,l),_=Array.isArray(g)?nee(g,u,d):g,N=(y=b?.dataKey)!==null&&y!==void 0?y:r,C=b?.nameKey,k;if(r&&Array.isArray(_)&&!Array.isArray(_[0])&&o==="axis"?k=cJ(_,r,a):k=s(_,e,c,C),Array.isArray(k))k.forEach(T=>{var D=jG(jG({},b),{},{name:T.name,unit:T.unit,color:void 0,fill:void 0});p.push(MV({tooltipEntrySettings:D,dataKey:T.dataKey,payload:T.payload,value:Tr(T.payload,T.dataKey),name:T.name}))});else{var P;p.push(MV({tooltipEntrySettings:b,dataKey:N,payload:k,value:Tr(k,N),name:(P=Tr(k,C))!==null&&P!==void 0?P:b?.name}))}return p},m)}},i4=yt([_a,Ute,MI],Zte),MIe=yt([t=>t.graphicalItems.cartesianItems,t=>t.graphicalItems.polarItems],(t,e)=>[...t,...e]),EIe=yt([za,ry],OI),oy=yt([MIe,_a,EIe],II,{memoizeOptions:{resultEqualityCheck:iA}}),jIe=yt([oy],t=>t.filter(nA)),DIe=yt([oy],zI,{memoizeOptions:{resultEqualityCheck:iA}}),ly=yt([DIe,im],UI),RIe=yt([jIe,im,_a],Lte),a4=yt([ly,_a,oy],HI),wne=yt([_a],$I),FIe=yt([_a],t=>t.allowDataOverflow),Sne=yt([wne,FIe],gte),LIe=yt([oy],t=>t.filter(nA)),OIe=yt([RIe,LIe,Uw,Pte],qte),IIe=yt([OIe,im,za,Sne],Vte),zIe=yt([oy],Hte),UIe=yt([ly,_a,zIe,sA,za],GI,{memoizeOptions:{resultEqualityCheck:rA}}),BIe=yt([Gte,za,ry],ay),HIe=yt([BIe,za],Yte),$Ie=yt([Wte,za,ry],ay),qIe=yt([$Ie,za],Xte),VIe=yt([Kte,za,ry],ay),GIe=yt([VIe,za],Qte),WIe=yt([HIe,GIe,qIe],$k),KIe=yt([_a,wne,Sne,IIe,UIe,WIe,dr,za],WI),Gw=yt([_a,dr,ly,a4,Uw,za,KIe],KI),YIe=yt([Gw,_a,i4],QI),XIe=yt([_a,Gw,YIe,za],JI),_ne=t=>{var e=za(t),n=ry(t),r=!1;return Vw(t,e,n,r)},Nne=yt([_a,_ne],ZT),kne=yt([_a,i4,XIe,Nne],XI),QIe=yt([dr,a4,_a,za],ane),ZIe=yt([dr,a4,_a,za],sne),JIe=(t,e,n,r,a,s,o,l)=>{if(e){var{type:c}=e,u=Fc(t,l);if(r){var d=n==="scaleBand"&&r.bandwidth?r.bandwidth()/2:2,m=c==="category"&&r.bandwidth?r.bandwidth()/d:0;return m=l==="angleAxis"&&a!=null&&a?.length>=2?Fa(a[0]-a[1])*2*m:m,u&&o?o.map((p,f)=>{var y=r.map(p);return Ln(y)?{coordinate:y+m,value:p,index:f,offset:m}:null}).filter(yo):r.domain().map((p,f)=>{var y=r.map(p);return Ln(y)?{coordinate:y+m,value:s?s[p]:p,index:f,offset:m}:null}).filter(yo)}}},am=yt([dr,_a,i4,kne,_ne,QIe,ZIe,za],JIe),s4=yt([lne,cne,lIe],(t,e,n)=>une(n.shared,t,e)),Cne=t=>t.tooltip.settings.trigger,o4=t=>t.tooltip.settings.defaultIndex,Ww=yt([sy,s4,Cne,o4],gne),Vh=yt([Ww,ly,qw,Gw],r4),Tne=yt([am,Vh],dne),l4=yt([Ww],t=>{if(t)return t.dataKey}),e4e=yt([Ww],t=>{if(t)return t.graphicalItemId}),Ane=yt([sy,s4,Cne,o4],xne),t4e=yt([tm,nm,dr,va,am,o4,Ane],bne),n4e=yt([Ww,t4e],(t,e)=>t!=null&&t.coordinate?t.coordinate:e),r4e=yt([Ww],t=>{var e;return(e=t?.active)!==null&&e!==void 0?e:!1}),i4e=yt([Ane,Vh,im,qw,Tne,yne,s4],vne),a4e=yt([i4e],t=>{if(t!=null){var e=t.map(n=>n.payload).filter(n=>n!=null);return Array.from(new Set(e))}});function DG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function RG(t){for(var e=1;een(_a),u4e=()=>{var t=c4e(),e=en(am),n=en(kne);return qh(!t||!n?void 0:RG(RG({},t),{},{scale:n}),e)};function FG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Sb(t){for(var e=1;e{var a=e.find(s=>s&&s.index===n);if(a){if(t==="horizontal")return{x:a.coordinate,y:r.chartY};if(t==="vertical")return{x:r.chartX,y:a.coordinate}}return{x:0,y:0}},f4e=(t,e,n,r)=>{var a=e.find(u=>u&&u.index===n);if(a){if(t==="centric"){var s=a.coordinate,{radius:o}=r;return Sb(Sb(Sb({},r),aa(r.cx,r.cy,o,s)),{},{angle:s,radius:o})}var l=a.coordinate,{angle:c}=r;return Sb(Sb(Sb({},r),aa(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 g4e(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 Pne=(t,e,n,r,a)=>{var s,o=(s=e?.length)!==null&&s!==void 0?s:0;if(o<=1||t==null)return 0;if(r==="angleAxis"&&a!=null&&Math.abs(Math.abs(a[1]-a[0])-360)<=1e-6)for(var l=0;l0?(c=n[l-1])===null||c===void 0?void 0:c.coordinate:(u=n[o-1])===null||u===void 0?void 0:u.coordinate,y=(d=n[l])===null||d===void 0?void 0:d.coordinate,v=l>=o-1?(m=n[0])===null||m===void 0?void 0:m.coordinate:(p=n[l+1])===null||p===void 0?void 0:p.coordinate,b=void 0;if(!(f==null||y==null||v==null))if(Fa(y-f)!==Fa(v-y)){var g=[];if(Fa(v-y)===Fa(a[1]-a[0])){b=v;var _=y+a[1]-a[0];g[0]=Math.min(_,(_+f)/2),g[1]=Math.max(_,(_+f)/2)}else{b=f;var N=v+a[1]-a[0];g[0]=Math.min(y,(N+y)/2),g[1]=Math.max(y,(N+y)/2)}var C=[Math.min(y,(b+y)/2),Math.max(y,(b+y)/2)];if(t>C[0]&&t<=C[1]||t>=g[0]&&t<=g[1]){var k;return(k=n[l])===null||k===void 0?void 0:k.index}}else{var P=Math.min(f,v),T=Math.max(f,v);if(t>(P+y)/2&&t<=(T+y)/2){var D;return(D=n[l])===null||D===void 0?void 0:D.index}}}else if(e)for(var A=0;A(R.coordinate+z.coordinate)/2||A>0&&A(R.coordinate+z.coordinate)/2&&t<=(R.coordinate+G.coordinate)/2)return R.index}}return-1},Mne=()=>en(MI),c4=(t,e)=>e,Ene=(t,e,n)=>n,u4=(t,e,n,r)=>r,b4e=yt(am,t=>AT(t,e=>e.coordinate)),d4=yt([sy,c4,Ene,u4],gne),m4=yt([d4,ly,qw,Gw],r4),x4e=(t,e,n)=>{if(e!=null){var r=sy(t);return e==="axis"?n==="hover"?r.axisInteraction.hover.dataKey:r.axisInteraction.click.dataKey:n==="hover"?r.itemInteraction.hover.dataKey:r.itemInteraction.click.dataKey}},jne=yt([sy,c4,Ene,u4],xne),qk=yt([tm,nm,dr,va,am,u4,jne],bne),y4e=yt([d4,qk],(t,e)=>{var n;return(n=t.coordinate)!==null&&n!==void 0?n:e}),Dne=yt([am,m4],dne),v4e=yt([jne,m4,im,qw,Dne,yne,c4],vne),w4e=yt([d4,m4],(t,e)=>({isActive:t.active&&e!=null,activeIndex:e})),S4e=(t,e,n,r,a,s,o)=>{if(!(!t||!n||!r||!a)&&g4e(t,o)){var l=q2e(t,e),c=Pne(l,s,a,n,r),u=p4e(e,a,c,t);return{activeIndex:String(c),activeCoordinate:u}}},_4e=(t,e,n,r,a,s,o)=>{if(!(!t||!r||!a||!s||!n)){var l=oRe(t,n);if(l){var c=V2e(l,e),u=Pne(c,o,s,r,a),d=f4e(e,s,u,l);return{activeIndex:String(u),activeCoordinate:d}}}},N4e=(t,e,n,r,a,s,o,l)=>{if(!(!t||!e||!r||!a||!s))return e==="horizontal"||e==="vertical"?S4e(t,e,r,a,s,o,l):_4e(t,e,n,r,a,s,o)},k4e=yt(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.panoramaElement:r.element}}),C4e=yt(t=>t.zIndex.zIndexMap,t=>{var e=Object.keys(t).map(r=>parseInt(r,10)).concat(Object.values(Fi)),n=Array.from(new Set(e));return n.sort((r,a)=>r-a)},{memoizeOptions:{resultEqualityCheck:oOe}});function LG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function OG(t){for(var e=1;eOG(OG({},t),{},{[e]:{element:void 0,panoramaElement:void 0,consumers:0}}),M4e)},j4e=new Set(Object.values(Fi));function D4e(t){return j4e.has(t)}var Rne=Ao({name:"zIndex",initialState:E4e,reducers:{registerZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]?t.zIndexMap[n].consumers+=1:t.zIndexMap[n]={consumers:1,element:void 0,panoramaElement:void 0}},prepare:mi()},unregisterZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(t.zIndexMap[n].consumers-=1,t.zIndexMap[n].consumers<=0&&!D4e(n)&&delete t.zIndexMap[n])},prepare:mi()},registerZIndexPortalElement:{reducer:(t,e)=>{var{zIndex:n,element:r,isPanorama:a}=e.payload;t.zIndexMap[n]?a?t.zIndexMap[n].panoramaElement=r:t.zIndexMap[n].element=r:t.zIndexMap[n]={consumers:0,element:a?void 0:r,panoramaElement:a?r:void 0}},prepare:mi()},unregisterZIndexPortalElement:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(e.payload.isPanorama?t.zIndexMap[n].panoramaElement=void 0:t.zIndexMap[n].element=void 0)},prepare:mi()}}}),{registerZIndexPortal:R4e,unregisterZIndexPortal:F4e,registerZIndexPortalElement:L4e,unregisterZIndexPortalElement:O4e}=Rne.actions,I4e=Rne.reducer;function Ns(t){var{zIndex:e,children:n}=t,r=SDe(),a=r&&e!==void 0&&e!==0,s=wa(),o=Jr();w.useLayoutEffect(()=>a?(o(R4e({zIndex:e})),()=>{o(F4e({zIndex:e}))}):Yh,[o,e,a]);var l=en(c=>k4e(c,e,s));return a?l?wd.createPortal(n,l):null:n}function SF(){return SF=Object.assign?Object.assign.bind():function(t){for(var e=1;ew.useContext(Fne),F2={exports:{}},zG;function G4e(){return zG||(zG=1,(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function a(c,u,d){this.fn=c,this.context=u,this.once=d||!1}function s(c,u,d,m,p){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new a(d,m||c,p),y=n?n+u:u;return c._events[y]?c._events[y].fn?c._events[y]=[c._events[y],f]:c._events[y].push(f):(c._events[y]=f,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,m;if(this._eventsCount===0)return u;for(m in d=this._events)e.call(d,m)&&u.push(n?m.slice(1):m);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},l.prototype.listeners=function(u){var d=n?n+u:u,m=this._events[d];if(!m)return[];if(m.fn)return[m.fn];for(var p=0,f=m.length,y=new Array(f);p{if(e&&Array.isArray(t)){var n=Number.parseInt(e,10);if(!Mc(n))return t[n]}},Y4e={chartName:"",tooltipPayloadSearcher:()=>{},eventEmitter:void 0,defaultTooltipEventType:"axis"},Lne=Ao({name:"options",initialState:Y4e,reducers:{createEventEmitter:t=>{t.eventEmitter==null&&(t.eventEmitter=Symbol("rechartsEventEmitter"))}}}),X4e=Lne.reducer,{createEventEmitter:Q4e}=Lne.actions;function Z4e(t){return t.tooltip.syncInteraction}var J4e={chartData:void 0,computedData:void 0,dataStartIndex:0,dataEndIndex:0},One=Ao({name:"chartData",initialState:J4e,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:BG,setDataStartEndIndexes:e5e,setComputedData:vit}=One.actions,t5e=One.reducer,n5e=["x","y"];function HG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function _b(t){for(var e=1;ec.rootProps.className);w.useEffect(()=>{if(t==null)return Yh;var c=(u,d,m)=>{if(e!==m&&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 f=d.payload.coordinate,{x:y,y:v}=f,b=s5e(f,n5e),{x:g,y:_,width:N,height:C}=d.payload.sourceViewBox,k=_b(_b({},b),{},{x:o.x+(N?(y-g)/N:0)*o.width,y:o.y+(C?(v-_)/C:0)*o.height});n(_b(_b({},d),{},{payload:_b(_b({},d.payload),{},{coordinate:k})}))}else n(d);return}if(a!=null){var P;if(typeof r=="function"){var T={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},D=r(a,T);P=a[D]}else r==="value"&&(P=a.find(ae=>String(ae.value)===d.payload.label));var{coordinate:A}=d.payload;if(P==null||d.payload.active===!1||A==null||o==null){n(vF({active:!1,coordinate:void 0,dataKey:void 0,index:null,label:void 0,sourceViewBox:void 0,graphicalItemId:void 0}));return}var{x:R,y:G}=A,z=Math.min(R,o.x+o.width),Z=Math.min(G,o.y+o.height),I={x:s==="horizontal"?P.coordinate:z,y:s==="horizontal"?Z:P.coordinate},J=vF({active:d.payload.active,coordinate:I,dataKey:d.payload.dataKey,index:String(P.index),label:d.payload.label,sourceViewBox:d.payload.sourceViewBox,graphicalItemId:d.payload.graphicalItemId});n(J)}}};return X0.on(_F,c),()=>{X0.off(_F,c)}},[l,n,e,t,r,a,s,o])}function c5e(){var t=en(EI),e=en(jI),n=Jr();w.useEffect(()=>{if(t==null)return Yh;var r=(a,s,o)=>{e!==o&&t===a&&n(e5e(s))};return X0.on(UG,r),()=>{X0.off(UG,r)}},[n,e,t])}function u5e(){var t=Jr();w.useEffect(()=>{t(Q4e())},[t]),l5e(),c5e()}function d5e(t,e,n,r,a,s){var o=en(f=>x4e(f,t,e)),l=en(jI),c=en(EI),u=en(Mte),d=en(Z4e),m=d?.active,p=jw();w.useEffect(()=>{if(!m&&c!=null&&l!=null){var f=vF({active:s,coordinate:n,dataKey:o,index:a,label:typeof r=="number"?String(r):r,sourceViewBox:p,graphicalItemId:void 0});X0.emit(_F,c,f,l)}},[m,n,o,a,r,l,c,u,s,p])}function $G(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function qG(t){for(var e=1;e{T(hIe({shared:_,trigger:N,axisId:P,active:a,defaultIndex:D}))},[T,_,N,P,a,D]);var A=jw(),R=kee(),G=oIe(_),{activeIndex:z,isActive:Z}=(e=en(X=>w4e(X,G,N,D)))!==null&&e!==void 0?e:{},I=en(X=>v4e(X,G,N,D)),J=en(X=>Dne(X,G,N,D)),ae=en(X=>y4e(X,G,N,D)),Y=I,ue=V4e(),de=(n=a??Z)!==null&&n!==void 0?n:!1,[he,V]=CJ([Y,de]),ne=G==="axis"?J:void 0;d5e(G,N,ae,ne,z,de);var se=k??ue;if(se==null||A==null||G==null)return null;var pe=Y??VG;de||(pe=VG),u&&pe.length&&(pe=vJ(pe.filter(X=>X.value!=null&&(X.hide!==!0||r.includeHidden)),p,f5e));var Te=pe.length>0,q=w.createElement(o3e,{allowEscapeViewBox:s,animationDuration:o,animationEasing:l,isAnimationActive:d,active:de,coordinate:ae,hasPayload:Te,offset:m,position:f,reverseDirection:y,useTranslate3d:v,viewBox:A,wrapperStyle:b,lastBoundingBox:he,innerRef:V,hasPortalFromProps:!!k},g5e(c,qG(qG({},r),{},{payload:pe,label:ne,active:de,activeIndex:z,coordinate:ae,accessibilityLayer:R})));return w.createElement(w.Fragment,null,wd.createPortal(q,se),de&&w.createElement(q4e,{cursor:g,tooltipEventType:G,coordinate:ae,payload:pe,index:z}))}var Mx=t=>null;Mx.displayName="Cell";function x5e(t,e,n){return(e=y5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function y5e(t){var e=v5e(t,"string");return typeof e=="symbol"?e:e+""}function v5e(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 w5e{constructor(e){x5e(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 GG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function S5e(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,T5e,e),n.textContent="".concat(t);var r=n.getBoundingClientRect();return{width:r.width,height:r.height}}catch{return{width:0,height:0}}},Jv=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||Fw.isSsr)return{width:0,height:0};if(!Ine.enableCache)return YG(e,n);var r=A5e(e,n),a=WG.get(r);if(a)return a;var s=YG(e,n);return WG.set(r,s),s},zne;function P5e(t,e,n){return(e=M5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function M5e(t){var e=E5e(t,"string");return typeof e=="symbol"?e:e+""}function E5e(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)}var XG=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,QG=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,j5e=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,D5e=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,R5e={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},F5e=["cm","mm","pt","pc","in","Q","px"];function L5e(t){return F5e.includes(t)}var $b="NaN";function O5e(t,e){return t*R5e[e]}class Ja{static parse(e){var n,[,r,a]=(n=D5e.exec(e))!==null&&n!==void 0?n:[];return r==null?Ja.NaN:new Ja(parseFloat(r),a??"")}constructor(e,n){this.num=e,this.unit=n,this.num=e,this.unit=n,Mc(e)&&(this.unit=""),n!==""&&!j5e.test(n)&&(this.num=NaN,this.unit=""),L5e(n)&&(this.num=O5e(e,n),this.unit="px")}add(e){return this.unit!==e.unit?new Ja(NaN,""):new Ja(this.num+e.num,this.unit)}subtract(e){return this.unit!==e.unit?new Ja(NaN,""):new Ja(this.num-e.num,this.unit)}multiply(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new Ja(NaN,""):new Ja(this.num*e.num,this.unit||e.unit)}divide(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new Ja(NaN,""):new Ja(this.num/e.num,this.unit||e.unit)}toString(){return"".concat(this.num).concat(this.unit)}isNaN(){return Mc(this.num)}}zne=Ja;P5e(Ja,"NaN",new zne(NaN,""));function Une(t){if(t==null||t.includes($b))return $b;for(var e=t;e.includes("*")||e.includes("/");){var n,[,r,a,s]=(n=XG.exec(e))!==null&&n!==void 0?n:[],o=Ja.parse(r??""),l=Ja.parse(s??""),c=a==="*"?o.multiply(l):o.divide(l);if(c.isNaN())return $b;e=e.replace(XG,c.toString())}for(;e.includes("+")||/.-\d+(?:\.\d+)?/.test(e);){var u,[,d,m,p]=(u=QG.exec(e))!==null&&u!==void 0?u:[],f=Ja.parse(d??""),y=Ja.parse(p??""),v=m==="+"?f.add(y):f.subtract(y);if(v.isNaN())return $b;e=e.replace(QG,v.toString())}return e}var ZG=/\(([^()]*)\)/;function I5e(t){for(var e=t,n;(n=ZG.exec(e))!=null;){var[,r]=n;e=e.replace(ZG,Une(r))}return e}function z5e(t){var e=t.replace(/\s+/g,"");return e=I5e(e),e=Une(e),e}function U5e(t){try{return z5e(t)}catch{return $b}}function L2(t){var e=U5e(t.slice(5,-1));return e===$b?"":e}var B5e=["x","y","lineHeight","capHeight","fill","scaleToFit","textAnchor","verticalAnchor"],H5e=["dx","dy","angle","className","breakAll"];function NF(){return NF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{children:e,breakAll:n,style:r}=t;try{var a=[];gi(e)||(n?a=e.toString().split(""):a=e.toString().split(Bne));var s=a.map(l=>({word:l,width:Jv(l,r).width})),o=n?0:Jv(" ",r).width;return{wordsWithComputedWidth:s,spaceWidth:o}}catch{return null}};function q5e(t){return t==="start"||t==="middle"||t==="end"||t==="inherit"}var $ne=(t,e,n,r)=>t.reduce((a,s)=>{var{word:o,width:l}=s,c=a[a.length-1];if(c&&l!=null&&(e==null||r||c.width+l+nt.reduce((e,n)=>e.width>n.width?e:n),V5e="…",e9=(t,e,n,r,a,s,o,l)=>{var c=t.slice(0,e),u=Hne({breakAll:n,style:r,children:c+V5e});if(!u)return[!1,[]];var d=$ne(u.wordsWithComputedWidth,s,o,l),m=d.length>a||qne(d).width>Number(s);return[m,d]},G5e=(t,e,n,r,a)=>{var{maxLines:s,children:o,style:l,breakAll:c}=t,u=Yt(s),d=String(o),m=$ne(e,r,n,a);if(!u||a)return m;var p=m.length>s||qne(m).width>Number(r);if(!p)return m;for(var f=0,y=d.length-1,v=0,b;f<=y&&v<=d.length-1;){var g=Math.floor((f+y)/2),_=g-1,[N,C]=e9(d,_,c,l,s,r,n,a),[k]=e9(d,g,c,l,s,r,n,a);if(!N&&!k&&(f=g+1),N&&k&&(y=g-1),!N&&k){b=C;break}v++}return b||m},t9=t=>{var e=gi(t)?[]:t.toString().split(Bne);return[{words:e,width:void 0}]},W5e=t=>{var{width:e,scaleToFit:n,children:r,style:a,breakAll:s,maxLines:o}=t;if((e||n)&&!Fw.isSsr){var l,c,u=Hne({breakAll:s,children:r,style:a});if(u){var{wordsWithComputedWidth:d,spaceWidth:m}=u;l=d,c=m}else return t9(r);return G5e({breakAll:s,children:r,maxLines:o,style:a},l,c,e,!!n)}return t9(r)},Vne="#808080",K5e={angle:0,breakAll:!1,capHeight:"0.71em",fill:Vne,lineHeight:"1em",scaleToFit:!1,textAnchor:"start",verticalAnchor:"end",x:0,y:0},uA=w.forwardRef((t,e)=>{var n=wi(t,K5e),{x:r,y:a,lineHeight:s,capHeight:o,fill:l,scaleToFit:c,textAnchor:u,verticalAnchor:d}=n,m=JG(n,B5e),p=w.useMemo(()=>W5e({breakAll:m.breakAll,children:m.children,maxLines:m.maxLines,scaleToFit:c,style:m.style,width:m.width}),[m.breakAll,m.children,m.maxLines,c,m.style,m.width]),{dx:f,dy:y,angle:v,className:b,breakAll:g}=m,_=JG(m,H5e);if(!Kl(r)||!Kl(a)||p.length===0)return null;var N=Number(r)+(Yt(f)?f:0),C=Number(a)+(Yt(y)?y:0);if(!Ln(N)||!Ln(C))return null;var k;switch(d){case"start":k=L2("calc(".concat(o,")"));break;case"middle":k=L2("calc(".concat((p.length-1)/2," * -").concat(s," + (").concat(o," / 2))"));break;default:k=L2("calc(".concat(p.length-1," * -").concat(s,")"));break}var P=[],T=p[0];if(c&&T!=null){var D=T.width,{width:A}=m;P.push("scale(".concat(Yt(A)&&Yt(D)?A/D:1,")"))}return v&&P.push("rotate(".concat(v,", ").concat(N,", ").concat(C,")")),P.length&&(_.transform=P.join(" ")),w.createElement("text",NF({},ls(_),{ref:e,x:N,y:C,className:hr("recharts-text",b),textAnchor:u,fill:l.includes("url")?Vne:l}),p.map((R,G)=>{var z=R.words.join(g?"":" ");return w.createElement("tspan",{x:N,dy:G===0?k:s,key:"".concat(z,"-").concat(G)},z)}))});uA.displayName="Text";function n9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Qc(t){for(var e=1;e{var{viewBox:e,position:n,offset:r=0,parentViewBox:a}=t,{x:s,y:o,height:l,upperWidth:c,lowerWidth:u}=ZO(e),d=s,m=s+(c-u)/2,p=(d+m)/2,f=(c+u)/2,y=d+c/2,v=l>=0?1:-1,b=v*r,g=v>0?"end":"start",_=v>0?"start":"end",N=c>=0?1:-1,C=N*r,k=N>0?"end":"start",P=N>0?"start":"end",T=a;if(n==="top"){var D={x:d+c/2,y:o-b,horizontalAnchor:"middle",verticalAnchor:g};return T&&(D.height=Math.max(o-T.y,0),D.width=c),D}if(n==="bottom"){var A={x:m+u/2,y:o+l+b,horizontalAnchor:"middle",verticalAnchor:_};return T&&(A.height=Math.max(T.y+T.height-(o+l),0),A.width=u),A}if(n==="left"){var R={x:p-C,y:o+l/2,horizontalAnchor:k,verticalAnchor:"middle"};return T&&(R.width=Math.max(R.x-T.x,0),R.height=l),R}if(n==="right"){var G={x:p+f+C,y:o+l/2,horizontalAnchor:P,verticalAnchor:"middle"};return T&&(G.width=Math.max(T.x+T.width-G.x,0),G.height=l),G}var z=T?{width:f,height:l}:{};return n==="insideLeft"?Qc({x:p+C,y:o+l/2,horizontalAnchor:P,verticalAnchor:"middle"},z):n==="insideRight"?Qc({x:p+f-C,y:o+l/2,horizontalAnchor:k,verticalAnchor:"middle"},z):n==="insideTop"?Qc({x:d+c/2,y:o+b,horizontalAnchor:"middle",verticalAnchor:_},z):n==="insideBottom"?Qc({x:m+u/2,y:o+l-b,horizontalAnchor:"middle",verticalAnchor:g},z):n==="insideTopLeft"?Qc({x:d+C,y:o+b,horizontalAnchor:P,verticalAnchor:_},z):n==="insideTopRight"?Qc({x:d+c-C,y:o+b,horizontalAnchor:k,verticalAnchor:_},z):n==="insideBottomLeft"?Qc({x:m+C,y:o+l-b,horizontalAnchor:P,verticalAnchor:g},z):n==="insideBottomRight"?Qc({x:m+u-C,y:o+l-b,horizontalAnchor:k,verticalAnchor:g},z):n&&typeof n=="object"&&(Yt(n.x)||Hf(n.x))&&(Yt(n.y)||Hf(n.y))?Qc({x:s+ws(n.x,f),y:o+ws(n.y,l),horizontalAnchor:"end",verticalAnchor:"end"},z):Qc({x:y,y:o+l/2,horizontalAnchor:"middle",verticalAnchor:"middle"},z)},J5e=["labelRef"],eze=["content"];function r9(t,e){if(t==null)return{};var n,r,a=tze(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var{x:e,y:n,upperWidth:r,lowerWidth:a,width:s,height:o,children:l}=t,c=w.useMemo(()=>({x:e,y:n,upperWidth:r,lowerWidth:a,width:s,height:o}),[e,n,r,a,s,o]);return w.createElement(Gne.Provider,{value:c},l)},Kne=()=>{var t=w.useContext(Gne),e=jw();return t||(e?ZO(e):void 0)},aze=w.createContext(null),sze=()=>{var t=w.useContext(aze),e=en(Fte);return t||e},oze=t=>{var{value:e,formatter:n}=t,r=gi(t.children)?e:t.children;return typeof n=="function"?n(r):r},h4=t=>t!=null&&typeof t=="function",lze=(t,e)=>{var n=Fa(e-t),r=Math.min(Math.abs(e-t),360);return n*r},cze=(t,e,n,r,a)=>{var{offset:s,className:o}=t,{cx:l,cy:c,innerRadius:u,outerRadius:d,startAngle:m,endAngle:p,clockWise:f}=a,y=(u+d)/2,v=lze(m,p),b=v>=0?1:-1,g,_;switch(e){case"insideStart":g=m+b*s,_=f;break;case"insideEnd":g=p-b*s,_=!f;break;case"end":g=p+b*s,_=f;break;default:throw new Error("Unsupported position ".concat(e))}_=v<=0?_:!_;var N=aa(l,c,y,g),C=aa(l,c,y,g+(_?1:-1)*359),k="M".concat(N.x,",").concat(N.y,` A`).concat(y,",").concat(y,",0,1,").concat(_?0:1,`, - `).concat(C.x,",").concat(C.y),P=gi(t.id)?O0("recharts-radial-line-"):t.id;return w.createElement("text",vd({},r,{dominantBaseline:"central",className:hr("recharts-radial-bar-label",o)}),w.createElement("defs",null,w.createElement("path",{id:P,d:k})),w.createElement("textPath",{xlinkHref:"#".concat(P)},n))},uze=(t,e,n)=>{var{cx:r,cy:a,innerRadius:s,outerRadius:o,startAngle:l,endAngle:c}=t,u=(l+c)/2;if(n==="outside"){var{x:d,y:m}=aa(r,a,o+e,u);return{x:d,y:m,textAnchor:d>=r?"start":"end",verticalAnchor:"middle"}}if(n==="center")return{x:r,y:a,textAnchor:"middle",verticalAnchor:"middle"};if(n==="centerTop")return{x:r,y:a,textAnchor:"middle",verticalAnchor:"start"};if(n==="centerBottom")return{x:r,y:a,textAnchor:"middle",verticalAnchor:"end"};var p=(s+o)/2,{x:f,y}=aa(r,a,p,u);return{x:f,y,textAnchor:"middle",verticalAnchor:"middle"}},gN=t=>t!=null&&"cx"in t&&Yt(t.cx),dze={angle:0,offset:5,zIndex:Fi.label,position:"middle",textBreakAll:!1};function mze(t){if(!gN(t))return t;var{cx:e,cy:n,outerRadius:r}=t,a=r*2;return{x:e-r,y:n-r,width:a,upperWidth:a,lowerWidth:a,height:a}}function Jm(t){var e=wi(t,dze),{viewBox:n,parentViewBox:r,position:a,value:s,children:o,content:l,className:c="",textBreakAll:u,labelRef:d}=e,m=sze(),p=Kne(),f=a==="center"?p:m??p,y,v,b;n==null?y=f:gN(n)?y=n:y=ZO(n);var g=mze(y);if(!y||gi(s)&&gi(o)&&!w.isValidElement(l)&&typeof l!="function")return null;var _=Ov(Ov({},e),{},{viewBox:y});if(w.isValidElement(l)){var{labelRef:N}=_,C=r9(_,J5e);return w.cloneElement(l,C)}if(typeof l=="function"){var{content:k}=_,P=r9(_,eze);if(v=w.createElement(l,P),w.isValidElement(v))return v}else v=oze(e);var T=ls(e);if(gN(y)){if(a==="insideStart"||a==="insideEnd"||a==="end")return cze(e,a,v,T,y);b=uze(y,e.offset,e.position)}else{if(!g)return null;var D=Z5e({viewBox:g,position:a,offset:e.offset,parentViewBox:gN(r)?void 0:r});b=Ov(Ov({x:D.x,y:D.y,textAnchor:D.horizontalAnchor,verticalAnchor:D.verticalAnchor},D.width!==void 0?{width:D.width}:{}),D.height!==void 0?{height:D.height}:{})}return w.createElement(Ns,{zIndex:e.zIndex},w.createElement(uA,vd({ref:d,className:hr("recharts-label",c)},T,b,{textAnchor:q5e(T.textAnchor)?T.textAnchor:b.textAnchor,breakAll:u}),v))}Jm.displayName="Label";var hze=(t,e,n)=>{if(!t)return null;var r={viewBox:e,labelRef:n};return t===!0?w.createElement(Jm,vd({key:"label-implicit"},r)):Kl(t)?w.createElement(Jm,vd({key:"label-implicit",value:t},r)):w.isValidElement(t)?t.type===Jm?w.cloneElement(t,Ov({key:"label-implicit"},r)):w.createElement(Jm,vd({key:"label-implicit",content:t},r)):hI(t)?w.createElement(Jm,vd({key:"label-implicit",content:t},r)):t&&typeof t=="object"?w.createElement(Jm,vd({},t,{key:"label-implicit"},r)):null};function Yne(t){var{label:e,labelRef:n}=t,r=Kne();return hze(e,r,n)||null}var Oj={},Ij={},a9;function pze(){return a9||(a9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n[n.length-1]}t.last=e})(Ij)),Ij}var zj={},s9;function fze(){return s9||(s9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Array.isArray(n)?n:Array.from(n)}t.toArray=e})(zj)),zj}var o9;function gze(){return o9||(o9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=pze(),n=fze(),r=BO();function a(s){if(r.isArrayLike(s))return e.last(n.toArray(s))}t.last=a})(Oj)),Oj}var Uj,l9;function bze(){return l9||(l9=1,Uj=gze().last),Uj}var xze=bze();const yze=Zl(xze);var vze=["valueAccessor"],wze=["dataKey","clockWise","id","textBreakAll","zIndex"];function Vk(){return Vk=Object.assign?Object.assign.bind():function(t){for(var e=1;eArray.isArray(t.value)?yze(t.value):t.value,Xne=w.createContext(void 0),pI=Xne.Provider,Qne=w.createContext(void 0),Nze=Qne.Provider;function kze(){return w.useContext(Xne)}function Cze(){return w.useContext(Qne)}function bN(t){var{valueAccessor:e=_ze}=t,n=c9(t,vze),{dataKey:r,clockWise:a,id:s,textBreakAll:o,zIndex:l}=n,c=c9(n,wze),u=kze(),d=Cze(),m=u||d;return!m||!m.length?null:w.createElement(Ns,{zIndex:l??Fi.label},w.createElement(vi,{className:"recharts-label-list"},m.map((p,f)=>{var y,v=gi(r)?e(p,f):Tr(p.payload,r),b=gi(s)?{}:{id:"".concat(s,"-").concat(f)};return w.createElement(Jm,Vk({key:"label-".concat(f)},ls(p),c,b,{fill:(y=n.fill)!==null&&y!==void 0?y:p.fill,parentViewBox:p.parentViewBox,value:v,textBreakAll:o,viewBox:p.viewBox,index:f,zIndex:0}))})))}bN.displayName="LabelList";function dA(t){var{label:e}=t;return e?e===!0?w.createElement(bN,{key:"labelList-implicit"}):w.isValidElement(e)||hI(e)?w.createElement(bN,{key:"labelList-implicit",content:e}):typeof e=="object"?w.createElement(bN,Vk({key:"labelList-implicit"},e,{type:String(e.type)})):null:null}function kF(){return kF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{cx:e,cy:n,r,className:a}=t,s=hr("recharts-dot",a);return Yt(e)&&Yt(n)&&Yt(r)?w.createElement("circle",kF({},Ys(t),UO(t),{className:s,cx:e,cy:n,r})):null},Jne=t=>t.graphicalItems.polarItems,Tze=yt([Si,Bw],O4),mA=yt([Jne,Ii,Tze],I4),Aze=yt([mA],z4),hA=yt([Aze,QT],U4),Pze=yt([hA,Ii,mA],H4);yt([hA,Ii,mA],(t,e,n)=>n.length>0?t.flatMap(r=>n.flatMap(a=>{var s,o=Tr(r,(s=e.dataKey)!==null&&s!==void 0?s:a.dataKey);return{value:o,errorDomain:[]}})).filter(Boolean):e?.dataKey!=null?t.map(r=>({value:Tr(r,e.dataKey),errorDomain:[]})):t.map(r=>({value:r,errorDomain:[]})));var u9=()=>{},Mze=yt([hA,Ii,mA,sA,Si],G4),Eze=yt([Ii,q4,V4,u9,Mze,u9,dr,Si],W4),ere=yt([Ii,dr,hA,Pze,Uw,Si,Eze],K4),jze=yt([ere,iy,ep],Q4),Dze=yt([Ii,ere,jze,Si],J4);yt([ep,Dze],Ote);var Rze={radiusAxis:{},angleAxis:{}},tre=Ao({name:"polarAxis",initialState:Rze,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:wit,removeRadiusAxis:Sit,addAngleAxis:_it,removeAngleAxis:Nit}=tre.actions,Fze=tre.reducer;function nre(t){return t&&typeof t=="object"&&"className"in t&&typeof t.className=="string"?t.className:""}function d9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function m9(t){for(var e=1;ee,fI=yt([Jne,zze],(t,e)=>t.filter(n=>n.type==="pie").find(n=>n.id===e)),Uze=[],gI=(t,e,n)=>n?.length===0?Uze:n,rre=yt([QT,fI,gI],(t,e,n)=>{var{chartData:r}=t;if(e!=null){var a;if(e?.data!=null&&e.data.length>0?a=e.data:a=r,(!a||!a.length)&&n!=null&&(a=n.map(s=>m9(m9({},e.presentationProps),s.props))),a!=null)return a}}),Bze=yt([rre,fI,gI],(t,e,n)=>{if(!(t==null||e==null))return t.map((r,a)=>{var s,o=Tr(r,e.nameKey,e.name),l;return n!=null&&(s=n[a])!==null&&s!==void 0&&(s=s.props)!==null&&s!==void 0&&s.fill?l=n[a].props.fill:typeof r=="object"&&r!=null&&"fill"in r?l=r.fill:l=e.fill,{value:Xh(o,e.dataKey),color:l,payload:r,type:e.legendType}})}),Hze=yt([rre,fI,gI,va],(t,e,n,r)=>{if(!(e==null||t==null))return $Ue({offset:r,pieSettings:e,displayedData:t,cells:n})}),Bj={exports:{}},zr={};var h9;function $ze(){if(h9)return zr;h9=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),a=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"),m=Symbol.for("react.lazy"),p=Symbol.for("react.view_transition"),f=Symbol.for("react.client.reference");function y(v){if(typeof v=="object"&&v!==null){var b=v.$$typeof;switch(b){case t:switch(v=v.type,v){case n:case a:case r:case c:case u:case p:return v;default:switch(v=v&&v.$$typeof,v){case o:case l:case m:case d:return v;case s:return v;default:return b}}case e:return b}}}return zr.ContextConsumer=s,zr.ContextProvider=o,zr.Element=t,zr.ForwardRef=l,zr.Fragment=n,zr.Lazy=m,zr.Memo=d,zr.Portal=e,zr.Profiler=a,zr.StrictMode=r,zr.Suspense=c,zr.SuspenseList=u,zr.isContextConsumer=function(v){return y(v)===s},zr.isContextProvider=function(v){return y(v)===o},zr.isElement=function(v){return typeof v=="object"&&v!==null&&v.$$typeof===t},zr.isForwardRef=function(v){return y(v)===l},zr.isFragment=function(v){return y(v)===n},zr.isLazy=function(v){return y(v)===m},zr.isMemo=function(v){return y(v)===d},zr.isPortal=function(v){return y(v)===e},zr.isProfiler=function(v){return y(v)===a},zr.isStrictMode=function(v){return y(v)===r},zr.isSuspense=function(v){return y(v)===c},zr.isSuspenseList=function(v){return y(v)===u},zr.isValidElementType=function(v){return typeof v=="string"||typeof v=="function"||v===n||v===a||v===r||v===c||v===u||typeof v=="object"&&v!==null&&(v.$$typeof===m||v.$$typeof===d||v.$$typeof===o||v.$$typeof===s||v.$$typeof===l||v.$$typeof===f||v.getModuleId!==void 0)},zr.typeOf=y,zr}var p9;function qze(){return p9||(p9=1,Bj.exports=$ze()),Bj.exports}var Vze=qze(),f9=t=>typeof t=="string"?t:t?t.displayName||t.name||"Component":"",g9=null,Hj=null,ire=t=>{if(t===g9&&Array.isArray(Hj))return Hj;var e=[];return w.Children.forEach(t,n=>{gi(n)||(Vze.isFragment(n)?e=e.concat(ire(n.props.children)):e.push(n))}),Hj=e,g9=t,e};function bI(t,e){var n=[],r=[];return Array.isArray(e)?r=e.map(a=>f9(a)):r=[f9(e)],ire(t).forEach(a=>{var s=Bf(a,"type.displayName")||Bf(a,"type.name");s&&r.indexOf(s)!==-1&&n.push(a)}),n}var xI=t=>t&&typeof t=="object"&&"clipDot"in t?!!t.clipDot:!0,$j={},b9;function Gze(){return b9||(b9=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 a=n[Symbol.toStringTag];return a==null||!Object.getOwnPropertyDescriptor(n,Symbol.toStringTag)?.writable?!1:n.toString()===`[object ${a}]`}let r=n;for(;Object.getPrototypeOf(r)!==null;)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(n)===r}t.isPlainObject=e})($j)),$j}var qj,x9;function Wze(){return x9||(x9=1,qj=Gze().isPlainObject),qj}var Kze=Wze();const Yze=Zl(Kze);var y9,v9,w9,S9,_9;function N9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function k9(t){for(var e=1;e{var s=n-r,o;return o=Mi(y9||(y9=Sv(["M ",",",""])),t,e),o+=Mi(v9||(v9=Sv(["L ",",",""])),t+n,e),o+=Mi(w9||(w9=Sv(["L ",",",""])),t+n-s/2,e+a),o+=Mi(S9||(S9=Sv(["L ",",",""])),t+n-s/2-r,e+a),o+=Mi(_9||(_9=Sv(["L ",","," Z"])),t,e),o},Jze={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},eUe=t=>{var e=wi(t,Jze),{x:n,y:r,upperWidth:a,lowerWidth:s,height:o,className:l}=e,{animationEasing:c,animationDuration:u,animationBegin:d,isUpdateAnimationActive:m}=e,p=w.useRef(null),[f,y]=w.useState(-1),v=w.useRef(a),b=w.useRef(s),g=w.useRef(o),_=w.useRef(n),N=w.useRef(r),C=Jx(t,"trapezoid-");if(w.useEffect(()=>{if(p.current&&p.current.getTotalLength)try{var I=p.current.getTotalLength();I&&y(I)}catch{}},[]),n!==+n||r!==+r||a!==+a||s!==+s||o!==+o||a===0&&s===0||o===0)return null;var k=hr("recharts-trapezoid",l);if(!m)return w.createElement("g",null,w.createElement("path",Gk({},ls(e),{className:k,d:C9(n,r,a,s,o)})));var P=v.current,T=b.current,D=g.current,A=_.current,R=N.current,G="0px ".concat(f===-1?1:f,"px"),z="".concat(f,"px 0px"),Z=Cee(["strokeDasharray"],u,c);return w.createElement(Zx,{animationId:C,key:C,canBegin:f>0,duration:u,easing:c,isActive:m,begin:d},I=>{var J=Cr(P,a,I),ae=Cr(T,s,I),Y=Cr(D,o,I),ue=Cr(A,n,I),de=Cr(R,r,I);p.current&&(v.current=J,b.current=ae,g.current=Y,_.current=ue,N.current=de);var he=I>0?{transition:Z,strokeDasharray:z}:{strokeDasharray:G};return w.createElement("path",Gk({},ls(e),{className:k,d:C9(ue,de,J,ae,Y),ref:p,style:k9(k9({},he),e.style)}))})},tUe=["option","shapeType","activeClassName"];function nUe(t,e){if(t==null)return{};var n,r,a=rUe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var r=Jr();return(a,s)=>o=>{t?.(a,s,o),r(hne({activeIndex:String(s),activeDataKey:e,activeCoordinate:a.tooltipPosition,activeGraphicalItemId:n}))}},wI=t=>{var e=Jr();return(n,r)=>a=>{t?.(n,r,a),e(p4e())}},SI=(t,e,n)=>{var r=Jr();return(a,s)=>o=>{t?.(a,s,o),r(f4e({activeIndex:String(s),activeDataKey:e,activeCoordinate:a.tooltipPosition,activeGraphicalItemId:n}))}};function pA(t){var{tooltipEntrySettings:e}=t,n=Jr(),r=wa(),a=w.useRef(null);return w.useLayoutEffect(()=>{r||(a.current===null?n(u4e(e)):a.current!==e&&n(d4e({prev:a.current,next:e})),a.current=e)},[e,n,r]),w.useLayoutEffect(()=>()=>{a.current&&(n(m4e(a.current)),a.current=null)},[n]),null}function _I(t){var{legendPayload:e}=t,n=Jr(),r=wa(),a=w.useRef(null);return w.useLayoutEffect(()=>{r||(a.current===null?n(wee(e)):a.current!==e&&n(See({prev:a.current,next:e})),a.current=e)},[n,r,e]),w.useLayoutEffect(()=>()=>{a.current&&(n(_ee(a.current)),a.current=null)},[n]),null}function uUe(t){var{legendPayload:e}=t,n=Jr(),r=en(dr),a=w.useRef(null);return w.useLayoutEffect(()=>{r!=="centric"&&r!=="radial"||(a.current===null?n(wee(e)):a.current!==e&&n(See({prev:a.current,next:e})),a.current=e)},[n,r,e]),w.useLayoutEffect(()=>()=>{a.current&&(n(_ee(a.current)),a.current=null)},[n]),null}var Vj,dUe=()=>{var[t]=w.useState(()=>O0("uid-"));return t},mUe=(Vj=Lce.useId)!==null&&Vj!==void 0?Vj:dUe;function hUe(t,e){var n=mUe();return e||(t?"".concat(t,"-").concat(n):n)}var pUe=w.createContext(void 0),fA=t=>{var{id:e,type:n,children:r}=t,a=hUe("recharts-".concat(n),e);return w.createElement(pUe.Provider,{value:a},r(a))},fUe={cartesianItems:[],polarItems:[]},are=Ao({name:"graphicalItems",initialState:fUe,reducers:{addCartesianGraphicalItem:{reducer(t,e){t.cartesianItems.push(e.payload)},prepare:mi()},replaceCartesianGraphicalItem:{reducer(t,e){var{prev:n,next:r}=e.payload,a=Nc(t).cartesianItems.indexOf(n);a>-1&&(t.cartesianItems[a]=r)},prepare:mi()},removeCartesianGraphicalItem:{reducer(t,e){var n=Nc(t).cartesianItems.indexOf(e.payload);n>-1&&t.cartesianItems.splice(n,1)},prepare:mi()},addPolarGraphicalItem:{reducer(t,e){t.polarItems.push(e.payload)},prepare:mi()},removePolarGraphicalItem:{reducer(t,e){var n=Nc(t).polarItems.indexOf(e.payload);n>-1&&t.polarItems.splice(n,1)},prepare:mi()}}}),{addCartesianGraphicalItem:gUe,replaceCartesianGraphicalItem:bUe,removeCartesianGraphicalItem:xUe,addPolarGraphicalItem:yUe,removePolarGraphicalItem:vUe}=are.actions,wUe=are.reducer,SUe=t=>{var e=Jr(),n=w.useRef(null);return w.useLayoutEffect(()=>{n.current===null?e(gUe(t)):n.current!==t&&e(bUe({prev:n.current,next:t})),n.current=t},[e,t]),w.useLayoutEffect(()=>()=>{n.current&&(e(xUe(n.current)),n.current=null)},[e]),null},NI=w.memo(SUe);function _Ue(t){var e=Jr();return w.useLayoutEffect(()=>(e(yUe(t)),()=>{e(vUe(t))}),[e,t]),null}var NUe=["key"],kUe=["onMouseEnter","onClick","onMouseLeave"],CUe=["id"],TUe=["id"];function P9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Ei(t){for(var e=1;ebI(t.children,Mx),[t.children]),n=en(r=>Bze(r,t.id,e));return n==null?null:w.createElement(uUe,{legendPayload:n})}var DUe=w.memo(t=>{var{dataKey:e,nameKey:n,sectors:r,stroke:a,strokeWidth:s,fill:o,name:l,hide:c,tooltipType:u,id:d}=t,m={dataDefinedOnItem:r.map(p=>p.tooltipPayload),getPosition:p=>{var f;return(f=r[Number(p)])===null||f===void 0?void 0:f.tooltipPosition},settings:{stroke:a,strokeWidth:s,fill:o,dataKey:e,nameKey:n,name:Xh(l,e),hide:c,type:u,color:o,unit:"",graphicalItemId:d}};return w.createElement(pA,{tooltipEntrySettings:m})}),RUe=(t,e)=>t>e?"start":tws(typeof e=="function"?e(t):e,n,n*.8),LUe=(t,e,n)=>{var{top:r,left:a,width:s,height:o}=e,l=Eee(s,o),c=a+ws(t.cx,s,s/2),u=r+ws(t.cy,o,o/2),d=ws(t.innerRadius,l,0),m=FUe(n,t.outerRadius,l),p=t.maxRadius||Math.sqrt(s*s+o*o)/2;return{cx:c,cy:u,innerRadius:d,outerRadius:m,maxRadius:p}},OUe=(t,e)=>{var n=Fa(e-t),r=Math.min(Math.abs(e-t),360);return n*r},IUe=(t,e)=>{if(w.isValidElement(t))return w.cloneElement(t,e);if(typeof t=="function")return t(e);var n=hr("recharts-pie-label-line",typeof t!="boolean"?t.className:""),{key:r}=e,a=gA(e,NUe);return w.createElement(nx,Gh({},a,{type:"linear",className:n}))},zUe=(t,e,n)=>{if(w.isValidElement(t))return w.cloneElement(t,e);var r=n;if(typeof t=="function"&&(r=t(e),w.isValidElement(r)))return r;var a=hr("recharts-pie-label-text",nre(t));return w.createElement(uA,Gh({},e,{alignmentBaseline:"middle",className:a}),r)};function UUe(t){var{sectors:e,props:n,showLabels:r}=t,{label:a,labelLine:s,dataKey:o}=n;if(!r||!a||!e)return null;var l=Ys(n),c=zf(a),u=zf(s),d=typeof a=="object"&&"offsetRadius"in a&&typeof a.offsetRadius=="number"&&a.offsetRadius||20,m=e.map((p,f)=>{var y=(p.startAngle+p.endAngle)/2,v=aa(p.cx,p.cy,p.outerRadius+d,y),b=Ei(Ei(Ei(Ei({},l),p),{},{stroke:"none"},c),{},{index:f,textAnchor:RUe(v.x,p.cx)},v),g=Ei(Ei(Ei(Ei({},l),p),{},{fill:"none",stroke:p.fill},u),{},{index:f,points:[aa(p.cx,p.cy,p.outerRadius,y),v],key:"line"});return w.createElement(Ns,{zIndex:Fi.label,key:"label-".concat(p.startAngle,"-").concat(p.endAngle,"-").concat(p.midAngle,"-").concat(f)},w.createElement(vi,null,s&&IUe(s,g),zUe(a,b,Tr(p,o))))});return w.createElement(vi,{className:"recharts-pie-labels"},m)}function BUe(t){var{sectors:e,props:n,showLabels:r}=t,{label:a}=n;return typeof a=="object"&&a!=null&&"position"in a?w.createElement(dA,{label:a}):w.createElement(UUe,{sectors:e,props:n,showLabels:r})}function HUe(t){var{sectors:e,activeShape:n,inactiveShape:r,allOtherPieProps:a,shape:s,id:o}=t,l=en(Vh),c=en(lI),u=en(eIe),{onMouseEnter:d,onClick:m,onMouseLeave:p}=a,f=gA(a,kUe),y=vI(d,a.dataKey,o),v=wI(p),b=SI(m,a.dataKey,o);return e==null||e.length===0?null:w.createElement(w.Fragment,null,e.map((g,_)=>{if(g?.startAngle===0&&g?.endAngle===0&&e.length!==1)return null;var N=u==null||u===o,C=String(_)===l&&(c==null||a.dataKey===c)&&N,k=l?r:null,P=n&&C?n:k,T=Ei(Ei({},g),{},{stroke:g.stroke,tabIndex:-1,[oee]:_,[lee]:o});return w.createElement(vi,Gh({key:"sector-".concat(g?.startAngle,"-").concat(g?.endAngle,"-").concat(g.midAngle,"-").concat(_),tabIndex:-1,className:"recharts-pie-sector"},Aw(f,g,_),{onMouseEnter:y(g,_),onMouseLeave:v(g,_),onClick:b(g,_)}),w.createElement(yI,Gh({option:s??P,index:_,shapeType:"sector",isActive:C},T)))}))}function $Ue(t){var e,{pieSettings:n,displayedData:r,cells:a,offset:s}=t,{cornerRadius:o,startAngle:l,endAngle:c,dataKey:u,nameKey:d,tooltipType:m}=n,p=Math.abs(n.minAngle),f=OUe(l,c),y=Math.abs(f),v=r.length<=1?0:(e=n.paddingAngle)!==null&&e!==void 0?e:0,b=r.filter(P=>Tr(P,u,0)!==0).length,g=(y>=360?b:b-1)*v,_=y-b*p-g,N=r.reduce((P,T)=>{var D=Tr(T,u,0);return P+(Yt(D)?D:0)},0),C;if(N>0){var k;C=r.map((P,T)=>{var D=Tr(P,u,0),A=Tr(P,d,T),R=LUe(n,s,P),G=(Yt(D)?D:0)/N,z,Z=Ei(Ei({},P),a&&a[T]&&a[T].props);T?z=k.endAngle+Fa(f)*v*(D!==0?1:0):z=l;var I=z+Fa(f)*((D!==0?p:0)+G*_),J=(z+I)/2,ae=(R.innerRadius+R.outerRadius)/2,Y=[{name:A,value:D,payload:Z,dataKey:u,type:m,graphicalItemId:n.id}],ue=aa(R.cx,R.cy,ae,J);return k=Ei(Ei(Ei(Ei({},n.presentationProps),{},{percent:G,cornerRadius:typeof o=="string"?parseFloat(o):o,name:A,tooltipPayload:Y,midAngle:J,middleRadius:ae,tooltipPosition:ue},Z),R),{},{value:D,dataKey:u,startAngle:z,endAngle:I,payload:Z,paddingAngle:Fa(f)*v}),k})}return C}function qUe(t){var{showLabels:e,sectors:n,children:r}=t,a=w.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 w.createElement(Nze,{value:e?a:void 0},r)}function VUe(t){var{props:e,previousSectorsRef:n,id:r}=t,{sectors:a,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,activeShape:u,inactiveShape:d,onAnimationStart:m,onAnimationEnd:p}=e,f=Jx(e,"recharts-pie-"),y=n.current,[v,b]=w.useState(!1),g=w.useCallback(()=>{typeof p=="function"&&p(),b(!1)},[p]),_=w.useCallback(()=>{typeof m=="function"&&m(),b(!0)},[m]);return w.createElement(qUe,{showLabels:!v,sectors:a},w.createElement(Zx,{animationId:f,begin:o,duration:l,isActive:s,easing:c,onAnimationStart:_,onAnimationEnd:g,key:f},N=>{var C,k=[],P=a&&a[0],T=(C=P?.startAngle)!==null&&C!==void 0?C:0;return a?.forEach((D,A)=>{var R=y&&y[A],G=A>0?Bf(D,"paddingAngle",0):0;if(R){var z=Cr(R.endAngle-R.startAngle,D.endAngle-D.startAngle,N),Z=Ei(Ei({},D),{},{startAngle:T+G,endAngle:T+z+G});k.push(Z),T=Z.endAngle}else{var{endAngle:I,startAngle:J}=D,ae=Cr(0,I-J,N),Y=Ei(Ei({},D),{},{startAngle:T+G,endAngle:T+ae+G});k.push(Y),T=Y.endAngle}}),n.current=k,w.createElement(vi,null,w.createElement(HUe,{sectors:k,activeShape:u,inactiveShape:d,allOtherPieProps:e,shape:e.shape,id:r}))}),w.createElement(BUe,{showLabels:!v,sectors:a,props:e}),e.children)}var GUe={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:Fi.area};function WUe(t){var{id:e}=t,n=gA(t,CUe),{hide:r,className:a,rootTabIndex:s}=t,o=w.useMemo(()=>bI(t.children,Mx),[t.children]),l=en(d=>Hze(d,e,o)),c=w.useRef(null),u=hr("recharts-pie",a);return r||l==null?(c.current=null,w.createElement(vi,{tabIndex:s,className:u})):w.createElement(Ns,{zIndex:t.zIndex},w.createElement(DUe,{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,id:e}),w.createElement(vi,{tabIndex:s,className:u},w.createElement(VUe,{props:Ei(Ei({},n),{},{sectors:l}),previousSectorsRef:c,id:e})))}function CF(t){var e=wi(t,GUe),{id:n}=e,r=gA(e,TUe),a=Ys(r);return w.createElement(fA,{id:n,type:"pie"},s=>w.createElement(w.Fragment,null,w.createElement(_Ue,{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:a,maxRadius:e.maxRadius}),w.createElement(jUe,Gh({},r,{id:s})),w.createElement(WUe,Gh({},r,{id:s}))))}CF.displayName="Pie";var KUe=["points"];function M9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Gj(t){for(var e=1;e{var b,g,_=Gj(Gj(Gj({r:3},o),m),{},{index:v,cx:(b=y.x)!==null&&b!==void 0?b:void 0,cy:(g=y.y)!==null&&g!==void 0?g:void 0,dataKey:s,value:y.value,payload:y.payload,points:e});return w.createElement(eBe,{key:"dot-".concat(v),option:n,dotProps:_,className:a})}),f={};return l&&c!=null&&(f.clipPath="url(#clipPath-".concat(d?"":"dots-").concat(c,")")),w.createElement(Ns,{zIndex:u},w.createElement(vi,Kk({className:r},f),p))}function E9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function j9(t){for(var e=1;e({top:t.top,bottom:t.bottom,left:t.left,right:t.right})),fBe=yt([pBe,tm,nm],(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)}}),bA=()=>en(fBe),gBe=()=>en(aIe);function D9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Wj(t){for(var e=1;e{var{point:e,childIndex:n,mainColor:r,activeDot:a,dataKey:s,clipPath:o}=t;if(a===!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=Wj(Wj(Wj({},l),zf(a)),UO(a)),u;return w.isValidElement(a)?u=w.cloneElement(a,c):typeof a=="function"?u=a(c):u=w.createElement(Zne,c),w.createElement(vi,{className:"recharts-active-dot",clipPath:o},u)};function TF(t){var{points:e,mainColor:n,activeDot:r,itemDataKey:a,clipPath:s,zIndex:o=Fi.activeDot}=t,l=en(Vh),c=gBe();if(e==null||c==null)return null;var u=e.find(d=>c.includes(d.payload));return gi(u)?null:w.createElement(Ns,{zIndex:o},w.createElement(vBe,{point:u,childIndex:Number(l),mainColor:n,dataKey:a,activeDot:r,clipPath:s}))}var R9=(t,e,n)=>{var r=n??t;if(!gi(r))return ws(r,e,0)},wBe=(t,e,n)=>{var r={},a=t.filter(nA),s=t.filter(u=>u.stackId==null),o=a.reduce((u,d)=>{var m=u[d.stackId];return m==null&&(m=[]),m.push(d),u[d.stackId]=m,u},r),l=Object.entries(o).map(u=>{var d,[m,p]=u,f=p.map(v=>v.dataKey),y=R9(e,n,(d=p[0])===null||d===void 0?void 0:d.barSize);return{stackId:m,dataKeys:f,barSize:y}}),c=s.map(u=>{var d=[u.dataKey].filter(p=>p!=null),m=R9(e,n,u.barSize);return{stackId:void 0,dataKeys:d,barSize:m}});return[...l,...c]};function F9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function P1(t){for(var e=1;e_+(N.barSize||0),0);p+=(o-1)*l,p>=n&&(p-=(o-1)*l,l=0),p>=n&&m>0&&(d=!0,m*=.9,p=o*m);var f=(n-p)/2>>0,y={offset:f-l,size:0};c=r.reduce((_,N)=>{var C,k={stackId:N.stackId,dataKeys:N.dataKeys,position:{offset:y.offset+y.size+l,size:d?m:(C=N.barSize)!==null&&C!==void 0?C:0}},P=[..._,k];return y=k.position,P},u)}else{var v=ws(e,n,0,!0);n-2*v-(o-1)*l<=0&&(l=0);var b=(n-2*v-(o-1)*l)/o;b>1&&(b>>=0);var g=Ln(a)?Math.min(b,a):b;c=r.reduce((_,N,C)=>[..._,{stackId:N.stackId,dataKeys:N.dataKeys,position:{offset:v+(b+l)*C+(b-g)/2,size:g}}],u)}return c}}var CBe=(t,e,n,r,a,s,o)=>{var l=gi(o)?e:o,c=kBe(n,r,a!==s?a:s,t,l);return a!==s&&c!=null&&(c=c.map(u=>P1(P1({},u),{},{position:P1(P1({},u.position),{},{offset:u.position.offset-a/2})}))),c},TBe=(t,e)=>{var n=tA(e);if(!(!t||n==null||e==null)){var{stackId:r}=e;if(r!=null){var a=t[r];if(a){var{stackedData:s}=a;if(s)return s.find(o=>o.key===n)}}}},ABe=(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}};function PBe(t,e){return t&&typeof t=="object"&&"zIndex"in t&&typeof t.zIndex=="number"&&Ln(t.zIndex)?t.zIndex:e}var cre=t=>{var{chartData:e}=t,n=Jr(),r=wa();return w.useEffect(()=>r?()=>{}:(n(BG(e)),()=>{n(BG(void 0))}),[e,n,r]),null},L9={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},ure=Ao({name:"brush",initialState:L9,reducers:{setBrushSettings(t,e){return e.payload==null?L9:e.payload}}}),{setBrushSettings:Ait}=ure.actions,MBe=ure.reducer,EBe=(t,e)=>{var{x:n,y:r}=t,{x:a,y:s}=e;return{x:Math.min(n,a),y:Math.min(r,s),width:Math.abs(a-n),height:Math.abs(s-r)}},jBe=t=>{var{x1:e,y1:n,x2:r,y2:a}=t;return EBe({x:e,y:n},{x:r,y:a})};function DBe(t){return(t%180+180)%180}var RBe=function(e){var{width:n,height:r}=e,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,s=DBe(a),o=s*Math.PI/180,l=Math.atan(r/n),c=o>l&&o{t.dots.push(e.payload)},removeDot:(t,e)=>{var n=Nc(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=Nc(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=Nc(t).lines.findIndex(r=>r===e.payload);n!==-1&&t.lines.splice(n,1)}}}),{addDot:Pit,removeDot:Mit,addArea:Eit,removeArea:jit,addLine:LBe,removeLine:OBe}=dre.actions,IBe=dre.reducer,mre=w.createContext(void 0),zBe=t=>{var{children:e}=t,[n]=w.useState("".concat(O0("recharts"),"-clip")),r=bA();if(r==null)return null;var{x:a,y:s,width:o,height:l}=r;return w.createElement(mre.Provider,{value:n},w.createElement("defs",null,w.createElement("clipPath",{id:n},w.createElement("rect",{x:a,y:s,height:l,width:o}))),e)},UBe=()=>w.useContext(mre);class BBe{constructor(e){var{x:n,y:r}=e;this.xAxisScale=n,this.yAxisScale=r}map(e,n){var r,a,{position:s}=n;return{x:(r=this.xAxisScale.map(e.x,{position:s}))!==null&&r!==void 0?r:0,y:(a=this.yAxisScale.map(e.y,{position:s}))!==null&&a!==void 0?a:0}}mapWithFallback(e,n){var r,a,{position:s,fallback:o}=n,l,c;return o==="rangeMin"?l=this.yAxisScale.rangeMin():o==="rangeMax"?l=this.yAxisScale.rangeMax():l=0,o==="rangeMin"?c=this.xAxisScale.rangeMin():o==="rangeMax"?c=this.xAxisScale.rangeMax():c=0,{x:(r=this.xAxisScale.map(e.x,{position:s}))!==null&&r!==void 0?r:c,y:(a=this.yAxisScale.map(e.y,{position:s}))!==null&&a!==void 0?a:l}}isInRange(e){var{x:n,y:r}=e,a=n==null||this.xAxisScale.isInRange(n),s=r==null||this.yAxisScale.isInRange(r);return a&&s}}function O9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function I9(t){for(var e=1;e{var n;if(w.isValidElement(t))n=w.cloneElement(t,e);else if(typeof t=="function")n=t(e);else{if(!Ln(e.x1)||!Ln(e.y1)||!Ln(e.x2)||!Ln(e.y2))return null;n=w.createElement("line",Yk({},e,{className:"recharts-reference-line-line"}))}return n},GBe=(t,e,n,r,a,s)=>{var{x:o,width:l}=s,c=a.map(t,{position:n});if(!Ln(c)||e==="discard"&&!a.isInRange(c))return null;var u=[{x:o+l,y:c},{x:o,y:c}];return r==="left"?u.reverse():u},WBe=(t,e,n,r,a,s)=>{var{y:o,height:l}=s,c=a.map(t,{position:n});if(!Ln(c)||e==="discard"&&!a.isInRange(c))return null;var u=[{x:c,y:o+l},{x:c,y:o}];return r==="top"?u.reverse():u},KBe=(t,e,n,r)=>{var a=[r.mapWithFallback(t[0],{position:n,fallback:"rangeMin"}),r.mapWithFallback(t[1],{position:n,fallback:"rangeMax"})];return e==="discard"&&a.some(s=>!r.isInRange(s))?null:a},YBe=(t,e,n,r,a,s,o)=>{var{x:l,y:c,segment:u,ifOverflow:d}=o,m=Kl(l),p=Kl(c);return p?GBe(c,d,r,s,e,n):m?WBe(l,d,r,a,t,n):u!=null&&u.length===2?KBe(u,d,r,new BBe({x:t,y:e})):null};function XBe(t){var e=Jr();return w.useEffect(()=>(e(LBe(t)),()=>{e(OBe(t))})),null}function QBe(t){var{xAxisId:e,yAxisId:n,shape:r,className:a,ifOverflow:s}=t,o=wa(),l=UBe(),c=en(T=>Au(T,e)),u=en(T=>Pu(T,n)),d=en(T=>Px(T,"xAxis",e,o)),m=en(T=>Px(T,"yAxis",n,o)),p=jw();if(!l||!p||c==null||u==null||d==null||m==null)return null;var f=YBe(d,m,p,t.position,c.orientation,u.orientation,t);if(!f)return null;var y=f[0],v=f[1];if(y==null||v==null)return null;var{x:b,y:g}=y,{x:_,y:N}=v,C=s==="hidden"?"url(#".concat(l,")"):void 0,k=I9(I9({clipPath:C},ls(t)),{},{x1:b,y1:g,x2:_,y2:N}),P=jBe({x1:b,y1:g,x2:_,y2:N});return w.createElement(Ns,{zIndex:t.zIndex},w.createElement(vi,{className:hr("recharts-reference-line",a)},VBe(r,k),w.createElement(Wne,Yk({},P,{lowerWidth:P.width,upperWidth:P.width}),w.createElement(Yne,{label:t.label}),t.children)))}var ZBe={ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",label:!1,stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle",zIndex:Fi.line};function Iv(t){var e=wi(t,ZBe);return w.createElement(w.Fragment,null,w.createElement(XBe,{yAxisId:e.yAxisId,xAxisId:e.xAxisId,ifOverflow:e.ifOverflow,x:e.x,y:e.y,segment:e.segment}),w.createElement(QBe,e))}Iv.displayName="ReferenceLine";function hre(t,e){if(e<1)return[];if(e===1)return t;for(var n=[],r=0;rt*a)return!1;var s=n();return t*(e-t*s/2-r)>=0&&t*(e+t*s/2-a)<=0}function t8e(t,e){return hre(t,e+1)}function n8e(t,e,n,r,a){for(var s=(r||[]).slice(),{start:o,end:l}=e,c=0,u=1,d=o,m=function(){var y=r?.[c];if(y===void 0)return{v:hre(r,u)};var v=c,b,g=()=>(b===void 0&&(b=n(y,v)),b),_=y.coordinate,N=c===0||Q0(t,_,g,d,l);N||(c=0,d=o,u+=1),N&&(d=_+t*(g()/2+a),c+=u)},p;u<=s.length;)if(p=m(),p)return p.v;return[]}function r8e(t,e,n,r,a){var s=(r||[]).slice(),o=s.length;if(o===0)return[];for(var{start:l,end:c}=e,u=1;u<=o;u++){for(var d=(o-1)%u,m=l,p=!0,f=function(){var C=r[v];if(C==null)return 0;var k=v,P,T=()=>(P===void 0&&(P=n(C,k)),P),D=C.coordinate,A=v===d||Q0(t,D,T,m,c);if(!A)return p=!1,1;A&&(m=D+t*(T()/2+a))},y,v=d;v(v===void 0&&(v=n(f,p)),v);if(p===o-1){var g=t*(y.coordinate+t*b()/2-c);s[p]=y=gs(gs({},y),{},{tickCoord:g>0?y.coordinate-g*t:y.coordinate})}else s[p]=y=gs(gs({},y),{},{tickCoord:y.coordinate});if(y.tickCoord!=null){var _=Q0(t,y.tickCoord,b,l,c);_&&(c=y.tickCoord-t*(b()/2+a),s[p]=gs(gs({},y),{},{isShow:!0}))}},d=o-1;d>=0;d--)u(d);return s}function l8e(t,e,n,r,a,s){var o=(r||[]).slice(),l=o.length,{start:c,end:u}=e;if(s){var d=r[l-1];if(d!=null){var m=n(d,l-1),p=t*(d.coordinate+t*m/2-u);if(o[l-1]=d=gs(gs({},d),{},{tickCoord:p>0?d.coordinate-p*t:d.coordinate}),d.tickCoord!=null){var f=Q0(t,d.tickCoord,()=>m,c,u);f&&(u=d.tickCoord-t*(m/2+a),o[l-1]=gs(gs({},d),{},{isShow:!0}))}}}for(var y=s?l-1:l,v=function(_){var N=o[_];if(N==null)return 1;var C=N,k,P=()=>(k===void 0&&(k=n(N,_)),k);if(_===0){var T=t*(C.coordinate-t*P()/2-c);o[_]=C=gs(gs({},C),{},{tickCoord:T<0?C.coordinate-T*t:C.coordinate})}else o[_]=C=gs(gs({},C),{},{tickCoord:C.coordinate});if(C.tickCoord!=null){var D=Q0(t,C.tickCoord,P,c,u);D&&(c=C.tickCoord+t*(P()/2+a),o[_]=gs(gs({},C),{},{isShow:!0}))}},b=0;b{var T=typeof u=="function"?u(k.value,P):k.value;return y==="width"?JBe(Jv(T,{fontSize:e,letterSpacing:n}),v,m):Jv(T,{fontSize:e,letterSpacing:n})[y]},g=a[0],_=a[1],N=a.length>=2&&g!=null&&_!=null?Fa(_.coordinate-g.coordinate):1,C=e8e(s,N,y);return c==="equidistantPreserveStart"?n8e(N,C,b,a,o):c==="equidistantPreserveEnd"?r8e(N,C,b,a,o):(c==="preserveStart"||c==="preserveStartEnd"?f=l8e(N,C,b,a,o,c==="preserveStartEnd"):f=o8e(N,C,b,a,o),f.filter(k=>k.isShow))}var c8e=t=>{var{ticks:e,label:n,labelGapWithTick:r=5,tickSize:a=0,tickMargin:s=0}=t,o=0;if(e){Array.from(e).forEach(d=>{if(d){var m=d.getBoundingClientRect();m.width>o&&(o=m.width)}});var l=n?n.getBoundingClientRect().width:0,c=a+s,u=o+c+l+(n?r:0);return Math.round(u)}return 0},u8e=["axisLine","width","height","className","hide","ticks","axisType"];function d8e(t,e){if(t==null)return{};var n,r,a=m8e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var{ticks:n=[],tick:r,tickLine:a,stroke:s,tickFormatter:o,unit:l,padding:c,tickTextProps:u,orientation:d,mirror:m,x:p,y:f,width:y,height:v,tickSize:b,tickMargin:g,fontSize:_,letterSpacing:N,getTicksConfig:C,events:k,axisType:P}=t,T=kI(Pi(Pi({},C),{},{ticks:n}),_,N),D=x8e(d,m),A=y8e(d,m),R=Ys(C),G=zf(r),z={};typeof a=="object"&&(z=a);var Z=Pi(Pi({},R),{},{fill:"none"},z),I=T.map(Y=>Pi({entry:Y},b8e(Y,p,f,y,v,d,b,m,g))),J=I.map(Y=>{var{entry:ue,line:de}=Y;return w.createElement(vi,{className:"recharts-cartesian-axis-tick",key:"tick-".concat(ue.value,"-").concat(ue.coordinate,"-").concat(ue.tickCoord)},a&&w.createElement("line",Wf({},Z,de,{className:hr("recharts-cartesian-axis-tick-line",Bf(a,"className"))})))}),ae=I.map((Y,ue)=>{var de,he,{entry:V,tick:ne}=Y,se=Pi(Pi(Pi(Pi({verticalAnchor:A},R),{},{textAnchor:D,stroke:"none",fill:s},ne),{},{index:ue,payload:V,visibleTicksCount:T.length,tickFormatter:o,padding:c},u),{},{angle:(de=(he=u?.angle)!==null&&he!==void 0?he:R.angle)!==null&&de!==void 0?de:0}),pe=Pi(Pi({},se),G);return w.createElement(vi,Wf({className:"recharts-cartesian-axis-tick-label",key:"tick-label-".concat(V.value,"-").concat(V.coordinate,"-").concat(V.tickCoord)},Aw(k,V,ue)),r&&w.createElement(v8e,{option:r,tickProps:pe,value:"".concat(typeof o=="function"?o(V.value,ue):V.value).concat(l||"")}))});return w.createElement("g",{className:"recharts-cartesian-axis-ticks recharts-".concat(P,"-ticks")},ae.length>0&&w.createElement(Ns,{zIndex:Fi.label},w.createElement("g",{className:"recharts-cartesian-axis-tick-labels recharts-".concat(P,"-tick-labels"),ref:e},ae)),J.length>0&&w.createElement("g",{className:"recharts-cartesian-axis-tick-lines recharts-".concat(P,"-tick-lines")},J))}),S8e=w.forwardRef((t,e)=>{var{axisLine:n,width:r,height:a,className:s,hide:o,ticks:l,axisType:c}=t,u=d8e(t,u8e),[d,m]=w.useState(""),[p,f]=w.useState(""),y=w.useRef(null);w.useImperativeHandle(e,()=>({getCalculatedWidth:()=>{var b;return c8e({ticks:y.current,label:(b=t.labelRef)===null||b===void 0?void 0:b.current,labelGapWithTick:5,tickSize:t.tickSize,tickMargin:t.tickMargin})}}));var v=w.useCallback(b=>{if(b){var g=b.getElementsByClassName("recharts-cartesian-axis-tick-value");y.current=g;var _=g[0];if(_){var N=window.getComputedStyle(_),C=N.fontSize,k=N.letterSpacing;(C!==d||k!==p)&&(m(C),f(k))}}},[d,p]);return o||r!=null&&r<=0||a!=null&&a<=0?null:w.createElement(Ns,{zIndex:t.zIndex},w.createElement(vi,{className:hr("recharts-cartesian-axis",s)},w.createElement(g8e,{x:t.x,y:t.y,width:r,height:a,orientation:t.orientation,mirror:t.mirror,axisLine:n,otherSvgProps:Ys(t)}),w.createElement(w8e,{ref:v,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}),w.createElement(Wne,{x:t.x,y:t.y,width:t.width,height:t.height,lowerWidth:t.width,upperWidth:t.width},w.createElement(Yne,{label:t.label,labelRef:t.labelRef}),t.children)))}),CI=w.forwardRef((t,e)=>{var n=wi(t,Fd);return w.createElement(S8e,Wf({},n,{ref:e}))});CI.displayName="CartesianAxis";var _8e=["x1","y1","x2","y2","key"],N8e=["offset"],k8e=["xAxisId","yAxisId"],C8e=["xAxisId","yAxisId"];function B9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function ys(t){for(var e=1;e{var{fill:e}=t;if(!e||e==="none")return null;var{fillOpacity:n,x:r,y:a,width:s,height:o,ry:l}=t;return w.createElement("rect",{x:r,y:a,ry:l,width:s,height:o,stroke:"none",fill:e,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function pre(t){var{option:e,lineItemProps:n}=t,r;if(w.isValidElement(e))r=w.cloneElement(e,n);else if(typeof e=="function")r=e(n);else{var a,{x1:s,y1:o,x2:l,y2:c,key:u}=n,d=Xk(n,_8e),m=(a=Ys(d))!==null&&a!==void 0?a:{},{offset:p}=m,f=Xk(m,N8e);r=w.createElement("line",nf({},f,{x1:s,y1:o,x2:l,y2:c,fill:"none",key:u}))}return r}function j8e(t){var{x:e,width:n,horizontal:r=!0,horizontalPoints:a}=t;if(!r||!a||!a.length)return null;var{xAxisId:s,yAxisId:o}=t,l=Xk(t,k8e),c=a.map((u,d)=>{var m=ys(ys({},l),{},{x1:e,y1:u,x2:e+n,y2:u,key:"line-".concat(d),index:d});return w.createElement(pre,{key:"line-".concat(d),option:r,lineItemProps:m})});return w.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function D8e(t){var{y:e,height:n,vertical:r=!0,verticalPoints:a}=t;if(!r||!a||!a.length)return null;var{xAxisId:s,yAxisId:o}=t,l=Xk(t,C8e),c=a.map((u,d)=>{var m=ys(ys({},l),{},{x1:u,y1:e,x2:u,y2:e+n,key:"line-".concat(d),index:d});return w.createElement(pre,{option:r,lineItemProps:m,key:"line-".concat(d)})});return w.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function R8e(t){var{horizontalFill:e,fillOpacity:n,x:r,y:a,width:s,height:o,horizontalPoints:l,horizontal:c=!0}=t;if(!c||!e||!e.length||l==null)return null;var u=l.map(m=>Math.round(m+a-a)).sort((m,p)=>m-p);a!==u[0]&&u.unshift(0);var d=u.map((m,p)=>{var f=u[p+1],y=f==null,v=y?a+o-m:f-m;if(v<=0)return null;var b=p%e.length;return w.createElement("rect",{key:"react-".concat(p),y:m,x:r,height:v,width:s,stroke:"none",fill:e[b],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return w.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},d)}function F8e(t){var{vertical:e=!0,verticalFill:n,fillOpacity:r,x:a,y:s,width:o,height:l,verticalPoints:c}=t;if(!e||!n||!n.length)return null;var u=c.map(m=>Math.round(m+a-a)).sort((m,p)=>m-p);a!==u[0]&&u.unshift(0);var d=u.map((m,p)=>{var f=u[p+1],y=f==null,v=y?a+o-m:f-m;if(v<=0)return null;var b=p%n.length;return w.createElement("rect",{key:"react-".concat(p),x:m,y:s,width:v,height:l,stroke:"none",fill:n[b],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return w.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},d)}var L8e=(t,e)=>{var{xAxis:n,width:r,height:a,offset:s}=t;return ree(kI(ys(ys(ys({},Fd),n),{},{ticks:iee(n),viewBox:{x:0,y:0,width:r,height:a}})),s.left,s.left+s.width,e)},O8e=(t,e)=>{var{yAxis:n,width:r,height:a,offset:s}=t;return ree(kI(ys(ys(ys({},Fd),n),{},{ticks:iee(n),viewBox:{x:0,y:0,width:r,height:a}})),s.top,s.top+s.height,e)},I8e={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:Fi.grid};function rf(t){var e=JO(),n=e4(),r=mee(),a=ys(ys({},wi(t,I8e)),{},{x:Yt(t.x)?t.x:r.left,y:Yt(t.y)?t.y:r.top,width:Yt(t.width)?t.width:r.width,height:Yt(t.height)?t.height:r.height}),{xAxisId:s,yAxisId:o,x:l,y:c,width:u,height:d,syncWithTicks:m,horizontalValues:p,verticalValues:f}=a,y=wa(),v=en(A=>PG(A,"xAxis",s,y)),b=en(A=>PG(A,"yAxis",o,y));if(!vu(u)||!vu(d)||!Yt(l)||!Yt(c))return null;var g=a.verticalCoordinatesGenerator||L8e,_=a.horizontalCoordinatesGenerator||O8e,{horizontalPoints:N,verticalPoints:C}=a;if((!N||!N.length)&&typeof _=="function"){var k=p&&p.length,P=_({yAxis:b?ys(ys({},b),{},{ticks:k?p:b.ticks}):void 0,width:e??u,height:n??d,offset:r},k?!0:m);vk(Array.isArray(P),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(typeof P,"]")),Array.isArray(P)&&(N=P)}if((!C||!C.length)&&typeof g=="function"){var T=f&&f.length,D=g({xAxis:v?ys(ys({},v),{},{ticks:T?f:v.ticks}):void 0,width:e??u,height:n??d,offset:r},T?!0:m);vk(Array.isArray(D),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(typeof D,"]")),Array.isArray(D)&&(C=D)}return w.createElement(Ns,{zIndex:a.zIndex},w.createElement("g",{className:"recharts-cartesian-grid"},w.createElement(E8e,{fill:a.fill,fillOpacity:a.fillOpacity,x:a.x,y:a.y,width:a.width,height:a.height,ry:a.ry}),w.createElement(R8e,nf({},a,{horizontalPoints:N})),w.createElement(F8e,nf({},a,{verticalPoints:C})),w.createElement(j8e,nf({},a,{offset:r,horizontalPoints:N,xAxis:v,yAxis:b})),w.createElement(D8e,nf({},a,{offset:r,verticalPoints:C,xAxis:v,yAxis:b}))))}rf.displayName="CartesianGrid";var z8e={},fre=Ao({name:"errorBars",initialState:z8e,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:a}=e.payload;t[n]&&(t[n]=t[n].map(s=>s.dataKey===r.dataKey&&s.direction===r.direction?a:s))},removeErrorBar:(t,e)=>{var{itemId:n,errorBar:r}=e.payload;t[n]&&(t[n]=t[n].filter(a=>a.dataKey!==r.dataKey||a.direction!==r.direction))}}}),{addErrorBar:Dit,replaceErrorBar:Rit,removeErrorBar:Fit}=fre.actions,U8e=fre.reducer,B8e=["children"];function H8e(t,e){if(t==null)return{};var n,r,a=$8e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r({x:0,y:0,value:0}),errorBarOffset:0},V8e=w.createContext(q8e);function gre(t){var{children:e}=t,n=H8e(t,B8e);return w.createElement(V8e.Provider,{value:n},e)}function xA(t,e){var n,r,a=en(u=>Au(u,t)),s=en(u=>Pu(u,e)),o=(n=a?.allowDataOverflow)!==null&&n!==void 0?n:Ma.allowDataOverflow,l=(r=s?.allowDataOverflow)!==null&&r!==void 0?r:Ea.allowDataOverflow,c=o||l;return{needClip:c,needClipX:o,needClipY:l}}function TI(t){var{xAxisId:e,yAxisId:n,clipPathId:r}=t,a=bA(),{needClipX:s,needClipY:o,needClip:l}=xA(e,n);if(!l||!a)return null;var{x:c,y:u,width:d,height:m}=a;return w.createElement("clipPath",{id:"clipPath-".concat(r)},w.createElement("rect",{x:s?c:c-d/2,y:o?u:u-m/2,width:s?d:d*2,height:o?m:m*2}))}var bre=(t,e,n,r)=>_u(t,"xAxis",e,r),xre=(t,e,n,r)=>Su(t,"xAxis",e,r),yre=(t,e,n,r)=>_u(t,"yAxis",n,r),vre=(t,e,n,r)=>Su(t,"yAxis",n,r),G8e=yt([dr,bre,yre,xre,vre],(t,e,n,r,a)=>Fc(t,"xAxis")?qh(e,r,!1):qh(n,a,!1)),W8e=(t,e,n,r,a)=>a;function K8e(t){return t.type==="line"}var Y8e=yt([Hw,W8e],(t,e)=>t.filter(K8e).find(n=>n.id===e)),X8e=yt([dr,bre,yre,xre,vre,Y8e,G8e,T4],(t,e,n,r,a,s,o,l)=>{var{chartData:c,dataStartIndex:u,dataEndIndex:d}=l;if(!(s==null||e==null||n==null||r==null||a==null||r.length===0||a.length===0||o==null||t!=="horizontal"&&t!=="vertical")){var{dataKey:m,data:p}=s,f;if(p!=null&&p.length>0?f=p:f=c?.slice(u,d+1),f!=null)return L6e({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:a,dataKey:m,bandSize:o,displayedData:f})}});function wre(t){var e=zf(t),n=3,r=2;if(e!=null){var{r:a,strokeWidth:s}=e,o=Number(a),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 Kj={exports:{}},Yj={};var H9;function Q8e(){if(H9)return Yj;H9=1;var t=Jf();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,a=t.useRef,s=t.useEffect,o=t.useMemo,l=t.useDebugValue;return Yj.useSyncExternalStoreWithSelector=function(c,u,d,m,p){var f=a(null);if(f.current===null){var y={hasValue:!1,value:null};f.current=y}else y=f.current;f=o(function(){function b(k){if(!g){if(g=!0,_=k,k=m(k),p!==void 0&&y.hasValue){var P=y.value;if(p(P,k))return N=P}return N=k}if(P=N,n(_,k))return P;var T=m(k);return p!==void 0&&p(P,T)?(_=k,P):(_=k,N=T)}var g=!1,_,N,C=d===void 0?null:d;return[function(){return b(u())},C===null?void 0:function(){return b(C())}]},[u,d,m,p]);var v=r(c,f[0],f[1]);return s(function(){y.hasValue=!0,y.value=v},[v]),l(v),v},Yj}var $9;function Z8e(){return $9||($9=1,Kj.exports=Q8e()),Kj.exports}Z8e();function J8e(t){t()}function e6e(){let t=null,e=null;return{clear(){t=null,e=null},notify(){J8e(()=>{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 a=e={callback:n,next:null,prev:e};return a.prev?a.prev.next=a:t=a,function(){!r||t===null||(r=!1,a.next?a.next.prev=a.prev:e=a.prev,a.prev?a.prev.next=a.next:t=a.next)}}}}var q9={notify(){},get:()=>[]};function t6e(t,e){let n,r=q9,a=0,s=!1;function o(v){d();const b=r.subscribe(v);let g=!1;return()=>{g||(g=!0,b(),m())}}function l(){r.notify()}function c(){y.onStateChange&&y.onStateChange()}function u(){return s}function d(){a++,n||(n=t.subscribe(c),r=e6e())}function m(){a--,n&&a===0&&(n(),n=void 0,r.clear(),r=q9)}function p(){s||(s=!0,d())}function f(){s&&(s=!1,m())}const y={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:u,trySubscribe:p,tryUnsubscribe:f,getListeners:()=>r};return y}var n6e=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",r6e=n6e(),i6e=()=>typeof navigator<"u"&&navigator.product==="ReactNative",a6e=i6e(),s6e=()=>r6e||a6e?w.useLayoutEffect:w.useEffect,o6e=s6e();function V9(t,e){return t===e?t!==0||e!==0||1/t===1/e:t!==t&&e!==e}function l6e(t,e){if(V9(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 a=0;a{const c=t6e(a);return{store:a,subscription:c,getServerState:r?()=>r:void 0}},[a,r]),o=w.useMemo(()=>a.getState(),[a]);o6e(()=>{const{subscription:c}=s;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),o!==a.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[s,o]);const l=n||m6e;return w.createElement(l.Provider,{value:s},e)}var p6e=h6e,f6e=new Set(["axisLine","tickLine","activeBar","activeDot","activeLabel","activeShape","allowEscapeViewBox","background","cursor","dot","label","line","margin","padding","position","shape","style","tick","wrapperStyle","radius"]);function g6e(t,e){return t==null&&e==null?!0:typeof t=="number"&&typeof e=="number"?t===e||t!==t&&e!==e:t===e}function Kw(t,e){var n=new Set([...Object.keys(t),...Object.keys(e)]);for(var r of n)if(f6e.has(r)){if(t[r]==null&&e[r]==null)continue;if(!l6e(t[r],e[r]))return!1}else if(!g6e(t[r],e[r]))return!1;return!0}var b6e=["id"],x6e=["type","layout","connectNulls","needClip","shape"],y6e=["activeDot","animateNewValues","animationBegin","animationDuration","animationEasing","connectNulls","dot","hide","isAnimationActive","label","legendType","xAxisId","yAxisId","id"];function Z0(){return Z0=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{dataKey:e,name:n,stroke:r,legendType:a,hide:s}=t;return[{inactive:s,dataKey:e,type:a,color:r,value:Xh(n,e),payload:t}]},k6e=w.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:a,fill:s,name:o,hide:l,unit:c,tooltipType:u,id:d}=t,m={dataDefinedOnItem:n,getPosition:Yh,settings:{stroke:r,strokeWidth:a,fill:s,dataKey:e,nameKey:void 0,name:Xh(o,e),hide:l,type:u,color:r,unit:c,graphicalItemId:d}};return w.createElement(pA,{tooltipEntrySettings:m})}),Sre=(t,e)=>"".concat(e,"px ").concat(t-e,"px");function C6e(t,e){for(var n=t.length%2!==0?[...t,0]:t,r=[],a=0;a{var r=n.reduce((f,y)=>f+y);if(!r)return Sre(e,t);for(var a=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 p=l.length%2===0?[0,o]:[o];return[...C6e(n,a),...l,...p].map(f=>"".concat(f,"px")).join(", ")};function A6e(t){var{clipPathId:e,points:n,props:r}=t,{dot:a,dataKey:s,needClip:o}=r,{id:l}=r,c=AI(r,b6e),u=Ys(c);return w.createElement(sre,{points:n,dot:a,className:"recharts-line-dots",dotClassName:"recharts-line-dot",dataKey:s,baseProps:u,needClip:o,clipPathId:e})}function P6e(t){var{showLabels:e,children:n,points:r}=t,a=w.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 iu(iu({},c),{},{value:s.value,payload:s.payload,viewBox:c,parentViewBox:void 0,fill:void 0})}),[r]);return w.createElement(pI,{value:e?a:void 0},n)}function W9(t){var{clipPathId:e,pathRef:n,points:r,strokeDasharray:a,props:s}=t,{type:o,layout:l,connectNulls:c,needClip:u,shape:d}=s,m=AI(s,x6e),p=iu(iu({},ls(m)),{},{fill:"none",className:"recharts-line-curve",clipPath:u?"url(#clipPath-".concat(e,")"):void 0,points:r,type:o,layout:l,connectNulls:c,strokeDasharray:a??s.strokeDasharray});return w.createElement(w.Fragment,null,r?.length>1&&w.createElement(yI,Z0({shapeType:"curve",option:d},p,{pathRef:n})),w.createElement(A6e,{points:r,clipPathId:e,props:s}))}function M6e(t){try{return t&&t.getTotalLength&&t.getTotalLength()||0}catch{return 0}}function E6e(t){var{clipPathId:e,props:n,pathRef:r,previousPointsRef:a,longestAnimatedLengthRef:s}=t,{points:o,strokeDasharray:l,isAnimationActive:c,animationBegin:u,animationDuration:d,animationEasing:m,animateNewValues:p,width:f,height:y,onAnimationEnd:v,onAnimationStart:b}=n,g=a.current,_=Jx(o,"recharts-line-"),N=w.useRef(_),[C,k]=w.useState(!1),P=!C,T=w.useCallback(()=>{typeof v=="function"&&v(),k(!1)},[v]),D=w.useCallback(()=>{typeof b=="function"&&b(),k(!0)},[b]),A=M6e(r.current),R=w.useRef(0);N.current!==_&&(R.current=s.current,N.current=_);var G=R.current;return w.createElement(P6e,{points:o,showLabels:P},n.children,w.createElement(Zx,{animationId:_,begin:u,duration:d,isActive:c,easing:m,onAnimationEnd:T,onAnimationStart:D,key:_},z=>{var Z=Cr(G,A+G,z),I=Math.min(Z,A),J;if(c)if(l){var ae="".concat(l).split(/[,\s]+/gim).map(de=>parseFloat(de));J=T6e(I,A,ae)}else J=Sre(A,I);else J=l==null?void 0:String(l);if(z>0&&A>0&&(a.current=o,s.current=Math.max(s.current,I)),g){var Y=g.length/o.length,ue=z===1?o:o.map((de,he)=>{var V=Math.floor(he*Y);if(g[V]){var ne=g[V];return iu(iu({},de),{},{x:Cr(ne.x,de.x,z),y:Cr(ne.y,de.y,z)})}return p?iu(iu({},de),{},{x:Cr(f*2,de.x,z),y:Cr(y/2,de.y,z)}):iu(iu({},de),{},{x:de.x,y:de.y})});return a.current=ue,w.createElement(W9,{props:n,points:ue,clipPathId:e,pathRef:r,strokeDasharray:J})}return w.createElement(W9,{props:n,points:o,clipPathId:e,pathRef:r,strokeDasharray:J})}),w.createElement(dA,{label:n.label}))}function j6e(t){var{clipPathId:e,props:n}=t,r=w.useRef(null),a=w.useRef(0),s=w.useRef(null);return w.createElement(E6e,{props:n,clipPathId:e,previousPointsRef:r,longestAnimatedLengthRef:a,pathRef:s})}var D6e=(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:Tr(t.payload,e)}};class R6e extends w.Component{render(){var{hide:e,dot:n,points:r,className:a,xAxisId:s,yAxisId:o,top:l,left:c,width:u,height:d,id:m,needClip:p,zIndex:f}=this.props;if(e)return null;var y=hr("recharts-line",a),v=m,{r:b,strokeWidth:g}=wre(n),_=xI(n),N=b*2+g,C=p?"url(#clipPath-".concat(_?"":"dots-").concat(v,")"):void 0;return w.createElement(Ns,{zIndex:f},w.createElement(vi,{className:y},p&&w.createElement("defs",null,w.createElement(TI,{clipPathId:v,xAxisId:s,yAxisId:o}),!_&&w.createElement("clipPath",{id:"clipPath-dots-".concat(v)},w.createElement("rect",{x:c-N/2,y:l-N/2,width:u+N,height:d+N}))),w.createElement(gre,{xAxisId:s,yAxisId:o,data:r,dataPointFormatter:D6e,errorBarOffset:0},w.createElement(j6e,{props:this.props,clipPathId:v}))),w.createElement(TF,{activeDot:this.props.activeDot,points:r,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:C}))}}var _re={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:Fi.line,type:"linear"};function F6e(t){var e=wi(t,_re),{activeDot:n,animateNewValues:r,animationBegin:a,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,hide:u,isAnimationActive:d,label:m,legendType:p,xAxisId:f,yAxisId:y,id:v}=e,b=AI(e,y6e),{needClip:g}=xA(f,y),_=bA(),N=Qh(),C=wa(),k=en(R=>X8e(R,f,y,C,v));if(N!=="horizontal"&&N!=="vertical"||k==null||_==null)return null;var{height:P,width:T,x:D,y:A}=_;return w.createElement(R6e,Z0({},b,{id:v,connectNulls:l,dot:c,activeDot:n,animateNewValues:r,animationBegin:a,animationDuration:s,animationEasing:o,isAnimationActive:d,hide:u,label:m,legendType:p,xAxisId:f,yAxisId:y,points:k,layout:N,height:P,width:T,left:D,top:A,needClip:g}))}function L6e(t){var{layout:e,xAxis:n,yAxis:r,xAxisTicks:a,yAxisTicks:s,dataKey:o,bandSize:l,displayedData:c}=t;return c.map((u,d)=>{var m=Tr(u,o);if(e==="horizontal"){var p=yk({axis:n,ticks:a,bandSize:l,entry:u,index:d}),f=gi(m)?null:r.scale.map(m);return{x:p,y:f??null,value:m,payload:u}}var y=gi(m)?null:n.scale.map(m),v=yk({axis:r,ticks:s,bandSize:l,entry:u,index:d});return y==null||v==null?null:{x:y,y:v,value:m,payload:u}}).filter(Boolean)}function O6e(t){var e=wi(t,_re),n=wa();return w.createElement(fA,{id:e.id,type:"line"},r=>w.createElement(w.Fragment,null,w.createElement(_I,{legendPayload:N6e(e)}),w.createElement(k6e,{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,id:r}),w.createElement(NI,{type:"line",id:r,data:e.data,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,hide:e.hide,isPanorama:n}),w.createElement(F6e,Z0({},e,{id:r}))))}var Nre=w.memo(O6e,Kw);Nre.displayName="Line";function Mu(t,e){var n,r;return(n=(r=t.graphicalItems.cartesianItems.find(a=>a.id===e))===null||r===void 0?void 0:r.xAxisId)!==null&&n!==void 0?n:ore}function Eu(t,e){var n,r;return(n=(r=t.graphicalItems.cartesianItems.find(a=>a.id===e))===null||r===void 0?void 0:r.yAxisId)!==null&&n!==void 0?n:ore}var kre=(t,e,n)=>_u(t,"xAxis",Mu(t,e),n),Cre=(t,e,n)=>Su(t,"xAxis",Mu(t,e),n),Tre=(t,e,n)=>_u(t,"yAxis",Eu(t,e),n),Are=(t,e,n)=>Su(t,"yAxis",Eu(t,e),n),I6e=yt([dr,kre,Tre,Cre,Are],(t,e,n,r,a)=>Fc(t,"xAxis")?qh(e,r,!1):qh(n,a,!1)),z6e=(t,e)=>e,Pre=yt([Hw,z6e],(t,e)=>t.filter(n=>n.type==="area").find(n=>n.id===e)),Mre=t=>{var e=dr(t),n=Fc(e,"xAxis");return n?"yAxis":"xAxis"},U6e=(t,e)=>{var n=Mre(t);return n==="yAxis"?Eu(t,e):Mu(t,e)},B6e=(t,e,n)=>Hk(t,Mre(t),U6e(t,e),n),H6e=yt([Pre,B6e],(t,e)=>{var n;if(!(t==null||e==null)){var{stackId:r}=t,a=tA(t);if(!(r==null||a==null)){var s=(n=e[r])===null||n===void 0?void 0:n.stackedData,o=s?.find(l=>l.key===a);if(o!=null)return o.map(l=>[l[0],l[1]])}}}),$6e=yt([dr,kre,Tre,Cre,Are,H6e,fte,I6e,Pre,eOe],(t,e,n,r,a,s,o,l,c,u)=>{var{chartData:d,dataStartIndex:m,dataEndIndex:p}=o;if(!(c==null||t!=="horizontal"&&t!=="vertical"||e==null||n==null||r==null||a==null||r.length===0||a.length===0||l==null)){var{data:f}=c,y;if(f&&f.length>0?y=f:y=d?.slice(m,p+1),y!=null)return lHe({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:a,dataStartIndex:m,areaSettings:c,stackedData:s,displayedData:y,chartBaseValue:u,bandSize:l})}}),q6e=["id"],V6e=["activeDot","animationBegin","animationDuration","animationEasing","connectNulls","dot","fill","fillOpacity","hide","isAnimationActive","legendType","stroke","xAxisId","yAxisId"];function yf(){return yf=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{dataKey:e,name:n,stroke:r,fill:a,legendType:s,hide:o}=t;return[{inactive:o,dataKey:e,type:s,color:Qk(r,a),value:Xh(n,e),payload:t}]},Q6e=w.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:a,fill:s,name:o,hide:l,unit:c,tooltipType:u,id:d}=t,m={dataDefinedOnItem:n,getPosition:Yh,settings:{stroke:r,strokeWidth:a,fill:s,dataKey:e,nameKey:void 0,name:Xh(o,e),hide:l,type:u,color:Qk(r,s),unit:c,graphicalItemId:d}};return w.createElement(pA,{tooltipEntrySettings:m})});function Z6e(t){var{clipPathId:e,points:n,props:r}=t,{needClip:a,dot:s,dataKey:o}=r,l=Ys(r);return w.createElement(sre,{points:n,dot:s,className:"recharts-area-dots",dotClassName:"recharts-area-dot",dataKey:o,baseProps:l,needClip:a,clipPathId:e})}function J6e(t){var{showLabels:e,children:n,points:r}=t,a=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 qb(qb({},c),{},{value:s.value,payload:s.payload,parentViewBox:void 0,viewBox:c,fill:void 0})});return w.createElement(pI,{value:e?a:void 0},n)}function Y9(t){var{points:e,baseLine:n,needClip:r,clipPathId:a,props:s}=t,{layout:o,type:l,stroke:c,connectNulls:u,isRange:d}=s,{id:m}=s,p=Ere(s,q6e),f=Ys(p),y=ls(p);return w.createElement(w.Fragment,null,e?.length>1&&w.createElement(vi,{clipPath:r?"url(#clipPath-".concat(a,")"):void 0},w.createElement(nx,yf({},y,{id:m,points:e,connectNulls:u,type:l,baseLine:n,layout:o,stroke:"none",className:"recharts-area-area"})),c!=="none"&&w.createElement(nx,yf({},f,{className:"recharts-area-curve",layout:o,type:l,connectNulls:u,fill:"none",points:e})),c!=="none"&&d&&w.createElement(nx,yf({},f,{className:"recharts-area-curve",layout:o,type:l,connectNulls:u,fill:"none",points:n}))),w.createElement(Z6e,{points:e,props:p,clipPathId:a}))}function eHe(t){var e,n,{alpha:r,baseLine:a,points:s,strokeWidth:o}=t,l=(e=s[0])===null||e===void 0?void 0:e.y,c=(n=s[s.length-1])===null||n===void 0?void 0:n.y;if(!Ln(l)||!Ln(c))return null;var u=r*Math.abs(l-c),d=Math.max(...s.map(m=>m.x||0));return Yt(a)?d=Math.max(a,d):a&&Array.isArray(a)&&a.length&&(d=Math.max(...a.map(m=>m.x||0),d)),Yt(d)?w.createElement("rect",{x:0,y:lm.y||0));return Yt(a)?d=Math.max(a,d):a&&Array.isArray(a)&&a.length&&(d=Math.max(...a.map(m=>m.y||0),d)),Yt(d)?w.createElement("rect",{x:l({points:o,baseLine:l}),[o,l]),v=Jx(y,"recharts-area-"),b=t4(),[g,_]=w.useState(!1),N=!g,C=w.useCallback(()=>{typeof f=="function"&&f(),_(!1)},[f]),k=w.useCallback(()=>{typeof p=="function"&&p(),_(!0)},[p]);if(b==null)return null;var P=a.current,T=s.current;return w.createElement(J6e,{showLabels:N,points:o},r.children,w.createElement(Zx,{animationId:v,begin:u,duration:d,isActive:c,easing:m,onAnimationEnd:C,onAnimationStart:k,key:v},D=>{if(P){var A=P.length/o.length,R=D===1?o:o.map((z,Z)=>{var I=Math.floor(Z*A);if(P[I]){var J=P[I];return qb(qb({},z),{},{x:Cr(J.x,z.x,D),y:Cr(J.y,z.y,D)})}return z}),G;return Yt(l)?G=Cr(T,l,D):gi(l)||Mc(l)?G=Cr(T,0,D):G=l.map((z,Z)=>{var I=Math.floor(Z*A);if(Array.isArray(T)&&T[I]){var J=T[I];return qb(qb({},z),{},{x:Cr(J.x,z.x,D),y:Cr(J.y,z.y,D)})}return z}),D>0&&(a.current=R,s.current=G),w.createElement(Y9,{points:R,baseLine:G,needClip:e,clipPathId:n,props:r})}return D>0&&(a.current=o,s.current=l),w.createElement(vi,null,c&&w.createElement("defs",null,w.createElement("clipPath",{id:"animationClipPath-".concat(n)},w.createElement(nHe,{alpha:D,points:o,baseLine:l,layout:b,strokeWidth:r.strokeWidth}))),w.createElement(vi,{clipPath:"url(#animationClipPath-".concat(n,")")},w.createElement(Y9,{points:o,baseLine:l,needClip:e,clipPathId:n,props:r})))}),w.createElement(dA,{label:r.label}))}function iHe(t){var{needClip:e,clipPathId:n,props:r}=t,a=w.useRef(null),s=w.useRef();return w.createElement(rHe,{needClip:e,clipPathId:n,props:r,previousPointsRef:a,previousBaselineRef:s})}class aHe extends w.PureComponent{render(){var{hide:e,dot:n,points:r,className:a,top:s,left:o,needClip:l,xAxisId:c,yAxisId:u,width:d,height:m,id:p,baseLine:f,zIndex:y}=this.props;if(e)return null;var v=hr("recharts-area",a),b=p,{r:g,strokeWidth:_}=wre(n),N=xI(n),C=g*2+_,k=l?"url(#clipPath-".concat(N?"":"dots-").concat(b,")"):void 0;return w.createElement(Ns,{zIndex:y},w.createElement(vi,{className:v},l&&w.createElement("defs",null,w.createElement(TI,{clipPathId:b,xAxisId:c,yAxisId:u}),!N&&w.createElement("clipPath",{id:"clipPath-dots-".concat(b)},w.createElement("rect",{x:o-C/2,y:s-C/2,width:d+C,height:m+C}))),w.createElement(iHe,{needClip:l,clipPathId:b,props:this.props})),w.createElement(TF,{points:r,mainColor:Qk(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:k}),this.props.isRange&&Array.isArray(f)&&w.createElement(TF,{points:f,mainColor:Qk(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:k}))}}var jre={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:Fi.area};function sHe(t){var e,n=wi(t,jre),{activeDot:r,animationBegin:a,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,fill:u,fillOpacity:d,hide:m,isAnimationActive:p,legendType:f,stroke:y,xAxisId:v,yAxisId:b}=n,g=Ere(n,V6e),_=Qh(),N=Mne(),{needClip:C}=xA(v,b),k=wa(),{points:P,isRange:T,baseLine:D}=(e=en(I=>$6e(I,t.id,k)))!==null&&e!==void 0?e:{},A=bA();if(_!=="horizontal"&&_!=="vertical"||A==null||N!=="AreaChart"&&N!=="ComposedChart")return null;var{height:R,width:G,x:z,y:Z}=A;return!P||!P.length?null:w.createElement(aHe,yf({},g,{activeDot:r,animationBegin:a,animationDuration:s,animationEasing:o,baseLine:D,connectNulls:l,dot:c,fill:u,fillOpacity:d,height:R,hide:m,layout:_,isAnimationActive:p==="auto"?!Fw.isSsr:p,isRange:T,legendType:f,needClip:C,points:P,stroke:y,width:G,left:z,top:Z,xAxisId:v,yAxisId:b}))}var oHe=(t,e,n,r,a)=>{var s=n??e;if(Yt(s))return s;var o=t==="horizontal"?a: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 lHe(t){var{areaSettings:{connectNulls:e,baseValue:n,dataKey:r},stackedData:a,layout:s,chartBaseValue:o,xAxis:l,yAxis:c,displayedData:u,dataStartIndex:d,xAxisTicks:m,yAxisTicks:p,bandSize:f}=t,y=a&&a.length,v=oHe(s,o,n,l,c),b=s==="horizontal",g=!1,_=u.map((C,k)=>{var P,T,D,A;if(y)A=a[d+k];else{var R=Tr(C,r);Array.isArray(R)?(A=R,g=!0):A=[v,R]}var G=(P=(T=A)===null||T===void 0?void 0:T[1])!==null&&P!==void 0?P:null,z=G==null||y&&!e&&Tr(C,r)==null;if(b){var Z;return{x:yk({axis:l,ticks:m,bandSize:f,entry:C,index:k}),y:z?null:(Z=c.scale.map(G))!==null&&Z!==void 0?Z:null,value:A,payload:C}}return{x:z?null:(D=l.scale.map(G))!==null&&D!==void 0?D:null,y:yk({axis:c,ticks:p,bandSize:f,entry:C,index:k}),value:A,payload:C}}),N;return y||g?N=_.map(C=>{var k,P=Array.isArray(C.value)?C.value[0]:null;if(b){var T;return{x:C.x,y:P!=null&&C.y!=null&&(T=c.scale.map(P))!==null&&T!==void 0?T:null,payload:C.payload}}return{x:P!=null&&(k=l.scale.map(P))!==null&&k!==void 0?k:null,y:C.y,payload:C.payload}}):N=b?c.scale.map(v):l.scale.map(v),{points:_,baseLine:N??0,isRange:g}}function cHe(t){var e=wi(t,jre),n=wa();return w.createElement(fA,{id:e.id,type:"area"},r=>w.createElement(w.Fragment,null,w.createElement(_I,{legendPayload:X6e(e)}),w.createElement(Q6e,{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,id:r}),w.createElement(NI,{type:"area",id:r,data:e.data,dataKey:e.dataKey,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,stackId:aee(e.stackId),hide:e.hide,barSize:void 0,baseValue:e.baseValue,isPanorama:n,connectNulls:e.connectNulls}),w.createElement(sHe,yf({},e,{id:r}))))}var Dre=w.memo(cHe,Kw);Dre.displayName="Area";var uHe="Invariant failed";function dHe(t,e){throw new Error(uHe)}function AF(){return AF=Object.assign?Object.assign.bind():function(t){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:0;return(r,a)=>{if(Yt(e))return e;var s=Yt(r)||gi(r);return s?e(r,a):(s||dHe(),n)}},hHe=(t,e,n)=>n,pHe=(t,e)=>e,Yw=yt([Hw,pHe],(t,e)=>t.filter(n=>n.type==="bar").find(n=>n.id===e)),fHe=yt([Yw],t=>t?.maxBarSize),gHe=(t,e,n,r)=>r,bHe=yt([dr,Hw,Mu,Eu,hHe],(t,e,n,r,a)=>e.filter(s=>t==="horizontal"?s.xAxisId===n:s.yAxisId===r).filter(s=>s.isPanorama===a).filter(s=>s.hide===!1).filter(s=>s.type==="bar")),xHe=(t,e,n)=>{var r=dr(t),a=Mu(t,e),s=Eu(t,e);if(!(a==null||s==null))return r==="horizontal"?Hk(t,"yAxis",s,n):Hk(t,"xAxis",a,n)},yHe=(t,e)=>{var n=dr(t),r=Mu(t,e),a=Eu(t,e);if(!(r==null||a==null))return n==="horizontal"?AG(t,"xAxis",r):AG(t,"yAxis",a)},vHe=yt([bHe,JLe,yHe],wBe),wHe=(t,e,n)=>{var r,a,s=Yw(t,e);if(s==null)return 0;var o=Mu(t,e),l=Eu(t,e);if(o==null||l==null)return 0;var c=dr(t),u=Tte(t),{maxBarSize:d}=s,m=gi(d)?u:d,p,f;return c==="horizontal"?(p=_u(t,"xAxis",o,n),f=Su(t,"xAxis",o,n)):(p=_u(t,"yAxis",l,n),f=Su(t,"yAxis",l,n)),(r=(a=qh(p,f,!0))!==null&&a!==void 0?a:m)!==null&&r!==void 0?r:0},Rre=(t,e,n)=>{var r=dr(t),a=Mu(t,e),s=Eu(t,e);if(!(a==null||s==null)){var o,l;return r==="horizontal"?(o=_u(t,"xAxis",a,n),l=Su(t,"xAxis",a,n)):(o=_u(t,"yAxis",s,n),l=Su(t,"yAxis",s,n)),qh(o,l)}},SHe=yt([vHe,Tte,ZLe,Ate,wHe,Rre,fHe],CBe),_He=(t,e,n)=>{var r=Mu(t,e);if(r!=null)return _u(t,"xAxis",r,n)},NHe=(t,e,n)=>{var r=Eu(t,e);if(r!=null)return _u(t,"yAxis",r,n)},kHe=(t,e,n)=>{var r=Mu(t,e);if(r!=null)return Su(t,"xAxis",r,n)},CHe=(t,e,n)=>{var r=Eu(t,e);if(r!=null)return Su(t,"yAxis",r,n)},THe=yt([SHe,Yw],ABe),AHe=yt([xHe,Yw],TBe),PHe=yt([va,XO,_He,NHe,kHe,CHe,THe,dr,fte,Rre,AHe,Yw,gHe],(t,e,n,r,a,s,o,l,c,u,d,m,p)=>{var{chartData:f,dataStartIndex:y,dataEndIndex:v}=c;if(!(m==null||o==null||e==null||l!=="horizontal"&&l!=="vertical"||n==null||r==null||a==null||s==null||u==null)){var{data:b}=m,g;if(b!=null&&b.length>0?g=b:g=f?.slice(y,v+1),g!=null)return r$e({layout:l,barSettings:m,pos:o,parentViewBox:e,bandSize:u,xAxis:n,yAxis:r,xAxisTicks:a,yAxisTicks:s,stackedData:d,displayedData:g,offset:t,cells:p,dataStartIndex:y})}}),MHe=["index"];function PF(){return PF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var e=w.useContext(Fre);if(e!=null)return e.stackId;if(t!=null)return aee(t)},RHe=(t,e)=>"recharts-bar-stack-clip-path-".concat(t,"-").concat(e),FHe=t=>{var e=w.useContext(Fre);if(e!=null){var{stackId:n}=e;return"url(#".concat(RHe(n,t),")")}},Lre=t=>{var{index:e}=t,n=EHe(t,MHe),r=FHe(e);return w.createElement(vi,PF({className:"recharts-bar-stack-layer",clipPath:r},n))},LHe=["onMouseEnter","onMouseLeave","onClick"],OHe=["value","background","tooltipPosition"],IHe=["id"],zHe=["onMouseEnter","onClick","onMouseLeave"];function Jd(){return Jd=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{dataKey:e,name:n,fill:r,legendType:a,hide:s}=t;return[{inactive:s,dataKey:e,type:a,color:r,value:Xh(n,e),payload:t}]},VHe=w.memo(t=>{var{dataKey:e,stroke:n,strokeWidth:r,fill:a,name:s,hide:o,unit:l,tooltipType:c,id:u}=t,d={dataDefinedOnItem:void 0,getPosition:Yh,settings:{stroke:n,strokeWidth:r,fill:a,dataKey:e,nameKey:void 0,name:Xh(s,e),hide:o,type:c,color:a,unit:l,graphicalItemId:u}};return w.createElement(pA,{tooltipEntrySettings:d})});function GHe(t){var e=en(Vh),{data:n,dataKey:r,background:a,allOtherBarProps:s}=t,{onMouseEnter:o,onMouseLeave:l,onClick:c}=s,u=Jk(s,LHe),d=vI(o,r,s.id),m=wI(l),p=SI(c,r,s.id);if(!a||n==null)return null;var f=zf(a);return w.createElement(Ns,{zIndex:PBe(a,Fi.barBackground)},n.map((y,v)=>{var{value:b,background:g,tooltipPosition:_}=y,N=Jk(y,OHe);if(!g)return null;var C=d(y,v),k=m(y,v),P=p(y,v),T=zs(zs(zs(zs(zs({option:a,isActive:String(v)===e},N),{},{fill:"#eee"},g),f),Aw(u,y,v)),{},{onMouseEnter:C,onMouseLeave:k,onClick:P,dataKey:r,index:v,className:"recharts-bar-background-rectangle"});return w.createElement(Zk,Jd({key:"background-bar-".concat(v)},T))}))}function WHe(t){var{showLabels:e,children:n,rects:r}=t,a=r?.map(s=>{var o={x:s.x,y:s.y,width:s.width,lowerWidth:s.width,upperWidth:s.width,height:s.height};return zs(zs({},o),{},{value:s.value,payload:s.payload,parentViewBox:s.parentViewBox,viewBox:o,fill:s.fill})});return w.createElement(pI,{value:e?a:void 0},n)}function KHe(t){var{shape:e,activeBar:n,baseProps:r,entry:a,index:s,dataKey:o}=t,l=en(Vh),c=en(lI),u=n&&String(s)===l&&(c==null||o===c),d=u?n:e;return u?w.createElement(Ns,{zIndex:Fi.activeBar},w.createElement(Lre,{index:s},w.createElement(Zk,Jd({},r,{name:String(r.name)},a,{isActive:u,option:d,index:s,dataKey:o})))):w.createElement(Zk,Jd({},r,{name:String(r.name)},a,{isActive:u,option:d,index:s,dataKey:o}))}function YHe(t){var{shape:e,baseProps:n,entry:r,index:a,dataKey:s}=t;return w.createElement(Zk,Jd({},n,{name:String(n.name)},r,{isActive:!1,option:e,index:a,dataKey:s}))}function XHe(t){var e,{data:n,props:r}=t,a=(e=Ys(r))!==null&&e!==void 0?e:{},{id:s}=a,o=Jk(a,IHe),{shape:l,dataKey:c,activeBar:u}=r,{onMouseEnter:d,onClick:m,onMouseLeave:p}=r,f=Jk(r,zHe),y=vI(d,c,s),v=wI(p),b=SI(m,c,s);return n?w.createElement(w.Fragment,null,n.map((g,_)=>w.createElement(Lre,Jd({index:_,key:"rectangle-".concat(g?.x,"-").concat(g?.y,"-").concat(g?.value,"-").concat(_),className:"recharts-bar-rectangle"},Aw(f,g,_),{onMouseEnter:y(g,_),onMouseLeave:v(g,_),onClick:b(g,_)}),u?w.createElement(KHe,{shape:l,activeBar:u,baseProps:o,entry:g,index:_,dataKey:c}):w.createElement(YHe,{shape:l,baseProps:o,entry:g,index:_,dataKey:c})))):null}function QHe(t){var{props:e,previousRectanglesRef:n}=t,{data:r,layout:a,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,onAnimationEnd:u,onAnimationStart:d}=e,m=n.current,p=Jx(e,"recharts-bar-"),[f,y]=w.useState(!1),v=!f,b=w.useCallback(()=>{typeof u=="function"&&u(),y(!1)},[u]),g=w.useCallback(()=>{typeof d=="function"&&d(),y(!0)},[d]);return w.createElement(WHe,{showLabels:v,rects:r},w.createElement(Zx,{animationId:p,begin:o,duration:l,isActive:s,easing:c,onAnimationEnd:b,onAnimationStart:g,key:p},_=>{var N=_===1?r:r?.map((C,k)=>{var P=m&&m[k];if(P)return zs(zs({},C),{},{x:Cr(P.x,C.x,_),y:Cr(P.y,C.y,_),width:Cr(P.width,C.width,_),height:Cr(P.height,C.height,_)});if(a==="horizontal"){var T=Cr(0,C.height,_),D=Cr(C.stackedBarStart,C.y,_);return zs(zs({},C),{},{y:D,height:T})}var A=Cr(0,C.width,_),R=Cr(C.stackedBarStart,C.x,_);return zs(zs({},C),{},{width:A,x:R})});return _>0&&(n.current=N??null),N==null?null:w.createElement(vi,null,w.createElement(XHe,{props:e,data:N}))}),w.createElement(dA,{label:e.label}),e.children)}function ZHe(t){var e=w.useRef(null);return w.createElement(QHe,{previousRectanglesRef:e,props:t})}var Ore=0,JHe=(t,e)=>{var n=Array.isArray(t.value)?t.value[1]:t.value;return{x:t.x,y:t.y,value:n,errorVal:Tr(t,e)}};class e$e extends w.PureComponent{render(){var{hide:e,data:n,dataKey:r,className:a,xAxisId:s,yAxisId:o,needClip:l,background:c,id:u}=this.props;if(e||n==null)return null;var d=hr("recharts-bar",a),m=u;return w.createElement(vi,{className:d,id:u},l&&w.createElement("defs",null,w.createElement(TI,{clipPathId:m,xAxisId:s,yAxisId:o})),w.createElement(vi,{className:"recharts-bar-rectangles",clipPath:l?"url(#clipPath-".concat(m,")"):void 0},w.createElement(GHe,{data:n,dataKey:r,background:c,allOtherBarProps:this.props}),w.createElement(ZHe,this.props)))}}var t$e={activeBar:!1,animationBegin:0,animationDuration:400,animationEasing:"ease",background:!1,hide:!1,isAnimationActive:"auto",label:!1,legendType:"rect",minPointSize:Ore,xAxisId:0,yAxisId:0,zIndex:Fi.bar};function n$e(t){var{xAxisId:e,yAxisId:n,hide:r,legendType:a,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:u,isAnimationActive:d}=t,{needClip:m}=xA(e,n),p=Qh(),f=wa(),y=bI(t.children,Mx),v=en(_=>PHe(_,t.id,f,y));if(p!=="vertical"&&p!=="horizontal")return null;var b,g=v?.[0];return g==null||g.height==null||g.width==null?b=0:b=p==="vertical"?g.height/2:g.width/2,w.createElement(gre,{xAxisId:e,yAxisId:n,data:v,dataPointFormatter:JHe,errorBarOffset:b},w.createElement(e$e,Jd({},t,{layout:p,needClip:m,data:v,xAxisId:e,yAxisId:n,hide:r,legendType:a,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:u,isAnimationActive:d})))}function r$e(t){var{layout:e,barSettings:{dataKey:n,minPointSize:r},pos:a,bandSize:s,xAxis:o,yAxis:l,xAxisTicks:c,yAxisTicks:u,stackedData:d,displayedData:m,offset:p,cells:f,parentViewBox:y,dataStartIndex:v}=t,b=e==="horizontal"?l:o,g=d?b.scale.domain():null,_=Uje({numericAxis:b}),N=b.scale.map(_);return m.map((C,k)=>{var P,T,D,A,R,G;if(d){var z=d[k+v];if(z==null)return null;P=Fje(z,g)}else P=Tr(C,n),Array.isArray(P)||(P=[_,P]);var Z=mHe(r,Ore)(P[1],k);if(e==="horizontal"){var I,J=l.scale.map(P[0]),ae=l.scale.map(P[1]);if(J==null||ae==null)return null;T=TV({axis:o,ticks:c,bandSize:s,offset:a.offset,entry:C,index:k}),D=(I=ae??J)!==null&&I!==void 0?I:void 0,A=a.size;var Y=J-ae;if(R=Mc(Y)?0:Y,G={x:T,y:p.top,width:A,height:p.height},Math.abs(Z)>0&&Math.abs(R)0&&Math.abs(A)w.createElement(w.Fragment,null,w.createElement(_I,{legendPayload:qHe(e)}),w.createElement(VHe,{dataKey:e.dataKey,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType,id:a}),w.createElement(NI,{type:"bar",id:a,data:void 0,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,stackId:n,hide:e.hide,barSize:e.barSize,minPointSize:e.minPointSize,maxBarSize:e.maxBarSize,isPanorama:r}),w.createElement(Ns,{zIndex:e.zIndex},w.createElement(n$e,Jd({},e,{id:a})))))}var Rb=w.memo(i$e,Kw);Rb.displayName="Bar";var a$e=["domain","range"],s$e=["domain","range"];function Q9(t,e){if(t==null)return{};var n,r,a=o$e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{if(o!=null)return eW(eW({},s),{},{type:o})},[s,o]);return w.useLayoutEffect(()=>{l!=null&&(n.current===null?e(sBe(l)):n.current!==l&&e(oBe({prev:n.current,next:l})),n.current=l)},[l,e]),w.useLayoutEffect(()=>()=>{n.current&&(e(lBe(n.current)),n.current=null)},[e]),null}var g$e=t=>{var{xAxisId:e,className:n}=t,r=en(XO),a=wa(),s="xAxis",o=en(g=>one(g,s,e,a)),l=en(g=>rne(g,e)),c=en(g=>e4e(g,e)),u=en(g=>Ite(g,e));if(l==null||c==null||u==null)return null;var{dangerouslySetInnerHTML:d,ticks:m,scale:p}=t,f=EF(t,c$e),{id:y,scale:v}=u,b=EF(u,u$e);return w.createElement(CI,MF({},f,b,{x:c.x,y:c.y,width:l.width,height:l.height,className:hr("recharts-".concat(s," ").concat(s),n),viewBox:r,ticks:o,axisType:s}))},b$e={allowDataOverflow:Ma.allowDataOverflow,allowDecimals:Ma.allowDecimals,allowDuplicatedCategory:Ma.allowDuplicatedCategory,angle:Ma.angle,axisLine:Fd.axisLine,height:Ma.height,hide:!1,includeHidden:Ma.includeHidden,interval:Ma.interval,label:!1,minTickGap:Ma.minTickGap,mirror:Ma.mirror,orientation:Ma.orientation,padding:Ma.padding,reversed:Ma.reversed,scale:Ma.scale,tick:Ma.tick,tickCount:Ma.tickCount,tickLine:Fd.tickLine,tickSize:Fd.tickSize,type:Ma.type,xAxisId:0},x$e=t=>{var e=wi(t,b$e);return w.createElement(w.Fragment,null,w.createElement(f$e,{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}),w.createElement(g$e,e))},af=w.memo(x$e,Ire);af.displayName="XAxis";var y$e=["type"],v$e=["dangerouslySetInnerHTML","ticks","scale"],w$e=["id","scale"];function jF(){return jF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{if(o!=null)return nW(nW({},s),{},{type:o})},[o,s]);return w.useLayoutEffect(()=>{l!=null&&(n.current===null?e(cBe(l)):n.current!==l&&e(uBe({prev:n.current,next:l})),n.current=l)},[l,e]),w.useLayoutEffect(()=>()=>{n.current&&(e(dBe(n.current)),n.current=null)},[e]),null}function T$e(t){var{yAxisId:e,className:n,width:r,label:a}=t,s=w.useRef(null),o=w.useRef(null),l=en(XO),c=wa(),u=Jr(),d="yAxis",m=en(P=>ine(P,e)),p=en(P=>n4e(P,e)),f=en(P=>one(P,d,e,c)),y=en(P=>zte(P,e));if(w.useLayoutEffect(()=>{if(!(r!=="auto"||!m||hI(a)||w.isValidElement(a)||y==null)){var P=s.current;if(P){var T=P.getCalculatedWidth();Math.round(m.width)!==Math.round(T)&&u(mBe({id:e,width:T}))}}},[f,m,u,a,e,r,y]),m==null||p==null||y==null)return null;var{dangerouslySetInnerHTML:v,ticks:b,scale:g}=t,_=DF(t,v$e),{id:N,scale:C}=y,k=DF(y,w$e);return w.createElement(CI,jF({},_,k,{ref:s,labelRef:o,x:p.x,y:p.y,tickTextProps:r==="auto"?{width:void 0}:{width:r},width:m.width,height:m.height,className:hr("recharts-".concat(d," ").concat(d),n),viewBox:l,ticks:f,axisType:d}))}var A$e={allowDataOverflow:Ea.allowDataOverflow,allowDecimals:Ea.allowDecimals,allowDuplicatedCategory:Ea.allowDuplicatedCategory,angle:Ea.angle,axisLine:Fd.axisLine,hide:!1,includeHidden:Ea.includeHidden,interval:Ea.interval,label:!1,minTickGap:Ea.minTickGap,mirror:Ea.mirror,orientation:Ea.orientation,padding:Ea.padding,reversed:Ea.reversed,scale:Ea.scale,tick:Ea.tick,tickCount:Ea.tickCount,tickLine:Fd.tickLine,tickSize:Fd.tickSize,type:Ea.type,width:Ea.width,yAxisId:0},P$e=t=>{var e=wi(t,A$e);return w.createElement(w.Fragment,null,w.createElement(C$e,{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}),w.createElement(T$e,e))},sf=w.memo(P$e,Ire);sf.displayName="YAxis";var M$e=(t,e)=>e,PI=yt([M$e,dr,Fte,za,Nne,am,bIe,va],NIe),MI=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)}},zre=Yl("mouseClick"),Ure=Mw();Ure.startListening({actionCreator:zre,effect:(t,e)=>{var n=t.payload,r=PI(e.getState(),MI(n));r?.activeIndex!=null&&e.dispatch(g4e({activeIndex:r.activeIndex,activeDataKey:void 0,activeCoordinate:r.activeCoordinate}))}});var RF=Yl("mouseMove"),Bre=Mw(),M1=null;Bre.startListening({actionCreator:RF,effect:(t,e)=>{var n=t.payload;M1!==null&&cancelAnimationFrame(M1);var r=MI(n);M1=requestAnimationFrame(()=>{var a=e.getState(),s=nI(a,a.tooltip.settings.shared);if(s==="axis"){var o=PI(a,r);o?.activeIndex!=null?e.dispatch(fne({activeIndex:o.activeIndex,activeDataKey:void 0,activeCoordinate:o.activeCoordinate})):e.dispatch(pne())}M1=null})}});function E$e(t,e){return e instanceof HTMLElement?"HTMLElement <".concat(e.tagName,' class="').concat(e.className,'">'):e===window?"global.window":t==="children"&&typeof e=="object"&&e!==null?"<>":e}var rW={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},Hre=Ao({name:"rootProps",initialState:rW,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:rW.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}}}),j$e=Hre.reducer,{updateOptions:D$e}=Hre.actions,R$e=null,F$e={updatePolarOptions:(t,e)=>e.payload},$re=Ao({name:"polarOptions",initialState:R$e,reducers:F$e}),{updatePolarOptions:L$e}=$re.actions,O$e=$re.reducer,qre=Yl("keyDown"),Vre=Yl("focus"),EI=Mw();EI.startListening({actionCreator:qre,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:a}=n.tooltip,s=t.payload;if(!(s!=="ArrowRight"&&s!=="ArrowLeft"&&s!=="Enter")){var o=rI(a,ly(n),qw(n),Gw(n)),l=o==null?-1:Number(o);if(!(!Number.isFinite(l)||l<0)){var c=am(n);if(s==="Enter"){var u=qk(n,"axis","hover",String(a.index));e.dispatch(wF({active:!a.active,activeIndex:a.index,activeCoordinate:u}));return}var d=s4e(n),m=d==="left-to-right"?1:-1,p=s==="ArrowRight"?1:-1,f=l+p*m;if(!(c==null||f>=c.length||f<0)){var y=qk(n,"axis","hover",String(f));e.dispatch(wF({active:!0,activeIndex:f.toString(),activeCoordinate:y}))}}}}}});EI.startListening({actionCreator:Vre,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:a}=n.tooltip;if(!a.active&&a.index==null){var s="0",o=qk(n,"axis","hover",String(s));e.dispatch(wF({active:!0,activeIndex:s,activeCoordinate:o}))}}}});var Cl=Yl("externalEvent"),Gre=Mw(),Xj=new Map;Gre.startListening({actionCreator:Cl,effect:(t,e)=>{var{handler:n,reactEvent:r}=t.payload;if(n!=null){r.persist();var a=r.type,s=Xj.get(a);s!==void 0&&cancelAnimationFrame(s);var o=requestAnimationFrame(()=>{try{var l=e.getState(),c={activeCoordinate:nIe(l),activeDataKey:lI(l),activeIndex:Vh(l),activeLabel:Tne(l),activeTooltipIndex:Vh(l),isTooltipActive:rIe(l)};n(c,r)}finally{Xj.delete(a)}});Xj.set(a,o)}}});var I$e=yt([sy],t=>t.tooltipItemPayloads),z$e=yt([I$e,(t,e)=>e,(t,e,n)=>n],(t,e,n)=>{if(e!=null){var r=t.find(s=>s.settings.graphicalItemId===n);if(r!=null){var{getPosition:a}=r;if(a!=null)return a(e)}}}),Wre=Yl("touchMove"),Kre=Mw();Kre.startListening({actionCreator:Wre,effect:(t,e)=>{var n=t.payload;if(!(n.touches==null||n.touches.length===0)){var r=e.getState(),a=nI(r,r.tooltip.settings.shared);if(a==="axis"){var s=n.touches[0];if(s==null)return;var o=PI(r,MI({clientX:s.clientX,clientY:s.clientY,currentTarget:n.currentTarget}));o?.activeIndex!=null&&e.dispatch(fne({activeIndex:o.activeIndex,activeDataKey:void 0,activeCoordinate:o.activeCoordinate}))}else if(a==="item"){var l,c=n.touches[0];if(document.elementFromPoint==null||c==null)return;var u=document.elementFromPoint(c.clientX,c.clientY);if(!u||!u.getAttribute)return;var d=u.getAttribute(oee),m=(l=u.getAttribute(lee))!==null&&l!==void 0?l:void 0,p=oy(r).find(v=>v.id===m);if(d==null||p==null||m==null)return;var{dataKey:f}=p,y=z$e(r,d,m);e.dispatch(hne({activeDataKey:f,activeIndex:d,activeCoordinate:y,activeGraphicalItemId:m}))}}}});var U$e=AJ({brush:MBe,cartesianAxis:hBe,chartData:t5e,errorBars:U8e,graphicalItems:wUe,layout:Mje,legend:LDe,options:XIe,polarAxis:Fze,polarOptions:O$e,referenceElements:IBe,rootProps:j$e,tooltip:b4e,zIndex:IIe}),B$e=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Chart";return tje({reducer:U$e,preloadedState:e,middleware:r=>{var a;return r({serializableCheck:!1,immutableCheck:!["commonjs","es6","production"].includes((a="es6")!==null&&a!==void 0?a:"")}).concat([Ure.middleware,Bre.middleware,EI.middleware,Gre.middleware,Kre.middleware])},enhancers:r=>{var a=r;return typeof r=="function"&&(a=r()),a.concat($J({type:"raf"}))},devTools:{serialize:{replacer:E$e},name:"recharts-".concat(n)}})};function Yre(t){var{preloadedState:e,children:n,reduxStoreName:r}=t,a=wa(),s=w.useRef(null);if(a)return n;s.current==null&&(s.current=B$e(e,r));var o=$O;return w.createElement(p6e,{context:o,store:s.current},n)}function H$e(t){var{layout:e,margin:n}=t,r=Jr(),a=wa();return w.useEffect(()=>{a||(r(Tje(e)),r(Cje(n)))},[r,a,e,n]),null}var Xre=w.memo(H$e,Kw);function Qre(t){var e=Jr();return w.useEffect(()=>{e(D$e(t))},[e,t]),null}function iW(t){var{zIndex:e,isPanorama:n}=t,r=w.useRef(null),a=Jr();return w.useLayoutEffect(()=>(r.current&&a(LIe({zIndex:e,element:r.current,isPanorama:n})),()=>{a(OIe({zIndex:e,isPanorama:n}))}),[a,e,n]),w.createElement("g",{tabIndex:-1,ref:r})}function aW(t){var{children:e,isPanorama:n}=t,r=en(CIe);if(!r||r.length===0)return e;var a=r.filter(o=>o<0),s=r.filter(o=>o>0);return w.createElement(w.Fragment,null,a.map(o=>w.createElement(iW,{key:o,zIndex:o,isPanorama:n})),e,s.map(o=>w.createElement(iW,{key:o,zIndex:o,isPanorama:n})))}var $$e=["children"];function q$e(t,e){if(t==null)return{};var n,r,a=V$e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var n=JO(),r=e4(),a=kee();if(!vu(n)||!vu(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=a?0:void 0,typeof o.role=="string"?d=o.role:d=a?"application":void 0),w.createElement(jO,eC({},o,{title:l,desc:c,role:d,tabIndex:u,width:n,height:r,style:G$e,ref:e}),s)}),K$e=t=>{var{children:e}=t,n=en(BT);if(!n)return null;var{width:r,height:a,y:s,x:o}=n;return w.createElement(jO,{width:r,height:a,x:o,y:s},e)},sW=w.forwardRef((t,e)=>{var{children:n}=t,r=q$e(t,$$e),a=wa();return a?w.createElement(K$e,null,w.createElement(aW,{isPanorama:!0},n)):w.createElement(W$e,eC({ref:e},r),w.createElement(aW,{isPanorama:!1},n))});function Y$e(){var t=Jr(),[e,n]=w.useState(null),r=en(Gje);return w.useEffect(()=>{if(e!=null){var a=e.getBoundingClientRect(),s=a.width/e.offsetWidth;Ln(s)&&s!==r&&t(Pje(s))}},[e,t,r]),n}function oW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function X$e(t){for(var e=1;e(u5e(),null);function tC(t){if(typeof t=="number")return t;if(typeof t=="string"){var e=parseFloat(t);if(!Number.isNaN(e))return e}return 0}var tqe=w.forwardRef((t,e)=>{var n,r,a=w.useRef(null),[s,o]=w.useState({containerWidth:tC((n=t.style)===null||n===void 0?void 0:n.width),containerHeight:tC((r=t.style)===null||r===void 0?void 0:r.height)}),l=w.useCallback((u,d)=>{o(m=>{var p=Math.round(u),f=Math.round(d);return m.containerWidth===p&&m.containerHeight===f?m:{containerWidth:p,containerHeight:f}})},[]),c=w.useCallback(u=>{if(typeof e=="function"&&e(u),u!=null&&typeof ResizeObserver<"u"){var{width:d,height:m}=u.getBoundingClientRect();l(d,m);var p=y=>{var v=y[0];if(v!=null){var{width:b,height:g}=v.contentRect;l(b,g)}},f=new ResizeObserver(p);f.observe(u),a.current=f}},[e,l]);return w.useEffect(()=>()=>{var u=a.current;u?.disconnect()},[l]),w.createElement(w.Fragment,null,w.createElement(Dw,{width:s.containerWidth,height:s.containerHeight}),w.createElement("div",Fh({ref:c},t)))}),nqe=w.forwardRef((t,e)=>{var{width:n,height:r}=t,[a,s]=w.useState({containerWidth:tC(n),containerHeight:tC(r)}),o=w.useCallback((c,u)=>{s(d=>{var m=Math.round(c),p=Math.round(u);return d.containerWidth===m&&d.containerHeight===p?d:{containerWidth:m,containerHeight:p}})},[]),l=w.useCallback(c=>{if(typeof e=="function"&&e(c),c!=null){var{width:u,height:d}=c.getBoundingClientRect();o(u,d)}},[e,o]);return w.createElement(w.Fragment,null,w.createElement(Dw,{width:a.containerWidth,height:a.containerHeight}),w.createElement("div",Fh({ref:l},t)))}),rqe=w.forwardRef((t,e)=>{var{width:n,height:r}=t;return w.createElement(w.Fragment,null,w.createElement(Dw,{width:n,height:r}),w.createElement("div",Fh({ref:e},t)))}),iqe=w.forwardRef((t,e)=>{var{width:n,height:r}=t;return typeof n=="string"||typeof r=="string"?w.createElement(nqe,Fh({},t,{ref:e})):typeof n=="number"&&typeof r=="number"?w.createElement(rqe,Fh({},t,{width:n,height:r,ref:e})):w.createElement(w.Fragment,null,w.createElement(Dw,{width:n,height:r}),w.createElement("div",Fh({ref:e},t)))});function aqe(t){return t?tqe:iqe}var sqe=w.forwardRef((t,e)=>{var{children:n,className:r,height:a,onClick:s,onContextMenu:o,onDoubleClick:l,onMouseDown:c,onMouseEnter:u,onMouseLeave:d,onMouseMove:m,onMouseUp:p,onTouchEnd:f,onTouchMove:y,onTouchStart:v,style:b,width:g,responsive:_,dispatchTouchEvents:N=!0}=t,C=w.useRef(null),k=Jr(),[P,T]=w.useState(null),[D,A]=w.useState(null),R=Y$e(),G=QO(),z=G?.width>0?G.width:g,Z=G?.height>0?G.height:a,I=w.useCallback(E=>{R(E),typeof e=="function"&&e(E),T(E),A(E),E!=null&&(C.current=E)},[R,e,T,A]),J=w.useCallback(E=>{k(zre(E)),k(Cl({handler:s,reactEvent:E}))},[k,s]),ae=w.useCallback(E=>{k(RF(E)),k(Cl({handler:u,reactEvent:E}))},[k,u]),Y=w.useCallback(E=>{k(pne()),k(Cl({handler:d,reactEvent:E}))},[k,d]),ue=w.useCallback(E=>{k(RF(E)),k(Cl({handler:m,reactEvent:E}))},[k,m]),de=w.useCallback(()=>{k(Vre())},[k]),he=w.useCallback(E=>{k(qre(E.key))},[k]),V=w.useCallback(E=>{k(Cl({handler:o,reactEvent:E}))},[k,o]),ne=w.useCallback(E=>{k(Cl({handler:l,reactEvent:E}))},[k,l]),se=w.useCallback(E=>{k(Cl({handler:c,reactEvent:E}))},[k,c]),pe=w.useCallback(E=>{k(Cl({handler:p,reactEvent:E}))},[k,p]),Te=w.useCallback(E=>{k(Cl({handler:v,reactEvent:E}))},[k,v]),q=w.useCallback(E=>{N&&k(Wre(E)),k(Cl({handler:y,reactEvent:E}))},[k,N,y]),X=w.useCallback(E=>{k(Cl({handler:f,reactEvent:E}))},[k,f]),j=aqe(_);return w.createElement(Fne.Provider,{value:P},w.createElement(qZ.Provider,{value:D},w.createElement(j,{width:z??b?.width,height:Z??b?.height,className:hr("recharts-wrapper",r),style:X$e({position:"relative",cursor:"default",width:z,height:Z},b),onClick:J,onContextMenu:V,onDoubleClick:ne,onFocus:de,onKeyDown:he,onMouseDown:se,onMouseEnter:ae,onMouseLeave:Y,onMouseMove:ue,onMouseUp:pe,onTouchEnd:X,onTouchMove:q,onTouchStart:Te,ref:I},w.createElement(eqe,null),n)))}),oqe=["width","height","responsive","children","className","style","compact","title","desc"];function lqe(t,e){if(t==null)return{};var n,r,a=cqe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var{width:n,height:r,responsive:a,children:s,className:o,style:l,compact:c,title:u,desc:d}=t,m=lqe(t,oqe),p=Ys(m);return c?w.createElement(w.Fragment,null,w.createElement(Dw,{width:n,height:r}),w.createElement(sW,{otherAttributes:p,title:u,desc:d},s)):w.createElement(sqe,{className:o,style:l,width:n,height:r,responsive:a??!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},w.createElement(sW,{otherAttributes:p,title:u,desc:d,ref:e},w.createElement(zBe,null,s)))});function FF(){return FF=Object.assign?Object.assign.bind():function(t){for(var e=1;ew.createElement(jI,{chartName:"LineChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:mqe,tooltipPayloadSearcher:cA,categoricalChartProps:t,ref:e})),pqe=["axis","item"],E1=w.forwardRef((t,e)=>w.createElement(jI,{chartName:"BarChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:pqe,tooltipPayloadSearcher:cA,categoricalChartProps:t,ref:e}));function fqe(t){var e=Jr();return w.useEffect(()=>{e(L$e(t))},[e,t]),null}var gqe=["layout"];function LF(){return LF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var n=wi(t,kqe);return w.createElement(vqe,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:Nqe,tooltipPayloadSearcher:cA,categoricalChartProps:n,ref:e})}),Cqe=["axis"],Tqe=w.forwardRef((t,e)=>w.createElement(jI,{chartName:"AreaChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:Cqe,tooltipPayloadSearcher:cA,categoricalChartProps:t,ref:e}));const dW=[{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 Aqe({isOpen:t,onClose:e,printerId:n,printerName:r,amsId:a,amsLabel:s,initialMode:o="humidity",thresholds:l}){const{t:c}=Dt(),{mode:u}=ng(),[d,m]=w.useState("24h"),[p,f]=w.useState(o),y=u==="dark",{data:v}=et({queryKey:["settings"],queryFn:ge.getSettings}),b=v?.time_format||"system";w.useEffect(()=>{if(!t)return;const X=j=>{j.key==="Escape"&&e()};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[t,e]);const g=dW.find(X=>X.value===d)?.hours||24,{data:_,isLoading:N,error:C}=et({queryKey:["ams-history",n,a,g],queryFn:()=>ge.getAMSHistory(n,a,g),enabled:t,refetchInterval:6e4});if(!t)return null;const k=_?.data.map(X=>({time:(Qn(X.recorded_at)||new Date).getTime(),humidity:X.humidity,temperature:X.temperature}))||[],P=Date.now()-g*60*60*1e3,T=Date.now(),D=[...k];if(D.length>0){const X=D[0];X.time>P&&D.unshift({...X,time:P});const j=D[D.length-1];j.time{const j=X.filter(O=>O!=null);if(j.length<4)return"stable";const E=j.slice(0,Math.floor(j.length/4)),U=j.slice(-Math.floor(j.length/4)),K=E.reduce((O,$)=>O+$,0)/E.length,re=U.reduce((O,$)=>O+$,0)/U.length-K;return Math.abs(re)<2?"stable":re>0?"up":"down"},Y=ae(D.map(X=>X.humidity)),ue=ae(D.map(X=>X.temperature)),de=({trend:X})=>X==="up"?i.jsx(T3,{className:"w-4 h-4 text-red-400"}):X==="down"?i.jsx(XL,{className:"w-4 h-4 text-green-400"}):i.jsx(zN,{className:"w-4 h-4 text-gray-400 dark:text-bambu-gray"}),he=X=>X==null?"#9ca3af":X<=A?"#22a352":X<=R?"#d4a017":"#c62828",V=X=>X==null?"#9ca3af":X<=G?"#22a352":X<=z?"#d4a017":"#c62828",ne=y?"#2d2d2d":"#ffffff",se=y?"#1d1d1d":"#f3f4f6",pe=y?"#3d3d3d":"#e5e7eb",Te=y?"#ffffff":"#111827",q=y?"#9ca3af":"#4b5563";return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:i.jsxs("div",{className:"rounded-xl w-full max-w-4xl max-h-[90vh] overflow-hidden shadow-xl",style:{backgroundColor:ne},onClick:X=>X.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",style:{borderColor:pe},children:[i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold",style:{color:Te},children:[s," ",c("common.history","History")]}),i.jsx("p",{className:"text-sm",style:{color:q},children:r})]}),i.jsx("button",{onClick:e,className:"p-2 rounded-lg transition-colors",style:{color:q},children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-6 space-y-6 overflow-y-auto max-h-[calc(90vh-80px)]",children:[i.jsxs("div",{className:"flex items-center justify-between max-[550px]:flex-col max-[550px]:items-start max-[550px]:gap-3",children:[i.jsxs("div",{className:"inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit",style:{backgroundColor:se},children:[i.jsxs("button",{onClick:()=>f("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:q}:void 0,children:[i.jsx(GL,{className:"w-4 h-4"}),c("common.humidity","Humidity")]}),i.jsxs("button",{onClick:()=>f("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:q}:void 0,children:[i.jsx(mT,{className:"w-4 h-4"}),c("common.temperature","Temperature")]})]}),i.jsx("div",{className:"inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit",style:{backgroundColor:se},children:dW.map(X=>i.jsx("button",{onClick:()=>m(X.value),className:`px-3 py-1 text-sm rounded-md transition-colors ${d===X.value?"bg-bambu-green text-white":""}`,style:d!==X.value?{color:q}:void 0,children:X.label},X.value))})]}),i.jsx("div",{className:"grid grid-cols-4 gap-4 max-[550px]:grid-cols-2",children:p==="humidity"?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-2",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.current","Current")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("p",{className:"text-2xl font-bold",style:{color:he(I)},children:I!=null?`${I}%`:"—"}),i.jsx(de,{trend:Y})]})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-4",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.average","Average")}),i.jsx("p",{className:"text-2xl font-bold",style:{color:Te},children:_?.avg_humidity!=null?`${_.avg_humidity}%`:"—"})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-1",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.min","Min")}),i.jsx("p",{className:"text-2xl font-bold text-green-500",children:_?.min_humidity!=null?`${_.min_humidity}%`:"—"})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-3",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.max","Max")}),i.jsx("p",{className:"text-2xl font-bold text-red-500",children:_?.max_humidity!=null?`${_.max_humidity}%`:"—"})]})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-2",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.current","Current")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("p",{className:"text-2xl font-bold",style:{color:V(J)},children:J!=null?`${J}°C`:"—"}),i.jsx(de,{trend:ue})]})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-4",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.average","Average")}),i.jsx("p",{className:"text-2xl font-bold",style:{color:Te},children:_?.avg_temperature!=null?`${_.avg_temperature}°C`:"—"})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-1",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.min","Min")}),i.jsx("p",{className:"text-2xl font-bold text-blue-500",children:_?.min_temperature!=null?`${_.min_temperature}°C`:"—"})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-3",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.max","Max")}),i.jsx("p",{className:"text-2xl font-bold text-red-500",children:_?.max_temperature!=null?`${_.max_temperature}°C`:"—"})]})]})}),i.jsx("div",{className:"rounded-lg p-4",style:{backgroundColor:se},children:N?i.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:q},children:c("common.loading","Loading...")}):C?i.jsx("div",{className:"h-[300px] flex items-center justify-center text-red-500",children:c("common.error","Error loading data")}):D.length===0?i.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:q},children:c("common.noData","No data available for this time range")}):i.jsx(bh,{width:"100%",height:300,children:i.jsxs(hqe,{data:D,children:[i.jsx(rf,{strokeDasharray:"3 3",stroke:y?"#3d3d3d":"#e5e7eb"}),i.jsx(af,{dataKey:"time",type:"number",domain:[Date.now()-g*60*60*1e3,Date.now()],tickFormatter:X=>{const j=new Date(X);return g>24?j.toLocaleDateString([],{day:"numeric",month:"short"}):j.toLocaleTimeString([],k0({hour:"2-digit",minute:"2-digit"},b))},stroke:y?"#9ca3af":"#6b7280",tick:{fontSize:12}}),i.jsx(sf,{stroke:y?"#9ca3af":"#6b7280",tick:{fontSize:12},domain:p==="humidity"?[0,100]:["auto","auto"],tickFormatter:X=>p==="humidity"?`${X}%`:`${X}°C`}),i.jsx(xh,{contentStyle:{backgroundColor:y?"#2d2d2d":"#ffffff",border:`1px solid ${y?"#3d3d3d":"#e5e7eb"}`,borderRadius:"8px",color:y?"#fff":"#000"},labelFormatter:X=>new Date(X).toLocaleString(void 0,k0({year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},b)),formatter:X=>[p==="humidity"?`${X??0}%`:`${X??0}°C`,p==="humidity"?"Humidity":"Temperature"]}),i.jsx(Nee,{}),p==="humidity"?i.jsxs(i.Fragment,{children:[i.jsx(Iv,{y:A,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),i.jsx(Iv,{y:R,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}):i.jsxs(i.Fragment,{children:[i.jsx(Iv,{y:G,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),i.jsx(Iv,{y:z,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}),i.jsx(Nre,{type:"monotone",dataKey:p,name:p==="humidity"?"Humidity":"Temperature",stroke:p==="humidity"?"#3b82f6":"#f97316",strokeWidth:2,dot:!1,activeDot:{r:4},connectNulls:!0})]})})}),i.jsx("div",{className:"text-xs text-center",style:{color:q},children:c("amsHistory.recordingInfo","Data is recorded every 5 minutes while the printer is connected")})]})]})})}const nC={"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 xN(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),a=parseInt(e.substring(4,6),16),s=Math.max(n,r,a)/255,o=Math.min(n,r,a)/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 m=n/255,p=r/255,f=a/255;s===m?c=((p-f)/d+(p.85?"White":u<.15?l<.4?"Dark Gray":l>.6?"Light Gray":"Gray":c>=15&&c<45&&l<.45||c>=45&&c<70&&l<.4?"Brown":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 Ld(t){const e=t.replace("#","").toLowerCase().substring(0,6);return nC[e]?nC[e]:xN(t)}function DI(t,e){if(t&&!/^[A-Z]\d+-[A-Z]\d+$/.test(t))return t;if(e&&e.length>=6){const n=e.substring(0,6).toLowerCase();if(nC[n])return nC[n]}return null}function RI(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),a=t.length>=8?parseInt(t.slice(6,8),16)/255:1;return a===0?null:`rgba(${parseInt(e,16)}, ${parseInt(n,16)}, ${parseInt(r,16)}, ${a})`}function eie(t){if(!t||t.length<6)return!1;const e=t.replace("#",""),n=parseInt(e.slice(0,2),16),r=parseInt(e.slice(2,4),16),a=parseInt(e.slice(4,6),16);return(.299*n+.587*r+.114*a)/255>.6}function Qj({data:t,children:e,disabled:n,className:r="",spoolman:a,inventory:s,configureSlot:o}){const{t:l}=Dt(),[c,u]=w.useState(!1),[d,m]=w.useState("top"),[p,f]=w.useState(!1),[y,v]=w.useState(!1),b=w.useRef(null),g=w.useRef(null),_=w.useRef(null),N=()=>{const R=t.trayUuid;R&&(navigator.clipboard&&window.isSecureContext?navigator.clipboard.writeText(R).then(()=>{f(!0),setTimeout(()=>f(!1),2e3)}).catch(()=>{C(R)}):C(R))},C=R=>{const G=document.createElement("textarea");G.value=R,G.style.position="fixed",G.style.opacity="0",document.body.appendChild(G),G.select();try{document.execCommand("copy"),f(!0),setTimeout(()=>f(!1),2e3)}catch{console.error("Failed to copy to clipboard")}document.body.removeChild(G)};w.useEffect(()=>{if(c&&b.current&&g.current){const R=b.current.getBoundingClientRect(),G=g.current.offsetHeight,Z=R.top-56,I=window.innerHeight-R.bottom;ZZ?m("bottom"):m("top")}},[c]);const k=()=>{n||(_.current&&clearTimeout(_.current),_.current=setTimeout(()=>u(!0),80))},P=()=>{_.current&&clearTimeout(_.current),_.current=setTimeout(()=>u(!1),100)};w.useEffect(()=>()=>{_.current&&clearTimeout(_.current)},[]);const T=R=>R<=15?"#ef4444":R<=30?"#f97316":R<=50?"#eab308":"#22c55e",D=t.colorHex?`#${t.colorHex.replace("#","")}`:null,A=s?.assignedSpool?.remainingWeightGrams??null;return i.jsxs("div",{ref:b,className:`relative ${r}`,onMouseEnter:k,onMouseLeave:P,children:[e,c&&i.jsxs("div",{ref:g,className:` + `).concat(C.x,",").concat(C.y),P=gi(t.id)?O0("recharts-radial-line-"):t.id;return w.createElement("text",vd({},r,{dominantBaseline:"central",className:hr("recharts-radial-bar-label",o)}),w.createElement("defs",null,w.createElement("path",{id:P,d:k})),w.createElement("textPath",{xlinkHref:"#".concat(P)},n))},uze=(t,e,n)=>{var{cx:r,cy:a,innerRadius:s,outerRadius:o,startAngle:l,endAngle:c}=t,u=(l+c)/2;if(n==="outside"){var{x:d,y:m}=aa(r,a,o+e,u);return{x:d,y:m,textAnchor:d>=r?"start":"end",verticalAnchor:"middle"}}if(n==="center")return{x:r,y:a,textAnchor:"middle",verticalAnchor:"middle"};if(n==="centerTop")return{x:r,y:a,textAnchor:"middle",verticalAnchor:"start"};if(n==="centerBottom")return{x:r,y:a,textAnchor:"middle",verticalAnchor:"end"};var p=(s+o)/2,{x:f,y}=aa(r,a,p,u);return{x:f,y,textAnchor:"middle",verticalAnchor:"middle"}},gN=t=>t!=null&&"cx"in t&&Yt(t.cx),dze={angle:0,offset:5,zIndex:Fi.label,position:"middle",textBreakAll:!1};function mze(t){if(!gN(t))return t;var{cx:e,cy:n,outerRadius:r}=t,a=r*2;return{x:e-r,y:n-r,width:a,upperWidth:a,lowerWidth:a,height:a}}function Jm(t){var e=wi(t,dze),{viewBox:n,parentViewBox:r,position:a,value:s,children:o,content:l,className:c="",textBreakAll:u,labelRef:d}=e,m=sze(),p=Kne(),f=a==="center"?p:m??p,y,v,b;n==null?y=f:gN(n)?y=n:y=ZO(n);var g=mze(y);if(!y||gi(s)&&gi(o)&&!w.isValidElement(l)&&typeof l!="function")return null;var _=Ov(Ov({},e),{},{viewBox:y});if(w.isValidElement(l)){var{labelRef:N}=_,C=r9(_,J5e);return w.cloneElement(l,C)}if(typeof l=="function"){var{content:k}=_,P=r9(_,eze);if(v=w.createElement(l,P),w.isValidElement(v))return v}else v=oze(e);var T=ls(e);if(gN(y)){if(a==="insideStart"||a==="insideEnd"||a==="end")return cze(e,a,v,T,y);b=uze(y,e.offset,e.position)}else{if(!g)return null;var D=Z5e({viewBox:g,position:a,offset:e.offset,parentViewBox:gN(r)?void 0:r});b=Ov(Ov({x:D.x,y:D.y,textAnchor:D.horizontalAnchor,verticalAnchor:D.verticalAnchor},D.width!==void 0?{width:D.width}:{}),D.height!==void 0?{height:D.height}:{})}return w.createElement(Ns,{zIndex:e.zIndex},w.createElement(uA,vd({ref:d,className:hr("recharts-label",c)},T,b,{textAnchor:q5e(T.textAnchor)?T.textAnchor:b.textAnchor,breakAll:u}),v))}Jm.displayName="Label";var hze=(t,e,n)=>{if(!t)return null;var r={viewBox:e,labelRef:n};return t===!0?w.createElement(Jm,vd({key:"label-implicit"},r)):Kl(t)?w.createElement(Jm,vd({key:"label-implicit",value:t},r)):w.isValidElement(t)?t.type===Jm?w.cloneElement(t,Ov({key:"label-implicit"},r)):w.createElement(Jm,vd({key:"label-implicit",content:t},r)):h4(t)?w.createElement(Jm,vd({key:"label-implicit",content:t},r)):t&&typeof t=="object"?w.createElement(Jm,vd({},t,{key:"label-implicit"},r)):null};function Yne(t){var{label:e,labelRef:n}=t,r=Kne();return hze(e,r,n)||null}var O2={},I2={},a9;function pze(){return a9||(a9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n[n.length-1]}t.last=e})(I2)),I2}var z2={},s9;function fze(){return s9||(s9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Array.isArray(n)?n:Array.from(n)}t.toArray=e})(z2)),z2}var o9;function gze(){return o9||(o9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=pze(),n=fze(),r=BO();function a(s){if(r.isArrayLike(s))return e.last(n.toArray(s))}t.last=a})(O2)),O2}var U2,l9;function bze(){return l9||(l9=1,U2=gze().last),U2}var xze=bze();const yze=Zl(xze);var vze=["valueAccessor"],wze=["dataKey","clockWise","id","textBreakAll","zIndex"];function Vk(){return Vk=Object.assign?Object.assign.bind():function(t){for(var e=1;eArray.isArray(t.value)?yze(t.value):t.value,Xne=w.createContext(void 0),p4=Xne.Provider,Qne=w.createContext(void 0),Nze=Qne.Provider;function kze(){return w.useContext(Xne)}function Cze(){return w.useContext(Qne)}function bN(t){var{valueAccessor:e=_ze}=t,n=c9(t,vze),{dataKey:r,clockWise:a,id:s,textBreakAll:o,zIndex:l}=n,c=c9(n,wze),u=kze(),d=Cze(),m=u||d;return!m||!m.length?null:w.createElement(Ns,{zIndex:l??Fi.label},w.createElement(vi,{className:"recharts-label-list"},m.map((p,f)=>{var y,v=gi(r)?e(p,f):Tr(p.payload,r),b=gi(s)?{}:{id:"".concat(s,"-").concat(f)};return w.createElement(Jm,Vk({key:"label-".concat(f)},ls(p),c,b,{fill:(y=n.fill)!==null&&y!==void 0?y:p.fill,parentViewBox:p.parentViewBox,value:v,textBreakAll:o,viewBox:p.viewBox,index:f,zIndex:0}))})))}bN.displayName="LabelList";function dA(t){var{label:e}=t;return e?e===!0?w.createElement(bN,{key:"labelList-implicit"}):w.isValidElement(e)||h4(e)?w.createElement(bN,{key:"labelList-implicit",content:e}):typeof e=="object"?w.createElement(bN,Vk({key:"labelList-implicit"},e,{type:String(e.type)})):null:null}function kF(){return kF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{cx:e,cy:n,r,className:a}=t,s=hr("recharts-dot",a);return Yt(e)&&Yt(n)&&Yt(r)?w.createElement("circle",kF({},Ys(t),UO(t),{className:s,cx:e,cy:n,r})):null},Jne=t=>t.graphicalItems.polarItems,Tze=yt([Si,Bw],OI),mA=yt([Jne,Ii,Tze],II),Aze=yt([mA],zI),hA=yt([Aze,QT],UI),Pze=yt([hA,Ii,mA],HI);yt([hA,Ii,mA],(t,e,n)=>n.length>0?t.flatMap(r=>n.flatMap(a=>{var s,o=Tr(r,(s=e.dataKey)!==null&&s!==void 0?s:a.dataKey);return{value:o,errorDomain:[]}})).filter(Boolean):e?.dataKey!=null?t.map(r=>({value:Tr(r,e.dataKey),errorDomain:[]})):t.map(r=>({value:r,errorDomain:[]})));var u9=()=>{},Mze=yt([hA,Ii,mA,sA,Si],GI),Eze=yt([Ii,qI,VI,u9,Mze,u9,dr,Si],WI),ere=yt([Ii,dr,hA,Pze,Uw,Si,Eze],KI),jze=yt([ere,iy,ep],QI),Dze=yt([Ii,ere,jze,Si],JI);yt([ep,Dze],Ote);var Rze={radiusAxis:{},angleAxis:{}},tre=Ao({name:"polarAxis",initialState:Rze,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:wit,removeRadiusAxis:Sit,addAngleAxis:_it,removeAngleAxis:Nit}=tre.actions,Fze=tre.reducer;function nre(t){return t&&typeof t=="object"&&"className"in t&&typeof t.className=="string"?t.className:""}function d9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function m9(t){for(var e=1;ee,f4=yt([Jne,zze],(t,e)=>t.filter(n=>n.type==="pie").find(n=>n.id===e)),Uze=[],g4=(t,e,n)=>n?.length===0?Uze:n,rre=yt([QT,f4,g4],(t,e,n)=>{var{chartData:r}=t;if(e!=null){var a;if(e?.data!=null&&e.data.length>0?a=e.data:a=r,(!a||!a.length)&&n!=null&&(a=n.map(s=>m9(m9({},e.presentationProps),s.props))),a!=null)return a}}),Bze=yt([rre,f4,g4],(t,e,n)=>{if(!(t==null||e==null))return t.map((r,a)=>{var s,o=Tr(r,e.nameKey,e.name),l;return n!=null&&(s=n[a])!==null&&s!==void 0&&(s=s.props)!==null&&s!==void 0&&s.fill?l=n[a].props.fill:typeof r=="object"&&r!=null&&"fill"in r?l=r.fill:l=e.fill,{value:Xh(o,e.dataKey),color:l,payload:r,type:e.legendType}})}),Hze=yt([rre,f4,g4,va],(t,e,n,r)=>{if(!(e==null||t==null))return $Ue({offset:r,pieSettings:e,displayedData:t,cells:n})}),B2={exports:{}},zr={};var h9;function $ze(){if(h9)return zr;h9=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),a=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"),m=Symbol.for("react.lazy"),p=Symbol.for("react.view_transition"),f=Symbol.for("react.client.reference");function y(v){if(typeof v=="object"&&v!==null){var b=v.$$typeof;switch(b){case t:switch(v=v.type,v){case n:case a:case r:case c:case u:case p:return v;default:switch(v=v&&v.$$typeof,v){case o:case l:case m:case d:return v;case s:return v;default:return b}}case e:return b}}}return zr.ContextConsumer=s,zr.ContextProvider=o,zr.Element=t,zr.ForwardRef=l,zr.Fragment=n,zr.Lazy=m,zr.Memo=d,zr.Portal=e,zr.Profiler=a,zr.StrictMode=r,zr.Suspense=c,zr.SuspenseList=u,zr.isContextConsumer=function(v){return y(v)===s},zr.isContextProvider=function(v){return y(v)===o},zr.isElement=function(v){return typeof v=="object"&&v!==null&&v.$$typeof===t},zr.isForwardRef=function(v){return y(v)===l},zr.isFragment=function(v){return y(v)===n},zr.isLazy=function(v){return y(v)===m},zr.isMemo=function(v){return y(v)===d},zr.isPortal=function(v){return y(v)===e},zr.isProfiler=function(v){return y(v)===a},zr.isStrictMode=function(v){return y(v)===r},zr.isSuspense=function(v){return y(v)===c},zr.isSuspenseList=function(v){return y(v)===u},zr.isValidElementType=function(v){return typeof v=="string"||typeof v=="function"||v===n||v===a||v===r||v===c||v===u||typeof v=="object"&&v!==null&&(v.$$typeof===m||v.$$typeof===d||v.$$typeof===o||v.$$typeof===s||v.$$typeof===l||v.$$typeof===f||v.getModuleId!==void 0)},zr.typeOf=y,zr}var p9;function qze(){return p9||(p9=1,B2.exports=$ze()),B2.exports}var Vze=qze(),f9=t=>typeof t=="string"?t:t?t.displayName||t.name||"Component":"",g9=null,H2=null,ire=t=>{if(t===g9&&Array.isArray(H2))return H2;var e=[];return w.Children.forEach(t,n=>{gi(n)||(Vze.isFragment(n)?e=e.concat(ire(n.props.children)):e.push(n))}),H2=e,g9=t,e};function b4(t,e){var n=[],r=[];return Array.isArray(e)?r=e.map(a=>f9(a)):r=[f9(e)],ire(t).forEach(a=>{var s=Bf(a,"type.displayName")||Bf(a,"type.name");s&&r.indexOf(s)!==-1&&n.push(a)}),n}var x4=t=>t&&typeof t=="object"&&"clipDot"in t?!!t.clipDot:!0,$2={},b9;function Gze(){return b9||(b9=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 a=n[Symbol.toStringTag];return a==null||!Object.getOwnPropertyDescriptor(n,Symbol.toStringTag)?.writable?!1:n.toString()===`[object ${a}]`}let r=n;for(;Object.getPrototypeOf(r)!==null;)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(n)===r}t.isPlainObject=e})($2)),$2}var q2,x9;function Wze(){return x9||(x9=1,q2=Gze().isPlainObject),q2}var Kze=Wze();const Yze=Zl(Kze);var y9,v9,w9,S9,_9;function N9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function k9(t){for(var e=1;e{var s=n-r,o;return o=Mi(y9||(y9=Sv(["M ",",",""])),t,e),o+=Mi(v9||(v9=Sv(["L ",",",""])),t+n,e),o+=Mi(w9||(w9=Sv(["L ",",",""])),t+n-s/2,e+a),o+=Mi(S9||(S9=Sv(["L ",",",""])),t+n-s/2-r,e+a),o+=Mi(_9||(_9=Sv(["L ",","," Z"])),t,e),o},Jze={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},eUe=t=>{var e=wi(t,Jze),{x:n,y:r,upperWidth:a,lowerWidth:s,height:o,className:l}=e,{animationEasing:c,animationDuration:u,animationBegin:d,isUpdateAnimationActive:m}=e,p=w.useRef(null),[f,y]=w.useState(-1),v=w.useRef(a),b=w.useRef(s),g=w.useRef(o),_=w.useRef(n),N=w.useRef(r),C=Jx(t,"trapezoid-");if(w.useEffect(()=>{if(p.current&&p.current.getTotalLength)try{var I=p.current.getTotalLength();I&&y(I)}catch{}},[]),n!==+n||r!==+r||a!==+a||s!==+s||o!==+o||a===0&&s===0||o===0)return null;var k=hr("recharts-trapezoid",l);if(!m)return w.createElement("g",null,w.createElement("path",Gk({},ls(e),{className:k,d:C9(n,r,a,s,o)})));var P=v.current,T=b.current,D=g.current,A=_.current,R=N.current,G="0px ".concat(f===-1?1:f,"px"),z="".concat(f,"px 0px"),Z=Cee(["strokeDasharray"],u,c);return w.createElement(Zx,{animationId:C,key:C,canBegin:f>0,duration:u,easing:c,isActive:m,begin:d},I=>{var J=Cr(P,a,I),ae=Cr(T,s,I),Y=Cr(D,o,I),ue=Cr(A,n,I),de=Cr(R,r,I);p.current&&(v.current=J,b.current=ae,g.current=Y,_.current=ue,N.current=de);var he=I>0?{transition:Z,strokeDasharray:z}:{strokeDasharray:G};return w.createElement("path",Gk({},ls(e),{className:k,d:C9(ue,de,J,ae,Y),ref:p,style:k9(k9({},he),e.style)}))})},tUe=["option","shapeType","activeClassName"];function nUe(t,e){if(t==null)return{};var n,r,a=rUe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var r=Jr();return(a,s)=>o=>{t?.(a,s,o),r(hne({activeIndex:String(s),activeDataKey:e,activeCoordinate:a.tooltipPosition,activeGraphicalItemId:n}))}},w4=t=>{var e=Jr();return(n,r)=>a=>{t?.(n,r,a),e(pIe())}},S4=(t,e,n)=>{var r=Jr();return(a,s)=>o=>{t?.(a,s,o),r(fIe({activeIndex:String(s),activeDataKey:e,activeCoordinate:a.tooltipPosition,activeGraphicalItemId:n}))}};function pA(t){var{tooltipEntrySettings:e}=t,n=Jr(),r=wa(),a=w.useRef(null);return w.useLayoutEffect(()=>{r||(a.current===null?n(uIe(e)):a.current!==e&&n(dIe({prev:a.current,next:e})),a.current=e)},[e,n,r]),w.useLayoutEffect(()=>()=>{a.current&&(n(mIe(a.current)),a.current=null)},[n]),null}function _4(t){var{legendPayload:e}=t,n=Jr(),r=wa(),a=w.useRef(null);return w.useLayoutEffect(()=>{r||(a.current===null?n(wee(e)):a.current!==e&&n(See({prev:a.current,next:e})),a.current=e)},[n,r,e]),w.useLayoutEffect(()=>()=>{a.current&&(n(_ee(a.current)),a.current=null)},[n]),null}function uUe(t){var{legendPayload:e}=t,n=Jr(),r=en(dr),a=w.useRef(null);return w.useLayoutEffect(()=>{r!=="centric"&&r!=="radial"||(a.current===null?n(wee(e)):a.current!==e&&n(See({prev:a.current,next:e})),a.current=e)},[n,r,e]),w.useLayoutEffect(()=>()=>{a.current&&(n(_ee(a.current)),a.current=null)},[n]),null}var V2,dUe=()=>{var[t]=w.useState(()=>O0("uid-"));return t},mUe=(V2=Lce.useId)!==null&&V2!==void 0?V2:dUe;function hUe(t,e){var n=mUe();return e||(t?"".concat(t,"-").concat(n):n)}var pUe=w.createContext(void 0),fA=t=>{var{id:e,type:n,children:r}=t,a=hUe("recharts-".concat(n),e);return w.createElement(pUe.Provider,{value:a},r(a))},fUe={cartesianItems:[],polarItems:[]},are=Ao({name:"graphicalItems",initialState:fUe,reducers:{addCartesianGraphicalItem:{reducer(t,e){t.cartesianItems.push(e.payload)},prepare:mi()},replaceCartesianGraphicalItem:{reducer(t,e){var{prev:n,next:r}=e.payload,a=Nc(t).cartesianItems.indexOf(n);a>-1&&(t.cartesianItems[a]=r)},prepare:mi()},removeCartesianGraphicalItem:{reducer(t,e){var n=Nc(t).cartesianItems.indexOf(e.payload);n>-1&&t.cartesianItems.splice(n,1)},prepare:mi()},addPolarGraphicalItem:{reducer(t,e){t.polarItems.push(e.payload)},prepare:mi()},removePolarGraphicalItem:{reducer(t,e){var n=Nc(t).polarItems.indexOf(e.payload);n>-1&&t.polarItems.splice(n,1)},prepare:mi()}}}),{addCartesianGraphicalItem:gUe,replaceCartesianGraphicalItem:bUe,removeCartesianGraphicalItem:xUe,addPolarGraphicalItem:yUe,removePolarGraphicalItem:vUe}=are.actions,wUe=are.reducer,SUe=t=>{var e=Jr(),n=w.useRef(null);return w.useLayoutEffect(()=>{n.current===null?e(gUe(t)):n.current!==t&&e(bUe({prev:n.current,next:t})),n.current=t},[e,t]),w.useLayoutEffect(()=>()=>{n.current&&(e(xUe(n.current)),n.current=null)},[e]),null},N4=w.memo(SUe);function _Ue(t){var e=Jr();return w.useLayoutEffect(()=>(e(yUe(t)),()=>{e(vUe(t))}),[e,t]),null}var NUe=["key"],kUe=["onMouseEnter","onClick","onMouseLeave"],CUe=["id"],TUe=["id"];function P9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Ei(t){for(var e=1;eb4(t.children,Mx),[t.children]),n=en(r=>Bze(r,t.id,e));return n==null?null:w.createElement(uUe,{legendPayload:n})}var DUe=w.memo(t=>{var{dataKey:e,nameKey:n,sectors:r,stroke:a,strokeWidth:s,fill:o,name:l,hide:c,tooltipType:u,id:d}=t,m={dataDefinedOnItem:r.map(p=>p.tooltipPayload),getPosition:p=>{var f;return(f=r[Number(p)])===null||f===void 0?void 0:f.tooltipPosition},settings:{stroke:a,strokeWidth:s,fill:o,dataKey:e,nameKey:n,name:Xh(l,e),hide:c,type:u,color:o,unit:"",graphicalItemId:d}};return w.createElement(pA,{tooltipEntrySettings:m})}),RUe=(t,e)=>t>e?"start":tws(typeof e=="function"?e(t):e,n,n*.8),LUe=(t,e,n)=>{var{top:r,left:a,width:s,height:o}=e,l=Eee(s,o),c=a+ws(t.cx,s,s/2),u=r+ws(t.cy,o,o/2),d=ws(t.innerRadius,l,0),m=FUe(n,t.outerRadius,l),p=t.maxRadius||Math.sqrt(s*s+o*o)/2;return{cx:c,cy:u,innerRadius:d,outerRadius:m,maxRadius:p}},OUe=(t,e)=>{var n=Fa(e-t),r=Math.min(Math.abs(e-t),360);return n*r},IUe=(t,e)=>{if(w.isValidElement(t))return w.cloneElement(t,e);if(typeof t=="function")return t(e);var n=hr("recharts-pie-label-line",typeof t!="boolean"?t.className:""),{key:r}=e,a=gA(e,NUe);return w.createElement(nx,Gh({},a,{type:"linear",className:n}))},zUe=(t,e,n)=>{if(w.isValidElement(t))return w.cloneElement(t,e);var r=n;if(typeof t=="function"&&(r=t(e),w.isValidElement(r)))return r;var a=hr("recharts-pie-label-text",nre(t));return w.createElement(uA,Gh({},e,{alignmentBaseline:"middle",className:a}),r)};function UUe(t){var{sectors:e,props:n,showLabels:r}=t,{label:a,labelLine:s,dataKey:o}=n;if(!r||!a||!e)return null;var l=Ys(n),c=zf(a),u=zf(s),d=typeof a=="object"&&"offsetRadius"in a&&typeof a.offsetRadius=="number"&&a.offsetRadius||20,m=e.map((p,f)=>{var y=(p.startAngle+p.endAngle)/2,v=aa(p.cx,p.cy,p.outerRadius+d,y),b=Ei(Ei(Ei(Ei({},l),p),{},{stroke:"none"},c),{},{index:f,textAnchor:RUe(v.x,p.cx)},v),g=Ei(Ei(Ei(Ei({},l),p),{},{fill:"none",stroke:p.fill},u),{},{index:f,points:[aa(p.cx,p.cy,p.outerRadius,y),v],key:"line"});return w.createElement(Ns,{zIndex:Fi.label,key:"label-".concat(p.startAngle,"-").concat(p.endAngle,"-").concat(p.midAngle,"-").concat(f)},w.createElement(vi,null,s&&IUe(s,g),zUe(a,b,Tr(p,o))))});return w.createElement(vi,{className:"recharts-pie-labels"},m)}function BUe(t){var{sectors:e,props:n,showLabels:r}=t,{label:a}=n;return typeof a=="object"&&a!=null&&"position"in a?w.createElement(dA,{label:a}):w.createElement(UUe,{sectors:e,props:n,showLabels:r})}function HUe(t){var{sectors:e,activeShape:n,inactiveShape:r,allOtherPieProps:a,shape:s,id:o}=t,l=en(Vh),c=en(l4),u=en(e4e),{onMouseEnter:d,onClick:m,onMouseLeave:p}=a,f=gA(a,kUe),y=v4(d,a.dataKey,o),v=w4(p),b=S4(m,a.dataKey,o);return e==null||e.length===0?null:w.createElement(w.Fragment,null,e.map((g,_)=>{if(g?.startAngle===0&&g?.endAngle===0&&e.length!==1)return null;var N=u==null||u===o,C=String(_)===l&&(c==null||a.dataKey===c)&&N,k=l?r:null,P=n&&C?n:k,T=Ei(Ei({},g),{},{stroke:g.stroke,tabIndex:-1,[oee]:_,[lee]:o});return w.createElement(vi,Gh({key:"sector-".concat(g?.startAngle,"-").concat(g?.endAngle,"-").concat(g.midAngle,"-").concat(_),tabIndex:-1,className:"recharts-pie-sector"},Aw(f,g,_),{onMouseEnter:y(g,_),onMouseLeave:v(g,_),onClick:b(g,_)}),w.createElement(y4,Gh({option:s??P,index:_,shapeType:"sector",isActive:C},T)))}))}function $Ue(t){var e,{pieSettings:n,displayedData:r,cells:a,offset:s}=t,{cornerRadius:o,startAngle:l,endAngle:c,dataKey:u,nameKey:d,tooltipType:m}=n,p=Math.abs(n.minAngle),f=OUe(l,c),y=Math.abs(f),v=r.length<=1?0:(e=n.paddingAngle)!==null&&e!==void 0?e:0,b=r.filter(P=>Tr(P,u,0)!==0).length,g=(y>=360?b:b-1)*v,_=y-b*p-g,N=r.reduce((P,T)=>{var D=Tr(T,u,0);return P+(Yt(D)?D:0)},0),C;if(N>0){var k;C=r.map((P,T)=>{var D=Tr(P,u,0),A=Tr(P,d,T),R=LUe(n,s,P),G=(Yt(D)?D:0)/N,z,Z=Ei(Ei({},P),a&&a[T]&&a[T].props);T?z=k.endAngle+Fa(f)*v*(D!==0?1:0):z=l;var I=z+Fa(f)*((D!==0?p:0)+G*_),J=(z+I)/2,ae=(R.innerRadius+R.outerRadius)/2,Y=[{name:A,value:D,payload:Z,dataKey:u,type:m,graphicalItemId:n.id}],ue=aa(R.cx,R.cy,ae,J);return k=Ei(Ei(Ei(Ei({},n.presentationProps),{},{percent:G,cornerRadius:typeof o=="string"?parseFloat(o):o,name:A,tooltipPayload:Y,midAngle:J,middleRadius:ae,tooltipPosition:ue},Z),R),{},{value:D,dataKey:u,startAngle:z,endAngle:I,payload:Z,paddingAngle:Fa(f)*v}),k})}return C}function qUe(t){var{showLabels:e,sectors:n,children:r}=t,a=w.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 w.createElement(Nze,{value:e?a:void 0},r)}function VUe(t){var{props:e,previousSectorsRef:n,id:r}=t,{sectors:a,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,activeShape:u,inactiveShape:d,onAnimationStart:m,onAnimationEnd:p}=e,f=Jx(e,"recharts-pie-"),y=n.current,[v,b]=w.useState(!1),g=w.useCallback(()=>{typeof p=="function"&&p(),b(!1)},[p]),_=w.useCallback(()=>{typeof m=="function"&&m(),b(!0)},[m]);return w.createElement(qUe,{showLabels:!v,sectors:a},w.createElement(Zx,{animationId:f,begin:o,duration:l,isActive:s,easing:c,onAnimationStart:_,onAnimationEnd:g,key:f},N=>{var C,k=[],P=a&&a[0],T=(C=P?.startAngle)!==null&&C!==void 0?C:0;return a?.forEach((D,A)=>{var R=y&&y[A],G=A>0?Bf(D,"paddingAngle",0):0;if(R){var z=Cr(R.endAngle-R.startAngle,D.endAngle-D.startAngle,N),Z=Ei(Ei({},D),{},{startAngle:T+G,endAngle:T+z+G});k.push(Z),T=Z.endAngle}else{var{endAngle:I,startAngle:J}=D,ae=Cr(0,I-J,N),Y=Ei(Ei({},D),{},{startAngle:T+G,endAngle:T+ae+G});k.push(Y),T=Y.endAngle}}),n.current=k,w.createElement(vi,null,w.createElement(HUe,{sectors:k,activeShape:u,inactiveShape:d,allOtherPieProps:e,shape:e.shape,id:r}))}),w.createElement(BUe,{showLabels:!v,sectors:a,props:e}),e.children)}var GUe={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:Fi.area};function WUe(t){var{id:e}=t,n=gA(t,CUe),{hide:r,className:a,rootTabIndex:s}=t,o=w.useMemo(()=>b4(t.children,Mx),[t.children]),l=en(d=>Hze(d,e,o)),c=w.useRef(null),u=hr("recharts-pie",a);return r||l==null?(c.current=null,w.createElement(vi,{tabIndex:s,className:u})):w.createElement(Ns,{zIndex:t.zIndex},w.createElement(DUe,{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,id:e}),w.createElement(vi,{tabIndex:s,className:u},w.createElement(VUe,{props:Ei(Ei({},n),{},{sectors:l}),previousSectorsRef:c,id:e})))}function CF(t){var e=wi(t,GUe),{id:n}=e,r=gA(e,TUe),a=Ys(r);return w.createElement(fA,{id:n,type:"pie"},s=>w.createElement(w.Fragment,null,w.createElement(_Ue,{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:a,maxRadius:e.maxRadius}),w.createElement(jUe,Gh({},r,{id:s})),w.createElement(WUe,Gh({},r,{id:s}))))}CF.displayName="Pie";var KUe=["points"];function M9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function G2(t){for(var e=1;e{var b,g,_=G2(G2(G2({r:3},o),m),{},{index:v,cx:(b=y.x)!==null&&b!==void 0?b:void 0,cy:(g=y.y)!==null&&g!==void 0?g:void 0,dataKey:s,value:y.value,payload:y.payload,points:e});return w.createElement(eBe,{key:"dot-".concat(v),option:n,dotProps:_,className:a})}),f={};return l&&c!=null&&(f.clipPath="url(#clipPath-".concat(d?"":"dots-").concat(c,")")),w.createElement(Ns,{zIndex:u},w.createElement(vi,Kk({className:r},f),p))}function E9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function j9(t){for(var e=1;e({top:t.top,bottom:t.bottom,left:t.left,right:t.right})),fBe=yt([pBe,tm,nm],(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)}}),bA=()=>en(fBe),gBe=()=>en(a4e);function D9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function W2(t){for(var e=1;e{var{point:e,childIndex:n,mainColor:r,activeDot:a,dataKey:s,clipPath:o}=t;if(a===!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=W2(W2(W2({},l),zf(a)),UO(a)),u;return w.isValidElement(a)?u=w.cloneElement(a,c):typeof a=="function"?u=a(c):u=w.createElement(Zne,c),w.createElement(vi,{className:"recharts-active-dot",clipPath:o},u)};function TF(t){var{points:e,mainColor:n,activeDot:r,itemDataKey:a,clipPath:s,zIndex:o=Fi.activeDot}=t,l=en(Vh),c=gBe();if(e==null||c==null)return null;var u=e.find(d=>c.includes(d.payload));return gi(u)?null:w.createElement(Ns,{zIndex:o},w.createElement(vBe,{point:u,childIndex:Number(l),mainColor:n,dataKey:a,activeDot:r,clipPath:s}))}var R9=(t,e,n)=>{var r=n??t;if(!gi(r))return ws(r,e,0)},wBe=(t,e,n)=>{var r={},a=t.filter(nA),s=t.filter(u=>u.stackId==null),o=a.reduce((u,d)=>{var m=u[d.stackId];return m==null&&(m=[]),m.push(d),u[d.stackId]=m,u},r),l=Object.entries(o).map(u=>{var d,[m,p]=u,f=p.map(v=>v.dataKey),y=R9(e,n,(d=p[0])===null||d===void 0?void 0:d.barSize);return{stackId:m,dataKeys:f,barSize:y}}),c=s.map(u=>{var d=[u.dataKey].filter(p=>p!=null),m=R9(e,n,u.barSize);return{stackId:void 0,dataKeys:d,barSize:m}});return[...l,...c]};function F9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function P1(t){for(var e=1;e_+(N.barSize||0),0);p+=(o-1)*l,p>=n&&(p-=(o-1)*l,l=0),p>=n&&m>0&&(d=!0,m*=.9,p=o*m);var f=(n-p)/2>>0,y={offset:f-l,size:0};c=r.reduce((_,N)=>{var C,k={stackId:N.stackId,dataKeys:N.dataKeys,position:{offset:y.offset+y.size+l,size:d?m:(C=N.barSize)!==null&&C!==void 0?C:0}},P=[..._,k];return y=k.position,P},u)}else{var v=ws(e,n,0,!0);n-2*v-(o-1)*l<=0&&(l=0);var b=(n-2*v-(o-1)*l)/o;b>1&&(b>>=0);var g=Ln(a)?Math.min(b,a):b;c=r.reduce((_,N,C)=>[..._,{stackId:N.stackId,dataKeys:N.dataKeys,position:{offset:v+(b+l)*C+(b-g)/2,size:g}}],u)}return c}}var CBe=(t,e,n,r,a,s,o)=>{var l=gi(o)?e:o,c=kBe(n,r,a!==s?a:s,t,l);return a!==s&&c!=null&&(c=c.map(u=>P1(P1({},u),{},{position:P1(P1({},u.position),{},{offset:u.position.offset-a/2})}))),c},TBe=(t,e)=>{var n=tA(e);if(!(!t||n==null||e==null)){var{stackId:r}=e;if(r!=null){var a=t[r];if(a){var{stackedData:s}=a;if(s)return s.find(o=>o.key===n)}}}},ABe=(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}};function PBe(t,e){return t&&typeof t=="object"&&"zIndex"in t&&typeof t.zIndex=="number"&&Ln(t.zIndex)?t.zIndex:e}var cre=t=>{var{chartData:e}=t,n=Jr(),r=wa();return w.useEffect(()=>r?()=>{}:(n(BG(e)),()=>{n(BG(void 0))}),[e,n,r]),null},L9={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},ure=Ao({name:"brush",initialState:L9,reducers:{setBrushSettings(t,e){return e.payload==null?L9:e.payload}}}),{setBrushSettings:Ait}=ure.actions,MBe=ure.reducer,EBe=(t,e)=>{var{x:n,y:r}=t,{x:a,y:s}=e;return{x:Math.min(n,a),y:Math.min(r,s),width:Math.abs(a-n),height:Math.abs(s-r)}},jBe=t=>{var{x1:e,y1:n,x2:r,y2:a}=t;return EBe({x:e,y:n},{x:r,y:a})};function DBe(t){return(t%180+180)%180}var RBe=function(e){var{width:n,height:r}=e,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,s=DBe(a),o=s*Math.PI/180,l=Math.atan(r/n),c=o>l&&o{t.dots.push(e.payload)},removeDot:(t,e)=>{var n=Nc(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=Nc(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=Nc(t).lines.findIndex(r=>r===e.payload);n!==-1&&t.lines.splice(n,1)}}}),{addDot:Pit,removeDot:Mit,addArea:Eit,removeArea:jit,addLine:LBe,removeLine:OBe}=dre.actions,IBe=dre.reducer,mre=w.createContext(void 0),zBe=t=>{var{children:e}=t,[n]=w.useState("".concat(O0("recharts"),"-clip")),r=bA();if(r==null)return null;var{x:a,y:s,width:o,height:l}=r;return w.createElement(mre.Provider,{value:n},w.createElement("defs",null,w.createElement("clipPath",{id:n},w.createElement("rect",{x:a,y:s,height:l,width:o}))),e)},UBe=()=>w.useContext(mre);class BBe{constructor(e){var{x:n,y:r}=e;this.xAxisScale=n,this.yAxisScale=r}map(e,n){var r,a,{position:s}=n;return{x:(r=this.xAxisScale.map(e.x,{position:s}))!==null&&r!==void 0?r:0,y:(a=this.yAxisScale.map(e.y,{position:s}))!==null&&a!==void 0?a:0}}mapWithFallback(e,n){var r,a,{position:s,fallback:o}=n,l,c;return o==="rangeMin"?l=this.yAxisScale.rangeMin():o==="rangeMax"?l=this.yAxisScale.rangeMax():l=0,o==="rangeMin"?c=this.xAxisScale.rangeMin():o==="rangeMax"?c=this.xAxisScale.rangeMax():c=0,{x:(r=this.xAxisScale.map(e.x,{position:s}))!==null&&r!==void 0?r:c,y:(a=this.yAxisScale.map(e.y,{position:s}))!==null&&a!==void 0?a:l}}isInRange(e){var{x:n,y:r}=e,a=n==null||this.xAxisScale.isInRange(n),s=r==null||this.yAxisScale.isInRange(r);return a&&s}}function O9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function I9(t){for(var e=1;e{var n;if(w.isValidElement(t))n=w.cloneElement(t,e);else if(typeof t=="function")n=t(e);else{if(!Ln(e.x1)||!Ln(e.y1)||!Ln(e.x2)||!Ln(e.y2))return null;n=w.createElement("line",Yk({},e,{className:"recharts-reference-line-line"}))}return n},GBe=(t,e,n,r,a,s)=>{var{x:o,width:l}=s,c=a.map(t,{position:n});if(!Ln(c)||e==="discard"&&!a.isInRange(c))return null;var u=[{x:o+l,y:c},{x:o,y:c}];return r==="left"?u.reverse():u},WBe=(t,e,n,r,a,s)=>{var{y:o,height:l}=s,c=a.map(t,{position:n});if(!Ln(c)||e==="discard"&&!a.isInRange(c))return null;var u=[{x:c,y:o+l},{x:c,y:o}];return r==="top"?u.reverse():u},KBe=(t,e,n,r)=>{var a=[r.mapWithFallback(t[0],{position:n,fallback:"rangeMin"}),r.mapWithFallback(t[1],{position:n,fallback:"rangeMax"})];return e==="discard"&&a.some(s=>!r.isInRange(s))?null:a},YBe=(t,e,n,r,a,s,o)=>{var{x:l,y:c,segment:u,ifOverflow:d}=o,m=Kl(l),p=Kl(c);return p?GBe(c,d,r,s,e,n):m?WBe(l,d,r,a,t,n):u!=null&&u.length===2?KBe(u,d,r,new BBe({x:t,y:e})):null};function XBe(t){var e=Jr();return w.useEffect(()=>(e(LBe(t)),()=>{e(OBe(t))})),null}function QBe(t){var{xAxisId:e,yAxisId:n,shape:r,className:a,ifOverflow:s}=t,o=wa(),l=UBe(),c=en(T=>Au(T,e)),u=en(T=>Pu(T,n)),d=en(T=>Px(T,"xAxis",e,o)),m=en(T=>Px(T,"yAxis",n,o)),p=jw();if(!l||!p||c==null||u==null||d==null||m==null)return null;var f=YBe(d,m,p,t.position,c.orientation,u.orientation,t);if(!f)return null;var y=f[0],v=f[1];if(y==null||v==null)return null;var{x:b,y:g}=y,{x:_,y:N}=v,C=s==="hidden"?"url(#".concat(l,")"):void 0,k=I9(I9({clipPath:C},ls(t)),{},{x1:b,y1:g,x2:_,y2:N}),P=jBe({x1:b,y1:g,x2:_,y2:N});return w.createElement(Ns,{zIndex:t.zIndex},w.createElement(vi,{className:hr("recharts-reference-line",a)},VBe(r,k),w.createElement(Wne,Yk({},P,{lowerWidth:P.width,upperWidth:P.width}),w.createElement(Yne,{label:t.label}),t.children)))}var ZBe={ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",label:!1,stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle",zIndex:Fi.line};function Iv(t){var e=wi(t,ZBe);return w.createElement(w.Fragment,null,w.createElement(XBe,{yAxisId:e.yAxisId,xAxisId:e.xAxisId,ifOverflow:e.ifOverflow,x:e.x,y:e.y,segment:e.segment}),w.createElement(QBe,e))}Iv.displayName="ReferenceLine";function hre(t,e){if(e<1)return[];if(e===1)return t;for(var n=[],r=0;rt*a)return!1;var s=n();return t*(e-t*s/2-r)>=0&&t*(e+t*s/2-a)<=0}function t8e(t,e){return hre(t,e+1)}function n8e(t,e,n,r,a){for(var s=(r||[]).slice(),{start:o,end:l}=e,c=0,u=1,d=o,m=function(){var y=r?.[c];if(y===void 0)return{v:hre(r,u)};var v=c,b,g=()=>(b===void 0&&(b=n(y,v)),b),_=y.coordinate,N=c===0||Q0(t,_,g,d,l);N||(c=0,d=o,u+=1),N&&(d=_+t*(g()/2+a),c+=u)},p;u<=s.length;)if(p=m(),p)return p.v;return[]}function r8e(t,e,n,r,a){var s=(r||[]).slice(),o=s.length;if(o===0)return[];for(var{start:l,end:c}=e,u=1;u<=o;u++){for(var d=(o-1)%u,m=l,p=!0,f=function(){var C=r[v];if(C==null)return 0;var k=v,P,T=()=>(P===void 0&&(P=n(C,k)),P),D=C.coordinate,A=v===d||Q0(t,D,T,m,c);if(!A)return p=!1,1;A&&(m=D+t*(T()/2+a))},y,v=d;v(v===void 0&&(v=n(f,p)),v);if(p===o-1){var g=t*(y.coordinate+t*b()/2-c);s[p]=y=gs(gs({},y),{},{tickCoord:g>0?y.coordinate-g*t:y.coordinate})}else s[p]=y=gs(gs({},y),{},{tickCoord:y.coordinate});if(y.tickCoord!=null){var _=Q0(t,y.tickCoord,b,l,c);_&&(c=y.tickCoord-t*(b()/2+a),s[p]=gs(gs({},y),{},{isShow:!0}))}},d=o-1;d>=0;d--)u(d);return s}function l8e(t,e,n,r,a,s){var o=(r||[]).slice(),l=o.length,{start:c,end:u}=e;if(s){var d=r[l-1];if(d!=null){var m=n(d,l-1),p=t*(d.coordinate+t*m/2-u);if(o[l-1]=d=gs(gs({},d),{},{tickCoord:p>0?d.coordinate-p*t:d.coordinate}),d.tickCoord!=null){var f=Q0(t,d.tickCoord,()=>m,c,u);f&&(u=d.tickCoord-t*(m/2+a),o[l-1]=gs(gs({},d),{},{isShow:!0}))}}}for(var y=s?l-1:l,v=function(_){var N=o[_];if(N==null)return 1;var C=N,k,P=()=>(k===void 0&&(k=n(N,_)),k);if(_===0){var T=t*(C.coordinate-t*P()/2-c);o[_]=C=gs(gs({},C),{},{tickCoord:T<0?C.coordinate-T*t:C.coordinate})}else o[_]=C=gs(gs({},C),{},{tickCoord:C.coordinate});if(C.tickCoord!=null){var D=Q0(t,C.tickCoord,P,c,u);D&&(c=C.tickCoord+t*(P()/2+a),o[_]=gs(gs({},C),{},{isShow:!0}))}},b=0;b{var T=typeof u=="function"?u(k.value,P):k.value;return y==="width"?JBe(Jv(T,{fontSize:e,letterSpacing:n}),v,m):Jv(T,{fontSize:e,letterSpacing:n})[y]},g=a[0],_=a[1],N=a.length>=2&&g!=null&&_!=null?Fa(_.coordinate-g.coordinate):1,C=e8e(s,N,y);return c==="equidistantPreserveStart"?n8e(N,C,b,a,o):c==="equidistantPreserveEnd"?r8e(N,C,b,a,o):(c==="preserveStart"||c==="preserveStartEnd"?f=l8e(N,C,b,a,o,c==="preserveStartEnd"):f=o8e(N,C,b,a,o),f.filter(k=>k.isShow))}var c8e=t=>{var{ticks:e,label:n,labelGapWithTick:r=5,tickSize:a=0,tickMargin:s=0}=t,o=0;if(e){Array.from(e).forEach(d=>{if(d){var m=d.getBoundingClientRect();m.width>o&&(o=m.width)}});var l=n?n.getBoundingClientRect().width:0,c=a+s,u=o+c+l+(n?r:0);return Math.round(u)}return 0},u8e=["axisLine","width","height","className","hide","ticks","axisType"];function d8e(t,e){if(t==null)return{};var n,r,a=m8e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var{ticks:n=[],tick:r,tickLine:a,stroke:s,tickFormatter:o,unit:l,padding:c,tickTextProps:u,orientation:d,mirror:m,x:p,y:f,width:y,height:v,tickSize:b,tickMargin:g,fontSize:_,letterSpacing:N,getTicksConfig:C,events:k,axisType:P}=t,T=k4(Pi(Pi({},C),{},{ticks:n}),_,N),D=x8e(d,m),A=y8e(d,m),R=Ys(C),G=zf(r),z={};typeof a=="object"&&(z=a);var Z=Pi(Pi({},R),{},{fill:"none"},z),I=T.map(Y=>Pi({entry:Y},b8e(Y,p,f,y,v,d,b,m,g))),J=I.map(Y=>{var{entry:ue,line:de}=Y;return w.createElement(vi,{className:"recharts-cartesian-axis-tick",key:"tick-".concat(ue.value,"-").concat(ue.coordinate,"-").concat(ue.tickCoord)},a&&w.createElement("line",Wf({},Z,de,{className:hr("recharts-cartesian-axis-tick-line",Bf(a,"className"))})))}),ae=I.map((Y,ue)=>{var de,he,{entry:V,tick:ne}=Y,se=Pi(Pi(Pi(Pi({verticalAnchor:A},R),{},{textAnchor:D,stroke:"none",fill:s},ne),{},{index:ue,payload:V,visibleTicksCount:T.length,tickFormatter:o,padding:c},u),{},{angle:(de=(he=u?.angle)!==null&&he!==void 0?he:R.angle)!==null&&de!==void 0?de:0}),pe=Pi(Pi({},se),G);return w.createElement(vi,Wf({className:"recharts-cartesian-axis-tick-label",key:"tick-label-".concat(V.value,"-").concat(V.coordinate,"-").concat(V.tickCoord)},Aw(k,V,ue)),r&&w.createElement(v8e,{option:r,tickProps:pe,value:"".concat(typeof o=="function"?o(V.value,ue):V.value).concat(l||"")}))});return w.createElement("g",{className:"recharts-cartesian-axis-ticks recharts-".concat(P,"-ticks")},ae.length>0&&w.createElement(Ns,{zIndex:Fi.label},w.createElement("g",{className:"recharts-cartesian-axis-tick-labels recharts-".concat(P,"-tick-labels"),ref:e},ae)),J.length>0&&w.createElement("g",{className:"recharts-cartesian-axis-tick-lines recharts-".concat(P,"-tick-lines")},J))}),S8e=w.forwardRef((t,e)=>{var{axisLine:n,width:r,height:a,className:s,hide:o,ticks:l,axisType:c}=t,u=d8e(t,u8e),[d,m]=w.useState(""),[p,f]=w.useState(""),y=w.useRef(null);w.useImperativeHandle(e,()=>({getCalculatedWidth:()=>{var b;return c8e({ticks:y.current,label:(b=t.labelRef)===null||b===void 0?void 0:b.current,labelGapWithTick:5,tickSize:t.tickSize,tickMargin:t.tickMargin})}}));var v=w.useCallback(b=>{if(b){var g=b.getElementsByClassName("recharts-cartesian-axis-tick-value");y.current=g;var _=g[0];if(_){var N=window.getComputedStyle(_),C=N.fontSize,k=N.letterSpacing;(C!==d||k!==p)&&(m(C),f(k))}}},[d,p]);return o||r!=null&&r<=0||a!=null&&a<=0?null:w.createElement(Ns,{zIndex:t.zIndex},w.createElement(vi,{className:hr("recharts-cartesian-axis",s)},w.createElement(g8e,{x:t.x,y:t.y,width:r,height:a,orientation:t.orientation,mirror:t.mirror,axisLine:n,otherSvgProps:Ys(t)}),w.createElement(w8e,{ref:v,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}),w.createElement(Wne,{x:t.x,y:t.y,width:t.width,height:t.height,lowerWidth:t.width,upperWidth:t.width},w.createElement(Yne,{label:t.label,labelRef:t.labelRef}),t.children)))}),C4=w.forwardRef((t,e)=>{var n=wi(t,Fd);return w.createElement(S8e,Wf({},n,{ref:e}))});C4.displayName="CartesianAxis";var _8e=["x1","y1","x2","y2","key"],N8e=["offset"],k8e=["xAxisId","yAxisId"],C8e=["xAxisId","yAxisId"];function B9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function ys(t){for(var e=1;e{var{fill:e}=t;if(!e||e==="none")return null;var{fillOpacity:n,x:r,y:a,width:s,height:o,ry:l}=t;return w.createElement("rect",{x:r,y:a,ry:l,width:s,height:o,stroke:"none",fill:e,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function pre(t){var{option:e,lineItemProps:n}=t,r;if(w.isValidElement(e))r=w.cloneElement(e,n);else if(typeof e=="function")r=e(n);else{var a,{x1:s,y1:o,x2:l,y2:c,key:u}=n,d=Xk(n,_8e),m=(a=Ys(d))!==null&&a!==void 0?a:{},{offset:p}=m,f=Xk(m,N8e);r=w.createElement("line",nf({},f,{x1:s,y1:o,x2:l,y2:c,fill:"none",key:u}))}return r}function j8e(t){var{x:e,width:n,horizontal:r=!0,horizontalPoints:a}=t;if(!r||!a||!a.length)return null;var{xAxisId:s,yAxisId:o}=t,l=Xk(t,k8e),c=a.map((u,d)=>{var m=ys(ys({},l),{},{x1:e,y1:u,x2:e+n,y2:u,key:"line-".concat(d),index:d});return w.createElement(pre,{key:"line-".concat(d),option:r,lineItemProps:m})});return w.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function D8e(t){var{y:e,height:n,vertical:r=!0,verticalPoints:a}=t;if(!r||!a||!a.length)return null;var{xAxisId:s,yAxisId:o}=t,l=Xk(t,C8e),c=a.map((u,d)=>{var m=ys(ys({},l),{},{x1:u,y1:e,x2:u,y2:e+n,key:"line-".concat(d),index:d});return w.createElement(pre,{option:r,lineItemProps:m,key:"line-".concat(d)})});return w.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function R8e(t){var{horizontalFill:e,fillOpacity:n,x:r,y:a,width:s,height:o,horizontalPoints:l,horizontal:c=!0}=t;if(!c||!e||!e.length||l==null)return null;var u=l.map(m=>Math.round(m+a-a)).sort((m,p)=>m-p);a!==u[0]&&u.unshift(0);var d=u.map((m,p)=>{var f=u[p+1],y=f==null,v=y?a+o-m:f-m;if(v<=0)return null;var b=p%e.length;return w.createElement("rect",{key:"react-".concat(p),y:m,x:r,height:v,width:s,stroke:"none",fill:e[b],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return w.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},d)}function F8e(t){var{vertical:e=!0,verticalFill:n,fillOpacity:r,x:a,y:s,width:o,height:l,verticalPoints:c}=t;if(!e||!n||!n.length)return null;var u=c.map(m=>Math.round(m+a-a)).sort((m,p)=>m-p);a!==u[0]&&u.unshift(0);var d=u.map((m,p)=>{var f=u[p+1],y=f==null,v=y?a+o-m:f-m;if(v<=0)return null;var b=p%n.length;return w.createElement("rect",{key:"react-".concat(p),x:m,y:s,width:v,height:l,stroke:"none",fill:n[b],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return w.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},d)}var L8e=(t,e)=>{var{xAxis:n,width:r,height:a,offset:s}=t;return ree(k4(ys(ys(ys({},Fd),n),{},{ticks:iee(n),viewBox:{x:0,y:0,width:r,height:a}})),s.left,s.left+s.width,e)},O8e=(t,e)=>{var{yAxis:n,width:r,height:a,offset:s}=t;return ree(k4(ys(ys(ys({},Fd),n),{},{ticks:iee(n),viewBox:{x:0,y:0,width:r,height:a}})),s.top,s.top+s.height,e)},I8e={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:Fi.grid};function rf(t){var e=JO(),n=eI(),r=mee(),a=ys(ys({},wi(t,I8e)),{},{x:Yt(t.x)?t.x:r.left,y:Yt(t.y)?t.y:r.top,width:Yt(t.width)?t.width:r.width,height:Yt(t.height)?t.height:r.height}),{xAxisId:s,yAxisId:o,x:l,y:c,width:u,height:d,syncWithTicks:m,horizontalValues:p,verticalValues:f}=a,y=wa(),v=en(A=>PG(A,"xAxis",s,y)),b=en(A=>PG(A,"yAxis",o,y));if(!vu(u)||!vu(d)||!Yt(l)||!Yt(c))return null;var g=a.verticalCoordinatesGenerator||L8e,_=a.horizontalCoordinatesGenerator||O8e,{horizontalPoints:N,verticalPoints:C}=a;if((!N||!N.length)&&typeof _=="function"){var k=p&&p.length,P=_({yAxis:b?ys(ys({},b),{},{ticks:k?p:b.ticks}):void 0,width:e??u,height:n??d,offset:r},k?!0:m);vk(Array.isArray(P),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(typeof P,"]")),Array.isArray(P)&&(N=P)}if((!C||!C.length)&&typeof g=="function"){var T=f&&f.length,D=g({xAxis:v?ys(ys({},v),{},{ticks:T?f:v.ticks}):void 0,width:e??u,height:n??d,offset:r},T?!0:m);vk(Array.isArray(D),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(typeof D,"]")),Array.isArray(D)&&(C=D)}return w.createElement(Ns,{zIndex:a.zIndex},w.createElement("g",{className:"recharts-cartesian-grid"},w.createElement(E8e,{fill:a.fill,fillOpacity:a.fillOpacity,x:a.x,y:a.y,width:a.width,height:a.height,ry:a.ry}),w.createElement(R8e,nf({},a,{horizontalPoints:N})),w.createElement(F8e,nf({},a,{verticalPoints:C})),w.createElement(j8e,nf({},a,{offset:r,horizontalPoints:N,xAxis:v,yAxis:b})),w.createElement(D8e,nf({},a,{offset:r,verticalPoints:C,xAxis:v,yAxis:b}))))}rf.displayName="CartesianGrid";var z8e={},fre=Ao({name:"errorBars",initialState:z8e,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:a}=e.payload;t[n]&&(t[n]=t[n].map(s=>s.dataKey===r.dataKey&&s.direction===r.direction?a:s))},removeErrorBar:(t,e)=>{var{itemId:n,errorBar:r}=e.payload;t[n]&&(t[n]=t[n].filter(a=>a.dataKey!==r.dataKey||a.direction!==r.direction))}}}),{addErrorBar:Dit,replaceErrorBar:Rit,removeErrorBar:Fit}=fre.actions,U8e=fre.reducer,B8e=["children"];function H8e(t,e){if(t==null)return{};var n,r,a=$8e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r({x:0,y:0,value:0}),errorBarOffset:0},V8e=w.createContext(q8e);function gre(t){var{children:e}=t,n=H8e(t,B8e);return w.createElement(V8e.Provider,{value:n},e)}function xA(t,e){var n,r,a=en(u=>Au(u,t)),s=en(u=>Pu(u,e)),o=(n=a?.allowDataOverflow)!==null&&n!==void 0?n:Ma.allowDataOverflow,l=(r=s?.allowDataOverflow)!==null&&r!==void 0?r:Ea.allowDataOverflow,c=o||l;return{needClip:c,needClipX:o,needClipY:l}}function T4(t){var{xAxisId:e,yAxisId:n,clipPathId:r}=t,a=bA(),{needClipX:s,needClipY:o,needClip:l}=xA(e,n);if(!l||!a)return null;var{x:c,y:u,width:d,height:m}=a;return w.createElement("clipPath",{id:"clipPath-".concat(r)},w.createElement("rect",{x:s?c:c-d/2,y:o?u:u-m/2,width:s?d:d*2,height:o?m:m*2}))}var bre=(t,e,n,r)=>_u(t,"xAxis",e,r),xre=(t,e,n,r)=>Su(t,"xAxis",e,r),yre=(t,e,n,r)=>_u(t,"yAxis",n,r),vre=(t,e,n,r)=>Su(t,"yAxis",n,r),G8e=yt([dr,bre,yre,xre,vre],(t,e,n,r,a)=>Fc(t,"xAxis")?qh(e,r,!1):qh(n,a,!1)),W8e=(t,e,n,r,a)=>a;function K8e(t){return t.type==="line"}var Y8e=yt([Hw,W8e],(t,e)=>t.filter(K8e).find(n=>n.id===e)),X8e=yt([dr,bre,yre,xre,vre,Y8e,G8e,TI],(t,e,n,r,a,s,o,l)=>{var{chartData:c,dataStartIndex:u,dataEndIndex:d}=l;if(!(s==null||e==null||n==null||r==null||a==null||r.length===0||a.length===0||o==null||t!=="horizontal"&&t!=="vertical")){var{dataKey:m,data:p}=s,f;if(p!=null&&p.length>0?f=p:f=c?.slice(u,d+1),f!=null)return L6e({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:a,dataKey:m,bandSize:o,displayedData:f})}});function wre(t){var e=zf(t),n=3,r=2;if(e!=null){var{r:a,strokeWidth:s}=e,o=Number(a),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 K2={exports:{}},Y2={};var H9;function Q8e(){if(H9)return Y2;H9=1;var t=Jf();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,a=t.useRef,s=t.useEffect,o=t.useMemo,l=t.useDebugValue;return Y2.useSyncExternalStoreWithSelector=function(c,u,d,m,p){var f=a(null);if(f.current===null){var y={hasValue:!1,value:null};f.current=y}else y=f.current;f=o(function(){function b(k){if(!g){if(g=!0,_=k,k=m(k),p!==void 0&&y.hasValue){var P=y.value;if(p(P,k))return N=P}return N=k}if(P=N,n(_,k))return P;var T=m(k);return p!==void 0&&p(P,T)?(_=k,P):(_=k,N=T)}var g=!1,_,N,C=d===void 0?null:d;return[function(){return b(u())},C===null?void 0:function(){return b(C())}]},[u,d,m,p]);var v=r(c,f[0],f[1]);return s(function(){y.hasValue=!0,y.value=v},[v]),l(v),v},Y2}var $9;function Z8e(){return $9||($9=1,K2.exports=Q8e()),K2.exports}Z8e();function J8e(t){t()}function e6e(){let t=null,e=null;return{clear(){t=null,e=null},notify(){J8e(()=>{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 a=e={callback:n,next:null,prev:e};return a.prev?a.prev.next=a:t=a,function(){!r||t===null||(r=!1,a.next?a.next.prev=a.prev:e=a.prev,a.prev?a.prev.next=a.next:t=a.next)}}}}var q9={notify(){},get:()=>[]};function t6e(t,e){let n,r=q9,a=0,s=!1;function o(v){d();const b=r.subscribe(v);let g=!1;return()=>{g||(g=!0,b(),m())}}function l(){r.notify()}function c(){y.onStateChange&&y.onStateChange()}function u(){return s}function d(){a++,n||(n=t.subscribe(c),r=e6e())}function m(){a--,n&&a===0&&(n(),n=void 0,r.clear(),r=q9)}function p(){s||(s=!0,d())}function f(){s&&(s=!1,m())}const y={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:u,trySubscribe:p,tryUnsubscribe:f,getListeners:()=>r};return y}var n6e=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",r6e=n6e(),i6e=()=>typeof navigator<"u"&&navigator.product==="ReactNative",a6e=i6e(),s6e=()=>r6e||a6e?w.useLayoutEffect:w.useEffect,o6e=s6e();function V9(t,e){return t===e?t!==0||e!==0||1/t===1/e:t!==t&&e!==e}function l6e(t,e){if(V9(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 a=0;a{const c=t6e(a);return{store:a,subscription:c,getServerState:r?()=>r:void 0}},[a,r]),o=w.useMemo(()=>a.getState(),[a]);o6e(()=>{const{subscription:c}=s;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),o!==a.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[s,o]);const l=n||m6e;return w.createElement(l.Provider,{value:s},e)}var p6e=h6e,f6e=new Set(["axisLine","tickLine","activeBar","activeDot","activeLabel","activeShape","allowEscapeViewBox","background","cursor","dot","label","line","margin","padding","position","shape","style","tick","wrapperStyle","radius"]);function g6e(t,e){return t==null&&e==null?!0:typeof t=="number"&&typeof e=="number"?t===e||t!==t&&e!==e:t===e}function Kw(t,e){var n=new Set([...Object.keys(t),...Object.keys(e)]);for(var r of n)if(f6e.has(r)){if(t[r]==null&&e[r]==null)continue;if(!l6e(t[r],e[r]))return!1}else if(!g6e(t[r],e[r]))return!1;return!0}var b6e=["id"],x6e=["type","layout","connectNulls","needClip","shape"],y6e=["activeDot","animateNewValues","animationBegin","animationDuration","animationEasing","connectNulls","dot","hide","isAnimationActive","label","legendType","xAxisId","yAxisId","id"];function Z0(){return Z0=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{dataKey:e,name:n,stroke:r,legendType:a,hide:s}=t;return[{inactive:s,dataKey:e,type:a,color:r,value:Xh(n,e),payload:t}]},k6e=w.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:a,fill:s,name:o,hide:l,unit:c,tooltipType:u,id:d}=t,m={dataDefinedOnItem:n,getPosition:Yh,settings:{stroke:r,strokeWidth:a,fill:s,dataKey:e,nameKey:void 0,name:Xh(o,e),hide:l,type:u,color:r,unit:c,graphicalItemId:d}};return w.createElement(pA,{tooltipEntrySettings:m})}),Sre=(t,e)=>"".concat(e,"px ").concat(t-e,"px");function C6e(t,e){for(var n=t.length%2!==0?[...t,0]:t,r=[],a=0;a{var r=n.reduce((f,y)=>f+y);if(!r)return Sre(e,t);for(var a=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 p=l.length%2===0?[0,o]:[o];return[...C6e(n,a),...l,...p].map(f=>"".concat(f,"px")).join(", ")};function A6e(t){var{clipPathId:e,points:n,props:r}=t,{dot:a,dataKey:s,needClip:o}=r,{id:l}=r,c=A4(r,b6e),u=Ys(c);return w.createElement(sre,{points:n,dot:a,className:"recharts-line-dots",dotClassName:"recharts-line-dot",dataKey:s,baseProps:u,needClip:o,clipPathId:e})}function P6e(t){var{showLabels:e,children:n,points:r}=t,a=w.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 iu(iu({},c),{},{value:s.value,payload:s.payload,viewBox:c,parentViewBox:void 0,fill:void 0})}),[r]);return w.createElement(p4,{value:e?a:void 0},n)}function W9(t){var{clipPathId:e,pathRef:n,points:r,strokeDasharray:a,props:s}=t,{type:o,layout:l,connectNulls:c,needClip:u,shape:d}=s,m=A4(s,x6e),p=iu(iu({},ls(m)),{},{fill:"none",className:"recharts-line-curve",clipPath:u?"url(#clipPath-".concat(e,")"):void 0,points:r,type:o,layout:l,connectNulls:c,strokeDasharray:a??s.strokeDasharray});return w.createElement(w.Fragment,null,r?.length>1&&w.createElement(y4,Z0({shapeType:"curve",option:d},p,{pathRef:n})),w.createElement(A6e,{points:r,clipPathId:e,props:s}))}function M6e(t){try{return t&&t.getTotalLength&&t.getTotalLength()||0}catch{return 0}}function E6e(t){var{clipPathId:e,props:n,pathRef:r,previousPointsRef:a,longestAnimatedLengthRef:s}=t,{points:o,strokeDasharray:l,isAnimationActive:c,animationBegin:u,animationDuration:d,animationEasing:m,animateNewValues:p,width:f,height:y,onAnimationEnd:v,onAnimationStart:b}=n,g=a.current,_=Jx(o,"recharts-line-"),N=w.useRef(_),[C,k]=w.useState(!1),P=!C,T=w.useCallback(()=>{typeof v=="function"&&v(),k(!1)},[v]),D=w.useCallback(()=>{typeof b=="function"&&b(),k(!0)},[b]),A=M6e(r.current),R=w.useRef(0);N.current!==_&&(R.current=s.current,N.current=_);var G=R.current;return w.createElement(P6e,{points:o,showLabels:P},n.children,w.createElement(Zx,{animationId:_,begin:u,duration:d,isActive:c,easing:m,onAnimationEnd:T,onAnimationStart:D,key:_},z=>{var Z=Cr(G,A+G,z),I=Math.min(Z,A),J;if(c)if(l){var ae="".concat(l).split(/[,\s]+/gim).map(de=>parseFloat(de));J=T6e(I,A,ae)}else J=Sre(A,I);else J=l==null?void 0:String(l);if(z>0&&A>0&&(a.current=o,s.current=Math.max(s.current,I)),g){var Y=g.length/o.length,ue=z===1?o:o.map((de,he)=>{var V=Math.floor(he*Y);if(g[V]){var ne=g[V];return iu(iu({},de),{},{x:Cr(ne.x,de.x,z),y:Cr(ne.y,de.y,z)})}return p?iu(iu({},de),{},{x:Cr(f*2,de.x,z),y:Cr(y/2,de.y,z)}):iu(iu({},de),{},{x:de.x,y:de.y})});return a.current=ue,w.createElement(W9,{props:n,points:ue,clipPathId:e,pathRef:r,strokeDasharray:J})}return w.createElement(W9,{props:n,points:o,clipPathId:e,pathRef:r,strokeDasharray:J})}),w.createElement(dA,{label:n.label}))}function j6e(t){var{clipPathId:e,props:n}=t,r=w.useRef(null),a=w.useRef(0),s=w.useRef(null);return w.createElement(E6e,{props:n,clipPathId:e,previousPointsRef:r,longestAnimatedLengthRef:a,pathRef:s})}var D6e=(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:Tr(t.payload,e)}};class R6e extends w.Component{render(){var{hide:e,dot:n,points:r,className:a,xAxisId:s,yAxisId:o,top:l,left:c,width:u,height:d,id:m,needClip:p,zIndex:f}=this.props;if(e)return null;var y=hr("recharts-line",a),v=m,{r:b,strokeWidth:g}=wre(n),_=x4(n),N=b*2+g,C=p?"url(#clipPath-".concat(_?"":"dots-").concat(v,")"):void 0;return w.createElement(Ns,{zIndex:f},w.createElement(vi,{className:y},p&&w.createElement("defs",null,w.createElement(T4,{clipPathId:v,xAxisId:s,yAxisId:o}),!_&&w.createElement("clipPath",{id:"clipPath-dots-".concat(v)},w.createElement("rect",{x:c-N/2,y:l-N/2,width:u+N,height:d+N}))),w.createElement(gre,{xAxisId:s,yAxisId:o,data:r,dataPointFormatter:D6e,errorBarOffset:0},w.createElement(j6e,{props:this.props,clipPathId:v}))),w.createElement(TF,{activeDot:this.props.activeDot,points:r,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:C}))}}var _re={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:Fi.line,type:"linear"};function F6e(t){var e=wi(t,_re),{activeDot:n,animateNewValues:r,animationBegin:a,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,hide:u,isAnimationActive:d,label:m,legendType:p,xAxisId:f,yAxisId:y,id:v}=e,b=A4(e,y6e),{needClip:g}=xA(f,y),_=bA(),N=Qh(),C=wa(),k=en(R=>X8e(R,f,y,C,v));if(N!=="horizontal"&&N!=="vertical"||k==null||_==null)return null;var{height:P,width:T,x:D,y:A}=_;return w.createElement(R6e,Z0({},b,{id:v,connectNulls:l,dot:c,activeDot:n,animateNewValues:r,animationBegin:a,animationDuration:s,animationEasing:o,isAnimationActive:d,hide:u,label:m,legendType:p,xAxisId:f,yAxisId:y,points:k,layout:N,height:P,width:T,left:D,top:A,needClip:g}))}function L6e(t){var{layout:e,xAxis:n,yAxis:r,xAxisTicks:a,yAxisTicks:s,dataKey:o,bandSize:l,displayedData:c}=t;return c.map((u,d)=>{var m=Tr(u,o);if(e==="horizontal"){var p=yk({axis:n,ticks:a,bandSize:l,entry:u,index:d}),f=gi(m)?null:r.scale.map(m);return{x:p,y:f??null,value:m,payload:u}}var y=gi(m)?null:n.scale.map(m),v=yk({axis:r,ticks:s,bandSize:l,entry:u,index:d});return y==null||v==null?null:{x:y,y:v,value:m,payload:u}}).filter(Boolean)}function O6e(t){var e=wi(t,_re),n=wa();return w.createElement(fA,{id:e.id,type:"line"},r=>w.createElement(w.Fragment,null,w.createElement(_4,{legendPayload:N6e(e)}),w.createElement(k6e,{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,id:r}),w.createElement(N4,{type:"line",id:r,data:e.data,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,hide:e.hide,isPanorama:n}),w.createElement(F6e,Z0({},e,{id:r}))))}var Nre=w.memo(O6e,Kw);Nre.displayName="Line";function Mu(t,e){var n,r;return(n=(r=t.graphicalItems.cartesianItems.find(a=>a.id===e))===null||r===void 0?void 0:r.xAxisId)!==null&&n!==void 0?n:ore}function Eu(t,e){var n,r;return(n=(r=t.graphicalItems.cartesianItems.find(a=>a.id===e))===null||r===void 0?void 0:r.yAxisId)!==null&&n!==void 0?n:ore}var kre=(t,e,n)=>_u(t,"xAxis",Mu(t,e),n),Cre=(t,e,n)=>Su(t,"xAxis",Mu(t,e),n),Tre=(t,e,n)=>_u(t,"yAxis",Eu(t,e),n),Are=(t,e,n)=>Su(t,"yAxis",Eu(t,e),n),I6e=yt([dr,kre,Tre,Cre,Are],(t,e,n,r,a)=>Fc(t,"xAxis")?qh(e,r,!1):qh(n,a,!1)),z6e=(t,e)=>e,Pre=yt([Hw,z6e],(t,e)=>t.filter(n=>n.type==="area").find(n=>n.id===e)),Mre=t=>{var e=dr(t),n=Fc(e,"xAxis");return n?"yAxis":"xAxis"},U6e=(t,e)=>{var n=Mre(t);return n==="yAxis"?Eu(t,e):Mu(t,e)},B6e=(t,e,n)=>Hk(t,Mre(t),U6e(t,e),n),H6e=yt([Pre,B6e],(t,e)=>{var n;if(!(t==null||e==null)){var{stackId:r}=t,a=tA(t);if(!(r==null||a==null)){var s=(n=e[r])===null||n===void 0?void 0:n.stackedData,o=s?.find(l=>l.key===a);if(o!=null)return o.map(l=>[l[0],l[1]])}}}),$6e=yt([dr,kre,Tre,Cre,Are,H6e,fte,I6e,Pre,eOe],(t,e,n,r,a,s,o,l,c,u)=>{var{chartData:d,dataStartIndex:m,dataEndIndex:p}=o;if(!(c==null||t!=="horizontal"&&t!=="vertical"||e==null||n==null||r==null||a==null||r.length===0||a.length===0||l==null)){var{data:f}=c,y;if(f&&f.length>0?y=f:y=d?.slice(m,p+1),y!=null)return lHe({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:a,dataStartIndex:m,areaSettings:c,stackedData:s,displayedData:y,chartBaseValue:u,bandSize:l})}}),q6e=["id"],V6e=["activeDot","animationBegin","animationDuration","animationEasing","connectNulls","dot","fill","fillOpacity","hide","isAnimationActive","legendType","stroke","xAxisId","yAxisId"];function yf(){return yf=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{dataKey:e,name:n,stroke:r,fill:a,legendType:s,hide:o}=t;return[{inactive:o,dataKey:e,type:s,color:Qk(r,a),value:Xh(n,e),payload:t}]},Q6e=w.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:a,fill:s,name:o,hide:l,unit:c,tooltipType:u,id:d}=t,m={dataDefinedOnItem:n,getPosition:Yh,settings:{stroke:r,strokeWidth:a,fill:s,dataKey:e,nameKey:void 0,name:Xh(o,e),hide:l,type:u,color:Qk(r,s),unit:c,graphicalItemId:d}};return w.createElement(pA,{tooltipEntrySettings:m})});function Z6e(t){var{clipPathId:e,points:n,props:r}=t,{needClip:a,dot:s,dataKey:o}=r,l=Ys(r);return w.createElement(sre,{points:n,dot:s,className:"recharts-area-dots",dotClassName:"recharts-area-dot",dataKey:o,baseProps:l,needClip:a,clipPathId:e})}function J6e(t){var{showLabels:e,children:n,points:r}=t,a=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 qb(qb({},c),{},{value:s.value,payload:s.payload,parentViewBox:void 0,viewBox:c,fill:void 0})});return w.createElement(p4,{value:e?a:void 0},n)}function Y9(t){var{points:e,baseLine:n,needClip:r,clipPathId:a,props:s}=t,{layout:o,type:l,stroke:c,connectNulls:u,isRange:d}=s,{id:m}=s,p=Ere(s,q6e),f=Ys(p),y=ls(p);return w.createElement(w.Fragment,null,e?.length>1&&w.createElement(vi,{clipPath:r?"url(#clipPath-".concat(a,")"):void 0},w.createElement(nx,yf({},y,{id:m,points:e,connectNulls:u,type:l,baseLine:n,layout:o,stroke:"none",className:"recharts-area-area"})),c!=="none"&&w.createElement(nx,yf({},f,{className:"recharts-area-curve",layout:o,type:l,connectNulls:u,fill:"none",points:e})),c!=="none"&&d&&w.createElement(nx,yf({},f,{className:"recharts-area-curve",layout:o,type:l,connectNulls:u,fill:"none",points:n}))),w.createElement(Z6e,{points:e,props:p,clipPathId:a}))}function eHe(t){var e,n,{alpha:r,baseLine:a,points:s,strokeWidth:o}=t,l=(e=s[0])===null||e===void 0?void 0:e.y,c=(n=s[s.length-1])===null||n===void 0?void 0:n.y;if(!Ln(l)||!Ln(c))return null;var u=r*Math.abs(l-c),d=Math.max(...s.map(m=>m.x||0));return Yt(a)?d=Math.max(a,d):a&&Array.isArray(a)&&a.length&&(d=Math.max(...a.map(m=>m.x||0),d)),Yt(d)?w.createElement("rect",{x:0,y:lm.y||0));return Yt(a)?d=Math.max(a,d):a&&Array.isArray(a)&&a.length&&(d=Math.max(...a.map(m=>m.y||0),d)),Yt(d)?w.createElement("rect",{x:l({points:o,baseLine:l}),[o,l]),v=Jx(y,"recharts-area-"),b=tI(),[g,_]=w.useState(!1),N=!g,C=w.useCallback(()=>{typeof f=="function"&&f(),_(!1)},[f]),k=w.useCallback(()=>{typeof p=="function"&&p(),_(!0)},[p]);if(b==null)return null;var P=a.current,T=s.current;return w.createElement(J6e,{showLabels:N,points:o},r.children,w.createElement(Zx,{animationId:v,begin:u,duration:d,isActive:c,easing:m,onAnimationEnd:C,onAnimationStart:k,key:v},D=>{if(P){var A=P.length/o.length,R=D===1?o:o.map((z,Z)=>{var I=Math.floor(Z*A);if(P[I]){var J=P[I];return qb(qb({},z),{},{x:Cr(J.x,z.x,D),y:Cr(J.y,z.y,D)})}return z}),G;return Yt(l)?G=Cr(T,l,D):gi(l)||Mc(l)?G=Cr(T,0,D):G=l.map((z,Z)=>{var I=Math.floor(Z*A);if(Array.isArray(T)&&T[I]){var J=T[I];return qb(qb({},z),{},{x:Cr(J.x,z.x,D),y:Cr(J.y,z.y,D)})}return z}),D>0&&(a.current=R,s.current=G),w.createElement(Y9,{points:R,baseLine:G,needClip:e,clipPathId:n,props:r})}return D>0&&(a.current=o,s.current=l),w.createElement(vi,null,c&&w.createElement("defs",null,w.createElement("clipPath",{id:"animationClipPath-".concat(n)},w.createElement(nHe,{alpha:D,points:o,baseLine:l,layout:b,strokeWidth:r.strokeWidth}))),w.createElement(vi,{clipPath:"url(#animationClipPath-".concat(n,")")},w.createElement(Y9,{points:o,baseLine:l,needClip:e,clipPathId:n,props:r})))}),w.createElement(dA,{label:r.label}))}function iHe(t){var{needClip:e,clipPathId:n,props:r}=t,a=w.useRef(null),s=w.useRef();return w.createElement(rHe,{needClip:e,clipPathId:n,props:r,previousPointsRef:a,previousBaselineRef:s})}class aHe extends w.PureComponent{render(){var{hide:e,dot:n,points:r,className:a,top:s,left:o,needClip:l,xAxisId:c,yAxisId:u,width:d,height:m,id:p,baseLine:f,zIndex:y}=this.props;if(e)return null;var v=hr("recharts-area",a),b=p,{r:g,strokeWidth:_}=wre(n),N=x4(n),C=g*2+_,k=l?"url(#clipPath-".concat(N?"":"dots-").concat(b,")"):void 0;return w.createElement(Ns,{zIndex:y},w.createElement(vi,{className:v},l&&w.createElement("defs",null,w.createElement(T4,{clipPathId:b,xAxisId:c,yAxisId:u}),!N&&w.createElement("clipPath",{id:"clipPath-dots-".concat(b)},w.createElement("rect",{x:o-C/2,y:s-C/2,width:d+C,height:m+C}))),w.createElement(iHe,{needClip:l,clipPathId:b,props:this.props})),w.createElement(TF,{points:r,mainColor:Qk(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:k}),this.props.isRange&&Array.isArray(f)&&w.createElement(TF,{points:f,mainColor:Qk(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:k}))}}var jre={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:Fi.area};function sHe(t){var e,n=wi(t,jre),{activeDot:r,animationBegin:a,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,fill:u,fillOpacity:d,hide:m,isAnimationActive:p,legendType:f,stroke:y,xAxisId:v,yAxisId:b}=n,g=Ere(n,V6e),_=Qh(),N=Mne(),{needClip:C}=xA(v,b),k=wa(),{points:P,isRange:T,baseLine:D}=(e=en(I=>$6e(I,t.id,k)))!==null&&e!==void 0?e:{},A=bA();if(_!=="horizontal"&&_!=="vertical"||A==null||N!=="AreaChart"&&N!=="ComposedChart")return null;var{height:R,width:G,x:z,y:Z}=A;return!P||!P.length?null:w.createElement(aHe,yf({},g,{activeDot:r,animationBegin:a,animationDuration:s,animationEasing:o,baseLine:D,connectNulls:l,dot:c,fill:u,fillOpacity:d,height:R,hide:m,layout:_,isAnimationActive:p==="auto"?!Fw.isSsr:p,isRange:T,legendType:f,needClip:C,points:P,stroke:y,width:G,left:z,top:Z,xAxisId:v,yAxisId:b}))}var oHe=(t,e,n,r,a)=>{var s=n??e;if(Yt(s))return s;var o=t==="horizontal"?a: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 lHe(t){var{areaSettings:{connectNulls:e,baseValue:n,dataKey:r},stackedData:a,layout:s,chartBaseValue:o,xAxis:l,yAxis:c,displayedData:u,dataStartIndex:d,xAxisTicks:m,yAxisTicks:p,bandSize:f}=t,y=a&&a.length,v=oHe(s,o,n,l,c),b=s==="horizontal",g=!1,_=u.map((C,k)=>{var P,T,D,A;if(y)A=a[d+k];else{var R=Tr(C,r);Array.isArray(R)?(A=R,g=!0):A=[v,R]}var G=(P=(T=A)===null||T===void 0?void 0:T[1])!==null&&P!==void 0?P:null,z=G==null||y&&!e&&Tr(C,r)==null;if(b){var Z;return{x:yk({axis:l,ticks:m,bandSize:f,entry:C,index:k}),y:z?null:(Z=c.scale.map(G))!==null&&Z!==void 0?Z:null,value:A,payload:C}}return{x:z?null:(D=l.scale.map(G))!==null&&D!==void 0?D:null,y:yk({axis:c,ticks:p,bandSize:f,entry:C,index:k}),value:A,payload:C}}),N;return y||g?N=_.map(C=>{var k,P=Array.isArray(C.value)?C.value[0]:null;if(b){var T;return{x:C.x,y:P!=null&&C.y!=null&&(T=c.scale.map(P))!==null&&T!==void 0?T:null,payload:C.payload}}return{x:P!=null&&(k=l.scale.map(P))!==null&&k!==void 0?k:null,y:C.y,payload:C.payload}}):N=b?c.scale.map(v):l.scale.map(v),{points:_,baseLine:N??0,isRange:g}}function cHe(t){var e=wi(t,jre),n=wa();return w.createElement(fA,{id:e.id,type:"area"},r=>w.createElement(w.Fragment,null,w.createElement(_4,{legendPayload:X6e(e)}),w.createElement(Q6e,{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,id:r}),w.createElement(N4,{type:"area",id:r,data:e.data,dataKey:e.dataKey,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,stackId:aee(e.stackId),hide:e.hide,barSize:void 0,baseValue:e.baseValue,isPanorama:n,connectNulls:e.connectNulls}),w.createElement(sHe,yf({},e,{id:r}))))}var Dre=w.memo(cHe,Kw);Dre.displayName="Area";var uHe="Invariant failed";function dHe(t,e){throw new Error(uHe)}function AF(){return AF=Object.assign?Object.assign.bind():function(t){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:0;return(r,a)=>{if(Yt(e))return e;var s=Yt(r)||gi(r);return s?e(r,a):(s||dHe(),n)}},hHe=(t,e,n)=>n,pHe=(t,e)=>e,Yw=yt([Hw,pHe],(t,e)=>t.filter(n=>n.type==="bar").find(n=>n.id===e)),fHe=yt([Yw],t=>t?.maxBarSize),gHe=(t,e,n,r)=>r,bHe=yt([dr,Hw,Mu,Eu,hHe],(t,e,n,r,a)=>e.filter(s=>t==="horizontal"?s.xAxisId===n:s.yAxisId===r).filter(s=>s.isPanorama===a).filter(s=>s.hide===!1).filter(s=>s.type==="bar")),xHe=(t,e,n)=>{var r=dr(t),a=Mu(t,e),s=Eu(t,e);if(!(a==null||s==null))return r==="horizontal"?Hk(t,"yAxis",s,n):Hk(t,"xAxis",a,n)},yHe=(t,e)=>{var n=dr(t),r=Mu(t,e),a=Eu(t,e);if(!(r==null||a==null))return n==="horizontal"?AG(t,"xAxis",r):AG(t,"yAxis",a)},vHe=yt([bHe,JLe,yHe],wBe),wHe=(t,e,n)=>{var r,a,s=Yw(t,e);if(s==null)return 0;var o=Mu(t,e),l=Eu(t,e);if(o==null||l==null)return 0;var c=dr(t),u=Tte(t),{maxBarSize:d}=s,m=gi(d)?u:d,p,f;return c==="horizontal"?(p=_u(t,"xAxis",o,n),f=Su(t,"xAxis",o,n)):(p=_u(t,"yAxis",l,n),f=Su(t,"yAxis",l,n)),(r=(a=qh(p,f,!0))!==null&&a!==void 0?a:m)!==null&&r!==void 0?r:0},Rre=(t,e,n)=>{var r=dr(t),a=Mu(t,e),s=Eu(t,e);if(!(a==null||s==null)){var o,l;return r==="horizontal"?(o=_u(t,"xAxis",a,n),l=Su(t,"xAxis",a,n)):(o=_u(t,"yAxis",s,n),l=Su(t,"yAxis",s,n)),qh(o,l)}},SHe=yt([vHe,Tte,ZLe,Ate,wHe,Rre,fHe],CBe),_He=(t,e,n)=>{var r=Mu(t,e);if(r!=null)return _u(t,"xAxis",r,n)},NHe=(t,e,n)=>{var r=Eu(t,e);if(r!=null)return _u(t,"yAxis",r,n)},kHe=(t,e,n)=>{var r=Mu(t,e);if(r!=null)return Su(t,"xAxis",r,n)},CHe=(t,e,n)=>{var r=Eu(t,e);if(r!=null)return Su(t,"yAxis",r,n)},THe=yt([SHe,Yw],ABe),AHe=yt([xHe,Yw],TBe),PHe=yt([va,XO,_He,NHe,kHe,CHe,THe,dr,fte,Rre,AHe,Yw,gHe],(t,e,n,r,a,s,o,l,c,u,d,m,p)=>{var{chartData:f,dataStartIndex:y,dataEndIndex:v}=c;if(!(m==null||o==null||e==null||l!=="horizontal"&&l!=="vertical"||n==null||r==null||a==null||s==null||u==null)){var{data:b}=m,g;if(b!=null&&b.length>0?g=b:g=f?.slice(y,v+1),g!=null)return r$e({layout:l,barSettings:m,pos:o,parentViewBox:e,bandSize:u,xAxis:n,yAxis:r,xAxisTicks:a,yAxisTicks:s,stackedData:d,displayedData:g,offset:t,cells:p,dataStartIndex:y})}}),MHe=["index"];function PF(){return PF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var e=w.useContext(Fre);if(e!=null)return e.stackId;if(t!=null)return aee(t)},RHe=(t,e)=>"recharts-bar-stack-clip-path-".concat(t,"-").concat(e),FHe=t=>{var e=w.useContext(Fre);if(e!=null){var{stackId:n}=e;return"url(#".concat(RHe(n,t),")")}},Lre=t=>{var{index:e}=t,n=EHe(t,MHe),r=FHe(e);return w.createElement(vi,PF({className:"recharts-bar-stack-layer",clipPath:r},n))},LHe=["onMouseEnter","onMouseLeave","onClick"],OHe=["value","background","tooltipPosition"],IHe=["id"],zHe=["onMouseEnter","onClick","onMouseLeave"];function Jd(){return Jd=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var{dataKey:e,name:n,fill:r,legendType:a,hide:s}=t;return[{inactive:s,dataKey:e,type:a,color:r,value:Xh(n,e),payload:t}]},VHe=w.memo(t=>{var{dataKey:e,stroke:n,strokeWidth:r,fill:a,name:s,hide:o,unit:l,tooltipType:c,id:u}=t,d={dataDefinedOnItem:void 0,getPosition:Yh,settings:{stroke:n,strokeWidth:r,fill:a,dataKey:e,nameKey:void 0,name:Xh(s,e),hide:o,type:c,color:a,unit:l,graphicalItemId:u}};return w.createElement(pA,{tooltipEntrySettings:d})});function GHe(t){var e=en(Vh),{data:n,dataKey:r,background:a,allOtherBarProps:s}=t,{onMouseEnter:o,onMouseLeave:l,onClick:c}=s,u=Jk(s,LHe),d=v4(o,r,s.id),m=w4(l),p=S4(c,r,s.id);if(!a||n==null)return null;var f=zf(a);return w.createElement(Ns,{zIndex:PBe(a,Fi.barBackground)},n.map((y,v)=>{var{value:b,background:g,tooltipPosition:_}=y,N=Jk(y,OHe);if(!g)return null;var C=d(y,v),k=m(y,v),P=p(y,v),T=zs(zs(zs(zs(zs({option:a,isActive:String(v)===e},N),{},{fill:"#eee"},g),f),Aw(u,y,v)),{},{onMouseEnter:C,onMouseLeave:k,onClick:P,dataKey:r,index:v,className:"recharts-bar-background-rectangle"});return w.createElement(Zk,Jd({key:"background-bar-".concat(v)},T))}))}function WHe(t){var{showLabels:e,children:n,rects:r}=t,a=r?.map(s=>{var o={x:s.x,y:s.y,width:s.width,lowerWidth:s.width,upperWidth:s.width,height:s.height};return zs(zs({},o),{},{value:s.value,payload:s.payload,parentViewBox:s.parentViewBox,viewBox:o,fill:s.fill})});return w.createElement(p4,{value:e?a:void 0},n)}function KHe(t){var{shape:e,activeBar:n,baseProps:r,entry:a,index:s,dataKey:o}=t,l=en(Vh),c=en(l4),u=n&&String(s)===l&&(c==null||o===c),d=u?n:e;return u?w.createElement(Ns,{zIndex:Fi.activeBar},w.createElement(Lre,{index:s},w.createElement(Zk,Jd({},r,{name:String(r.name)},a,{isActive:u,option:d,index:s,dataKey:o})))):w.createElement(Zk,Jd({},r,{name:String(r.name)},a,{isActive:u,option:d,index:s,dataKey:o}))}function YHe(t){var{shape:e,baseProps:n,entry:r,index:a,dataKey:s}=t;return w.createElement(Zk,Jd({},n,{name:String(n.name)},r,{isActive:!1,option:e,index:a,dataKey:s}))}function XHe(t){var e,{data:n,props:r}=t,a=(e=Ys(r))!==null&&e!==void 0?e:{},{id:s}=a,o=Jk(a,IHe),{shape:l,dataKey:c,activeBar:u}=r,{onMouseEnter:d,onClick:m,onMouseLeave:p}=r,f=Jk(r,zHe),y=v4(d,c,s),v=w4(p),b=S4(m,c,s);return n?w.createElement(w.Fragment,null,n.map((g,_)=>w.createElement(Lre,Jd({index:_,key:"rectangle-".concat(g?.x,"-").concat(g?.y,"-").concat(g?.value,"-").concat(_),className:"recharts-bar-rectangle"},Aw(f,g,_),{onMouseEnter:y(g,_),onMouseLeave:v(g,_),onClick:b(g,_)}),u?w.createElement(KHe,{shape:l,activeBar:u,baseProps:o,entry:g,index:_,dataKey:c}):w.createElement(YHe,{shape:l,baseProps:o,entry:g,index:_,dataKey:c})))):null}function QHe(t){var{props:e,previousRectanglesRef:n}=t,{data:r,layout:a,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,onAnimationEnd:u,onAnimationStart:d}=e,m=n.current,p=Jx(e,"recharts-bar-"),[f,y]=w.useState(!1),v=!f,b=w.useCallback(()=>{typeof u=="function"&&u(),y(!1)},[u]),g=w.useCallback(()=>{typeof d=="function"&&d(),y(!0)},[d]);return w.createElement(WHe,{showLabels:v,rects:r},w.createElement(Zx,{animationId:p,begin:o,duration:l,isActive:s,easing:c,onAnimationEnd:b,onAnimationStart:g,key:p},_=>{var N=_===1?r:r?.map((C,k)=>{var P=m&&m[k];if(P)return zs(zs({},C),{},{x:Cr(P.x,C.x,_),y:Cr(P.y,C.y,_),width:Cr(P.width,C.width,_),height:Cr(P.height,C.height,_)});if(a==="horizontal"){var T=Cr(0,C.height,_),D=Cr(C.stackedBarStart,C.y,_);return zs(zs({},C),{},{y:D,height:T})}var A=Cr(0,C.width,_),R=Cr(C.stackedBarStart,C.x,_);return zs(zs({},C),{},{width:A,x:R})});return _>0&&(n.current=N??null),N==null?null:w.createElement(vi,null,w.createElement(XHe,{props:e,data:N}))}),w.createElement(dA,{label:e.label}),e.children)}function ZHe(t){var e=w.useRef(null);return w.createElement(QHe,{previousRectanglesRef:e,props:t})}var Ore=0,JHe=(t,e)=>{var n=Array.isArray(t.value)?t.value[1]:t.value;return{x:t.x,y:t.y,value:n,errorVal:Tr(t,e)}};class e$e extends w.PureComponent{render(){var{hide:e,data:n,dataKey:r,className:a,xAxisId:s,yAxisId:o,needClip:l,background:c,id:u}=this.props;if(e||n==null)return null;var d=hr("recharts-bar",a),m=u;return w.createElement(vi,{className:d,id:u},l&&w.createElement("defs",null,w.createElement(T4,{clipPathId:m,xAxisId:s,yAxisId:o})),w.createElement(vi,{className:"recharts-bar-rectangles",clipPath:l?"url(#clipPath-".concat(m,")"):void 0},w.createElement(GHe,{data:n,dataKey:r,background:c,allOtherBarProps:this.props}),w.createElement(ZHe,this.props)))}}var t$e={activeBar:!1,animationBegin:0,animationDuration:400,animationEasing:"ease",background:!1,hide:!1,isAnimationActive:"auto",label:!1,legendType:"rect",minPointSize:Ore,xAxisId:0,yAxisId:0,zIndex:Fi.bar};function n$e(t){var{xAxisId:e,yAxisId:n,hide:r,legendType:a,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:u,isAnimationActive:d}=t,{needClip:m}=xA(e,n),p=Qh(),f=wa(),y=b4(t.children,Mx),v=en(_=>PHe(_,t.id,f,y));if(p!=="vertical"&&p!=="horizontal")return null;var b,g=v?.[0];return g==null||g.height==null||g.width==null?b=0:b=p==="vertical"?g.height/2:g.width/2,w.createElement(gre,{xAxisId:e,yAxisId:n,data:v,dataPointFormatter:JHe,errorBarOffset:b},w.createElement(e$e,Jd({},t,{layout:p,needClip:m,data:v,xAxisId:e,yAxisId:n,hide:r,legendType:a,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:u,isAnimationActive:d})))}function r$e(t){var{layout:e,barSettings:{dataKey:n,minPointSize:r},pos:a,bandSize:s,xAxis:o,yAxis:l,xAxisTicks:c,yAxisTicks:u,stackedData:d,displayedData:m,offset:p,cells:f,parentViewBox:y,dataStartIndex:v}=t,b=e==="horizontal"?l:o,g=d?b.scale.domain():null,_=U2e({numericAxis:b}),N=b.scale.map(_);return m.map((C,k)=>{var P,T,D,A,R,G;if(d){var z=d[k+v];if(z==null)return null;P=F2e(z,g)}else P=Tr(C,n),Array.isArray(P)||(P=[_,P]);var Z=mHe(r,Ore)(P[1],k);if(e==="horizontal"){var I,J=l.scale.map(P[0]),ae=l.scale.map(P[1]);if(J==null||ae==null)return null;T=TV({axis:o,ticks:c,bandSize:s,offset:a.offset,entry:C,index:k}),D=(I=ae??J)!==null&&I!==void 0?I:void 0,A=a.size;var Y=J-ae;if(R=Mc(Y)?0:Y,G={x:T,y:p.top,width:A,height:p.height},Math.abs(Z)>0&&Math.abs(R)0&&Math.abs(A)w.createElement(w.Fragment,null,w.createElement(_4,{legendPayload:qHe(e)}),w.createElement(VHe,{dataKey:e.dataKey,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType,id:a}),w.createElement(N4,{type:"bar",id:a,data:void 0,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,stackId:n,hide:e.hide,barSize:e.barSize,minPointSize:e.minPointSize,maxBarSize:e.maxBarSize,isPanorama:r}),w.createElement(Ns,{zIndex:e.zIndex},w.createElement(n$e,Jd({},e,{id:a})))))}var Rb=w.memo(i$e,Kw);Rb.displayName="Bar";var a$e=["domain","range"],s$e=["domain","range"];function Q9(t,e){if(t==null)return{};var n,r,a=o$e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{if(o!=null)return eW(eW({},s),{},{type:o})},[s,o]);return w.useLayoutEffect(()=>{l!=null&&(n.current===null?e(sBe(l)):n.current!==l&&e(oBe({prev:n.current,next:l})),n.current=l)},[l,e]),w.useLayoutEffect(()=>()=>{n.current&&(e(lBe(n.current)),n.current=null)},[e]),null}var g$e=t=>{var{xAxisId:e,className:n}=t,r=en(XO),a=wa(),s="xAxis",o=en(g=>one(g,s,e,a)),l=en(g=>rne(g,e)),c=en(g=>eIe(g,e)),u=en(g=>Ite(g,e));if(l==null||c==null||u==null)return null;var{dangerouslySetInnerHTML:d,ticks:m,scale:p}=t,f=EF(t,c$e),{id:y,scale:v}=u,b=EF(u,u$e);return w.createElement(C4,MF({},f,b,{x:c.x,y:c.y,width:l.width,height:l.height,className:hr("recharts-".concat(s," ").concat(s),n),viewBox:r,ticks:o,axisType:s}))},b$e={allowDataOverflow:Ma.allowDataOverflow,allowDecimals:Ma.allowDecimals,allowDuplicatedCategory:Ma.allowDuplicatedCategory,angle:Ma.angle,axisLine:Fd.axisLine,height:Ma.height,hide:!1,includeHidden:Ma.includeHidden,interval:Ma.interval,label:!1,minTickGap:Ma.minTickGap,mirror:Ma.mirror,orientation:Ma.orientation,padding:Ma.padding,reversed:Ma.reversed,scale:Ma.scale,tick:Ma.tick,tickCount:Ma.tickCount,tickLine:Fd.tickLine,tickSize:Fd.tickSize,type:Ma.type,xAxisId:0},x$e=t=>{var e=wi(t,b$e);return w.createElement(w.Fragment,null,w.createElement(f$e,{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}),w.createElement(g$e,e))},af=w.memo(x$e,Ire);af.displayName="XAxis";var y$e=["type"],v$e=["dangerouslySetInnerHTML","ticks","scale"],w$e=["id","scale"];function jF(){return jF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{if(o!=null)return nW(nW({},s),{},{type:o})},[o,s]);return w.useLayoutEffect(()=>{l!=null&&(n.current===null?e(cBe(l)):n.current!==l&&e(uBe({prev:n.current,next:l})),n.current=l)},[l,e]),w.useLayoutEffect(()=>()=>{n.current&&(e(dBe(n.current)),n.current=null)},[e]),null}function T$e(t){var{yAxisId:e,className:n,width:r,label:a}=t,s=w.useRef(null),o=w.useRef(null),l=en(XO),c=wa(),u=Jr(),d="yAxis",m=en(P=>ine(P,e)),p=en(P=>nIe(P,e)),f=en(P=>one(P,d,e,c)),y=en(P=>zte(P,e));if(w.useLayoutEffect(()=>{if(!(r!=="auto"||!m||h4(a)||w.isValidElement(a)||y==null)){var P=s.current;if(P){var T=P.getCalculatedWidth();Math.round(m.width)!==Math.round(T)&&u(mBe({id:e,width:T}))}}},[f,m,u,a,e,r,y]),m==null||p==null||y==null)return null;var{dangerouslySetInnerHTML:v,ticks:b,scale:g}=t,_=DF(t,v$e),{id:N,scale:C}=y,k=DF(y,w$e);return w.createElement(C4,jF({},_,k,{ref:s,labelRef:o,x:p.x,y:p.y,tickTextProps:r==="auto"?{width:void 0}:{width:r},width:m.width,height:m.height,className:hr("recharts-".concat(d," ").concat(d),n),viewBox:l,ticks:f,axisType:d}))}var A$e={allowDataOverflow:Ea.allowDataOverflow,allowDecimals:Ea.allowDecimals,allowDuplicatedCategory:Ea.allowDuplicatedCategory,angle:Ea.angle,axisLine:Fd.axisLine,hide:!1,includeHidden:Ea.includeHidden,interval:Ea.interval,label:!1,minTickGap:Ea.minTickGap,mirror:Ea.mirror,orientation:Ea.orientation,padding:Ea.padding,reversed:Ea.reversed,scale:Ea.scale,tick:Ea.tick,tickCount:Ea.tickCount,tickLine:Fd.tickLine,tickSize:Fd.tickSize,type:Ea.type,width:Ea.width,yAxisId:0},P$e=t=>{var e=wi(t,A$e);return w.createElement(w.Fragment,null,w.createElement(C$e,{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}),w.createElement(T$e,e))},sf=w.memo(P$e,Ire);sf.displayName="YAxis";var M$e=(t,e)=>e,P4=yt([M$e,dr,Fte,za,Nne,am,b4e,va],N4e),M4=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)}},zre=Yl("mouseClick"),Ure=Mw();Ure.startListening({actionCreator:zre,effect:(t,e)=>{var n=t.payload,r=P4(e.getState(),M4(n));r?.activeIndex!=null&&e.dispatch(gIe({activeIndex:r.activeIndex,activeDataKey:void 0,activeCoordinate:r.activeCoordinate}))}});var RF=Yl("mouseMove"),Bre=Mw(),M1=null;Bre.startListening({actionCreator:RF,effect:(t,e)=>{var n=t.payload;M1!==null&&cancelAnimationFrame(M1);var r=M4(n);M1=requestAnimationFrame(()=>{var a=e.getState(),s=n4(a,a.tooltip.settings.shared);if(s==="axis"){var o=P4(a,r);o?.activeIndex!=null?e.dispatch(fne({activeIndex:o.activeIndex,activeDataKey:void 0,activeCoordinate:o.activeCoordinate})):e.dispatch(pne())}M1=null})}});function E$e(t,e){return e instanceof HTMLElement?"HTMLElement <".concat(e.tagName,' class="').concat(e.className,'">'):e===window?"global.window":t==="children"&&typeof e=="object"&&e!==null?"<>":e}var rW={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},Hre=Ao({name:"rootProps",initialState:rW,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:rW.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}}}),j$e=Hre.reducer,{updateOptions:D$e}=Hre.actions,R$e=null,F$e={updatePolarOptions:(t,e)=>e.payload},$re=Ao({name:"polarOptions",initialState:R$e,reducers:F$e}),{updatePolarOptions:L$e}=$re.actions,O$e=$re.reducer,qre=Yl("keyDown"),Vre=Yl("focus"),E4=Mw();E4.startListening({actionCreator:qre,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:a}=n.tooltip,s=t.payload;if(!(s!=="ArrowRight"&&s!=="ArrowLeft"&&s!=="Enter")){var o=r4(a,ly(n),qw(n),Gw(n)),l=o==null?-1:Number(o);if(!(!Number.isFinite(l)||l<0)){var c=am(n);if(s==="Enter"){var u=qk(n,"axis","hover",String(a.index));e.dispatch(wF({active:!a.active,activeIndex:a.index,activeCoordinate:u}));return}var d=sIe(n),m=d==="left-to-right"?1:-1,p=s==="ArrowRight"?1:-1,f=l+p*m;if(!(c==null||f>=c.length||f<0)){var y=qk(n,"axis","hover",String(f));e.dispatch(wF({active:!0,activeIndex:f.toString(),activeCoordinate:y}))}}}}}});E4.startListening({actionCreator:Vre,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:a}=n.tooltip;if(!a.active&&a.index==null){var s="0",o=qk(n,"axis","hover",String(s));e.dispatch(wF({active:!0,activeIndex:s,activeCoordinate:o}))}}}});var Cl=Yl("externalEvent"),Gre=Mw(),X2=new Map;Gre.startListening({actionCreator:Cl,effect:(t,e)=>{var{handler:n,reactEvent:r}=t.payload;if(n!=null){r.persist();var a=r.type,s=X2.get(a);s!==void 0&&cancelAnimationFrame(s);var o=requestAnimationFrame(()=>{try{var l=e.getState(),c={activeCoordinate:n4e(l),activeDataKey:l4(l),activeIndex:Vh(l),activeLabel:Tne(l),activeTooltipIndex:Vh(l),isTooltipActive:r4e(l)};n(c,r)}finally{X2.delete(a)}});X2.set(a,o)}}});var I$e=yt([sy],t=>t.tooltipItemPayloads),z$e=yt([I$e,(t,e)=>e,(t,e,n)=>n],(t,e,n)=>{if(e!=null){var r=t.find(s=>s.settings.graphicalItemId===n);if(r!=null){var{getPosition:a}=r;if(a!=null)return a(e)}}}),Wre=Yl("touchMove"),Kre=Mw();Kre.startListening({actionCreator:Wre,effect:(t,e)=>{var n=t.payload;if(!(n.touches==null||n.touches.length===0)){var r=e.getState(),a=n4(r,r.tooltip.settings.shared);if(a==="axis"){var s=n.touches[0];if(s==null)return;var o=P4(r,M4({clientX:s.clientX,clientY:s.clientY,currentTarget:n.currentTarget}));o?.activeIndex!=null&&e.dispatch(fne({activeIndex:o.activeIndex,activeDataKey:void 0,activeCoordinate:o.activeCoordinate}))}else if(a==="item"){var l,c=n.touches[0];if(document.elementFromPoint==null||c==null)return;var u=document.elementFromPoint(c.clientX,c.clientY);if(!u||!u.getAttribute)return;var d=u.getAttribute(oee),m=(l=u.getAttribute(lee))!==null&&l!==void 0?l:void 0,p=oy(r).find(v=>v.id===m);if(d==null||p==null||m==null)return;var{dataKey:f}=p,y=z$e(r,d,m);e.dispatch(hne({activeDataKey:f,activeIndex:d,activeCoordinate:y,activeGraphicalItemId:m}))}}}});var U$e=AJ({brush:MBe,cartesianAxis:hBe,chartData:t5e,errorBars:U8e,graphicalItems:wUe,layout:M2e,legend:LDe,options:X4e,polarAxis:Fze,polarOptions:O$e,referenceElements:IBe,rootProps:j$e,tooltip:bIe,zIndex:I4e}),B$e=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Chart";return t2e({reducer:U$e,preloadedState:e,middleware:r=>{var a;return r({serializableCheck:!1,immutableCheck:!["commonjs","es6","production"].includes((a="es6")!==null&&a!==void 0?a:"")}).concat([Ure.middleware,Bre.middleware,E4.middleware,Gre.middleware,Kre.middleware])},enhancers:r=>{var a=r;return typeof r=="function"&&(a=r()),a.concat($J({type:"raf"}))},devTools:{serialize:{replacer:E$e},name:"recharts-".concat(n)}})};function Yre(t){var{preloadedState:e,children:n,reduxStoreName:r}=t,a=wa(),s=w.useRef(null);if(a)return n;s.current==null&&(s.current=B$e(e,r));var o=$O;return w.createElement(p6e,{context:o,store:s.current},n)}function H$e(t){var{layout:e,margin:n}=t,r=Jr(),a=wa();return w.useEffect(()=>{a||(r(T2e(e)),r(C2e(n)))},[r,a,e,n]),null}var Xre=w.memo(H$e,Kw);function Qre(t){var e=Jr();return w.useEffect(()=>{e(D$e(t))},[e,t]),null}function iW(t){var{zIndex:e,isPanorama:n}=t,r=w.useRef(null),a=Jr();return w.useLayoutEffect(()=>(r.current&&a(L4e({zIndex:e,element:r.current,isPanorama:n})),()=>{a(O4e({zIndex:e,isPanorama:n}))}),[a,e,n]),w.createElement("g",{tabIndex:-1,ref:r})}function aW(t){var{children:e,isPanorama:n}=t,r=en(C4e);if(!r||r.length===0)return e;var a=r.filter(o=>o<0),s=r.filter(o=>o>0);return w.createElement(w.Fragment,null,a.map(o=>w.createElement(iW,{key:o,zIndex:o,isPanorama:n})),e,s.map(o=>w.createElement(iW,{key:o,zIndex:o,isPanorama:n})))}var $$e=["children"];function q$e(t,e){if(t==null)return{};var n,r,a=V$e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var n=JO(),r=eI(),a=kee();if(!vu(n)||!vu(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=a?0:void 0,typeof o.role=="string"?d=o.role:d=a?"application":void 0),w.createElement(jO,eC({},o,{title:l,desc:c,role:d,tabIndex:u,width:n,height:r,style:G$e,ref:e}),s)}),K$e=t=>{var{children:e}=t,n=en(BT);if(!n)return null;var{width:r,height:a,y:s,x:o}=n;return w.createElement(jO,{width:r,height:a,x:o,y:s},e)},sW=w.forwardRef((t,e)=>{var{children:n}=t,r=q$e(t,$$e),a=wa();return a?w.createElement(K$e,null,w.createElement(aW,{isPanorama:!0},n)):w.createElement(W$e,eC({ref:e},r),w.createElement(aW,{isPanorama:!1},n))});function Y$e(){var t=Jr(),[e,n]=w.useState(null),r=en(G2e);return w.useEffect(()=>{if(e!=null){var a=e.getBoundingClientRect(),s=a.width/e.offsetWidth;Ln(s)&&s!==r&&t(P2e(s))}},[e,t,r]),n}function oW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function X$e(t){for(var e=1;e(u5e(),null);function tC(t){if(typeof t=="number")return t;if(typeof t=="string"){var e=parseFloat(t);if(!Number.isNaN(e))return e}return 0}var tqe=w.forwardRef((t,e)=>{var n,r,a=w.useRef(null),[s,o]=w.useState({containerWidth:tC((n=t.style)===null||n===void 0?void 0:n.width),containerHeight:tC((r=t.style)===null||r===void 0?void 0:r.height)}),l=w.useCallback((u,d)=>{o(m=>{var p=Math.round(u),f=Math.round(d);return m.containerWidth===p&&m.containerHeight===f?m:{containerWidth:p,containerHeight:f}})},[]),c=w.useCallback(u=>{if(typeof e=="function"&&e(u),u!=null&&typeof ResizeObserver<"u"){var{width:d,height:m}=u.getBoundingClientRect();l(d,m);var p=y=>{var v=y[0];if(v!=null){var{width:b,height:g}=v.contentRect;l(b,g)}},f=new ResizeObserver(p);f.observe(u),a.current=f}},[e,l]);return w.useEffect(()=>()=>{var u=a.current;u?.disconnect()},[l]),w.createElement(w.Fragment,null,w.createElement(Dw,{width:s.containerWidth,height:s.containerHeight}),w.createElement("div",Fh({ref:c},t)))}),nqe=w.forwardRef((t,e)=>{var{width:n,height:r}=t,[a,s]=w.useState({containerWidth:tC(n),containerHeight:tC(r)}),o=w.useCallback((c,u)=>{s(d=>{var m=Math.round(c),p=Math.round(u);return d.containerWidth===m&&d.containerHeight===p?d:{containerWidth:m,containerHeight:p}})},[]),l=w.useCallback(c=>{if(typeof e=="function"&&e(c),c!=null){var{width:u,height:d}=c.getBoundingClientRect();o(u,d)}},[e,o]);return w.createElement(w.Fragment,null,w.createElement(Dw,{width:a.containerWidth,height:a.containerHeight}),w.createElement("div",Fh({ref:l},t)))}),rqe=w.forwardRef((t,e)=>{var{width:n,height:r}=t;return w.createElement(w.Fragment,null,w.createElement(Dw,{width:n,height:r}),w.createElement("div",Fh({ref:e},t)))}),iqe=w.forwardRef((t,e)=>{var{width:n,height:r}=t;return typeof n=="string"||typeof r=="string"?w.createElement(nqe,Fh({},t,{ref:e})):typeof n=="number"&&typeof r=="number"?w.createElement(rqe,Fh({},t,{width:n,height:r,ref:e})):w.createElement(w.Fragment,null,w.createElement(Dw,{width:n,height:r}),w.createElement("div",Fh({ref:e},t)))});function aqe(t){return t?tqe:iqe}var sqe=w.forwardRef((t,e)=>{var{children:n,className:r,height:a,onClick:s,onContextMenu:o,onDoubleClick:l,onMouseDown:c,onMouseEnter:u,onMouseLeave:d,onMouseMove:m,onMouseUp:p,onTouchEnd:f,onTouchMove:y,onTouchStart:v,style:b,width:g,responsive:_,dispatchTouchEvents:N=!0}=t,C=w.useRef(null),k=Jr(),[P,T]=w.useState(null),[D,A]=w.useState(null),R=Y$e(),G=QO(),z=G?.width>0?G.width:g,Z=G?.height>0?G.height:a,I=w.useCallback(E=>{R(E),typeof e=="function"&&e(E),T(E),A(E),E!=null&&(C.current=E)},[R,e,T,A]),J=w.useCallback(E=>{k(zre(E)),k(Cl({handler:s,reactEvent:E}))},[k,s]),ae=w.useCallback(E=>{k(RF(E)),k(Cl({handler:u,reactEvent:E}))},[k,u]),Y=w.useCallback(E=>{k(pne()),k(Cl({handler:d,reactEvent:E}))},[k,d]),ue=w.useCallback(E=>{k(RF(E)),k(Cl({handler:m,reactEvent:E}))},[k,m]),de=w.useCallback(()=>{k(Vre())},[k]),he=w.useCallback(E=>{k(qre(E.key))},[k]),V=w.useCallback(E=>{k(Cl({handler:o,reactEvent:E}))},[k,o]),ne=w.useCallback(E=>{k(Cl({handler:l,reactEvent:E}))},[k,l]),se=w.useCallback(E=>{k(Cl({handler:c,reactEvent:E}))},[k,c]),pe=w.useCallback(E=>{k(Cl({handler:p,reactEvent:E}))},[k,p]),Te=w.useCallback(E=>{k(Cl({handler:v,reactEvent:E}))},[k,v]),q=w.useCallback(E=>{N&&k(Wre(E)),k(Cl({handler:y,reactEvent:E}))},[k,N,y]),X=w.useCallback(E=>{k(Cl({handler:f,reactEvent:E}))},[k,f]),j=aqe(_);return w.createElement(Fne.Provider,{value:P},w.createElement(qZ.Provider,{value:D},w.createElement(j,{width:z??b?.width,height:Z??b?.height,className:hr("recharts-wrapper",r),style:X$e({position:"relative",cursor:"default",width:z,height:Z},b),onClick:J,onContextMenu:V,onDoubleClick:ne,onFocus:de,onKeyDown:he,onMouseDown:se,onMouseEnter:ae,onMouseLeave:Y,onMouseMove:ue,onMouseUp:pe,onTouchEnd:X,onTouchMove:q,onTouchStart:Te,ref:I},w.createElement(eqe,null),n)))}),oqe=["width","height","responsive","children","className","style","compact","title","desc"];function lqe(t,e){if(t==null)return{};var n,r,a=cqe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r{var{width:n,height:r,responsive:a,children:s,className:o,style:l,compact:c,title:u,desc:d}=t,m=lqe(t,oqe),p=Ys(m);return c?w.createElement(w.Fragment,null,w.createElement(Dw,{width:n,height:r}),w.createElement(sW,{otherAttributes:p,title:u,desc:d},s)):w.createElement(sqe,{className:o,style:l,width:n,height:r,responsive:a??!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},w.createElement(sW,{otherAttributes:p,title:u,desc:d,ref:e},w.createElement(zBe,null,s)))});function FF(){return FF=Object.assign?Object.assign.bind():function(t){for(var e=1;ew.createElement(j4,{chartName:"LineChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:mqe,tooltipPayloadSearcher:cA,categoricalChartProps:t,ref:e})),pqe=["axis","item"],E1=w.forwardRef((t,e)=>w.createElement(j4,{chartName:"BarChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:pqe,tooltipPayloadSearcher:cA,categoricalChartProps:t,ref:e}));function fqe(t){var e=Jr();return w.useEffect(()=>{e(L$e(t))},[e,t]),null}var gqe=["layout"];function LF(){return LF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{var n=wi(t,kqe);return w.createElement(vqe,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:Nqe,tooltipPayloadSearcher:cA,categoricalChartProps:n,ref:e})}),Cqe=["axis"],Tqe=w.forwardRef((t,e)=>w.createElement(j4,{chartName:"AreaChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:Cqe,tooltipPayloadSearcher:cA,categoricalChartProps:t,ref:e}));const dW=[{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 Aqe({isOpen:t,onClose:e,printerId:n,printerName:r,amsId:a,amsLabel:s,initialMode:o="humidity",thresholds:l}){const{t:c}=Dt(),{mode:u}=ng(),[d,m]=w.useState("24h"),[p,f]=w.useState(o),y=u==="dark",{data:v}=et({queryKey:["settings"],queryFn:ge.getSettings}),b=v?.time_format||"system";w.useEffect(()=>{if(!t)return;const X=j=>{j.key==="Escape"&&e()};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[t,e]);const g=dW.find(X=>X.value===d)?.hours||24,{data:_,isLoading:N,error:C}=et({queryKey:["ams-history",n,a,g],queryFn:()=>ge.getAMSHistory(n,a,g),enabled:t,refetchInterval:6e4});if(!t)return null;const k=_?.data.map(X=>({time:(Qn(X.recorded_at)||new Date).getTime(),humidity:X.humidity,temperature:X.temperature}))||[],P=Date.now()-g*60*60*1e3,T=Date.now(),D=[...k];if(D.length>0){const X=D[0];X.time>P&&D.unshift({...X,time:P});const j=D[D.length-1];j.time{const j=X.filter(O=>O!=null);if(j.length<4)return"stable";const E=j.slice(0,Math.floor(j.length/4)),U=j.slice(-Math.floor(j.length/4)),K=E.reduce((O,$)=>O+$,0)/E.length,re=U.reduce((O,$)=>O+$,0)/U.length-K;return Math.abs(re)<2?"stable":re>0?"up":"down"},Y=ae(D.map(X=>X.humidity)),ue=ae(D.map(X=>X.temperature)),de=({trend:X})=>X==="up"?i.jsx(T3,{className:"w-4 h-4 text-red-400"}):X==="down"?i.jsx(XL,{className:"w-4 h-4 text-green-400"}):i.jsx(zN,{className:"w-4 h-4 text-gray-400 dark:text-bambu-gray"}),he=X=>X==null?"#9ca3af":X<=A?"#22a352":X<=R?"#d4a017":"#c62828",V=X=>X==null?"#9ca3af":X<=G?"#22a352":X<=z?"#d4a017":"#c62828",ne=y?"#2d2d2d":"#ffffff",se=y?"#1d1d1d":"#f3f4f6",pe=y?"#3d3d3d":"#e5e7eb",Te=y?"#ffffff":"#111827",q=y?"#9ca3af":"#4b5563";return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:i.jsxs("div",{className:"rounded-xl w-full max-w-4xl max-h-[90vh] overflow-hidden shadow-xl",style:{backgroundColor:ne},onClick:X=>X.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",style:{borderColor:pe},children:[i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold",style:{color:Te},children:[s," ",c("common.history","History")]}),i.jsx("p",{className:"text-sm",style:{color:q},children:r})]}),i.jsx("button",{onClick:e,className:"p-2 rounded-lg transition-colors",style:{color:q},children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-6 space-y-6 overflow-y-auto max-h-[calc(90vh-80px)]",children:[i.jsxs("div",{className:"flex items-center justify-between max-[550px]:flex-col max-[550px]:items-start max-[550px]:gap-3",children:[i.jsxs("div",{className:"inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit",style:{backgroundColor:se},children:[i.jsxs("button",{onClick:()=>f("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:q}:void 0,children:[i.jsx(GL,{className:"w-4 h-4"}),c("common.humidity","Humidity")]}),i.jsxs("button",{onClick:()=>f("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:q}:void 0,children:[i.jsx(mT,{className:"w-4 h-4"}),c("common.temperature","Temperature")]})]}),i.jsx("div",{className:"inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit",style:{backgroundColor:se},children:dW.map(X=>i.jsx("button",{onClick:()=>m(X.value),className:`px-3 py-1 text-sm rounded-md transition-colors ${d===X.value?"bg-bambu-green text-white":""}`,style:d!==X.value?{color:q}:void 0,children:X.label},X.value))})]}),i.jsx("div",{className:"grid grid-cols-4 gap-4 max-[550px]:grid-cols-2",children:p==="humidity"?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-2",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.current","Current")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("p",{className:"text-2xl font-bold",style:{color:he(I)},children:I!=null?`${I}%`:"—"}),i.jsx(de,{trend:Y})]})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-4",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.average","Average")}),i.jsx("p",{className:"text-2xl font-bold",style:{color:Te},children:_?.avg_humidity!=null?`${_.avg_humidity}%`:"—"})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-1",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.min","Min")}),i.jsx("p",{className:"text-2xl font-bold text-green-500",children:_?.min_humidity!=null?`${_.min_humidity}%`:"—"})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-3",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.max","Max")}),i.jsx("p",{className:"text-2xl font-bold text-red-500",children:_?.max_humidity!=null?`${_.max_humidity}%`:"—"})]})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-2",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.current","Current")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("p",{className:"text-2xl font-bold",style:{color:V(J)},children:J!=null?`${J}°C`:"—"}),i.jsx(de,{trend:ue})]})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-4",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.average","Average")}),i.jsx("p",{className:"text-2xl font-bold",style:{color:Te},children:_?.avg_temperature!=null?`${_.avg_temperature}°C`:"—"})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-1",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.min","Min")}),i.jsx("p",{className:"text-2xl font-bold text-blue-500",children:_?.min_temperature!=null?`${_.min_temperature}°C`:"—"})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-3",style:{backgroundColor:se},children:[i.jsx("p",{className:"text-xs",style:{color:q},children:c("common.max","Max")}),i.jsx("p",{className:"text-2xl font-bold text-red-500",children:_?.max_temperature!=null?`${_.max_temperature}°C`:"—"})]})]})}),i.jsx("div",{className:"rounded-lg p-4",style:{backgroundColor:se},children:N?i.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:q},children:c("common.loading","Loading...")}):C?i.jsx("div",{className:"h-[300px] flex items-center justify-center text-red-500",children:c("common.error","Error loading data")}):D.length===0?i.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:q},children:c("common.noData","No data available for this time range")}):i.jsx(bh,{width:"100%",height:300,children:i.jsxs(hqe,{data:D,children:[i.jsx(rf,{strokeDasharray:"3 3",stroke:y?"#3d3d3d":"#e5e7eb"}),i.jsx(af,{dataKey:"time",type:"number",domain:[Date.now()-g*60*60*1e3,Date.now()],tickFormatter:X=>{const j=new Date(X);return g>24?j.toLocaleDateString([],{day:"numeric",month:"short"}):j.toLocaleTimeString([],k0({hour:"2-digit",minute:"2-digit"},b))},stroke:y?"#9ca3af":"#6b7280",tick:{fontSize:12}}),i.jsx(sf,{stroke:y?"#9ca3af":"#6b7280",tick:{fontSize:12},domain:p==="humidity"?[0,100]:["auto","auto"],tickFormatter:X=>p==="humidity"?`${X}%`:`${X}°C`}),i.jsx(xh,{contentStyle:{backgroundColor:y?"#2d2d2d":"#ffffff",border:`1px solid ${y?"#3d3d3d":"#e5e7eb"}`,borderRadius:"8px",color:y?"#fff":"#000"},labelFormatter:X=>new Date(X).toLocaleString(void 0,k0({year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},b)),formatter:X=>[p==="humidity"?`${X??0}%`:`${X??0}°C`,p==="humidity"?"Humidity":"Temperature"]}),i.jsx(Nee,{}),p==="humidity"?i.jsxs(i.Fragment,{children:[i.jsx(Iv,{y:A,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),i.jsx(Iv,{y:R,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}):i.jsxs(i.Fragment,{children:[i.jsx(Iv,{y:G,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),i.jsx(Iv,{y:z,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}),i.jsx(Nre,{type:"monotone",dataKey:p,name:p==="humidity"?"Humidity":"Temperature",stroke:p==="humidity"?"#3b82f6":"#f97316",strokeWidth:2,dot:!1,activeDot:{r:4},connectNulls:!0})]})})}),i.jsx("div",{className:"text-xs text-center",style:{color:q},children:c("amsHistory.recordingInfo","Data is recorded every 5 minutes while the printer is connected")})]})]})})}const nC={"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 xN(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),a=parseInt(e.substring(4,6),16),s=Math.max(n,r,a)/255,o=Math.min(n,r,a)/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 m=n/255,p=r/255,f=a/255;s===m?c=((p-f)/d+(p.85?"White":u<.15?l<.4?"Dark Gray":l>.6?"Light Gray":"Gray":c>=15&&c<45&&l<.45||c>=45&&c<70&&l<.4?"Brown":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 Ld(t){const e=t.replace("#","").toLowerCase().substring(0,6);return nC[e]?nC[e]:xN(t)}function D4(t,e){if(t&&!/^[A-Z]\d+-[A-Z]\d+$/.test(t))return t;if(e&&e.length>=6){const n=e.substring(0,6).toLowerCase();if(nC[n])return nC[n]}return null}function R4(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),a=t.length>=8?parseInt(t.slice(6,8),16)/255:1;return a===0?null:`rgba(${parseInt(e,16)}, ${parseInt(n,16)}, ${parseInt(r,16)}, ${a})`}function eie(t){if(!t||t.length<6)return!1;const e=t.replace("#",""),n=parseInt(e.slice(0,2),16),r=parseInt(e.slice(2,4),16),a=parseInt(e.slice(4,6),16);return(.299*n+.587*r+.114*a)/255>.6}function Q2({data:t,children:e,disabled:n,className:r="",spoolman:a,inventory:s,configureSlot:o}){const{t:l}=Dt(),[c,u]=w.useState(!1),[d,m]=w.useState("top"),[p,f]=w.useState(!1),[y,v]=w.useState(!1),b=w.useRef(null),g=w.useRef(null),_=w.useRef(null),N=()=>{const R=t.trayUuid;R&&(navigator.clipboard&&window.isSecureContext?navigator.clipboard.writeText(R).then(()=>{f(!0),setTimeout(()=>f(!1),2e3)}).catch(()=>{C(R)}):C(R))},C=R=>{const G=document.createElement("textarea");G.value=R,G.style.position="fixed",G.style.opacity="0",document.body.appendChild(G),G.select();try{document.execCommand("copy"),f(!0),setTimeout(()=>f(!1),2e3)}catch{console.error("Failed to copy to clipboard")}document.body.removeChild(G)};w.useEffect(()=>{if(c&&b.current&&g.current){const R=b.current.getBoundingClientRect(),G=g.current.offsetHeight,Z=R.top-56,I=window.innerHeight-R.bottom;ZZ?m("bottom"):m("top")}},[c]);const k=()=>{n||(_.current&&clearTimeout(_.current),_.current=setTimeout(()=>u(!0),80))},P=()=>{_.current&&clearTimeout(_.current),_.current=setTimeout(()=>u(!1),100)};w.useEffect(()=>()=>{_.current&&clearTimeout(_.current)},[]);const T=R=>R<=15?"#ef4444":R<=30?"#f97316":R<=50?"#eab308":"#22c55e",D=t.colorHex?`#${t.colorHex.replace("#","")}`:null,A=s?.assignedSpool?.remainingWeightGrams??null;return i.jsxs("div",{ref:b,className:`relative ${r}`,onMouseEnter:k,onMouseLeave:P,children:[e,c&&i.jsxs("div",{ref:g,className:` absolute left-1/2 -translate-x-1/2 z-50 ${d==="top"?"bottom-full mb-2":"top-full mt-2"} animate-in fade-in-0 zoom-in-95 duration-150 @@ -8492,7 +8492,7 @@ void main() { border-l-[6px] border-l-transparent border-r-[6px] border-r-transparent ${d==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"} - `})]}),y&&i.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center",onClick:()=>v(!1),children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),i.jsx("div",{className:"relative bg-bambu-dark-secondary rounded-lg shadow-xl w-full max-w-sm mx-4 border border-bambu-dark-tertiary",onClick:R=>R.stopPropagation(),children:i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("div",{className:"space-y-2",children:[i.jsx("h3",{className:"text-base font-semibold text-white",children:l("spoolman.unlinkConfirmTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:l("spoolman.unlinkConfirmMessage")})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>v(!1),className:"flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-bambu-dark hover:bg-bambu-dark-tertiary text-white",children:l("common.cancel")}),i.jsx("button",{onClick:()=>{a?.onUnlinkSpool?.(),v(!1)},className:"flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-red-500/20 hover:bg-red-500/30 text-red-400",children:l("spoolman.unlinkSpool")})]})]})})]})]})}function Zj({children:t,className:e="",configureSlot:n,inventory:r}){const{t:a}=Dt(),[s,o]=w.useState(!1),l=w.useRef(null),c=()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>o(!0),80)},u=()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>o(!1),100)};return w.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]),i.jsxs("div",{className:`relative ${e}`,onMouseEnter:c,onMouseLeave:u,children:[t,s&&i.jsxs("div",{className:` + `})]}),y&&i.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center",onClick:()=>v(!1),children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),i.jsx("div",{className:"relative bg-bambu-dark-secondary rounded-lg shadow-xl w-full max-w-sm mx-4 border border-bambu-dark-tertiary",onClick:R=>R.stopPropagation(),children:i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("div",{className:"space-y-2",children:[i.jsx("h3",{className:"text-base font-semibold text-white",children:l("spoolman.unlinkConfirmTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:l("spoolman.unlinkConfirmMessage")})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>v(!1),className:"flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-bambu-dark hover:bg-bambu-dark-tertiary text-white",children:l("common.cancel")}),i.jsx("button",{onClick:()=>{a?.onUnlinkSpool?.(),v(!1)},className:"flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-red-500/20 hover:bg-red-500/30 text-red-400",children:l("spoolman.unlinkSpool")})]})]})})]})]})}function Z2({children:t,className:e="",configureSlot:n,inventory:r}){const{t:a}=Dt(),[s,o]=w.useState(!1),l=w.useRef(null),c=()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>o(!0),80)},u=()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>o(!1),100)};return w.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]),i.jsxs("div",{className:`relative ${e}`,onMouseEnter:c,onMouseLeave:u,children:[t,s&&i.jsxs("div",{className:` absolute left-1/2 -translate-x-1/2 bottom-full mb-2 z-50 animate-in fade-in-0 zoom-in-95 duration-150 `,children:[i.jsxs("div",{className:` @@ -8507,8 +8507,8 @@ void main() { ${o("inventory.assignProfileMismatchMessage",{spoolProfile:g.spoolProfile||o("common.unknown"),trayProfile:g.trayProfile||o("common.unknown"),location:s.location})}`:g.type==="partial_profile"?Y=`${o("inventory.assignPartialMismatchMessage",{spoolMaterial:g.spoolMaterial,trayMaterial:g.trayMaterial,location:s.location})} -${o("inventory.assignProfileMismatchMessage",{spoolProfile:g.spoolProfile||o("common.unknown"),trayProfile:g.trayProfile||o("common.unknown"),location:s.location})}`:g.type==="profile"&&(Y=o("inventory.assignProfileMismatchMessage",{spoolProfile:g.spoolProfile||o("common.unknown"),trayProfile:g.trayProfile||o("common.unknown"),location:s.location})),i.jsx(Nn,{title:o("inventory.assignMismatchTitle"),message:Y,confirmText:o("inventory.assignMismatchConfirm"),variant:"warning",isLoading:T.isPending,onConfirm:ae,onCancel:()=>{T.isPending||(b(!1),y(null),_(null))}})})()]})}function mW(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 a=String.fromCharCode(65+n);return r?`HT-${a}`:`AMS-${a}`}function j1(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 e0=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function hW(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase(),r=n.match(/\bSUPPORT\s+FOR\s+/);if(r){const s=n.slice(r.index+r[0].length);for(const o of e0)if(new RegExp(`\\b${o}\\b`).test(s)){const c=e.slice(0,r.index).trim();return{material:o,brand:c,variant:"Support"}}}for(const s of e0){const o=new RegExp(`\\b${s}\\b`,"i");if(o.test(n)){const l=e.split(o),c=l[0]?.trim()||"",u=l[1]?.trim()||"";return{material:s,brand:c,variant:u}}}const a=e.split(/\s+/);return a.length>=2?{material:a[1],brand:a[0],variant:a.slice(2).join(" ")}:{material:e,brand:"",variant:""}}function Eqe(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const jqe={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"},pW=[{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"}],fW=[{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 gW(t){const e=t.toLowerCase().trim();return jqe[e]||null}function Dqe(t){const e=t.indexOf("@");if(e<0)return null;const r=t.slice(e+1).trim().match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);return r?r[1].trim():null}function tie({isOpen:t,onClose:e,printerId:n,slotInfo:r,nozzleDiameter:a="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=Dt(),[u,d]=w.useState(""),[m,p]=w.useState(null),[f,y]=w.useState(""),[v,b]=w.useState(""),[g,_]=w.useState(""),[N,C]=w.useState(!1),[k,P]=w.useState(!1),T=w.useRef(""),{data:D,isLoading:A,isError:R}=et({queryKey:["cloudSettings"],queryFn:()=>ge.getCloudSettings(),enabled:t,retry:!1}),{data:G,isLoading:z}=et({queryKey:["localPresets"],queryFn:()=>ge.getLocalPresets(),enabled:t}),{data:Z,isLoading:I}=et({queryKey:["builtinFilaments"],queryFn:()=>ge.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:J,isLoading:ae}=et({queryKey:["kprofiles",n,a],queryFn:()=>ge.getKProfiles(n,a),enabled:t&&!!n}),{data:Y}=et({queryKey:["colorCatalog"],queryFn:()=>ge.getColorCatalog(),enabled:t,staleTime:1/0}),ue=gt({mutationFn:async()=>{if(!u)throw new Error("No filament preset selected");const E=u.startsWith("local_"),U=u.startsWith("builtin_"),K=E?parseInt(u.replace("local_",""),10):null,H=U?u.replace("builtin_",""):null,re=E?G?.filament.find(Fe=>Fe.id===K):null,O=U?Z?.find(Fe=>Fe.filament_id===H):null,$=!E&&!U?D?.filament.find(Fe=>Fe.setting_id===u):null;if(!E&&!U&&!$)throw new Error("Selected preset not found");if(E&&!re)throw new Error("Selected local preset not found");if(U&&!O)throw new Error("Selected builtin preset not found");const ee=E?re.name:U?O.name:$.name,W=hW(ee),ie=m?.slot_id??-1,ce=f||r.trayColor?.slice(0,6)||"FFFFFF",be=ee.replace(/@.+$/,"").trim();let xe,oe;const L=W.material.toUpperCase();if(E){const Fe=(e0.includes(L)?L:re?.filament_type||W.material||"").toUpperCase(),He={PLA:"GFL99","PLA-CF":"GFL98","PLA SILK":"GFL96","PLA HIGH SPEED":"GFL95",PETG:"GFG99","PETG HF":"GFG96","PETG-CF":"GFG98",PCTG:"GFG97",ABS:"GFB99",ASA:"GFB98",PC:"GFC99",PA:"GFN99","PA-CF":"GFN98",NYLON:"GFN99",TPU:"GFU99",PVA:"GFS99",HIPS:"GFS98",PE:"GFP99",PP:"GFP97"};xe=He[Fe]||He[Fe.replace(/[-\s]?CF$/,"")]||He[Fe.replace(/\+$/,"")]||He[Fe.split(/[-\s]/)[0]]||"",oe=""}else if(U)xe=H,oe="";else if(xe=j1(u),oe=u,!u.startsWith("GFS"))try{const Fe=await ge.getCloudSettingDetail(u);Fe.filament_id?xe=Fe.filament_id:Fe.base_id&&(xe=j1(Fe.base_id),console.log(`Derived tray_info_idx from base_id: ${Fe.base_id} -> ${xe}`))}catch(Fe){console.warn("Failed to fetch preset detail for filament_id:",Fe)}let F=E&&re?.nozzle_temp_min?re.nozzle_temp_min:190,te=E&&re?.nozzle_temp_max?re.nozzle_temp_max:230;if(!E||U||!re?.nozzle_temp_min&&!re?.nozzle_temp_max){const Fe=(E?e0.includes(L)?L:re?.filament_type||W.material||"":W.material).toUpperCase();Fe.includes("PLA")?(F=190,te=230):Fe.includes("PETG")?(F=220,te=260):Fe.includes("ABS")||Fe.includes("ASA")?(F=240,te=280):Fe.includes("TPU")?(F=200,te=240):Fe==="PCTG"?(F=220,te=260):Fe.includes("PC")?(F=260,te=300):(Fe.includes("PA")||Fe.includes("NYLON"))&&(F=250,te=290)}const ve=m?.k_value?parseFloat(m.k_value):0,fe=E?e0.includes(L)?L:re?.filament_type||W.material||"PLA":W.material||"PLA",me=await ge.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:xe,tray_type:fe,tray_sub_brands:be,tray_color:ce+"FF",nozzle_temp_min:F,nozzle_temp_max:te,cali_idx:ie,nozzle_diameter:a,setting_id:oe,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:ve}),je=E?`local_${K}`:U?`builtin_${H}`:u,we=E?"local":U?"builtin":"cloud";try{await ge.saveSlotPreset(n,r.amsId,r.trayId,je,be,we)}catch(Fe){console.warn("Failed to save slot preset mapping:",Fe)}return me},onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),de=gt({mutationFn:async()=>ge.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),he=w.useMemo(()=>{const E=g.toLowerCase(),U=[],K=new Set,H=r.savedPresetId,re=r.trayInfoIdx;if(D?.filament)for(const O of D.filament){K.add(O.setting_id);const ee=H===O.setting_id||re&&(O.setting_id===re||j1(O.setting_id)===re);if(!(E&&!O.name.toLowerCase().includes(E))){if(!ee&&s){const W=Dqe(O.name);if(W&&W.toUpperCase()!==s.toUpperCase())continue}U.push({id:O.setting_id,name:O.name,source:"cloud",isUser:Eqe(O.setting_id)})}}if(G?.filament)for(const O of G.filament){const $=`local_${O.id}`;E&&!O.name.toLowerCase().includes(E)||U.push({id:$,name:O.name,source:"local",isUser:!1})}if(Z)for(const O of Z){if(K.has(O.filament_id))continue;const $=O.filament_id.startsWith("GF")?"GFS"+O.filament_id.slice(2):O.filament_id;K.has($)||(!E||O.name.toLowerCase().includes(E))&&U.push({id:`builtin_${O.filament_id}`,name:O.name,source:"builtin",isUser:!1})}return U.sort((O,$)=>{const ee={cloud:0,local:1,builtin:2};return O.source!==$.source?ee[O.source]-ee[$.source]:O.isUser&&!$.isUser?-1:!O.isUser&&$.isUser?1:O.name.localeCompare($.name)})},[D?.filament,G?.filament,Z,g,s,r.savedPresetId,r.trayInfoIdx]),V=w.useMemo(()=>{if(!u)return null;let E=null;if(u.startsWith("local_")){const H=parseInt(u.replace("local_",""),10);E=G?.filament.find(O=>O.id===H)?.name||null}else if(u.startsWith("builtin_")){const H=u.replace("builtin_","");E=Z?.find(O=>O.filament_id===H)?.name||null}else D?.filament&&(E=D.filament.find(re=>re.setting_id===u)?.name||null);if(!E)return null;let U=E.replace(/@.+$/,"").trim();U.startsWith("# ")&&(U=U.slice(2).trim());const K=hW(U);return{fullName:U,material:K.material,brand:K.brand}},[u,D?.filament,G?.filament,Z]),ne=V?.fullName||"",se=w.useMemo(()=>{if(!Y||!V)return[];const{fullName:E,brand:U}=V,K=E.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return Y.filter(H=>{const re=(H.material||"").toUpperCase(),O=H.manufacturer.toUpperCase();if(!(re===K.toUpperCase()||re.includes(K.toUpperCase())||K.toUpperCase().includes(re)))return!1;if(U){const ee=U.toUpperCase();if(!O.includes(ee)&&!ee.includes(O))return!1}return!0})},[Y,V]),pe=w.useMemo(()=>{if(!J?.profiles||!V)return[];const{fullName:E,material:U,brand:K}=V,H=E.toUpperCase(),re=U.toUpperCase(),O=K.toUpperCase();if(!re||re.length<2)return[];const $=J.profiles.filter(W=>{const ie=W.name.toUpperCase();if(O)return!(!ie.includes(O)||!ie.includes(re));if(ie.includes(H)||ie.includes(re))return!0;const be={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[re]||[];for(const xe of be)if(ie.includes(xe))return!0;return!1}),ee=new Map;for(const W of $){const ie=`${W.name}|${W.k_value}`,ce=ee.get(ie);ce?r.extruderId!==void 0&&W.extruder_id===r.extruderId&&ce.extruder_id!==r.extruderId&&ee.set(ie,W):ee.set(ie,W)}return Array.from(ee.values())},[J?.profiles,V,r.extruderId]);w.useEffect(()=>{if(t){if(r.savedPresetId)d(r.savedPresetId);else if(r.trayInfoIdx&&D?.filament){let E=D.filament.find(U=>U.setting_id===r.trayInfoIdx);E||(E=D.filament.find(U=>j1(U.setting_id)===r.trayInfoIdx)),E&&d(E.setting_id)}else if(r.trayInfoIdx&&Z?.length){const E=r.trayInfoIdx,U=Z.find(K=>K.filament_id===E);U&&d(`builtin_${U.filament_id}`)}if(r.trayColor){const E=r.trayColor.slice(0,6);E&&y(E)}}else d(""),p(null),y(""),b(""),_(""),C(!1),T.current=""},[t,r.savedPresetId,r.trayInfoIdx,r.trayColor,D?.filament,Z]),w.useEffect(()=>{if(pe.length>0){if(r.caliIdx!=null&&r.caliIdx>0){const E=pe.find(U=>U.slot_id===r.caliIdx);if(E){p(E);return}}p(pe[0])}else p(null)},[u,pe,r.caliIdx]);const Te=w.useCallback(E=>{E.key==="Escape"&&e()},[e]);w.useEffect(()=>{if(t)return document.addEventListener("keydown",Te),()=>document.removeEventListener("keydown",Te)},[t,Te]);const q=A&&!R||z||I||ae;if(w.useEffect(()=>{if(!q&&u&&u!==T.current){const E=requestAnimationFrame(()=>{const K=document.querySelector('[class*="fixed inset-0 z-50"]')?.querySelector(`[data-preset-id="${CSS.escape(u)}"]`);K&&(T.current=u,K.scrollIntoView({block:"nearest"}))});return()=>cancelAnimationFrame(E)}},[u,q]),!t)return null;const X=u&&!ue.isPending,j=f||r.trayColor?.slice(0,6)||"FFFFFF";return i.jsxs("div",{className:`fixed inset-0 z-50 flex ${l?"":"items-center justify-center"}`,children:[!l&&i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:l?"relative w-full h-full bg-bambu-dark-secondary flex flex-col":"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Bd,{className:"w-5 h-5 text-bambu-blue"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.title")}),l&&i.jsxs("div",{className:"flex items-center gap-2 ml-4 text-sm text-bambu-gray",children:[i.jsx("span",{className:"text-white/30",children:"|"}),r.trayColor&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),i.jsx("span",{className:"text-white/70",children:c("configureAmsSlot.slotLabel",{ams:mW(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&i.jsxs("span",{children:["(",r.traySubBrands,")"]})]})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:`p-4 overflow-y-auto ${l?"flex-1 min-h-0":"space-y-4 max-h-[60vh]"}`,children:[N&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl",children:i.jsxs("div",{className:"text-center space-y-3",children:[i.jsx(vc,{className:"w-16 h-16 text-bambu-green mx-auto"}),i.jsx("p",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.slotConfigured")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:c("configureAmsSlot.settingsSentToPrinter")})]})}),!l&&i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:c("configureAmsSlot.configuringSlot")}),i.jsxs("div",{className:"flex items-center gap-2",children:[r.trayColor&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),i.jsx("span",{className:"text-white font-medium",children:c("configureAmsSlot.slotLabel",{ams:mW(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&i.jsxs("span",{className:"text-bambu-gray",children:["(",r.traySubBrands,")"]})]})]}),q?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):l?i.jsxs("div",{className:"flex gap-4 h-full",children:[i.jsxs("div",{className:"w-1/2 flex flex-col min-h-0",children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:g,onChange:E=>_(E.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 shrink-0"}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-1",children:he.length===0?i.jsx("p",{className:"text-center py-4 text-bambu-gray",children:D?.filament?.length===0&&!G?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):he.map(E=>i.jsx("button",{"data-preset-id":E.id,onClick:()=>d(E.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${u===E.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-white text-sm truncate",children:E.name}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[E.source==="local"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),E.source==="builtin"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),E.isUser&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},E.id))})]}),i.jsxs("div",{className:"w-1/2 flex flex-col gap-4 min-h-0 overflow-y-auto",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),ne&&i.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ne})})]}),pe.length>0?i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:m?.name||"",onChange:E=>{const U=pe.find(K=>K.name===E.target.value);p(U||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:[i.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),pe.map(E=>i.jsxs("option",{value:E.name,children:[E.name," (K=",E.k_value,")"]},`${E.name}-${E.extruder_id}`))]}),i.jsx(In,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):u?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):i.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:c("configureAmsSlot.selectFilamentFirst")}),m&&i.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),se.length>0&&i.jsxs("div",{className:"mb-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:V?.fullName})}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:se.map(E=>i.jsxs("button",{onClick:()=>{const U=E.hex_color.replace("#","").toUpperCase();y(U),b(E.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===E.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:E.color_name,children:[i.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:E.hex_color}}),i.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:E.color_name})]},E.id))})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[pW.map(E=>i.jsx("button",{onClick:()=>{y(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.hex)),i.jsx("button",{onClick:()=>P(!k),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:c(k?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:k?"−":"+"})]}),k&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:fW.map(E=>i.jsx("button",{onClick:()=>{y(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.hex))}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${j}`}}),i.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:v,onChange:E=>{const U=E.target.value;b(U);const K=gW(U);if(K)y(K);else{const H=U.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();H.length===6?y(H):H.length===3&&y(H.split("").map(re=>re+re).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"}),f&&i.jsx("button",{onClick:()=>{y(""),b("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:c("configureAmsSlot.clearCustomColor"),children:c("configureAmsSlot.clear")})]}),f&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:g,onChange:E=>_(E.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"}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:he.length===0?i.jsx("p",{className:"text-center py-4 text-bambu-gray",children:D?.filament?.length===0&&!G?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):he.map(E=>i.jsx("button",{"data-preset-id":E.id,onClick:()=>d(E.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${u===E.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-white text-sm truncate",children:E.name}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[E.source==="local"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),E.source==="builtin"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),E.isUser&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},E.id))})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),ne&&i.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ne})})]}),pe.length>0?i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:m?.name||"",onChange:E=>{const U=pe.find(K=>K.name===E.target.value);p(U||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:[i.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),pe.map(E=>i.jsxs("option",{value:E.name,children:[E.name," (K=",E.k_value,")"]},`${E.name}-${E.extruder_id}`))]}),i.jsx(In,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):u?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):i.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:c("configureAmsSlot.selectFilamentFirst")}),m&&i.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),se.length>0&&i.jsxs("div",{className:"mb-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:V?.fullName})}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:se.map(E=>i.jsxs("button",{onClick:()=>{const U=E.hex_color.replace("#","").toUpperCase();y(U),b(E.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===E.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:E.color_name,children:[i.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:E.hex_color}}),i.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:E.color_name})]},E.id))})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[pW.map(E=>i.jsx("button",{onClick:()=>{y(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.hex)),i.jsx("button",{onClick:()=>P(!k),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:c(k?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:k?"−":"+"})]}),k&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:fW.map(E=>i.jsx("button",{onClick:()=>{y(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.hex))}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${j}`}}),i.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:v,onChange:E=>{const U=E.target.value;b(U);const K=gW(U);if(K)y(K);else{const H=U.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();H.length===6?y(H):H.length===3&&y(H.split("").map(re=>re+re).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"}),f&&i.jsx("button",{onClick:()=>{y(""),b("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:c("configureAmsSlot.clearCustomColor"),children:c("configureAmsSlot.clear")})]}),f&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}),i.jsxs("div",{className:"flex justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[i.jsx(ze,{variant:"secondary",onClick:()=>de.mutate(),disabled:de.isPending||ue.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:de.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):i.jsxs(i.Fragment,{children:[i.jsx(To,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),i.jsx(ze,{onClick:()=>ue.mutate(),disabled:!X,children:ue.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):i.jsxs(i.Fragment,{children:[i.jsx(Bd,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(ue.isError||de.isError)&&i.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:ue.error?.message||de.error?.message})]})]})}function nie({folderId:t,onClose:e,onUploadComplete:n,onFileUploaded:r,autoUpload:a,validateFile:s,accept:o}){const{t:l}=Dt(),[c,u]=w.useState([]),[d,m]=w.useState(!1),[p,f]=w.useState(!1),[y,v]=w.useState(!0),[b,g]=w.useState(!1),[_,N]=w.useState(!0),[C,k]=w.useState(null),P=w.useRef(null),T=he=>{he.preventDefault(),m(!0)},D=he=>{he.preventDefault(),m(!1)},A=he=>{he.preventDefault(),m(!1),Z(Array.from(he.dataTransfer.files))},R=he=>{he.target.files&&Z(Array.from(he.target.files))},G=(he,V)=>{u(ne=>ne.map(se=>se.file===he?{...se,...V}:se))},z=async he=>{f(!0);for(const V of he)if(V.status==="pending"){G(V.file,{status:"uploading"});try{if(V.isZip){const ne=await ge.extractZipFile(V.file,t,y,b,_);G(V.file,{status:ne.errors.length>0&&ne.extracted===0?"error":"success",extractedCount:ne.extracted,error:ne.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:ne.errors.length}):void 0})}else{const ne=await ge.uploadLibraryFile(V.file,t,_);G(V.file,{status:"success"});const se=r?.(ne);if(se){k(se),u([]),f(!1);return}}}catch(ne){G(V.file,{status:"error",error:ne instanceof Error?ne.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),n(),e()},Z=he=>{if(k(null),s)for(const ne of he){const se=s(ne);if(se){k(se);return}}const V=he.map(ne=>({file:ne,status:"pending",isZip:ne.name.toLowerCase().endsWith(".zip"),is3mf:ne.name.toLowerCase().endsWith(".3mf")}));u(ne=>[...ne,...V]),a&&he.length>0&&z(V)},I=he=>{u(V=>V.filter((ne,se)=>se!==he))},J=c.some(he=>he.isZip&&he.status==="pending"),ae=c.some(he=>he.file.name.toLowerCase().endsWith(".stl")&&he.status==="pending"),Y=c.some(he=>he.is3mf&&he.status==="pending"),ue=c.filter(he=>he.status==="pending").length,de=c.length>0&&ue===0&&!p;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:l("fileManager.uploadFiles")}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("div",{onDragOver:T,onDragLeave:D,onDrop:A,onClick:()=>P.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${d?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[i.jsx(yi,{className:`w-10 h-10 mx-auto mb-3 ${d?"text-bambu-green":"text-bambu-gray"}`}),i.jsx("p",{className:"text-white font-medium",children:l(d?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:l("fileManager.orClickToBrowse")}),i.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:l("fileManager.allFileTypesSupported")})]}),i.jsx("input",{ref:P,type:"file",multiple:!0,accept:o,className:"hidden",onChange:R}),J&&i.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Vs,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-blue-300 font-medium",children:l("fileManager.zipFilesDetected")}),i.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:l("fileManager.zipExtractOptions")}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:y,onChange:he=>v(he.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:l("fileManager.preserveZipStructure")})]}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:b,onChange:he=>g(he.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:l("fileManager.createFolderFromZip")})]})]})]})}),Y&&i.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(_r,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-purple-300 font-medium",children:l("fileManager.threemfDetected")}),i.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:l("fileManager.threemfExtractionInfo")})]})]})}),(ae||J)&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Ud,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-bambu-green font-medium",children:l("fileManager.stlThumbnailGeneration")}),i.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:l(J&&!ae?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:_,onChange:he=>N(he.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:l("fileManager.generateThumbnailsForStl")})]})]})]})}),c.length>0&&i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:c.map((he,V)=>i.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[he.isZip?i.jsx(Vs,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):i.jsx(iT,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:he.file.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[(he.file.size/1024/1024).toFixed(2)," MB",he.isZip&&he.status==="pending"&&i.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",l("fileManager.willBeExtracted")]}),he.extractedCount!==void 0&&i.jsxs("span",{className:"text-green-400 ml-2",children:["• ",l("fileManager.filesExtracted",{count:he.extractedCount})]})]})]}),he.status==="pending"&&i.jsx("button",{onClick:()=>I(V),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Ht,{className:"w-4 h-4 text-bambu-gray"})}),he.status==="uploading"&&i.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"}),he.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-500"}),he.status==="error"&&i.jsx("span",{title:he.error,children:i.jsx(Vi,{className:"w-4 h-4 text-red-500"})})]},V))}),C&&i.jsx("div",{className:"p-3 bg-red-500/10 border border-red-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Vi,{className:"w-5 h-5 text-red-400 mt-0.5 flex-shrink-0"}),i.jsx("p",{className:"text-sm text-red-300",children:C})]})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:e,children:l("common.cancel")}),!de&&i.jsx(ze,{onClick:()=>z(c),disabled:ue===0||p,children:p?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(yi,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",ue>0?`(${ue})`:""]})})]})]})})}function bW(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Ri(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}const Rqe=[["PA-CF","PA12-CF","PAHT-CF"]],rie={};for(const t of Rqe){const e=t[0];for(const n of t)rie[n.toUpperCase()]=e.toUpperCase()}function rC(t){if(!t)return"";const e=t.toUpperCase();return rie[e]??e}function Jj(t,e){return rC(t)===rC(e)}function bu(t,e,n=40){const r=Ri(t),a=Ri(e);if(!r||!a||r.length<6||a.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(a.substring(0,2),16),u=parseInt(a.substring(2,4),16),d=parseInt(a.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-u)<=n&&Math.abs(l-d)<=n}function FI(t,e,n,r){if(r)return"Ext";const a=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${a}`:`${a}${e+1}`}function Ex(t,e,n){return n?254+e:t>=128?t:t*4+e}function ix(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function yN(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 xW(t,e){return(Number.isFinite(t)?Math.max(0,Math.trunc(t)):0).toString(16).toUpperCase().padStart(e,"0").slice(-e)}function Fqe(t){const e=(t||"").trim().toUpperCase();let n=2166136261;for(let r=0;r>>0).toString(16).toUpperCase().padStart(8,"0")}function $p(t,e,n){return`${Fqe(t)}${xW(e,4)}${xW(n,4)}`}function yW(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(Qn(t)?.getTime()??0)>e}function Lqe(t,e,n){const r=iie(e,t.nozzle_id),a=r.find(l=>!n.has(l.globalTrayId)&&Jj(l.type,t.type)&&Ri(l.color)===Ri(t.color)),s=a?void 0:r.find(l=>!n.has(l.globalTrayId)&&Jj(l.type,t.type)&&bu(l.color,t.color)),o=a||s?void 0:r.find(l=>!n.has(l.globalTrayId)&&Jj(l.type,t.type));return a??s??o}function iie(t,e){return t.filter(n=>e==null||n.extruderId===e)}function Xw(t){const e=[],n=t?.ams_extruder_map,r=n&&Object.keys(n).length>0;t?.ams?.forEach(a=>{const s=a.tray.length===1;a.tray.forEach(o=>{if(o.tray_type){const l=bW(o.tray_color);e.push({type:o.tray_type,color:l,colorName:Ld(l),amsId:a.id,trayId:o.id,isHt:s,isExternal:!1,label:FI(a.id,o.id,s,!1),globalTrayId:Ex(a.id,o.id,!1),trayInfoIdx:o.tray_info_idx||"",traySubBrands:o.tray_sub_brands||"",extruderId:n?.[String(a.id)]})}})});for(const a of t?.vt_tray??[])if(a.tray_type){const s=bW(a.tray_color),o=a.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:a.tray_type,color:s,colorName:Ld(s),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:l?o===254?"Ext-L":"Ext-R":"External",globalTrayId:o,trayInfoIdx:a.tray_info_idx||"",traySubBrands:a.tray_sub_brands||"",extruderId:r?255-o:void 0})}return e}function vW(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=Xw(e);if(n.length===0)return;const r=new Set,a=t.filaments.map(l=>{const c=l.tray_info_idx||"";let u=n.filter(v=>!r.has(v.globalTrayId));l.nozzle_id!=null&&(u=u.filter(v=>v.extruderId===l.nozzle_id));let d,m,p,f;if(c){const v=u.filter(b=>b.trayInfoIdx===c);v.length===1?d=v[0]:v.length>1&&(m=v.find(b=>b.type?.toUpperCase()===l.type?.toUpperCase()&&Ri(b.color)===Ri(l.color)),m||(p=v.find(b=>b.type?.toUpperCase()===l.type?.toUpperCase()&&bu(b.color,l.color))),!m&&!p&&(f=v.find(b=>b.type?.toUpperCase()===l.type?.toUpperCase())))}!d&&!m&&!p&&!f&&(m=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Ri(v.color)===Ri(l.color)),m||(p=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&bu(v.color,l.color))),!m&&!p&&(f=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase())));const y=d||m||p||f||void 0;return y&&r.add(y.globalTrayId),{slot_id:l.slot_id,globalTrayId:y?.globalTrayId??-1}}),s=Math.max(...a.map(l=>l.slot_id||0));if(s<=0)return;const o=new Array(s).fill(-1);return a.forEach(l=>{l.slot_id&&l.slot_id>0&&(o[l.slot_id-1]=l.globalTrayId)}),o}function Oqe(t){return w.useMemo(()=>Xw(t),[t])}function aie(t,e,n){const r=Oqe(e),a=w.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 P=n[d],T=r.find(D=>D.globalTrayId===P);if(T){const D=T.type?.toUpperCase()===u.type?.toUpperCase(),A=Ri(T.color)===Ri(u.color)||bu(T.color,u.color);let R;return D&&A?R="match":D?R="type_only":R="mismatch",{...u,loaded:T,hasFilament:!0,typeMatch:D,colorMatch:A,status:R,isManual:!0}}}const m=u.tray_info_idx||"";let p=r.filter(P=>!c.has(P.globalTrayId));u.nozzle_id!=null&&(p=p.filter(P=>P.extruderId===u.nozzle_id));let f,y,v,b;if(m){const P=p.filter(T=>T.trayInfoIdx===m);P.length===1?f=P[0]:P.length>1&&(y=P.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase()&&Ri(T.color)===Ri(u.color)),y||(v=P.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase()&&bu(T.color,u.color))),!y&&!v&&(b=P.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase())))}!f&&!y&&!v&&!b&&(y=p.find(P=>P.type?.toUpperCase()===u.type?.toUpperCase()&&Ri(P.color)===Ri(u.color)),y||(v=p.find(P=>P.type?.toUpperCase()===u.type?.toUpperCase()&&bu(P.color,u.color))),!y&&!v&&(b=p.find(P=>P.type?.toUpperCase()===u.type?.toUpperCase())));const g=f||y||v||b||void 0;g&&c.add(g.globalTrayId);const _=!!g,N=_,C=!!f||!!y||!!v;let k;return f||y||v?k="match":b?k="type_only":k="mismatch",{...u,loaded:g,hasFilament:_,typeMatch:N,colorMatch:C,status:k,isManual:!1}})},[t,r,n]),s=w.useMemo(()=>{if(a.length===0)return;const c=Math.max(...a.map(d=>d.slot_id||0));if(c<=0)return;const u=new Array(c).fill(-1);return a.forEach(d=>{d.slot_id&&d.slot_id>0&&(u[d.slot_id-1]=d.loaded?.globalTrayId??-1)}),u},[a]),o=a.some(c=>c.status==="mismatch"),l=a.some(c=>c.status==="type_only");return{loadedFilaments:r,filamentComparison:a,amsMapping:s,hasTypeMismatch:o,hasColorMismatch:l}}function Iqe(t,e,n){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let r=0,a=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 b=n[d],g=e.find(_=>_.globalTrayId===b);if(g){const _=g.type?.toUpperCase()===u.type?.toUpperCase(),N=Ri(g.color)===Ri(u.color)||bu(g.color,u.color);_&&N?r++:_?a++:s++;continue}}let m=e.filter(b=>!o.has(b.globalTrayId));if(u.nozzle_id!=null){const b=m.filter(g=>g.extruderId===u.nozzle_id);b.length>0&&(m=b)}const p=m.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()&&Ri(b.color)===Ri(u.color)),f=p?void 0:m.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()&&bu(b.color,u.color)),y=p||f?void 0:m.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()),v=p??f??y;v&&o.add(v.globalTrayId),p||f?r++:y?a++:s++}const l=t.length;let c="full";return s>0?c="missing":a>0&&(c="partial"),{exactMatches:r,typeOnlyMatches:a,missingTypes:s,totalSlots:l,status:c}}function zqe(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=Xw(e);if(r.length===0)return;const a=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}let d=r.filter(v=>!a.has(v.globalTrayId));if(c.nozzle_id!=null){const v=d.filter(b=>b.extruderId===c.nozzle_id);v.length>0&&(d=v)}const m=d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Ri(v.color)===Ri(c.color)),p=m?void 0:d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&bu(v.color,c.color)),f=m||p?void 0:d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()),y=m??p??f;y&&a.add(y.globalTrayId),s.push({slot_id:u,globalTrayId:y?.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 wW={useDefault:!0,manualMappings:{},autoConfigured:!1};function Uqe(t,e,n,r,a,s){const o=tg({queries:t.map(y=>({queryKey:["printer-status",y],queryFn:()=>ge.getPrinterStatus(y),enabled:t.length>0,staleTime:5e3}))}),l=w.useMemo(()=>t.map((y,v)=>{const b=o[v],g=b?.data,N=e?.find(R=>R.id===y)?.name||`Printer ${y}`,C=Xw(g),k=a[y]||wW,P=vW(n,g),T=k.useDefault?r:k.manualMappings,D=zqe(n,g,T),A=Iqe(n?.filaments,C,T);return{printerId:y,printerName:N,status:g,isLoading:b?.isLoading??!1,loadedFilaments:C,autoMapping:P,finalMapping:D,matchStatus:A.status,exactMatches:A.exactMatches,typeOnlyMatches:A.typeOnlyMatches,missingTypes:A.missingTypes,totalSlots:A.totalSlots,config:k}}),[t,o,e,n,a,r]),c=o.some(y=>y.isLoading),u=(y,v)=>{s(b=>({...b,[y]:{...b[y]||wW,...v}}))},d=y=>{const v=l.find(_=>_.printerId===y);if(!v||!v.status||!n?.filaments)return;const b=vW(n,v.status);if(!b)return;const g={};b.forEach((_,N)=>{_!==-1&&(g[N+1]=_)}),u(y,{useDefault:!1,manualMappings:g,autoConfigured:!0})},m=()=>{for(const y of t)d(y)},p=y=>l.find(b=>b.printerId===y)?.finalMapping,f=l.every(y=>y.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:a,updatePrinterConfig:u,autoConfigureAll:m,autoConfigurePrinter:d,getFinalMapping:p,allPrintersReady:f}}const sie={USD:"$",EUR:"€",GBP:"£",CHF:"Fr.",JPY:"¥",CNY:"¥",CAD:"$",AUD:"$",INR:"₹",HKD:"HK$",KRW:"₩",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"zł",BRL:"R$",TWD:"NT$",SGD:"S$",NZD:"NZ$",MXN:"MX$",MYR:"RM",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽",HUF:"Ft",ILS:"₪"};function Wo(t){return sie[t.toUpperCase()]||t}const Bqe=Object.entries(sie).map(([t,e])=>({code:t,label:`${t} (${e})`}));function Hqe({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,currencySymbol:a,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=Dt(),c=sn(),[u,d]=w.useState(!1),[m,p]=w.useState(o),{data:f}=et({queryKey:["printer-status",t],queryFn:()=>ge.getPrinterStatus(t),enabled:!!t}),{data:y}=et({queryKey:["spool-assignments",t],queryFn:()=>ge.getAssignments(t),enabled:!!t}),{loadedFilaments:v,filamentComparison:b,hasTypeMismatch:g,hasColorMismatch:_}=aie(e,f,n),N=w.useMemo(()=>{const z=new Map;for(const Z of y||[]){const I=Z.ams_id===255,J=Ex(Z.ams_id,Z.tray_id,I);z.set(J,Z.spool?.cost_per_kg??null)}return z},[y]),C=w.useMemo(()=>{const z=new Map;for(const Z of y||[]){const I=Z.ams_id===255,J=Ex(Z.ams_id,Z.tray_id,I),ae=Z.spool;if(!ae){z.set(J,null);continue}z.set(J,Math.max(0,Math.round((ae.label_weight??0)-(ae.weight_used??0))))}return z},[y]),k=w.useMemo(()=>{let z=0;for(const Z of b){const I=Z.loaded?.globalTrayId;if(I==null)continue;const ae=N.get(I)??null??s;ae>0&&(z+=Z.used_grams/1e3*ae)}return z},[b,N,s]),P=w.useMemo(()=>Array.from(N.values()).some(z=>z!=null&&z>0),[N]),T=e?.filaments&&e.filaments.length>0,D=e?.filaments?.some(z=>z.nozzle_id!=null)??!1;if(!T||!f)return null;const A=g?"#f97316":_?"#facc15":"#00ae42",R=(z,Z)=>{if(z>0)if(Z===""){const I={...n};delete I[z],r(I)}else r({...n,[z]:parseInt(Z,10)})},G=async()=>{d(!0);try{await ge.refreshPrinterStatus(t),await new Promise(z=>setTimeout(z,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{d(!1)}};return i.jsxs("div",{className:"mb-4",children:[i.jsxs("button",{type:"button",onClick:()=>p(!m),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[i.jsx(S0,{className:"w-4 h-4",fill:A,stroke:"none"}),i.jsx("span",{children:l("printModal.filamentMapping")}),g?i.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):_?i.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):i.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),m?i.jsx(Vl,{className:"w-4 h-4 ml-auto"}):i.jsx(In,{className:"w-4 h-4 ml-auto"})]}),m&&i.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),i.jsxs("button",{type:"button",onClick:G,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:u,children:[i.jsx(Sr,{className:`w-3 h-3 ${u?"animate-spin":""}`}),i.jsx("span",{children:"Re-read"})]})]}),b.map((z,Z)=>i.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[i.jsx("span",{title:`Required: ${z.type} - ${Ld(z.color)}`,children:i.jsx(S0,{className:"w-3 h-3",fill:z.color,stroke:z.color})}),i.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[D&&z.nozzle_id!=null&&i.jsx("span",{className:"inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0",title:z.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:z.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),z.type," ",i.jsxs("span",{className:"text-bambu-gray",children:["(",z.used_grams,"g)"]})]}),i.jsx("span",{className:"text-bambu-gray",children:"→"}),i.jsxs("select",{value:z.loaded?.globalTrayId??"",onChange:I=>R(z.slot_id||0,I.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 ${z.status==="match"?"border-bambu-green/50 text-bambu-green":z.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${z.isManual?"ring-1 ring-blue-400/50":""}`,title:z.isManual?"Manually selected":"Auto-matched",children:[i.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),v.filter(I=>z.nozzle_id==null||I.extruderId===z.nozzle_id).map(I=>{const J=C.get(I.globalTrayId),ae=J!=null?l("printModal.slotRemainingShort",{grams:J,defaultValue:` - ${J}g left`}):"";return i.jsxs("option",{value:I.globalTrayId,className:"bg-bambu-dark text-white",children:[I.label,": ",I.traySubBrands||I.type," (",I.colorName,")",ae]},I.globalTrayId)})]}),z.status==="match"?i.jsx(Zr,{className:"w-3 h-3 text-bambu-green"}):z.status==="type_only"?i.jsx("span",{title:"Same type, different color",children:i.jsx(jn,{className:"w-3 h-3 text-yellow-400"})}):i.jsx("span",{title:"Filament type not loaded",children:i.jsx(jn,{className:"w-3 h-3 text-orange-400"})})]},Z)),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",i.jsx("span",{className:"text-white",children:k>0||P?`${a}${k.toFixed(2)}`:"N/A"})]}),g&&i.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function $qe({filamentReqs:t,availableFilaments:e,overrides:n,onChange:r,forceColorMatch:a,onForceColorMatchChange:s}){const{t:o}=Dt(),l=w.useMemo(()=>{const d={};for(const m of e){const p=rC(m.type);d[p]||(d[p]=[]),d[p].push(m)}return d},[e]),c=t?.filaments;if(!c||c.length===0||e.length===0)return null;const u=(d,m)=>{if(m===""){const p={...n};delete p[d],r(p)}else{const[p,f]=m.split("|");r({...n,[d]:{type:p,color:f}})}};return i.jsxs("div",{className:"mb-4",children:[i.jsx("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:i.jsx("span",{children:o("printModal.filamentOverride")})}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("printModal.filamentOverrideHint")}),i.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 space-y-2",children:c.map(d=>{const m=n[d.slot_id],p=!!m,f=l[rC(d.type)]||[],y=d.nozzle_id!=null?f.filter(v=>v.extruder_id==null||v.extruder_id===d.nozzle_id):f;return i.jsxs("div",{className:"space-y-1",children:[i.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 20px"},children:[i.jsx("span",{title:`${o("printModal.originalFilament")}: ${d.type} - ${Ld(d.color)}`,children:i.jsx(S0,{className:"w-3 h-3",fill:d.color,stroke:d.color})}),i.jsxs("span",{className:"text-white truncate",children:[d.type," ",i.jsxs("span",{className:"text-bambu-gray",children:["(",d.used_grams,"g)"]})]}),i.jsx("span",{className:"text-bambu-gray",children:"→"}),i.jsxs("select",{value:p?`${m.type}|${m.color}`:"",onChange:v=>u(d.slot_id,v.target.value),disabled:y.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${p?"border-blue-400/50 text-blue-400":"border-bambu-gray/30 text-bambu-gray"}`,children:[i.jsxs("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:[o("printModal.originalFilament"),": ",d.type," (",Ld(d.color),")"]}),y.map((v,b)=>i.jsxs("option",{value:`${v.type}|${v.color}`,className:"bg-bambu-dark text-white",children:[v.tray_sub_brands||v.type," (",Ld(v.color),")"]},`${v.type}-${v.color}-${v.tray_sub_brands}-${b}`))]}),p?i.jsx("button",{type:"button",onClick:()=>u(d.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:o("printModal.resetToOriginal"),children:i.jsx(To,{className:"w-3 h-3"})}):i.jsx("span",{className:"w-3"})]}),i.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5",children:[i.jsx("input",{type:"checkbox",checked:a?.[d.slot_id]??!1,onChange:v=>s?.(d.slot_id,v.target.checked),className:"accent-bambu-green w-3 h-3"}),i.jsx(Sw,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},d.slot_id)})})]})}function qqe({plates:t,isMultiPlate:e,selectedPlates:n,onToggle:r,onSelectAll:a,onDeselectAll:s,multiSelect:o}){const{t:l}=Dt();if(!e||t.length<=1)return null;const c=n.size===t.length;return i.jsxs("div",{className:"mb-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx(Gi,{className:"w-4 h-4 text-bambu-gray"}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:["Select Plate",o?"s":""," to Print"]}),n.size===0&&i.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[i.jsx(jn,{className:"w-3 h-3"}),"Selection required"]}),o&&a&&s&&i.jsx("button",{type:"button",onClick:c?s:a,className:`ml-auto text-xs px-2 py-0.5 rounded-full border transition-colors ${c?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray"}`,children:c?l("queue.deselectAll"):l("queue.selectAllPlates",{count:t.length})})]}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(u=>{const d=n.has(u.index);return i.jsxs("button",{type:"button",onClick:()=>r(u.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${d?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[o&&(d?i.jsx(Ks,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}):i.jsx(rl,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})),u.has_thumbnail&&u.thumbnail_url!=null?i.jsx("img",{src:u.thumbnail_url,alt:`Plate ${u.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:i.jsx(Gi,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white font-medium truncate",children:u.name||`Plate ${u.index}`}),i.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[u.objects.length>0?u.objects.slice(0,3).join(", ")+(u.objects.length>3?"...":""):`${u.filaments.length} filament${u.filaments.length!==1?"s":""}`,u.print_time_seconds!=null?` • ${Us(u.print_time_seconds)}`:""]})]}),!o&&d&&i.jsx(Zr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},u.index)})})]})}const Vqe=new Set(["IDLE","FINISH","FAILED"]);function Gqe({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=sn(),[a,s]=w.useState(!1),o=(u,d)=>{if(u<=0)return;const m={...t.config.manualMappings};d===""?delete m[u]:m[u]=parseInt(d,10),n({useDefault:!1,manualMappings:m,autoConfigured:!1})},l=async()=>{s(!0);try{await ge.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,m=t.config.manualMappings[d];let p,f=!1;if(m!==void 0)p=t.loadedFilaments.find(v=>v.globalTrayId===m),f=!0;else{const v=new Set(Object.values(t.config.manualMappings));p=Lqe(u,t.loadedFilaments,v)}let y="mismatch";if(p){const v=p.type?.toUpperCase()===u.type?.toUpperCase(),b=Ri(p.color)===Ri(u.color)||bu(p.color,u.color);v&&b?y="match":v&&(y="type_only")}return{req:u,loaded:p,status:y,isManual:f}});return i.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),i.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:a,children:[i.jsx(Sr,{className:`w-3 h-3 ${a?"animate-spin":""}`}),i.jsx("span",{children:"Re-read"})]})]}),c.map(({req:u,loaded:d,status:m,isManual:p},f)=>i.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[i.jsx("span",{title:`Required: ${u.type} - ${Ld(u.color)}`,children:i.jsx(S0,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),i.jsxs("span",{className:"text-white truncate",children:[u.type," ",i.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),i.jsx("span",{className:"text-bambu-gray",children:"→"}),i.jsxs("select",{value:d?.globalTrayId??"",onChange:y=>o(u.slot_id||0,y.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 ${m==="match"?"border-bambu-green/50 text-bambu-green":m==="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:[i.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),iie(t.loadedFilaments,u.nozzle_id).map(y=>i.jsxs("option",{value:y.globalTrayId,className:"bg-bambu-dark text-white",children:[y.label,": ",y.traySubBrands||y.type," (",y.colorName,")"]},y.globalTrayId))]}),m==="match"?i.jsx(Zr,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?i.jsx("span",{title:"Same type, different color",children:i.jsx(jn,{className:"w-3 h-3 text-yellow-400"})}):i.jsx("span",{title:"Filament type not loaded",children:i.jsx(jn,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function Wqe({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:a=!1,showInactive:s=!1,disableBusy:o=!1,printerMappingResults:l,filamentReqs:c,onAutoConfigurePrinter:u,onUpdatePrinterConfig:d,assignmentMode:m="printer",onAssignmentModeChange:p,targetModel:f,onTargetModelChange:y,targetLocation:v,onTargetLocationChange:b,slicedForModel:g}){const[_,N]=w.useState(!1),C=s?t:t.filter(ne=>ne.is_active),k=tg({queries:C.map(ne=>({queryKey:["printerStatus",ne.id],queryFn:()=>ge.getPrinterStatus(ne.id),staleTime:5e3}))}),P=w.useMemo(()=>{const ne=new Map;return C.forEach((se,pe)=>{const Te=k[pe];Te?.data&&ne.set(se.id,Te.data)}),ne},[C,k]),T=ne=>{const se=P.get(ne);return se?se.connected?!Vqe.has(se.state??""):!0:!1},D=ne=>{const se=P.get(ne);if(!se)return null;if(!se.connected)return"Offline";const pe=se.state;return pe?pe==="RUNNING"?se.stg_cur_name||"Printing":pe==="PREPARE"?"Preparing":pe==="PAUSE"?"Paused":pe==="IDLE"?"Idle":pe==="FINISH"?"Finished":pe==="FAILED"?"Failed":pe:null},A=w.useMemo(()=>{if(m!=="printer"||!g||_)return C;const ne=C.filter(se=>se.model===g);return ne.length>0?ne:C},[C,m,g,_]),R=C.length-A.length,G=w.useMemo(()=>{const ne=C.map(se=>se.model).filter(se=>!!se);return[...new Set(ne)].sort()},[C]),z=w.useMemo(()=>{if(!f)return[];const ne=C.filter(se=>se.model===f&&se.location).map(se=>se.location).filter(se=>!!se);return[...new Set(ne)].sort()},[C,f]),Z=p&&y&&G.length>0,I=a&&e.length>1&&l&&c?.filaments&&c.filaments.length>0&&u&&d;if(r)return i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(A.length===0)return i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[i.jsx(Li,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const J=ne=>{o&&T(ne)||(a?e.includes(ne)?n(e.filter(se=>se!==ne)):n([...e,ne]):n([ne]))},ae=()=>{const ne=o?A.filter(se=>!T(se.id)):A;n(ne.map(se=>se.id))},Y=()=>{n([])},ue=(ne,se,pe)=>{pe.stopPropagation(),!(!u||!d)&&(se?u(ne):d(ne,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},de=ne=>e.includes(ne),he=e.length,V=ne=>l?.find(se=>se.printerId===ne);return i.jsxs("div",{className:"space-y-2 mb-6",children:[Z&&i.jsxs("div",{className:"flex gap-2 mb-4",children:[i.jsxs("button",{type:"button",onClick:()=>{p("printer"),y(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${m==="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:[i.jsx(_r,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),i.jsxs("button",{type:"button",onClick:()=>{p("model"),n([]);const ne=g&&G.includes(g)?g:G[0];y(ne)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${m==="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:[i.jsx(ih,{className:"w-4 h-4"}),i.jsxs("span",{className:"text-sm",children:["Any ",g||"Model"]})]})]}),m==="model"&&Z&&i.jsxs("div",{className:"space-y-3 mb-4",children:[!g&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),i.jsxs("select",{value:f||"",onChange:ne=>{y(ne.target.value||null),b&&b(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:[i.jsx("option",{value:"",children:"Select a model..."}),G.map(ne=>i.jsx("option",{value:ne,children:ne},ne))]})]}),f&&z.length>0&&b&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),i.jsxs("select",{value:v||"",onChange:ne=>b(ne.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:[i.jsx("option",{value:"",children:"Any location"}),z.map(ne=>i.jsx("option",{value:ne,children:ne},ne))]})]}),f&&i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",v?` in ${v}`:""]})]}),m==="printer"&&a&&A.length>1&&i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[i.jsx("span",{children:he===0?"Select printers":`${he} printer${he!==1?"s":""} selected`}),i.jsxs("div",{className:"flex gap-2",children:[he0&&i.jsx("button",{type:"button",onClick:Y,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&A.map(ne=>{const se=de(ne.id),pe=V(ne.id),Te=pe&&!pe.config.useDefault,q=T(ne.id),X=o&&q,j=D(ne.id);return i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>J(ne.id),disabled:X,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${X?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":se?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${ne.is_active?"":"opacity-60"}`,children:[i.jsx("div",{className:`p-2 rounded-lg ${X?"bg-bambu-dark-tertiary":se?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:i.jsx(_r,{className:`w-5 h-5 ${X?"text-bambu-gray/50":se?"text-bambu-green":"text-bambu-gray"}`})}),i.jsxs("div",{className:"text-left flex-1",children:[i.jsxs("p",{className:`font-medium ${X?"text-bambu-gray":"text-white"}`,children:[ne.name,!ne.is_active&&i.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[ne.model||"Unknown model"," • ",ne.ip_address]})]}),j&&i.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${q?"bg-yellow-500/20 text-yellow-400":"bg-bambu-green/20 text-bambu-green"}`,children:j}),a&&i.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${X?"border-bambu-gray/30":se?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:se&&i.jsx(Zr,{className:"w-3 h-3 text-white"})})]}),se&&I&&pe&&i.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:E=>E.stopPropagation(),children:[i.jsx("input",{type:"checkbox",checked:Te,onChange:E=>ue(ne.id,E.target.checked,E),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"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),i.jsxs("span",{className:`text-xs ml-2 ${pe.matchStatus==="full"?"text-bambu-green":pe.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",pe.exactMatches,"/",pe.totalSlots," matched)"]}),pe.isLoading&&i.jsx(Sr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),Te&&i.jsxs("button",{type:"button",onClick:E=>{E.stopPropagation(),u(ne.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:[i.jsx(Rbe,{className:"w-3 h-3"}),"Auto"]})]}),Te&&i.jsx(Gqe,{printerResult:pe,filamentReqs:c.filaments,onUpdateConfig:E=>d(ne.id,E)})]})]},ne.id)}),m==="printer"&&R>0&&!_&&i.jsxs("button",{type:"button",onClick:()=>N(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[i.jsx(jn,{className:"w-3 h-3 text-yellow-400"}),R," other printer",R>1?"s":""," hidden (different model) —",i.jsx("span",{className:"underline",children:"show all"})]}),m==="printer"&&_&&g&&i.jsx("button",{type:"button",onClick:()=>N(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:i.jsxs("span",{className:"underline",children:["Show only ",g," printers"]})}),m==="printer"&&he===0&&i.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[i.jsx(Li,{className:"w-3 h-3"}),"Select at least one printer"]}),m==="model"&&!f&&i.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[i.jsx(Li,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const Kqe=[{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 Yqe({options:t,onChange:e,defaultExpanded:n=!1}){const[r,a]=w.useState(n),s=o=>{e({...t,[o]:!t[o]})};return i.jsxs("div",{className:"mb-4",children:[i.jsxs("button",{type:"button",onClick:()=>a(!r),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[i.jsx(dT,{className:"w-4 h-4"}),i.jsx("span",{children:"Print Options"}),r?i.jsx(Vl,{className:"w-4 h-4 ml-auto"}):i.jsx(In,{className:"w-4 h-4 ml-auto"})]}),r&&i.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:Kqe.map(({key:o,label:l,desc:c})=>i.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-sm text-white",children:l}),i.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),i.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:i.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 Xqe({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system",canControlPrinter:a=!0}){const[s,o]=w.useState(""),[l,c]=w.useState(""),[u,d]=w.useState(!0),[m,p]=w.useState(!0),f=w.useRef(null),y=w.useRef(!1);w.useEffect(()=>{if(t.scheduleType!=="scheduled"){y.current=!1;return}if(!y.current){y.current=!0;let k;t.scheduledTime?(k=new Date(t.scheduledTime),isNaN(k.getTime())&&(k=new Date,k.setHours(k.getHours()+1,0,0,0))):(k=new Date,k.setHours(k.getHours()+1,0,0,0),e({...t,scheduledTime:P3(k)})),o(A3(k,n)),c(n6(k,r)),d(!0),p(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const v=k=>{e({...t,scheduleType:k})},b=(k,P)=>{const T=rxe(k,n),D=ixe(P);d(!!T),p(!!D),T&&D&&(T.setHours(D.hours,D.minutes,0,0),T>new Date&&e({...t,scheduledTime:P3(T)}))},g=k=>{o(k),b(k,l)},_=k=>{c(k),b(s,k)},N=k=>{const P=k.target.value;if(P){const T=new Date(P);isNaN(T.getTime())||(o(A3(T,n)),c(n6(T,r)),d(!0),p(!0),e({...t,scheduledTime:P}))}},C=()=>{f.current?.showPicker()};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("asap"),children:[i.jsx(Zn,{className:"w-4 h-4"}),"ASAP"]}),i.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("scheduled"),children:[i.jsx(Xr,{className:"w-4 h-4"}),"Scheduled"]}),i.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("manual"),children:[i.jsx(QX,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"flex-1 relative",children:[i.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${u?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:s,onChange:k=>g(k.target.value),placeholder:exe(n)}),i.jsx("button",{type:"button",onClick:C,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:i.jsx(Xr,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"w-32",children:i.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${m?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:l,onChange:k=>_(k.target.value),placeholder:txe(r)})})]}),i.jsx("input",{ref:f,type:"datetime-local",className:"sr-only",value:t.scheduledTime,onChange:N,tabIndex:-1}),(!u||!m)&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:k=>e({...t,requirePreviousSuccess:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:k=>e({...t,autoOffAfter:k.target.checked}),disabled:!a,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green disabled:opacity-50"}),i.jsxs("label",{htmlFor:"autoOffAfter",className:`text-sm flex items-center gap-1 ${a?"text-bambu-gray":"text-bambu-gray/50"}`,children:[i.jsx(em,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),i.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 Nb={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},Qqe={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function xu({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:a,initialSelectedPrinterIds:s,onClose:o,onSuccess:l}){const{t:c}=Dt(),u=sn(),{showToast:d}=bn(),{hasPermission:m}=Ar(),p=!!n&&!e,[f,y]=w.useState(()=>t==="edit-queue-item"&&a?.printer_id?[a.printer_id]:s?.length?s:[]),[v,b]=w.useState(()=>t==="edit-queue-item"&&a?.plate_id!=null?new Set([a.plate_id]):new Set),g=v.size===1?[...v][0]:null,[_,N]=w.useState(()=>t==="edit-queue-item"&&a?{bed_levelling:a.bed_levelling??Nb.bed_levelling,flow_cali:a.flow_cali??Nb.flow_cali,vibration_cali:a.vibration_cali??Nb.vibration_cali,layer_inspect:a.layer_inspect??Nb.layer_inspect,timelapse:a.timelapse??Nb.timelapse}:Nb),[C,k]=w.useState(()=>{if(t==="edit-queue-item"&&a){let _t="asap";a.manual_start?_t="manual":a.scheduled_time&&!yW(a.scheduled_time)&&(_t="scheduled");let rt="";if(a.scheduled_time&&!yW(a.scheduled_time)){const Rt=Qn(a.scheduled_time)??new Date;rt=P3(Rt)}return{scheduleType:_t,scheduledTime:rt,requirePreviousSuccess:a.require_previous_success,autoOffAfter:a.auto_off_after}}return Qqe}),[P,T]=w.useState(()=>{if(t==="edit-queue-item"&&a?.ams_mapping&&Array.isArray(a.ams_mapping)){const _t={};return a.ams_mapping.forEach((rt,Rt)=>{rt!==-1&&(_t[Rt+1]=rt)}),_t}return{}}),[D,A]=w.useState({}),[R,G]=w.useState(()=>t==="edit-queue-item"&&a?.target_model?"model":"printer"),[z,Z]=w.useState(()=>t==="edit-queue-item"&&a?.target_model?a.target_model:null),[I,J]=w.useState(()=>t==="edit-queue-item"&&a?.target_location?a.target_location:null),[ae,Y]=w.useState(()=>{if(t==="edit-queue-item"&&a?.filament_overrides){const _t={};for(const rt of a.filament_overrides)_t[rt.slot_id]={type:rt.type,color:rt.color};return _t}return{}}),[ue,de]=w.useState(()=>{if(t==="edit-queue-item"&&a?.filament_overrides){const _t={};for(const rt of a.filament_overrides)_t[rt.slot_id]=rt.force_color_match===!0;return _t}return{}}),[he]=w.useState(()=>t==="edit-queue-item"&&a?.printer_id?[a.printer_id]:[]),[V]=w.useState(()=>t==="edit-queue-item"&&a?a.plate_id:null),[ne,se]=w.useState(!1),[pe,Te]=w.useState({current:0,total:0}),[q,X]=w.useState(null),[j,E]=w.useState(new Set),U=f.length,K=f.length>0?f[0]:null,{data:H}=et({queryKey:["settings"],queryFn:ge.getSettings}),re=Wo(H?.currency||"USD"),O=H?.default_filament_cost??0,{data:$,isLoading:ee}=et({queryKey:["printers"],queryFn:ge.getPrinters}),{data:W}=et({queryKey:["spool-assignments"],queryFn:()=>ge.getAssignments(),staleTime:30*1e3,enabled:(t==="reprint"||t==="add-to-queue")&&R==="printer"||p&&t==="reprint"}),{data:ie}=et({queryKey:["archive",e],queryFn:()=>ge.getArchive(e),enabled:!!e&&!p}),{data:ce}=et({queryKey:["library-file",n],queryFn:()=>ge.getLibraryFile(n),enabled:p&&!!n}),be=ie?.sliced_for_model||ce?.sliced_for_model||null,{data:xe,isError:oe}=et({queryKey:["archive-plates",e],queryFn:()=>ge.getArchivePlates(e),enabled:!!e&&!p,retry:!1}),{data:L}=et({queryKey:["library-file-plates",n],queryFn:()=>ge.getLibraryFilePlates(n),enabled:p&&!!n}),F=p?L:xe,{data:te,isError:ve}=et({queryKey:["archive-filaments",e,g],queryFn:()=>ge.getArchiveFilamentRequirements(e,g??void 0),enabled:!!e&&!p&&(g!==null||!F?.is_multi_plate),retry:!1}),{data:fe}=et({queryKey:["library-file-filaments",n,g],queryFn:()=>ge.getLibraryFileFilamentRequirements(n,g??void 0),enabled:p&&!!n&&(g!==null||!F?.is_multi_plate)}),me=!p&&(oe||ve),je=p?fe:te,we=w.useMemo(()=>{if(!(g===null||!F?.plates?.length))return F.plates.find(_t=>_t.index===g)?.name||void 0},[F,g]),{data:Fe}=et({queryKey:["available-filaments",z,I],queryFn:()=>ge.getAvailableFilaments(z,I??void 0),enabled:R==="model"&&!!z}),{data:He}=et({queryKey:["printer-status",K],queryFn:()=>ge.getPrinterStatus(K),enabled:!!K}),{amsMapping:Oe}=aie(je,He,P),_e=Uqe(f,$,je,P,D,A);w.useEffect(()=>{F?.plates&&F.plates.length>=1&&v.size===0&&b(new Set([F.plates[0].index]))},[F,v.size]),w.useEffect(()=>{if(t==="edit-queue-item")return;const _t=$?.filter(rt=>rt.is_active)||[];_t.length===1&&f.length===0&&y([_t[0].id])},[t,$,f.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(f.sort())!==JSON.stringify(he.sort())||g!==V)&&(T({}),A({}),E(new Set)):(T({}),A({}),E(new Set))},[t,f,g,he,V]);const[Ae,Be]=w.useState(z),[Me,Xe]=w.useState(g);w.useEffect(()=>{(z!==Ae||g!==Me)&&(Be(z),Xe(g),(t!=="edit-queue-item"||Ae!==null)&&(Y({}),de({})))},[z,g,Ae,Me,t]),w.useEffect(()=>{if(!H?.per_printer_mapping_expanded||f.length<=1)return;const _t=f.filter(rt=>{if(j.has(rt))return!1;const Rt=_e.printerResults.find(qt=>qt.printerId===rt);return Rt&&Rt.status&&!Rt.isLoading});_t.length>0&&(E(rt=>{const Rt=new Set(rt);return _t.forEach(qt=>Rt.add(qt)),Rt}),_t.forEach(rt=>{_e.autoConfigurePrinter(rt)}))},[H?.per_printer_mapping_expanded,f,j,_e]),w.useEffect(()=>{const _t=rt=>{rt.key==="Escape"&&!ne&&o()};return window.addEventListener("keydown",_t),()=>window.removeEventListener("keydown",_t)},[o,ne]);const ye=F?.is_multi_plate??!1,We=F?.plates??[],Pe=w.useMemo(()=>{const _t=new Map;return W&&W.forEach(rt=>{const Rt=rt.ams_id===255,qt=Ex(rt.ams_id,rt.tray_id,Rt),Kt=_t.get(rt.printer_id)??new Map;Kt.set(qt,rt),_t.set(rt.printer_id,Kt)}),_t},[W]),Ke=w.useMemo(()=>{if(!q||q.length===0)return"";const _t=q.map(rt=>c("printModal.insufficientFilamentLine",{printer:rt.printerName,slot:rt.slotLabel,required:Math.round(rt.requiredGrams),remaining:Math.round(rt.remainingGrams)}));return[c("printModal.insufficientFilamentMessage"),..._t].join(` -`)},[q,c]),Ve=gt({mutationFn:_t=>ge.addToQueue(_t)}),ke=gt({mutationFn:_t=>ge.updateQueueItem(a.id,_t),onSuccess:()=>{u.invalidateQueries({queryKey:["queue"]}),d("Queue item updated"),l?.(),o()},onError:_t=>{d(_t.message||"Failed to update queue item","error")}}),Ce=async(_t,rt)=>{if(_t?.preventDefault(),!rt?.skipFilamentCheck&&!H?.disable_filament_warnings&&(t==="reprint"||t==="add-to-queue")&&R==="printer"){const Qe=[],De=je?.filaments??[];if(De.length>0&&Pe.size>0){const ot=(st,Ze)=>!Number.isFinite(st)||st<=0||!Number.isFinite(Ze)||Ze<0?null:Math.max(0,st-Ze);for(const st of f){const Ze=f.length>1?_e.getFinalMapping(st):Oe;if(!Ze)continue;const Ee=f.length>1?_e.printerResults.find(Ge=>Ge.printerId===st)?.status:He,ct=Xw(Ee),le=new Map(ct.map(Ge=>[Ge.globalTrayId,Ge.label])),Le=Pe.get(st),Ye=$?.find(Ge=>Ge.id===st)?.name??`Printer ${st}`;Le&&De.forEach(Ge=>{if(!Ge.slot_id||Ge.slot_id<=0)return;const Ie=Ze[Ge.slot_id-1];if(!Number.isFinite(Ie)||Ie<0)return;const dt=Le.get(Ie)?.spool;if(!dt)return;const Je=ot(dt.label_weight,dt.weight_used);Je!==null&&(Je>=Ge.used_grams||Qe.push({printerName:Ye,slotLabel:le.get(Ie)??`Slot ${Ge.slot_id}`,requiredGrams:Ge.used_grams,remainingGrams:Je}))})}}if(Qe.length>0){X(Qe);return}}if(R==="printer"&&f.length===0){d("Please select at least one printer","error");return}if(R==="model"&&!z){d("Please select a target printer model","error");return}se(!0);const Rt=v.size>1?We.filter(Qe=>v.has(Qe.index)):[null],qt=R==="model"?Rt.length:f.length*Rt.length;Te({current:0,total:qt});const Kt={success:0,failed:0,errors:[]},Qt=Qe=>{if(f.length>1){const De=D[Qe];if(De&&!De.useDefault)return _e.getFinalMapping(Qe)}return Oe},hn=(()=>{const Qe=[];if(je?.filaments)for(const De of je.filaments){const ot=ae[De.slot_id],st=ue[De.slot_id]??!1,Ze=ot?.type??De.type,Ee=ot?.color??De.color;(ot||st)&&Qe.push({slot_id:De.slot_id,type:Ze,color:Ee,color_name:Ld(Ee),force_color_match:st})}else for(const[De,{type:ot,color:st}]of Object.entries(ae)){const Ze=parseInt(De,10),Ee=ue[Ze]??!1;Qe.push({slot_id:Ze,type:ot,color:st,color_name:Ld(st),force_color_match:Ee})}return Qe.length>0?Qe:void 0})(),Hn=(Qe,De)=>({printer_id:R==="printer"?Qe:null,target_model:R==="model"?z:null,target_location:R==="model"?I:null,filament_overrides:R==="model"?hn:void 0,archive_id:p?void 0:e,library_file_id:p?n:void 0,require_previous_success:C.requirePreviousSuccess,auto_off_after:C.autoOffAfter,manual_start:C.scheduleType==="manual",ams_mapping:Qe?Qt(Qe):void 0,plate_id:De!==void 0?De:g,scheduled_time:C.scheduleType==="scheduled"&&C.scheduledTime?new Date(C.scheduledTime).toISOString():void 0,..._});if(R==="model"){if(t==="reprint"){d("Model-based assignment only works with queue mode","error"),se(!1);return}let Qe=0;for(const De of Rt){Qe++,Te({current:Qe,total:qt});const ot=De?De.index:g;try{if(t==="edit-queue-item"&&!De){const st={printer_id:null,target_model:z,target_location:I,filament_overrides:hn||null,require_previous_success:C.requirePreviousSuccess,auto_off_after:C.autoOffAfter,manual_start:C.scheduleType==="manual",ams_mapping:void 0,plate_id:ot,scheduled_time:C.scheduleType==="scheduled"&&C.scheduledTime?new Date(C.scheduledTime).toISOString():null,..._};await ke.mutateAsync(st)}else await Ve.mutateAsync(Hn(null,ot));Kt.success++}catch(st){Kt.failed++;const Ze=De?De.name||`Plate ${De.index}`:"";Kt.errors.push(Ze?`${Ze}: ${st.message}`:st.message)}}}else{let Qe=0;for(const De of Rt){const ot=De?De.index:g;for(let st=0;stYe.id===Ze)?.name||`Printer ${Ze}`,le=De?De.name||`Plate ${De.index}`:"",Le=le?`${ct} (${le})`:ct;Kt.errors.push(`${Le}: ${Ee.message}`)}}}}se(!1),Kt.failed===0?(t!=="reprint"&&(t==="edit-queue-item"?d("Queue item updated"):Kt.success===1?d(R==="model"?`Queued for any ${z}`:c("queue.printQueued")):d(c("queue.itemsQueued",{count:Kt.success}))),u.invalidateQueries({queryKey:["queue"]}),l?.(),o()):Kt.success===0?d(`Failed: ${Kt.errors[0]}`,"error"):(d(`${Kt.success} succeeded, ${Kt.failed} failed`,"error"),u.invalidateQueries({queryKey:["queue"]}))},$e=ne||ke.isPending,nt=w.useMemo(()=>!($e||R==="printer"&&f.length===0||R==="model"&&!z||R==="model"&&t==="reprint"||ye&&v.size===0),[f.length,R,z,t,ye,v.size,$e]),vt=(()=>{const _t=f.length;if(t==="reprint")return{title:c(p?"queue.print":"queue.reprint"),icon:_r,submitText:_t>1?c("queue.printToPrinters",{count:_t}):c("queue.print"),submitIcon:_r,loadingText:pe.total>1?c("queue.sendingProgress",{current:pe.current,total:pe.total}):c("queue.sending")};if(t==="add-to-queue"){let rt=c("queue.addToQueue");return v.size>1?rt=c("queue.queueSelectedPlates",{count:v.size}):_t>1&&(rt=c("queue.queueToPrinters",{count:_t})),{title:c("queue.schedulePrint"),icon:Xr,submitText:rt,submitIcon:Xr,loadingText:pe.total>1?c("queue.addingProgress",{current:pe.current,total:pe.total}):c("queue.adding")}}return{title:c("queue.editQueueItem"),icon:Yi,submitText:c("common.save"),submitIcon:Yi,loadingText:pe.total>1?c("queue.savingProgress",{current:pe.current,total:pe.total}):c("common.saving")}})(),mt=vt.icon,qe=vt.submitIcon,Nt=K&&v.size<=1&&(p||(ye?g!==null:!0));return i.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:ne?void 0:o,children:[i.jsx(Pt,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:_t=>_t.stopPropagation(),children:i.jsxs(Et,{className:t==="reprint"?"":"p-0",children:[i.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(mt,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:vt.title})]}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:o,disabled:ne,children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:Ce,className:t==="reprint"?"":"p-4 space-y-4",children:[i.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?i.jsxs(i.Fragment,{children:["Send ",i.jsx("span",{className:"text-white",children:r})," to"," ",s?.length===1&&$?i.jsx("span",{className:"text-white",children:$.find(_t=>_t.id===s[0])?.name??"printer(s)"}):"printer(s)"]}):i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),i.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),i.jsx(qqe,{plates:We,isMultiPlate:ye,selectedPlates:v,onToggle:_t=>{b(rt=>{const Rt=new Set(rt);return t==="add-to-queue"?Rt.has(_t)?Rt.delete(_t):Rt.add(_t):(Rt.clear(),Rt.add(_t)),Rt})},onSelectAll:t==="add-to-queue"?()=>b(new Set(We.map(_t=>_t.index))):void 0,onDeselectAll:t==="add-to-queue"?()=>b(new Set):void 0,multiSelect:t==="add-to-queue"}),!s?.length&&i.jsx(Wqe,{printers:$||[],selectedPrinterIds:f,onMultiSelect:y,isLoading:ee,allowMultiple:!0,showInactive:t==="edit-queue-item",disableBusy:t==="reprint",printerMappingResults:_e.printerResults,filamentReqs:je,onAutoConfigurePrinter:_e.autoConfigurePrinter,onUpdatePrinterConfig:_e.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":R,onAssignmentModeChange:t!=="reprint"?G:void 0,targetModel:z,onTargetModelChange:t!=="reprint"?Z:void 0,targetLocation:I,onTargetLocationChange:t!=="reprint"?J:void 0,slicedForModel:be}),R==="model"&&z&&je&&Fe&&Fe.length>0&&i.jsx($qe,{filamentReqs:je,availableFilaments:Fe,overrides:ae,onChange:Y,forceColorMatch:ue,onForceColorMatchChange:(_t,rt)=>de(Rt=>({...Rt,[_t]:rt}))}),be&&R==="printer"&&f.length===1&&(()=>{const _t=$?.find(rt=>rt.id===f[0]);return _t&&_t.model&&be!==_t.model?i.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[i.jsx(jn,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),i.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",be,", but printing on ",_t.model]})]}):null})(),me&&i.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:[i.jsx(Li,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),i.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),Nt&&!me&&f.length===1&&i.jsx(Hqe,{printerId:K,filamentReqs:je,manualMappings:P,onManualMappingChange:T,defaultExpanded:!!s?.length||(H?.per_printer_mapping_expanded??!1),currencySymbol:re,defaultCostPerKg:O}),(t==="reprint"||U>0||R==="model"&&z)&&i.jsx(Yqe,{options:_,onChange:N,defaultExpanded:!!s?.length}),t!=="reprint"&&i.jsx(Xqe,{options:C,onChange:k,dateFormat:H?.date_format||"system",timeFormat:H?.time_format||"system",canControlPrinter:m("printers:control")}),ke.isError&&i.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:ke.error?.message||"Failed to complete operation"}),i.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:o,className:"flex-1",disabled:ne,children:"Cancel"}),i.jsx(ze,{type:"submit",disabled:!nt,className:"flex-1",children:$e?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),vt.loadingText]}):i.jsxs(i.Fragment,{children:[i.jsx(qe,{className:"w-4 h-4"}),vt.submitText]})})]})]})]})}),q&&q.length>0&&i.jsx(Nn,{title:c("printModal.insufficientFilamentTitle"),message:Ke,confirmText:c("printModal.printAnyway"),cancelText:c("common.cancel"),variant:"warning",onConfirm:()=>{X(null),Ce(void 0,{skipFilamentCheck:!0})},onCancel:()=>X(null)})]})}function SW({value:t}){const{t:e}=Dt(),[n,r]=w.useState(!1),a=async()=>{try{await navigator.clipboard.writeText(t),r(!0),setTimeout(()=>r(!1),2e3)}catch{}};return i.jsx("button",{onClick:a,className:"ml-2 p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:e(n?"printers.copied":"printers.copyToClipboard"),children:n?i.jsx(Zr,{className:"w-3.5 h-3.5 text-bambu-green"}):i.jsx(ko,{className:"w-3.5 h-3.5"})})}function Zqe({printer:t,status:e,totalPrintHours:n,onClose:r}){const{t:a}=Dt();w.useEffect(()=>{const o=l=>{l.key==="Escape"&&r()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[r]);const s=[];if(s.push({label:a("printers.model"),value:t.model??"—"}),s.push({label:a("common.status"),value:i.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${e?.connected?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[i.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${e?.connected?"bg-bambu-green":"bg-red-400"}`}),e?.connected?a("printers.status.available"):a("printers.status.offline")]})}),e?.state){const o={IDLE:"printers.status.idle",RUNNING:"printers.status.printing",PAUSE:"printers.status.paused",FINISH:"printers.status.finished",FAILED:"printers.status.error"};s.push({label:a("printers.state"),value:a(o[e.state]??"printers.status.unknown")})}if(s.push({label:a("printers.ipAddress"),value:i.jsxs("span",{className:"flex items-center",children:[i.jsx("span",{className:"font-mono",children:t.ip_address}),i.jsx(SW,{value:t.ip_address})]})}),s.push({label:a("printers.serialNumber"),value:i.jsxs("span",{className:"flex items-center",children:[i.jsx("span",{className:"font-mono truncate",children:t.serial_number}),i.jsx(SW,{value:t.serial_number})]})}),e?.wired_network)s.push({label:a("printers.networkLabel","Network"),value:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(VL,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-bambu-green",children:a("printers.connection.ethernet","Ethernet")})]})});else if(e?.wifi_signal!=null){const o=zZ(e.wifi_signal);s.push({label:a("printers.wifiSignalLabel"),value:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(nQ,{className:`w-4 h-4 ${o.color}`}),i.jsx("span",{className:o.color,children:a(o.labelKey)}),i.jsxs("span",{className:"text-bambu-gray text-xs",children:["(",e.wifi_signal," dBm)"]})]})})}return s.push({label:a("printers.firmware"),value:e?.firmware_version??"—"}),e?.developer_mode!=null&&s.push({label:a("printers.developerMode"),value:i.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${e.developer_mode?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:e.developer_mode?a("printers.enabled"):a("printers.disabled")})}),s.push({label:a("printers.nozzleCount"),value:t.nozzle_count}),e?.sdcard!=null&&s.push({label:a("printers.sdCard"),value:i.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${e.sdcard?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:e.sdcard?a("printers.inserted"):a("printers.notInserted")})}),s.push({label:a("printers.autoArchive"),value:i.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${t.auto_archive?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:t.auto_archive?a("printers.enabled"):a("printers.disabled")})}),n!=null&&n>0&&s.push({label:a("printers.totalPrintHours"),value:`${Math.round(n)}h`}),t.location&&s.push({label:a("printers.sort.location"),value:t.location}),s.push({label:a("printers.addedOn"),value:jf(t.created_at)}),i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",role:"dialog","aria-modal":"true",onClick:r,children:i.jsx(Pt,{className:"w-full max-w-md",onClick:o=>o.stopPropagation(),children:i.jsxs(Et,{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:t.name}),i.jsx("button",{onClick:r,className:"p-1 hover:bg-bambu-dark rounded flex-shrink-0",children:i.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsx("div",{className:"flex justify-center mb-4",children:i.jsx("img",{src:IZ(t.model),alt:t.model??t.name,className:"h-24 object-contain"})}),i.jsx("div",{className:"space-y-0",children:s.map((o,l)=>i.jsxs("div",{className:"flex items-center justify-between gap-4 py-2.5 border-b border-bambu-dark-tertiary last:border-0",children:[i.jsx("span",{className:"text-sm text-bambu-gray whitespace-nowrap",children:o.label}),i.jsx("span",{className:"text-sm text-white text-right",children:o.value})]},l))})]})})})}function Jqe(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 eD({trayColor:t,trayType:e,isEmpty:n,slotNumber:r}){return i.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2 flex items-center justify-center",style:{backgroundColor:t?`#${t}`:e?"#333":"transparent",borderColor:n?"#666":"rgba(255,255,255,0.1)",borderStyle:n?"dashed":"solid"},children:i.jsx("span",{className:"text-[6px] font-bold leading-none select-none",style:{color:t&&Jqe(t)?"#000":"#fff"},children:r})})}const _W={"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"},eVe={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 tD(t){if(!t)return null;if(_W[t])return _W[t];const e=t.split("-");if(e.length<2)return null;const n=e[1];return eVe[n]||null}function nD(t){return(t??.02).toFixed(3)}function NW({side:t}){const{mode:e}=ng(),n=e==="dark"?"#1a4d2e":"#e7f5e9";return i.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 oie(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 lie(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function cie({slot:t,index:e,activeStatus:n,filamentName:r,children:a}){const{t:s}=Dt(),[o,l]=w.useState(!1),[c,u]=w.useState("top"),d=w.useRef(null),m=w.useRef(null),p=w.useRef(null),f=!t.nozzle_diameter&&!t.nozzle_type,y=t.stat===1;w.useEffect(()=>{if(o&&d.current&&m.current){const C=d.current.getBoundingClientRect(),k=m.current.offsetHeight,T=C.top-56,D=window.innerHeight-C.bottom;TT?u("bottom"):u("top")}},[o]);const v=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},b=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const g=RI(t.filament_color),_=oie(t.nozzle_type,s),N=lie(t.nozzle_type,s);return i.jsxs("div",{ref:d,className:"relative",onMouseEnter:v,onMouseLeave:b,children:[a,o&&i.jsxs("div",{ref:m,className:` +${o("inventory.assignProfileMismatchMessage",{spoolProfile:g.spoolProfile||o("common.unknown"),trayProfile:g.trayProfile||o("common.unknown"),location:s.location})}`:g.type==="profile"&&(Y=o("inventory.assignProfileMismatchMessage",{spoolProfile:g.spoolProfile||o("common.unknown"),trayProfile:g.trayProfile||o("common.unknown"),location:s.location})),i.jsx(Nn,{title:o("inventory.assignMismatchTitle"),message:Y,confirmText:o("inventory.assignMismatchConfirm"),variant:"warning",isLoading:T.isPending,onConfirm:ae,onCancel:()=>{T.isPending||(b(!1),y(null),_(null))}})})()]})}function mW(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 a=String.fromCharCode(65+n);return r?`HT-${a}`:`AMS-${a}`}function j1(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 e0=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function hW(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase(),r=n.match(/\bSUPPORT\s+FOR\s+/);if(r){const s=n.slice(r.index+r[0].length);for(const o of e0)if(new RegExp(`\\b${o}\\b`).test(s)){const c=e.slice(0,r.index).trim();return{material:o,brand:c,variant:"Support"}}}for(const s of e0){const o=new RegExp(`\\b${s}\\b`,"i");if(o.test(n)){const l=e.split(o),c=l[0]?.trim()||"",u=l[1]?.trim()||"";return{material:s,brand:c,variant:u}}}const a=e.split(/\s+/);return a.length>=2?{material:a[1],brand:a[0],variant:a.slice(2).join(" ")}:{material:e,brand:"",variant:""}}function Eqe(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const jqe={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"},pW=[{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"}],fW=[{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 gW(t){const e=t.toLowerCase().trim();return jqe[e]||null}function Dqe(t){const e=t.indexOf("@");if(e<0)return null;const r=t.slice(e+1).trim().match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);return r?r[1].trim():null}function tie({isOpen:t,onClose:e,printerId:n,slotInfo:r,nozzleDiameter:a="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=Dt(),[u,d]=w.useState(""),[m,p]=w.useState(null),[f,y]=w.useState(""),[v,b]=w.useState(""),[g,_]=w.useState(""),[N,C]=w.useState(!1),[k,P]=w.useState(!1),T=w.useRef(""),{data:D,isLoading:A,isError:R}=et({queryKey:["cloudSettings"],queryFn:()=>ge.getCloudSettings(),enabled:t,retry:!1}),{data:G,isLoading:z}=et({queryKey:["localPresets"],queryFn:()=>ge.getLocalPresets(),enabled:t}),{data:Z,isLoading:I}=et({queryKey:["builtinFilaments"],queryFn:()=>ge.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:J,isLoading:ae}=et({queryKey:["kprofiles",n,a],queryFn:()=>ge.getKProfiles(n,a),enabled:t&&!!n}),{data:Y}=et({queryKey:["colorCatalog"],queryFn:()=>ge.getColorCatalog(),enabled:t,staleTime:1/0}),ue=gt({mutationFn:async()=>{if(!u)throw new Error("No filament preset selected");const E=u.startsWith("local_"),U=u.startsWith("builtin_"),K=E?parseInt(u.replace("local_",""),10):null,H=U?u.replace("builtin_",""):null,re=E?G?.filament.find(Fe=>Fe.id===K):null,O=U?Z?.find(Fe=>Fe.filament_id===H):null,$=!E&&!U?D?.filament.find(Fe=>Fe.setting_id===u):null;if(!E&&!U&&!$)throw new Error("Selected preset not found");if(E&&!re)throw new Error("Selected local preset not found");if(U&&!O)throw new Error("Selected builtin preset not found");const ee=E?re.name:U?O.name:$.name,W=hW(ee),ie=m?.slot_id??-1,ce=f||r.trayColor?.slice(0,6)||"FFFFFF",be=ee.replace(/@.+$/,"").trim();let xe,oe;const L=W.material.toUpperCase();if(E){const Fe=(e0.includes(L)?L:re?.filament_type||W.material||"").toUpperCase(),He={PLA:"GFL99","PLA-CF":"GFL98","PLA SILK":"GFL96","PLA HIGH SPEED":"GFL95",PETG:"GFG99","PETG HF":"GFG96","PETG-CF":"GFG98",PCTG:"GFG97",ABS:"GFB99",ASA:"GFB98",PC:"GFC99",PA:"GFN99","PA-CF":"GFN98",NYLON:"GFN99",TPU:"GFU99",PVA:"GFS99",HIPS:"GFS98",PE:"GFP99",PP:"GFP97"};xe=He[Fe]||He[Fe.replace(/[-\s]?CF$/,"")]||He[Fe.replace(/\+$/,"")]||He[Fe.split(/[-\s]/)[0]]||"",oe=""}else if(U)xe=H,oe="";else if(xe=j1(u),oe=u,!u.startsWith("GFS"))try{const Fe=await ge.getCloudSettingDetail(u);Fe.filament_id?xe=Fe.filament_id:Fe.base_id&&(xe=j1(Fe.base_id),console.log(`Derived tray_info_idx from base_id: ${Fe.base_id} -> ${xe}`))}catch(Fe){console.warn("Failed to fetch preset detail for filament_id:",Fe)}let F=E&&re?.nozzle_temp_min?re.nozzle_temp_min:190,te=E&&re?.nozzle_temp_max?re.nozzle_temp_max:230;if(!E||U||!re?.nozzle_temp_min&&!re?.nozzle_temp_max){const Fe=(E?e0.includes(L)?L:re?.filament_type||W.material||"":W.material).toUpperCase();Fe.includes("PLA")?(F=190,te=230):Fe.includes("PETG")?(F=220,te=260):Fe.includes("ABS")||Fe.includes("ASA")?(F=240,te=280):Fe.includes("TPU")?(F=200,te=240):Fe==="PCTG"?(F=220,te=260):Fe.includes("PC")?(F=260,te=300):(Fe.includes("PA")||Fe.includes("NYLON"))&&(F=250,te=290)}const ve=m?.k_value?parseFloat(m.k_value):0,fe=E?e0.includes(L)?L:re?.filament_type||W.material||"PLA":W.material||"PLA",me=await ge.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:xe,tray_type:fe,tray_sub_brands:be,tray_color:ce+"FF",nozzle_temp_min:F,nozzle_temp_max:te,cali_idx:ie,nozzle_diameter:a,setting_id:oe,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:ve}),je=E?`local_${K}`:U?`builtin_${H}`:u,we=E?"local":U?"builtin":"cloud";try{await ge.saveSlotPreset(n,r.amsId,r.trayId,je,be,we)}catch(Fe){console.warn("Failed to save slot preset mapping:",Fe)}return me},onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),de=gt({mutationFn:async()=>ge.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),he=w.useMemo(()=>{const E=g.toLowerCase(),U=[],K=new Set,H=r.savedPresetId,re=r.trayInfoIdx;if(D?.filament)for(const O of D.filament){K.add(O.setting_id);const ee=H===O.setting_id||re&&(O.setting_id===re||j1(O.setting_id)===re);if(!(E&&!O.name.toLowerCase().includes(E))){if(!ee&&s){const W=Dqe(O.name);if(W&&W.toUpperCase()!==s.toUpperCase())continue}U.push({id:O.setting_id,name:O.name,source:"cloud",isUser:Eqe(O.setting_id)})}}if(G?.filament)for(const O of G.filament){const $=`local_${O.id}`;E&&!O.name.toLowerCase().includes(E)||U.push({id:$,name:O.name,source:"local",isUser:!1})}if(Z)for(const O of Z){if(K.has(O.filament_id))continue;const $=O.filament_id.startsWith("GF")?"GFS"+O.filament_id.slice(2):O.filament_id;K.has($)||(!E||O.name.toLowerCase().includes(E))&&U.push({id:`builtin_${O.filament_id}`,name:O.name,source:"builtin",isUser:!1})}return U.sort((O,$)=>{const ee={cloud:0,local:1,builtin:2};return O.source!==$.source?ee[O.source]-ee[$.source]:O.isUser&&!$.isUser?-1:!O.isUser&&$.isUser?1:O.name.localeCompare($.name)})},[D?.filament,G?.filament,Z,g,s,r.savedPresetId,r.trayInfoIdx]),V=w.useMemo(()=>{if(!u)return null;let E=null;if(u.startsWith("local_")){const H=parseInt(u.replace("local_",""),10);E=G?.filament.find(O=>O.id===H)?.name||null}else if(u.startsWith("builtin_")){const H=u.replace("builtin_","");E=Z?.find(O=>O.filament_id===H)?.name||null}else D?.filament&&(E=D.filament.find(re=>re.setting_id===u)?.name||null);if(!E)return null;let U=E.replace(/@.+$/,"").trim();U.startsWith("# ")&&(U=U.slice(2).trim());const K=hW(U);return{fullName:U,material:K.material,brand:K.brand}},[u,D?.filament,G?.filament,Z]),ne=V?.fullName||"",se=w.useMemo(()=>{if(!Y||!V)return[];const{fullName:E,brand:U}=V,K=E.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return Y.filter(H=>{const re=(H.material||"").toUpperCase(),O=H.manufacturer.toUpperCase();if(!(re===K.toUpperCase()||re.includes(K.toUpperCase())||K.toUpperCase().includes(re)))return!1;if(U){const ee=U.toUpperCase();if(!O.includes(ee)&&!ee.includes(O))return!1}return!0})},[Y,V]),pe=w.useMemo(()=>{if(!J?.profiles||!V)return[];const{fullName:E,material:U,brand:K}=V,H=E.toUpperCase(),re=U.toUpperCase(),O=K.toUpperCase();if(!re||re.length<2)return[];const $=J.profiles.filter(W=>{const ie=W.name.toUpperCase();if(O)return!(!ie.includes(O)||!ie.includes(re));if(ie.includes(H)||ie.includes(re))return!0;const be={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[re]||[];for(const xe of be)if(ie.includes(xe))return!0;return!1}),ee=new Map;for(const W of $){const ie=`${W.name}|${W.k_value}`,ce=ee.get(ie);ce?r.extruderId!==void 0&&W.extruder_id===r.extruderId&&ce.extruder_id!==r.extruderId&&ee.set(ie,W):ee.set(ie,W)}return Array.from(ee.values())},[J?.profiles,V,r.extruderId]);w.useEffect(()=>{if(t){if(r.savedPresetId)d(r.savedPresetId);else if(r.trayInfoIdx&&D?.filament){let E=D.filament.find(U=>U.setting_id===r.trayInfoIdx);E||(E=D.filament.find(U=>j1(U.setting_id)===r.trayInfoIdx)),E&&d(E.setting_id)}else if(r.trayInfoIdx&&Z?.length){const E=r.trayInfoIdx,U=Z.find(K=>K.filament_id===E);U&&d(`builtin_${U.filament_id}`)}if(r.trayColor){const E=r.trayColor.slice(0,6);E&&y(E)}}else d(""),p(null),y(""),b(""),_(""),C(!1),T.current=""},[t,r.savedPresetId,r.trayInfoIdx,r.trayColor,D?.filament,Z]),w.useEffect(()=>{if(pe.length>0){if(r.caliIdx!=null&&r.caliIdx>0){const E=pe.find(U=>U.slot_id===r.caliIdx);if(E){p(E);return}}p(pe[0])}else p(null)},[u,pe,r.caliIdx]);const Te=w.useCallback(E=>{E.key==="Escape"&&e()},[e]);w.useEffect(()=>{if(t)return document.addEventListener("keydown",Te),()=>document.removeEventListener("keydown",Te)},[t,Te]);const q=A&&!R||z||I||ae;if(w.useEffect(()=>{if(!q&&u&&u!==T.current){const E=requestAnimationFrame(()=>{const K=document.querySelector('[class*="fixed inset-0 z-50"]')?.querySelector(`[data-preset-id="${CSS.escape(u)}"]`);K&&(T.current=u,K.scrollIntoView({block:"nearest"}))});return()=>cancelAnimationFrame(E)}},[u,q]),!t)return null;const X=u&&!ue.isPending,j=f||r.trayColor?.slice(0,6)||"FFFFFF";return i.jsxs("div",{className:`fixed inset-0 z-50 flex ${l?"":"items-center justify-center"}`,children:[!l&&i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:l?"relative w-full h-full bg-bambu-dark-secondary flex flex-col":"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Bd,{className:"w-5 h-5 text-bambu-blue"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.title")}),l&&i.jsxs("div",{className:"flex items-center gap-2 ml-4 text-sm text-bambu-gray",children:[i.jsx("span",{className:"text-white/30",children:"|"}),r.trayColor&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),i.jsx("span",{className:"text-white/70",children:c("configureAmsSlot.slotLabel",{ams:mW(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&i.jsxs("span",{children:["(",r.traySubBrands,")"]})]})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:`p-4 overflow-y-auto ${l?"flex-1 min-h-0":"space-y-4 max-h-[60vh]"}`,children:[N&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl",children:i.jsxs("div",{className:"text-center space-y-3",children:[i.jsx(vc,{className:"w-16 h-16 text-bambu-green mx-auto"}),i.jsx("p",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.slotConfigured")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:c("configureAmsSlot.settingsSentToPrinter")})]})}),!l&&i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:c("configureAmsSlot.configuringSlot")}),i.jsxs("div",{className:"flex items-center gap-2",children:[r.trayColor&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),i.jsx("span",{className:"text-white font-medium",children:c("configureAmsSlot.slotLabel",{ams:mW(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&i.jsxs("span",{className:"text-bambu-gray",children:["(",r.traySubBrands,")"]})]})]}),q?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):l?i.jsxs("div",{className:"flex gap-4 h-full",children:[i.jsxs("div",{className:"w-1/2 flex flex-col min-h-0",children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:g,onChange:E=>_(E.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 shrink-0"}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-1",children:he.length===0?i.jsx("p",{className:"text-center py-4 text-bambu-gray",children:D?.filament?.length===0&&!G?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):he.map(E=>i.jsx("button",{"data-preset-id":E.id,onClick:()=>d(E.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${u===E.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-white text-sm truncate",children:E.name}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[E.source==="local"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),E.source==="builtin"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),E.isUser&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},E.id))})]}),i.jsxs("div",{className:"w-1/2 flex flex-col gap-4 min-h-0 overflow-y-auto",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),ne&&i.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ne})})]}),pe.length>0?i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:m?.name||"",onChange:E=>{const U=pe.find(K=>K.name===E.target.value);p(U||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:[i.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),pe.map(E=>i.jsxs("option",{value:E.name,children:[E.name," (K=",E.k_value,")"]},`${E.name}-${E.extruder_id}`))]}),i.jsx(In,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):u?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):i.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:c("configureAmsSlot.selectFilamentFirst")}),m&&i.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),se.length>0&&i.jsxs("div",{className:"mb-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:V?.fullName})}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:se.map(E=>i.jsxs("button",{onClick:()=>{const U=E.hex_color.replace("#","").toUpperCase();y(U),b(E.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===E.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:E.color_name,children:[i.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:E.hex_color}}),i.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:E.color_name})]},E.id))})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[pW.map(E=>i.jsx("button",{onClick:()=>{y(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.hex)),i.jsx("button",{onClick:()=>P(!k),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:c(k?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:k?"−":"+"})]}),k&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:fW.map(E=>i.jsx("button",{onClick:()=>{y(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.hex))}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${j}`}}),i.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:v,onChange:E=>{const U=E.target.value;b(U);const K=gW(U);if(K)y(K);else{const H=U.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();H.length===6?y(H):H.length===3&&y(H.split("").map(re=>re+re).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"}),f&&i.jsx("button",{onClick:()=>{y(""),b("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:c("configureAmsSlot.clearCustomColor"),children:c("configureAmsSlot.clear")})]}),f&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:g,onChange:E=>_(E.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"}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:he.length===0?i.jsx("p",{className:"text-center py-4 text-bambu-gray",children:D?.filament?.length===0&&!G?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):he.map(E=>i.jsx("button",{"data-preset-id":E.id,onClick:()=>d(E.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${u===E.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-white text-sm truncate",children:E.name}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[E.source==="local"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),E.source==="builtin"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),E.isUser&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},E.id))})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),ne&&i.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ne})})]}),pe.length>0?i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:m?.name||"",onChange:E=>{const U=pe.find(K=>K.name===E.target.value);p(U||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:[i.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),pe.map(E=>i.jsxs("option",{value:E.name,children:[E.name," (K=",E.k_value,")"]},`${E.name}-${E.extruder_id}`))]}),i.jsx(In,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):u?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):i.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:c("configureAmsSlot.selectFilamentFirst")}),m&&i.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),se.length>0&&i.jsxs("div",{className:"mb-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:V?.fullName})}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:se.map(E=>i.jsxs("button",{onClick:()=>{const U=E.hex_color.replace("#","").toUpperCase();y(U),b(E.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===E.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:E.color_name,children:[i.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:E.hex_color}}),i.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:E.color_name})]},E.id))})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[pW.map(E=>i.jsx("button",{onClick:()=>{y(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.hex)),i.jsx("button",{onClick:()=>P(!k),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:c(k?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:k?"−":"+"})]}),k&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:fW.map(E=>i.jsx("button",{onClick:()=>{y(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.hex))}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${j}`}}),i.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:v,onChange:E=>{const U=E.target.value;b(U);const K=gW(U);if(K)y(K);else{const H=U.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();H.length===6?y(H):H.length===3&&y(H.split("").map(re=>re+re).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"}),f&&i.jsx("button",{onClick:()=>{y(""),b("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:c("configureAmsSlot.clearCustomColor"),children:c("configureAmsSlot.clear")})]}),f&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}),i.jsxs("div",{className:"flex justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[i.jsx(ze,{variant:"secondary",onClick:()=>de.mutate(),disabled:de.isPending||ue.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:de.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):i.jsxs(i.Fragment,{children:[i.jsx(To,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),i.jsx(ze,{onClick:()=>ue.mutate(),disabled:!X,children:ue.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):i.jsxs(i.Fragment,{children:[i.jsx(Bd,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(ue.isError||de.isError)&&i.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:ue.error?.message||de.error?.message})]})]})}function nie({folderId:t,onClose:e,onUploadComplete:n,onFileUploaded:r,autoUpload:a,validateFile:s,accept:o}){const{t:l}=Dt(),[c,u]=w.useState([]),[d,m]=w.useState(!1),[p,f]=w.useState(!1),[y,v]=w.useState(!0),[b,g]=w.useState(!1),[_,N]=w.useState(!0),[C,k]=w.useState(null),P=w.useRef(null),T=he=>{he.preventDefault(),m(!0)},D=he=>{he.preventDefault(),m(!1)},A=he=>{he.preventDefault(),m(!1),Z(Array.from(he.dataTransfer.files))},R=he=>{he.target.files&&Z(Array.from(he.target.files))},G=(he,V)=>{u(ne=>ne.map(se=>se.file===he?{...se,...V}:se))},z=async he=>{f(!0);for(const V of he)if(V.status==="pending"){G(V.file,{status:"uploading"});try{if(V.isZip){const ne=await ge.extractZipFile(V.file,t,y,b,_);G(V.file,{status:ne.errors.length>0&&ne.extracted===0?"error":"success",extractedCount:ne.extracted,error:ne.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:ne.errors.length}):void 0})}else{const ne=await ge.uploadLibraryFile(V.file,t,_);G(V.file,{status:"success"});const se=r?.(ne);if(se){k(se),u([]),f(!1);return}}}catch(ne){G(V.file,{status:"error",error:ne instanceof Error?ne.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),n(),e()},Z=he=>{if(k(null),s)for(const ne of he){const se=s(ne);if(se){k(se);return}}const V=he.map(ne=>({file:ne,status:"pending",isZip:ne.name.toLowerCase().endsWith(".zip"),is3mf:ne.name.toLowerCase().endsWith(".3mf")}));u(ne=>[...ne,...V]),a&&he.length>0&&z(V)},I=he=>{u(V=>V.filter((ne,se)=>se!==he))},J=c.some(he=>he.isZip&&he.status==="pending"),ae=c.some(he=>he.file.name.toLowerCase().endsWith(".stl")&&he.status==="pending"),Y=c.some(he=>he.is3mf&&he.status==="pending"),ue=c.filter(he=>he.status==="pending").length,de=c.length>0&&ue===0&&!p;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:l("fileManager.uploadFiles")}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("div",{onDragOver:T,onDragLeave:D,onDrop:A,onClick:()=>P.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${d?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[i.jsx(yi,{className:`w-10 h-10 mx-auto mb-3 ${d?"text-bambu-green":"text-bambu-gray"}`}),i.jsx("p",{className:"text-white font-medium",children:l(d?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:l("fileManager.orClickToBrowse")}),i.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:l("fileManager.allFileTypesSupported")})]}),i.jsx("input",{ref:P,type:"file",multiple:!0,accept:o,className:"hidden",onChange:R}),J&&i.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Vs,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-blue-300 font-medium",children:l("fileManager.zipFilesDetected")}),i.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:l("fileManager.zipExtractOptions")}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:y,onChange:he=>v(he.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:l("fileManager.preserveZipStructure")})]}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:b,onChange:he=>g(he.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:l("fileManager.createFolderFromZip")})]})]})]})}),Y&&i.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(_r,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-purple-300 font-medium",children:l("fileManager.threemfDetected")}),i.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:l("fileManager.threemfExtractionInfo")})]})]})}),(ae||J)&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Ud,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-bambu-green font-medium",children:l("fileManager.stlThumbnailGeneration")}),i.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:l(J&&!ae?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:_,onChange:he=>N(he.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:l("fileManager.generateThumbnailsForStl")})]})]})]})}),c.length>0&&i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:c.map((he,V)=>i.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[he.isZip?i.jsx(Vs,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):i.jsx(iT,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:he.file.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[(he.file.size/1024/1024).toFixed(2)," MB",he.isZip&&he.status==="pending"&&i.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",l("fileManager.willBeExtracted")]}),he.extractedCount!==void 0&&i.jsxs("span",{className:"text-green-400 ml-2",children:["• ",l("fileManager.filesExtracted",{count:he.extractedCount})]})]})]}),he.status==="pending"&&i.jsx("button",{onClick:()=>I(V),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Ht,{className:"w-4 h-4 text-bambu-gray"})}),he.status==="uploading"&&i.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"}),he.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-500"}),he.status==="error"&&i.jsx("span",{title:he.error,children:i.jsx(Vi,{className:"w-4 h-4 text-red-500"})})]},V))}),C&&i.jsx("div",{className:"p-3 bg-red-500/10 border border-red-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Vi,{className:"w-5 h-5 text-red-400 mt-0.5 flex-shrink-0"}),i.jsx("p",{className:"text-sm text-red-300",children:C})]})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:e,children:l("common.cancel")}),!de&&i.jsx(ze,{onClick:()=>z(c),disabled:ue===0||p,children:p?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(yi,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",ue>0?`(${ue})`:""]})})]})]})})}function bW(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Ri(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}const Rqe=[["PA-CF","PA12-CF","PAHT-CF"]],rie={};for(const t of Rqe){const e=t[0];for(const n of t)rie[n.toUpperCase()]=e.toUpperCase()}function rC(t){if(!t)return"";const e=t.toUpperCase();return rie[e]??e}function J2(t,e){return rC(t)===rC(e)}function bu(t,e,n=40){const r=Ri(t),a=Ri(e);if(!r||!a||r.length<6||a.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(a.substring(0,2),16),u=parseInt(a.substring(2,4),16),d=parseInt(a.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-u)<=n&&Math.abs(l-d)<=n}function F4(t,e,n,r){if(r)return"Ext";const a=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${a}`:`${a}${e+1}`}function Ex(t,e,n){return n?254+e:t>=128?t:t*4+e}function ix(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function yN(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 xW(t,e){return(Number.isFinite(t)?Math.max(0,Math.trunc(t)):0).toString(16).toUpperCase().padStart(e,"0").slice(-e)}function Fqe(t){const e=(t||"").trim().toUpperCase();let n=2166136261;for(let r=0;r>>0).toString(16).toUpperCase().padStart(8,"0")}function $p(t,e,n){return`${Fqe(t)}${xW(e,4)}${xW(n,4)}`}function yW(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(Qn(t)?.getTime()??0)>e}function Lqe(t,e,n){const r=iie(e,t.nozzle_id),a=r.find(l=>!n.has(l.globalTrayId)&&J2(l.type,t.type)&&Ri(l.color)===Ri(t.color)),s=a?void 0:r.find(l=>!n.has(l.globalTrayId)&&J2(l.type,t.type)&&bu(l.color,t.color)),o=a||s?void 0:r.find(l=>!n.has(l.globalTrayId)&&J2(l.type,t.type));return a??s??o}function iie(t,e){return t.filter(n=>e==null||n.extruderId===e)}function Xw(t){const e=[],n=t?.ams_extruder_map,r=n&&Object.keys(n).length>0;t?.ams?.forEach(a=>{const s=a.tray.length===1;a.tray.forEach(o=>{if(o.tray_type){const l=bW(o.tray_color);e.push({type:o.tray_type,color:l,colorName:Ld(l),amsId:a.id,trayId:o.id,isHt:s,isExternal:!1,label:F4(a.id,o.id,s,!1),globalTrayId:Ex(a.id,o.id,!1),trayInfoIdx:o.tray_info_idx||"",traySubBrands:o.tray_sub_brands||"",extruderId:n?.[String(a.id)]})}})});for(const a of t?.vt_tray??[])if(a.tray_type){const s=bW(a.tray_color),o=a.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:a.tray_type,color:s,colorName:Ld(s),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:l?o===254?"Ext-L":"Ext-R":"External",globalTrayId:o,trayInfoIdx:a.tray_info_idx||"",traySubBrands:a.tray_sub_brands||"",extruderId:r?255-o:void 0})}return e}function vW(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=Xw(e);if(n.length===0)return;const r=new Set,a=t.filaments.map(l=>{const c=l.tray_info_idx||"";let u=n.filter(v=>!r.has(v.globalTrayId));l.nozzle_id!=null&&(u=u.filter(v=>v.extruderId===l.nozzle_id));let d,m,p,f;if(c){const v=u.filter(b=>b.trayInfoIdx===c);v.length===1?d=v[0]:v.length>1&&(m=v.find(b=>b.type?.toUpperCase()===l.type?.toUpperCase()&&Ri(b.color)===Ri(l.color)),m||(p=v.find(b=>b.type?.toUpperCase()===l.type?.toUpperCase()&&bu(b.color,l.color))),!m&&!p&&(f=v.find(b=>b.type?.toUpperCase()===l.type?.toUpperCase())))}!d&&!m&&!p&&!f&&(m=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Ri(v.color)===Ri(l.color)),m||(p=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&bu(v.color,l.color))),!m&&!p&&(f=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase())));const y=d||m||p||f||void 0;return y&&r.add(y.globalTrayId),{slot_id:l.slot_id,globalTrayId:y?.globalTrayId??-1}}),s=Math.max(...a.map(l=>l.slot_id||0));if(s<=0)return;const o=new Array(s).fill(-1);return a.forEach(l=>{l.slot_id&&l.slot_id>0&&(o[l.slot_id-1]=l.globalTrayId)}),o}function Oqe(t){return w.useMemo(()=>Xw(t),[t])}function aie(t,e,n){const r=Oqe(e),a=w.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 P=n[d],T=r.find(D=>D.globalTrayId===P);if(T){const D=T.type?.toUpperCase()===u.type?.toUpperCase(),A=Ri(T.color)===Ri(u.color)||bu(T.color,u.color);let R;return D&&A?R="match":D?R="type_only":R="mismatch",{...u,loaded:T,hasFilament:!0,typeMatch:D,colorMatch:A,status:R,isManual:!0}}}const m=u.tray_info_idx||"";let p=r.filter(P=>!c.has(P.globalTrayId));u.nozzle_id!=null&&(p=p.filter(P=>P.extruderId===u.nozzle_id));let f,y,v,b;if(m){const P=p.filter(T=>T.trayInfoIdx===m);P.length===1?f=P[0]:P.length>1&&(y=P.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase()&&Ri(T.color)===Ri(u.color)),y||(v=P.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase()&&bu(T.color,u.color))),!y&&!v&&(b=P.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase())))}!f&&!y&&!v&&!b&&(y=p.find(P=>P.type?.toUpperCase()===u.type?.toUpperCase()&&Ri(P.color)===Ri(u.color)),y||(v=p.find(P=>P.type?.toUpperCase()===u.type?.toUpperCase()&&bu(P.color,u.color))),!y&&!v&&(b=p.find(P=>P.type?.toUpperCase()===u.type?.toUpperCase())));const g=f||y||v||b||void 0;g&&c.add(g.globalTrayId);const _=!!g,N=_,C=!!f||!!y||!!v;let k;return f||y||v?k="match":b?k="type_only":k="mismatch",{...u,loaded:g,hasFilament:_,typeMatch:N,colorMatch:C,status:k,isManual:!1}})},[t,r,n]),s=w.useMemo(()=>{if(a.length===0)return;const c=Math.max(...a.map(d=>d.slot_id||0));if(c<=0)return;const u=new Array(c).fill(-1);return a.forEach(d=>{d.slot_id&&d.slot_id>0&&(u[d.slot_id-1]=d.loaded?.globalTrayId??-1)}),u},[a]),o=a.some(c=>c.status==="mismatch"),l=a.some(c=>c.status==="type_only");return{loadedFilaments:r,filamentComparison:a,amsMapping:s,hasTypeMismatch:o,hasColorMismatch:l}}function Iqe(t,e,n){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let r=0,a=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 b=n[d],g=e.find(_=>_.globalTrayId===b);if(g){const _=g.type?.toUpperCase()===u.type?.toUpperCase(),N=Ri(g.color)===Ri(u.color)||bu(g.color,u.color);_&&N?r++:_?a++:s++;continue}}let m=e.filter(b=>!o.has(b.globalTrayId));if(u.nozzle_id!=null){const b=m.filter(g=>g.extruderId===u.nozzle_id);b.length>0&&(m=b)}const p=m.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()&&Ri(b.color)===Ri(u.color)),f=p?void 0:m.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()&&bu(b.color,u.color)),y=p||f?void 0:m.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()),v=p??f??y;v&&o.add(v.globalTrayId),p||f?r++:y?a++:s++}const l=t.length;let c="full";return s>0?c="missing":a>0&&(c="partial"),{exactMatches:r,typeOnlyMatches:a,missingTypes:s,totalSlots:l,status:c}}function zqe(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=Xw(e);if(r.length===0)return;const a=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}let d=r.filter(v=>!a.has(v.globalTrayId));if(c.nozzle_id!=null){const v=d.filter(b=>b.extruderId===c.nozzle_id);v.length>0&&(d=v)}const m=d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Ri(v.color)===Ri(c.color)),p=m?void 0:d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&bu(v.color,c.color)),f=m||p?void 0:d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()),y=m??p??f;y&&a.add(y.globalTrayId),s.push({slot_id:u,globalTrayId:y?.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 wW={useDefault:!0,manualMappings:{},autoConfigured:!1};function Uqe(t,e,n,r,a,s){const o=tg({queries:t.map(y=>({queryKey:["printer-status",y],queryFn:()=>ge.getPrinterStatus(y),enabled:t.length>0,staleTime:5e3}))}),l=w.useMemo(()=>t.map((y,v)=>{const b=o[v],g=b?.data,N=e?.find(R=>R.id===y)?.name||`Printer ${y}`,C=Xw(g),k=a[y]||wW,P=vW(n,g),T=k.useDefault?r:k.manualMappings,D=zqe(n,g,T),A=Iqe(n?.filaments,C,T);return{printerId:y,printerName:N,status:g,isLoading:b?.isLoading??!1,loadedFilaments:C,autoMapping:P,finalMapping:D,matchStatus:A.status,exactMatches:A.exactMatches,typeOnlyMatches:A.typeOnlyMatches,missingTypes:A.missingTypes,totalSlots:A.totalSlots,config:k}}),[t,o,e,n,a,r]),c=o.some(y=>y.isLoading),u=(y,v)=>{s(b=>({...b,[y]:{...b[y]||wW,...v}}))},d=y=>{const v=l.find(_=>_.printerId===y);if(!v||!v.status||!n?.filaments)return;const b=vW(n,v.status);if(!b)return;const g={};b.forEach((_,N)=>{_!==-1&&(g[N+1]=_)}),u(y,{useDefault:!1,manualMappings:g,autoConfigured:!0})},m=()=>{for(const y of t)d(y)},p=y=>l.find(b=>b.printerId===y)?.finalMapping,f=l.every(y=>y.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:a,updatePrinterConfig:u,autoConfigureAll:m,autoConfigurePrinter:d,getFinalMapping:p,allPrintersReady:f}}const sie={USD:"$",EUR:"€",GBP:"£",CHF:"Fr.",JPY:"¥",CNY:"¥",CAD:"$",AUD:"$",INR:"₹",HKD:"HK$",KRW:"₩",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"zł",BRL:"R$",TWD:"NT$",SGD:"S$",NZD:"NZ$",MXN:"MX$",MYR:"RM",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽",HUF:"Ft",ILS:"₪"};function Wo(t){return sie[t.toUpperCase()]||t}const Bqe=Object.entries(sie).map(([t,e])=>({code:t,label:`${t} (${e})`}));function Hqe({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,currencySymbol:a,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=Dt(),c=sn(),[u,d]=w.useState(!1),[m,p]=w.useState(o),{data:f}=et({queryKey:["printer-status",t],queryFn:()=>ge.getPrinterStatus(t),enabled:!!t}),{data:y}=et({queryKey:["spool-assignments",t],queryFn:()=>ge.getAssignments(t),enabled:!!t}),{loadedFilaments:v,filamentComparison:b,hasTypeMismatch:g,hasColorMismatch:_}=aie(e,f,n),N=w.useMemo(()=>{const z=new Map;for(const Z of y||[]){const I=Z.ams_id===255,J=Ex(Z.ams_id,Z.tray_id,I);z.set(J,Z.spool?.cost_per_kg??null)}return z},[y]),C=w.useMemo(()=>{const z=new Map;for(const Z of y||[]){const I=Z.ams_id===255,J=Ex(Z.ams_id,Z.tray_id,I),ae=Z.spool;if(!ae){z.set(J,null);continue}z.set(J,Math.max(0,Math.round((ae.label_weight??0)-(ae.weight_used??0))))}return z},[y]),k=w.useMemo(()=>{let z=0;for(const Z of b){const I=Z.loaded?.globalTrayId;if(I==null)continue;const ae=N.get(I)??null??s;ae>0&&(z+=Z.used_grams/1e3*ae)}return z},[b,N,s]),P=w.useMemo(()=>Array.from(N.values()).some(z=>z!=null&&z>0),[N]),T=e?.filaments&&e.filaments.length>0,D=e?.filaments?.some(z=>z.nozzle_id!=null)??!1;if(!T||!f)return null;const A=g?"#f97316":_?"#facc15":"#00ae42",R=(z,Z)=>{if(z>0)if(Z===""){const I={...n};delete I[z],r(I)}else r({...n,[z]:parseInt(Z,10)})},G=async()=>{d(!0);try{await ge.refreshPrinterStatus(t),await new Promise(z=>setTimeout(z,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{d(!1)}};return i.jsxs("div",{className:"mb-4",children:[i.jsxs("button",{type:"button",onClick:()=>p(!m),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[i.jsx(S0,{className:"w-4 h-4",fill:A,stroke:"none"}),i.jsx("span",{children:l("printModal.filamentMapping")}),g?i.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):_?i.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):i.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),m?i.jsx(Vl,{className:"w-4 h-4 ml-auto"}):i.jsx(In,{className:"w-4 h-4 ml-auto"})]}),m&&i.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),i.jsxs("button",{type:"button",onClick:G,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:u,children:[i.jsx(Sr,{className:`w-3 h-3 ${u?"animate-spin":""}`}),i.jsx("span",{children:"Re-read"})]})]}),b.map((z,Z)=>i.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[i.jsx("span",{title:`Required: ${z.type} - ${Ld(z.color)}`,children:i.jsx(S0,{className:"w-3 h-3",fill:z.color,stroke:z.color})}),i.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[D&&z.nozzle_id!=null&&i.jsx("span",{className:"inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0",title:z.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:z.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),z.type," ",i.jsxs("span",{className:"text-bambu-gray",children:["(",z.used_grams,"g)"]})]}),i.jsx("span",{className:"text-bambu-gray",children:"→"}),i.jsxs("select",{value:z.loaded?.globalTrayId??"",onChange:I=>R(z.slot_id||0,I.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 ${z.status==="match"?"border-bambu-green/50 text-bambu-green":z.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${z.isManual?"ring-1 ring-blue-400/50":""}`,title:z.isManual?"Manually selected":"Auto-matched",children:[i.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),v.filter(I=>z.nozzle_id==null||I.extruderId===z.nozzle_id).map(I=>{const J=C.get(I.globalTrayId),ae=J!=null?l("printModal.slotRemainingShort",{grams:J,defaultValue:` - ${J}g left`}):"";return i.jsxs("option",{value:I.globalTrayId,className:"bg-bambu-dark text-white",children:[I.label,": ",I.traySubBrands||I.type," (",I.colorName,")",ae]},I.globalTrayId)})]}),z.status==="match"?i.jsx(Zr,{className:"w-3 h-3 text-bambu-green"}):z.status==="type_only"?i.jsx("span",{title:"Same type, different color",children:i.jsx(jn,{className:"w-3 h-3 text-yellow-400"})}):i.jsx("span",{title:"Filament type not loaded",children:i.jsx(jn,{className:"w-3 h-3 text-orange-400"})})]},Z)),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",i.jsx("span",{className:"text-white",children:k>0||P?`${a}${k.toFixed(2)}`:"N/A"})]}),g&&i.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function $qe({filamentReqs:t,availableFilaments:e,overrides:n,onChange:r,forceColorMatch:a,onForceColorMatchChange:s}){const{t:o}=Dt(),l=w.useMemo(()=>{const d={};for(const m of e){const p=rC(m.type);d[p]||(d[p]=[]),d[p].push(m)}return d},[e]),c=t?.filaments;if(!c||c.length===0||e.length===0)return null;const u=(d,m)=>{if(m===""){const p={...n};delete p[d],r(p)}else{const[p,f]=m.split("|");r({...n,[d]:{type:p,color:f}})}};return i.jsxs("div",{className:"mb-4",children:[i.jsx("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:i.jsx("span",{children:o("printModal.filamentOverride")})}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("printModal.filamentOverrideHint")}),i.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 space-y-2",children:c.map(d=>{const m=n[d.slot_id],p=!!m,f=l[rC(d.type)]||[],y=d.nozzle_id!=null?f.filter(v=>v.extruder_id==null||v.extruder_id===d.nozzle_id):f;return i.jsxs("div",{className:"space-y-1",children:[i.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 20px"},children:[i.jsx("span",{title:`${o("printModal.originalFilament")}: ${d.type} - ${Ld(d.color)}`,children:i.jsx(S0,{className:"w-3 h-3",fill:d.color,stroke:d.color})}),i.jsxs("span",{className:"text-white truncate",children:[d.type," ",i.jsxs("span",{className:"text-bambu-gray",children:["(",d.used_grams,"g)"]})]}),i.jsx("span",{className:"text-bambu-gray",children:"→"}),i.jsxs("select",{value:p?`${m.type}|${m.color}`:"",onChange:v=>u(d.slot_id,v.target.value),disabled:y.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${p?"border-blue-400/50 text-blue-400":"border-bambu-gray/30 text-bambu-gray"}`,children:[i.jsxs("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:[o("printModal.originalFilament"),": ",d.type," (",Ld(d.color),")"]}),y.map((v,b)=>i.jsxs("option",{value:`${v.type}|${v.color}`,className:"bg-bambu-dark text-white",children:[v.tray_sub_brands||v.type," (",Ld(v.color),")"]},`${v.type}-${v.color}-${v.tray_sub_brands}-${b}`))]}),p?i.jsx("button",{type:"button",onClick:()=>u(d.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:o("printModal.resetToOriginal"),children:i.jsx(To,{className:"w-3 h-3"})}):i.jsx("span",{className:"w-3"})]}),i.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5",children:[i.jsx("input",{type:"checkbox",checked:a?.[d.slot_id]??!1,onChange:v=>s?.(d.slot_id,v.target.checked),className:"accent-bambu-green w-3 h-3"}),i.jsx(Sw,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},d.slot_id)})})]})}function qqe({plates:t,isMultiPlate:e,selectedPlates:n,onToggle:r,onSelectAll:a,onDeselectAll:s,multiSelect:o}){const{t:l}=Dt();if(!e||t.length<=1)return null;const c=n.size===t.length;return i.jsxs("div",{className:"mb-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx(Gi,{className:"w-4 h-4 text-bambu-gray"}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:["Select Plate",o?"s":""," to Print"]}),n.size===0&&i.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[i.jsx(jn,{className:"w-3 h-3"}),"Selection required"]}),o&&a&&s&&i.jsx("button",{type:"button",onClick:c?s:a,className:`ml-auto text-xs px-2 py-0.5 rounded-full border transition-colors ${c?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray"}`,children:c?l("queue.deselectAll"):l("queue.selectAllPlates",{count:t.length})})]}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(u=>{const d=n.has(u.index);return i.jsxs("button",{type:"button",onClick:()=>r(u.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${d?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[o&&(d?i.jsx(Ks,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}):i.jsx(rl,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})),u.has_thumbnail&&u.thumbnail_url!=null?i.jsx("img",{src:u.thumbnail_url,alt:`Plate ${u.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:i.jsx(Gi,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white font-medium truncate",children:u.name||`Plate ${u.index}`}),i.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[u.objects.length>0?u.objects.slice(0,3).join(", ")+(u.objects.length>3?"...":""):`${u.filaments.length} filament${u.filaments.length!==1?"s":""}`,u.print_time_seconds!=null?` • ${Us(u.print_time_seconds)}`:""]})]}),!o&&d&&i.jsx(Zr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},u.index)})})]})}const Vqe=new Set(["IDLE","FINISH","FAILED"]);function Gqe({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=sn(),[a,s]=w.useState(!1),o=(u,d)=>{if(u<=0)return;const m={...t.config.manualMappings};d===""?delete m[u]:m[u]=parseInt(d,10),n({useDefault:!1,manualMappings:m,autoConfigured:!1})},l=async()=>{s(!0);try{await ge.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,m=t.config.manualMappings[d];let p,f=!1;if(m!==void 0)p=t.loadedFilaments.find(v=>v.globalTrayId===m),f=!0;else{const v=new Set(Object.values(t.config.manualMappings));p=Lqe(u,t.loadedFilaments,v)}let y="mismatch";if(p){const v=p.type?.toUpperCase()===u.type?.toUpperCase(),b=Ri(p.color)===Ri(u.color)||bu(p.color,u.color);v&&b?y="match":v&&(y="type_only")}return{req:u,loaded:p,status:y,isManual:f}});return i.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),i.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:a,children:[i.jsx(Sr,{className:`w-3 h-3 ${a?"animate-spin":""}`}),i.jsx("span",{children:"Re-read"})]})]}),c.map(({req:u,loaded:d,status:m,isManual:p},f)=>i.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[i.jsx("span",{title:`Required: ${u.type} - ${Ld(u.color)}`,children:i.jsx(S0,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),i.jsxs("span",{className:"text-white truncate",children:[u.type," ",i.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),i.jsx("span",{className:"text-bambu-gray",children:"→"}),i.jsxs("select",{value:d?.globalTrayId??"",onChange:y=>o(u.slot_id||0,y.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 ${m==="match"?"border-bambu-green/50 text-bambu-green":m==="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:[i.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),iie(t.loadedFilaments,u.nozzle_id).map(y=>i.jsxs("option",{value:y.globalTrayId,className:"bg-bambu-dark text-white",children:[y.label,": ",y.traySubBrands||y.type," (",y.colorName,")"]},y.globalTrayId))]}),m==="match"?i.jsx(Zr,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?i.jsx("span",{title:"Same type, different color",children:i.jsx(jn,{className:"w-3 h-3 text-yellow-400"})}):i.jsx("span",{title:"Filament type not loaded",children:i.jsx(jn,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function Wqe({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:a=!1,showInactive:s=!1,disableBusy:o=!1,printerMappingResults:l,filamentReqs:c,onAutoConfigurePrinter:u,onUpdatePrinterConfig:d,assignmentMode:m="printer",onAssignmentModeChange:p,targetModel:f,onTargetModelChange:y,targetLocation:v,onTargetLocationChange:b,slicedForModel:g}){const[_,N]=w.useState(!1),C=s?t:t.filter(ne=>ne.is_active),k=tg({queries:C.map(ne=>({queryKey:["printerStatus",ne.id],queryFn:()=>ge.getPrinterStatus(ne.id),staleTime:5e3}))}),P=w.useMemo(()=>{const ne=new Map;return C.forEach((se,pe)=>{const Te=k[pe];Te?.data&&ne.set(se.id,Te.data)}),ne},[C,k]),T=ne=>{const se=P.get(ne);return se?se.connected?!Vqe.has(se.state??""):!0:!1},D=ne=>{const se=P.get(ne);if(!se)return null;if(!se.connected)return"Offline";const pe=se.state;return pe?pe==="RUNNING"?se.stg_cur_name||"Printing":pe==="PREPARE"?"Preparing":pe==="PAUSE"?"Paused":pe==="IDLE"?"Idle":pe==="FINISH"?"Finished":pe==="FAILED"?"Failed":pe:null},A=w.useMemo(()=>{if(m!=="printer"||!g||_)return C;const ne=C.filter(se=>se.model===g);return ne.length>0?ne:C},[C,m,g,_]),R=C.length-A.length,G=w.useMemo(()=>{const ne=C.map(se=>se.model).filter(se=>!!se);return[...new Set(ne)].sort()},[C]),z=w.useMemo(()=>{if(!f)return[];const ne=C.filter(se=>se.model===f&&se.location).map(se=>se.location).filter(se=>!!se);return[...new Set(ne)].sort()},[C,f]),Z=p&&y&&G.length>0,I=a&&e.length>1&&l&&c?.filaments&&c.filaments.length>0&&u&&d;if(r)return i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(A.length===0)return i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[i.jsx(Li,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const J=ne=>{o&&T(ne)||(a?e.includes(ne)?n(e.filter(se=>se!==ne)):n([...e,ne]):n([ne]))},ae=()=>{const ne=o?A.filter(se=>!T(se.id)):A;n(ne.map(se=>se.id))},Y=()=>{n([])},ue=(ne,se,pe)=>{pe.stopPropagation(),!(!u||!d)&&(se?u(ne):d(ne,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},de=ne=>e.includes(ne),he=e.length,V=ne=>l?.find(se=>se.printerId===ne);return i.jsxs("div",{className:"space-y-2 mb-6",children:[Z&&i.jsxs("div",{className:"flex gap-2 mb-4",children:[i.jsxs("button",{type:"button",onClick:()=>{p("printer"),y(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${m==="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:[i.jsx(_r,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),i.jsxs("button",{type:"button",onClick:()=>{p("model"),n([]);const ne=g&&G.includes(g)?g:G[0];y(ne)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${m==="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:[i.jsx(ih,{className:"w-4 h-4"}),i.jsxs("span",{className:"text-sm",children:["Any ",g||"Model"]})]})]}),m==="model"&&Z&&i.jsxs("div",{className:"space-y-3 mb-4",children:[!g&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),i.jsxs("select",{value:f||"",onChange:ne=>{y(ne.target.value||null),b&&b(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:[i.jsx("option",{value:"",children:"Select a model..."}),G.map(ne=>i.jsx("option",{value:ne,children:ne},ne))]})]}),f&&z.length>0&&b&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),i.jsxs("select",{value:v||"",onChange:ne=>b(ne.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:[i.jsx("option",{value:"",children:"Any location"}),z.map(ne=>i.jsx("option",{value:ne,children:ne},ne))]})]}),f&&i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",v?` in ${v}`:""]})]}),m==="printer"&&a&&A.length>1&&i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[i.jsx("span",{children:he===0?"Select printers":`${he} printer${he!==1?"s":""} selected`}),i.jsxs("div",{className:"flex gap-2",children:[he0&&i.jsx("button",{type:"button",onClick:Y,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&A.map(ne=>{const se=de(ne.id),pe=V(ne.id),Te=pe&&!pe.config.useDefault,q=T(ne.id),X=o&&q,j=D(ne.id);return i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>J(ne.id),disabled:X,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${X?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":se?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${ne.is_active?"":"opacity-60"}`,children:[i.jsx("div",{className:`p-2 rounded-lg ${X?"bg-bambu-dark-tertiary":se?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:i.jsx(_r,{className:`w-5 h-5 ${X?"text-bambu-gray/50":se?"text-bambu-green":"text-bambu-gray"}`})}),i.jsxs("div",{className:"text-left flex-1",children:[i.jsxs("p",{className:`font-medium ${X?"text-bambu-gray":"text-white"}`,children:[ne.name,!ne.is_active&&i.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[ne.model||"Unknown model"," • ",ne.ip_address]})]}),j&&i.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${q?"bg-yellow-500/20 text-yellow-400":"bg-bambu-green/20 text-bambu-green"}`,children:j}),a&&i.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${X?"border-bambu-gray/30":se?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:se&&i.jsx(Zr,{className:"w-3 h-3 text-white"})})]}),se&&I&&pe&&i.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:E=>E.stopPropagation(),children:[i.jsx("input",{type:"checkbox",checked:Te,onChange:E=>ue(ne.id,E.target.checked,E),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"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),i.jsxs("span",{className:`text-xs ml-2 ${pe.matchStatus==="full"?"text-bambu-green":pe.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",pe.exactMatches,"/",pe.totalSlots," matched)"]}),pe.isLoading&&i.jsx(Sr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),Te&&i.jsxs("button",{type:"button",onClick:E=>{E.stopPropagation(),u(ne.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:[i.jsx(Rbe,{className:"w-3 h-3"}),"Auto"]})]}),Te&&i.jsx(Gqe,{printerResult:pe,filamentReqs:c.filaments,onUpdateConfig:E=>d(ne.id,E)})]})]},ne.id)}),m==="printer"&&R>0&&!_&&i.jsxs("button",{type:"button",onClick:()=>N(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[i.jsx(jn,{className:"w-3 h-3 text-yellow-400"}),R," other printer",R>1?"s":""," hidden (different model) —",i.jsx("span",{className:"underline",children:"show all"})]}),m==="printer"&&_&&g&&i.jsx("button",{type:"button",onClick:()=>N(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:i.jsxs("span",{className:"underline",children:["Show only ",g," printers"]})}),m==="printer"&&he===0&&i.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[i.jsx(Li,{className:"w-3 h-3"}),"Select at least one printer"]}),m==="model"&&!f&&i.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[i.jsx(Li,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const Kqe=[{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 Yqe({options:t,onChange:e,defaultExpanded:n=!1}){const[r,a]=w.useState(n),s=o=>{e({...t,[o]:!t[o]})};return i.jsxs("div",{className:"mb-4",children:[i.jsxs("button",{type:"button",onClick:()=>a(!r),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[i.jsx(dT,{className:"w-4 h-4"}),i.jsx("span",{children:"Print Options"}),r?i.jsx(Vl,{className:"w-4 h-4 ml-auto"}):i.jsx(In,{className:"w-4 h-4 ml-auto"})]}),r&&i.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:Kqe.map(({key:o,label:l,desc:c})=>i.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-sm text-white",children:l}),i.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),i.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:i.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 Xqe({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system",canControlPrinter:a=!0}){const[s,o]=w.useState(""),[l,c]=w.useState(""),[u,d]=w.useState(!0),[m,p]=w.useState(!0),f=w.useRef(null),y=w.useRef(!1);w.useEffect(()=>{if(t.scheduleType!=="scheduled"){y.current=!1;return}if(!y.current){y.current=!0;let k;t.scheduledTime?(k=new Date(t.scheduledTime),isNaN(k.getTime())&&(k=new Date,k.setHours(k.getHours()+1,0,0,0))):(k=new Date,k.setHours(k.getHours()+1,0,0,0),e({...t,scheduledTime:P3(k)})),o(A3(k,n)),c(n6(k,r)),d(!0),p(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const v=k=>{e({...t,scheduleType:k})},b=(k,P)=>{const T=rxe(k,n),D=ixe(P);d(!!T),p(!!D),T&&D&&(T.setHours(D.hours,D.minutes,0,0),T>new Date&&e({...t,scheduledTime:P3(T)}))},g=k=>{o(k),b(k,l)},_=k=>{c(k),b(s,k)},N=k=>{const P=k.target.value;if(P){const T=new Date(P);isNaN(T.getTime())||(o(A3(T,n)),c(n6(T,r)),d(!0),p(!0),e({...t,scheduledTime:P}))}},C=()=>{f.current?.showPicker()};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("asap"),children:[i.jsx(Zn,{className:"w-4 h-4"}),"ASAP"]}),i.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("scheduled"),children:[i.jsx(Xr,{className:"w-4 h-4"}),"Scheduled"]}),i.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("manual"),children:[i.jsx(QX,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"flex-1 relative",children:[i.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${u?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:s,onChange:k=>g(k.target.value),placeholder:exe(n)}),i.jsx("button",{type:"button",onClick:C,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:i.jsx(Xr,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"w-32",children:i.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${m?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:l,onChange:k=>_(k.target.value),placeholder:txe(r)})})]}),i.jsx("input",{ref:f,type:"datetime-local",className:"sr-only",value:t.scheduledTime,onChange:N,tabIndex:-1}),(!u||!m)&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:k=>e({...t,requirePreviousSuccess:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:k=>e({...t,autoOffAfter:k.target.checked}),disabled:!a,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green disabled:opacity-50"}),i.jsxs("label",{htmlFor:"autoOffAfter",className:`text-sm flex items-center gap-1 ${a?"text-bambu-gray":"text-bambu-gray/50"}`,children:[i.jsx(em,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),i.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 Nb={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},Qqe={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function xu({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:a,initialSelectedPrinterIds:s,onClose:o,onSuccess:l}){const{t:c}=Dt(),u=sn(),{showToast:d}=bn(),{hasPermission:m}=Ar(),p=!!n&&!e,[f,y]=w.useState(()=>t==="edit-queue-item"&&a?.printer_id?[a.printer_id]:s?.length?s:[]),[v,b]=w.useState(()=>t==="edit-queue-item"&&a?.plate_id!=null?new Set([a.plate_id]):new Set),g=v.size===1?[...v][0]:null,[_,N]=w.useState(()=>t==="edit-queue-item"&&a?{bed_levelling:a.bed_levelling??Nb.bed_levelling,flow_cali:a.flow_cali??Nb.flow_cali,vibration_cali:a.vibration_cali??Nb.vibration_cali,layer_inspect:a.layer_inspect??Nb.layer_inspect,timelapse:a.timelapse??Nb.timelapse}:Nb),[C,k]=w.useState(()=>{if(t==="edit-queue-item"&&a){let _t="asap";a.manual_start?_t="manual":a.scheduled_time&&!yW(a.scheduled_time)&&(_t="scheduled");let rt="";if(a.scheduled_time&&!yW(a.scheduled_time)){const Rt=Qn(a.scheduled_time)??new Date;rt=P3(Rt)}return{scheduleType:_t,scheduledTime:rt,requirePreviousSuccess:a.require_previous_success,autoOffAfter:a.auto_off_after}}return Qqe}),[P,T]=w.useState(()=>{if(t==="edit-queue-item"&&a?.ams_mapping&&Array.isArray(a.ams_mapping)){const _t={};return a.ams_mapping.forEach((rt,Rt)=>{rt!==-1&&(_t[Rt+1]=rt)}),_t}return{}}),[D,A]=w.useState({}),[R,G]=w.useState(()=>t==="edit-queue-item"&&a?.target_model?"model":"printer"),[z,Z]=w.useState(()=>t==="edit-queue-item"&&a?.target_model?a.target_model:null),[I,J]=w.useState(()=>t==="edit-queue-item"&&a?.target_location?a.target_location:null),[ae,Y]=w.useState(()=>{if(t==="edit-queue-item"&&a?.filament_overrides){const _t={};for(const rt of a.filament_overrides)_t[rt.slot_id]={type:rt.type,color:rt.color};return _t}return{}}),[ue,de]=w.useState(()=>{if(t==="edit-queue-item"&&a?.filament_overrides){const _t={};for(const rt of a.filament_overrides)_t[rt.slot_id]=rt.force_color_match===!0;return _t}return{}}),[he]=w.useState(()=>t==="edit-queue-item"&&a?.printer_id?[a.printer_id]:[]),[V]=w.useState(()=>t==="edit-queue-item"&&a?a.plate_id:null),[ne,se]=w.useState(!1),[pe,Te]=w.useState({current:0,total:0}),[q,X]=w.useState(null),[j,E]=w.useState(new Set),U=f.length,K=f.length>0?f[0]:null,{data:H}=et({queryKey:["settings"],queryFn:ge.getSettings}),re=Wo(H?.currency||"USD"),O=H?.default_filament_cost??0,{data:$,isLoading:ee}=et({queryKey:["printers"],queryFn:ge.getPrinters}),{data:W}=et({queryKey:["spool-assignments"],queryFn:()=>ge.getAssignments(),staleTime:30*1e3,enabled:(t==="reprint"||t==="add-to-queue")&&R==="printer"||p&&t==="reprint"}),{data:ie}=et({queryKey:["archive",e],queryFn:()=>ge.getArchive(e),enabled:!!e&&!p}),{data:ce}=et({queryKey:["library-file",n],queryFn:()=>ge.getLibraryFile(n),enabled:p&&!!n}),be=ie?.sliced_for_model||ce?.sliced_for_model||null,{data:xe,isError:oe}=et({queryKey:["archive-plates",e],queryFn:()=>ge.getArchivePlates(e),enabled:!!e&&!p,retry:!1}),{data:L}=et({queryKey:["library-file-plates",n],queryFn:()=>ge.getLibraryFilePlates(n),enabled:p&&!!n}),F=p?L:xe,{data:te,isError:ve}=et({queryKey:["archive-filaments",e,g],queryFn:()=>ge.getArchiveFilamentRequirements(e,g??void 0),enabled:!!e&&!p&&(g!==null||!F?.is_multi_plate),retry:!1}),{data:fe}=et({queryKey:["library-file-filaments",n,g],queryFn:()=>ge.getLibraryFileFilamentRequirements(n,g??void 0),enabled:p&&!!n&&(g!==null||!F?.is_multi_plate)}),me=!p&&(oe||ve),je=p?fe:te,we=w.useMemo(()=>{if(!(g===null||!F?.plates?.length))return F.plates.find(_t=>_t.index===g)?.name||void 0},[F,g]),{data:Fe}=et({queryKey:["available-filaments",z,I],queryFn:()=>ge.getAvailableFilaments(z,I??void 0),enabled:R==="model"&&!!z}),{data:He}=et({queryKey:["printer-status",K],queryFn:()=>ge.getPrinterStatus(K),enabled:!!K}),{amsMapping:Oe}=aie(je,He,P),_e=Uqe(f,$,je,P,D,A);w.useEffect(()=>{F?.plates&&F.plates.length>=1&&v.size===0&&b(new Set([F.plates[0].index]))},[F,v.size]),w.useEffect(()=>{if(t==="edit-queue-item")return;const _t=$?.filter(rt=>rt.is_active)||[];_t.length===1&&f.length===0&&y([_t[0].id])},[t,$,f.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(f.sort())!==JSON.stringify(he.sort())||g!==V)&&(T({}),A({}),E(new Set)):(T({}),A({}),E(new Set))},[t,f,g,he,V]);const[Ae,Be]=w.useState(z),[Me,Xe]=w.useState(g);w.useEffect(()=>{(z!==Ae||g!==Me)&&(Be(z),Xe(g),(t!=="edit-queue-item"||Ae!==null)&&(Y({}),de({})))},[z,g,Ae,Me,t]),w.useEffect(()=>{if(!H?.per_printer_mapping_expanded||f.length<=1)return;const _t=f.filter(rt=>{if(j.has(rt))return!1;const Rt=_e.printerResults.find(qt=>qt.printerId===rt);return Rt&&Rt.status&&!Rt.isLoading});_t.length>0&&(E(rt=>{const Rt=new Set(rt);return _t.forEach(qt=>Rt.add(qt)),Rt}),_t.forEach(rt=>{_e.autoConfigurePrinter(rt)}))},[H?.per_printer_mapping_expanded,f,j,_e]),w.useEffect(()=>{const _t=rt=>{rt.key==="Escape"&&!ne&&o()};return window.addEventListener("keydown",_t),()=>window.removeEventListener("keydown",_t)},[o,ne]);const ye=F?.is_multi_plate??!1,We=F?.plates??[],Pe=w.useMemo(()=>{const _t=new Map;return W&&W.forEach(rt=>{const Rt=rt.ams_id===255,qt=Ex(rt.ams_id,rt.tray_id,Rt),Kt=_t.get(rt.printer_id)??new Map;Kt.set(qt,rt),_t.set(rt.printer_id,Kt)}),_t},[W]),Ke=w.useMemo(()=>{if(!q||q.length===0)return"";const _t=q.map(rt=>c("printModal.insufficientFilamentLine",{printer:rt.printerName,slot:rt.slotLabel,required:Math.round(rt.requiredGrams),remaining:Math.round(rt.remainingGrams)}));return[c("printModal.insufficientFilamentMessage"),..._t].join(` +`)},[q,c]),Ve=gt({mutationFn:_t=>ge.addToQueue(_t)}),ke=gt({mutationFn:_t=>ge.updateQueueItem(a.id,_t),onSuccess:()=>{u.invalidateQueries({queryKey:["queue"]}),d("Queue item updated"),l?.(),o()},onError:_t=>{d(_t.message||"Failed to update queue item","error")}}),Ce=async(_t,rt)=>{if(_t?.preventDefault(),!rt?.skipFilamentCheck&&!H?.disable_filament_warnings&&(t==="reprint"||t==="add-to-queue")&&R==="printer"){const Qe=[],De=je?.filaments??[];if(De.length>0&&Pe.size>0){const ot=(st,Ze)=>!Number.isFinite(st)||st<=0||!Number.isFinite(Ze)||Ze<0?null:Math.max(0,st-Ze);for(const st of f){const Ze=f.length>1?_e.getFinalMapping(st):Oe;if(!Ze)continue;const Ee=f.length>1?_e.printerResults.find(Ge=>Ge.printerId===st)?.status:He,ct=Xw(Ee),le=new Map(ct.map(Ge=>[Ge.globalTrayId,Ge.label])),Le=Pe.get(st),Ye=$?.find(Ge=>Ge.id===st)?.name??`Printer ${st}`;Le&&De.forEach(Ge=>{if(!Ge.slot_id||Ge.slot_id<=0)return;const Ie=Ze[Ge.slot_id-1];if(!Number.isFinite(Ie)||Ie<0)return;const dt=Le.get(Ie)?.spool;if(!dt)return;const Je=ot(dt.label_weight,dt.weight_used);Je!==null&&(Je>=Ge.used_grams||Qe.push({printerName:Ye,slotLabel:le.get(Ie)??`Slot ${Ge.slot_id}`,requiredGrams:Ge.used_grams,remainingGrams:Je}))})}}if(Qe.length>0){X(Qe);return}}if(R==="printer"&&f.length===0){d("Please select at least one printer","error");return}if(R==="model"&&!z){d("Please select a target printer model","error");return}se(!0);const Rt=v.size>1?We.filter(Qe=>v.has(Qe.index)):[null],qt=R==="model"?Rt.length:f.length*Rt.length;Te({current:0,total:qt});const Kt={success:0,failed:0,errors:[]},Qt=Qe=>{if(f.length>1){const De=D[Qe];if(De&&!De.useDefault)return _e.getFinalMapping(Qe)}return Oe},hn=(()=>{const Qe=[];if(je?.filaments)for(const De of je.filaments){const ot=ae[De.slot_id],st=ue[De.slot_id]??!1,Ze=ot?.type??De.type,Ee=ot?.color??De.color;(ot||st)&&Qe.push({slot_id:De.slot_id,type:Ze,color:Ee,color_name:Ld(Ee),force_color_match:st})}else for(const[De,{type:ot,color:st}]of Object.entries(ae)){const Ze=parseInt(De,10),Ee=ue[Ze]??!1;Qe.push({slot_id:Ze,type:ot,color:st,color_name:Ld(st),force_color_match:Ee})}return Qe.length>0?Qe:void 0})(),Hn=(Qe,De)=>({printer_id:R==="printer"?Qe:null,target_model:R==="model"?z:null,target_location:R==="model"?I:null,filament_overrides:R==="model"?hn:void 0,archive_id:p?void 0:e,library_file_id:p?n:void 0,require_previous_success:C.requirePreviousSuccess,auto_off_after:C.autoOffAfter,manual_start:C.scheduleType==="manual",ams_mapping:Qe?Qt(Qe):void 0,plate_id:De!==void 0?De:g,scheduled_time:C.scheduleType==="scheduled"&&C.scheduledTime?new Date(C.scheduledTime).toISOString():void 0,..._});if(R==="model"){if(t==="reprint"){d("Model-based assignment only works with queue mode","error"),se(!1);return}let Qe=0;for(const De of Rt){Qe++,Te({current:Qe,total:qt});const ot=De?De.index:g;try{if(t==="edit-queue-item"&&!De){const st={printer_id:null,target_model:z,target_location:I,filament_overrides:hn||null,require_previous_success:C.requirePreviousSuccess,auto_off_after:C.autoOffAfter,manual_start:C.scheduleType==="manual",ams_mapping:void 0,plate_id:ot,scheduled_time:C.scheduleType==="scheduled"&&C.scheduledTime?new Date(C.scheduledTime).toISOString():null,..._};await ke.mutateAsync(st)}else await Ve.mutateAsync(Hn(null,ot));Kt.success++}catch(st){Kt.failed++;const Ze=De?De.name||`Plate ${De.index}`:"";Kt.errors.push(Ze?`${Ze}: ${st.message}`:st.message)}}}else{let Qe=0;for(const De of Rt){const ot=De?De.index:g;for(let st=0;stYe.id===Ze)?.name||`Printer ${Ze}`,le=De?De.name||`Plate ${De.index}`:"",Le=le?`${ct} (${le})`:ct;Kt.errors.push(`${Le}: ${Ee.message}`)}}}}se(!1),Kt.failed===0?(t!=="reprint"&&(t==="edit-queue-item"?d("Queue item updated"):Kt.success===1?d(R==="model"?`Queued for any ${z}`:c("queue.printQueued")):d(c("queue.itemsQueued",{count:Kt.success}))),u.invalidateQueries({queryKey:["queue"]}),l?.(),o()):Kt.success===0?d(`Failed: ${Kt.errors[0]}`,"error"):(d(`${Kt.success} succeeded, ${Kt.failed} failed`,"error"),u.invalidateQueries({queryKey:["queue"]}))},$e=ne||ke.isPending,nt=w.useMemo(()=>!($e||R==="printer"&&f.length===0||R==="model"&&!z||R==="model"&&t==="reprint"||ye&&v.size===0),[f.length,R,z,t,ye,v.size,$e]),vt=(()=>{const _t=f.length;if(t==="reprint")return{title:c(p?"queue.print":"queue.reprint"),icon:_r,submitText:_t>1?c("queue.printToPrinters",{count:_t}):c("queue.print"),submitIcon:_r,loadingText:pe.total>1?c("queue.sendingProgress",{current:pe.current,total:pe.total}):c("queue.sending")};if(t==="add-to-queue"){let rt=c("queue.addToQueue");return v.size>1?rt=c("queue.queueSelectedPlates",{count:v.size}):_t>1&&(rt=c("queue.queueToPrinters",{count:_t})),{title:c("queue.schedulePrint"),icon:Xr,submitText:rt,submitIcon:Xr,loadingText:pe.total>1?c("queue.addingProgress",{current:pe.current,total:pe.total}):c("queue.adding")}}return{title:c("queue.editQueueItem"),icon:Yi,submitText:c("common.save"),submitIcon:Yi,loadingText:pe.total>1?c("queue.savingProgress",{current:pe.current,total:pe.total}):c("common.saving")}})(),mt=vt.icon,qe=vt.submitIcon,Nt=K&&v.size<=1&&(p||(ye?g!==null:!0));return i.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:ne?void 0:o,children:[i.jsx(Pt,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:_t=>_t.stopPropagation(),children:i.jsxs(Et,{className:t==="reprint"?"":"p-0",children:[i.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(mt,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:vt.title})]}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:o,disabled:ne,children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:Ce,className:t==="reprint"?"":"p-4 space-y-4",children:[i.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?i.jsxs(i.Fragment,{children:["Send ",i.jsx("span",{className:"text-white",children:r})," to"," ",s?.length===1&&$?i.jsx("span",{className:"text-white",children:$.find(_t=>_t.id===s[0])?.name??"printer(s)"}):"printer(s)"]}):i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),i.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),i.jsx(qqe,{plates:We,isMultiPlate:ye,selectedPlates:v,onToggle:_t=>{b(rt=>{const Rt=new Set(rt);return t==="add-to-queue"?Rt.has(_t)?Rt.delete(_t):Rt.add(_t):(Rt.clear(),Rt.add(_t)),Rt})},onSelectAll:t==="add-to-queue"?()=>b(new Set(We.map(_t=>_t.index))):void 0,onDeselectAll:t==="add-to-queue"?()=>b(new Set):void 0,multiSelect:t==="add-to-queue"}),!s?.length&&i.jsx(Wqe,{printers:$||[],selectedPrinterIds:f,onMultiSelect:y,isLoading:ee,allowMultiple:!0,showInactive:t==="edit-queue-item",disableBusy:t==="reprint",printerMappingResults:_e.printerResults,filamentReqs:je,onAutoConfigurePrinter:_e.autoConfigurePrinter,onUpdatePrinterConfig:_e.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":R,onAssignmentModeChange:t!=="reprint"?G:void 0,targetModel:z,onTargetModelChange:t!=="reprint"?Z:void 0,targetLocation:I,onTargetLocationChange:t!=="reprint"?J:void 0,slicedForModel:be}),R==="model"&&z&&je&&Fe&&Fe.length>0&&i.jsx($qe,{filamentReqs:je,availableFilaments:Fe,overrides:ae,onChange:Y,forceColorMatch:ue,onForceColorMatchChange:(_t,rt)=>de(Rt=>({...Rt,[_t]:rt}))}),be&&R==="printer"&&f.length===1&&(()=>{const _t=$?.find(rt=>rt.id===f[0]);return _t&&_t.model&&be!==_t.model?i.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[i.jsx(jn,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),i.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",be,", but printing on ",_t.model]})]}):null})(),me&&i.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:[i.jsx(Li,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),i.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),Nt&&!me&&f.length===1&&i.jsx(Hqe,{printerId:K,filamentReqs:je,manualMappings:P,onManualMappingChange:T,defaultExpanded:!!s?.length||(H?.per_printer_mapping_expanded??!1),currencySymbol:re,defaultCostPerKg:O}),(t==="reprint"||U>0||R==="model"&&z)&&i.jsx(Yqe,{options:_,onChange:N,defaultExpanded:!!s?.length}),t!=="reprint"&&i.jsx(Xqe,{options:C,onChange:k,dateFormat:H?.date_format||"system",timeFormat:H?.time_format||"system",canControlPrinter:m("printers:control")}),ke.isError&&i.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:ke.error?.message||"Failed to complete operation"}),i.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:o,className:"flex-1",disabled:ne,children:"Cancel"}),i.jsx(ze,{type:"submit",disabled:!nt,className:"flex-1",children:$e?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),vt.loadingText]}):i.jsxs(i.Fragment,{children:[i.jsx(qe,{className:"w-4 h-4"}),vt.submitText]})})]})]})]})}),q&&q.length>0&&i.jsx(Nn,{title:c("printModal.insufficientFilamentTitle"),message:Ke,confirmText:c("printModal.printAnyway"),cancelText:c("common.cancel"),variant:"warning",onConfirm:()=>{X(null),Ce(void 0,{skipFilamentCheck:!0})},onCancel:()=>X(null)})]})}function SW({value:t}){const{t:e}=Dt(),[n,r]=w.useState(!1),a=async()=>{try{await navigator.clipboard.writeText(t),r(!0),setTimeout(()=>r(!1),2e3)}catch{}};return i.jsx("button",{onClick:a,className:"ml-2 p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:e(n?"printers.copied":"printers.copyToClipboard"),children:n?i.jsx(Zr,{className:"w-3.5 h-3.5 text-bambu-green"}):i.jsx(ko,{className:"w-3.5 h-3.5"})})}function Zqe({printer:t,status:e,totalPrintHours:n,onClose:r}){const{t:a}=Dt();w.useEffect(()=>{const o=l=>{l.key==="Escape"&&r()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[r]);const s=[];if(s.push({label:a("printers.model"),value:t.model??"—"}),s.push({label:a("common.status"),value:i.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${e?.connected?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[i.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${e?.connected?"bg-bambu-green":"bg-red-400"}`}),e?.connected?a("printers.status.available"):a("printers.status.offline")]})}),e?.state){const o={IDLE:"printers.status.idle",RUNNING:"printers.status.printing",PAUSE:"printers.status.paused",FINISH:"printers.status.finished",FAILED:"printers.status.error"};s.push({label:a("printers.state"),value:a(o[e.state]??"printers.status.unknown")})}if(s.push({label:a("printers.ipAddress"),value:i.jsxs("span",{className:"flex items-center",children:[i.jsx("span",{className:"font-mono",children:t.ip_address}),i.jsx(SW,{value:t.ip_address})]})}),s.push({label:a("printers.serialNumber"),value:i.jsxs("span",{className:"flex items-center",children:[i.jsx("span",{className:"font-mono truncate",children:t.serial_number}),i.jsx(SW,{value:t.serial_number})]})}),e?.wired_network)s.push({label:a("printers.networkLabel","Network"),value:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(VL,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-bambu-green",children:a("printers.connection.ethernet","Ethernet")})]})});else if(e?.wifi_signal!=null){const o=zZ(e.wifi_signal);s.push({label:a("printers.wifiSignalLabel"),value:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(nQ,{className:`w-4 h-4 ${o.color}`}),i.jsx("span",{className:o.color,children:a(o.labelKey)}),i.jsxs("span",{className:"text-bambu-gray text-xs",children:["(",e.wifi_signal," dBm)"]})]})})}return s.push({label:a("printers.firmware"),value:e?.firmware_version??"—"}),e?.developer_mode!=null&&s.push({label:a("printers.developerMode"),value:i.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${e.developer_mode?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:e.developer_mode?a("printers.enabled"):a("printers.disabled")})}),s.push({label:a("printers.nozzleCount"),value:t.nozzle_count}),e?.sdcard!=null&&s.push({label:a("printers.sdCard"),value:i.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${e.sdcard?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:e.sdcard?a("printers.inserted"):a("printers.notInserted")})}),s.push({label:a("printers.autoArchive"),value:i.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${t.auto_archive?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:t.auto_archive?a("printers.enabled"):a("printers.disabled")})}),n!=null&&n>0&&s.push({label:a("printers.totalPrintHours"),value:`${Math.round(n)}h`}),t.location&&s.push({label:a("printers.sort.location"),value:t.location}),s.push({label:a("printers.addedOn"),value:jf(t.created_at)}),i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",role:"dialog","aria-modal":"true",onClick:r,children:i.jsx(Pt,{className:"w-full max-w-md",onClick:o=>o.stopPropagation(),children:i.jsxs(Et,{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:t.name}),i.jsx("button",{onClick:r,className:"p-1 hover:bg-bambu-dark rounded flex-shrink-0",children:i.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsx("div",{className:"flex justify-center mb-4",children:i.jsx("img",{src:IZ(t.model),alt:t.model??t.name,className:"h-24 object-contain"})}),i.jsx("div",{className:"space-y-0",children:s.map((o,l)=>i.jsxs("div",{className:"flex items-center justify-between gap-4 py-2.5 border-b border-bambu-dark-tertiary last:border-0",children:[i.jsx("span",{className:"text-sm text-bambu-gray whitespace-nowrap",children:o.label}),i.jsx("span",{className:"text-sm text-white text-right",children:o.value})]},l))})]})})})}function Jqe(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 eD({trayColor:t,trayType:e,isEmpty:n,slotNumber:r}){return i.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2 flex items-center justify-center",style:{backgroundColor:t?`#${t}`:e?"#333":"transparent",borderColor:n?"#666":"rgba(255,255,255,0.1)",borderStyle:n?"dashed":"solid"},children:i.jsx("span",{className:"text-[6px] font-bold leading-none select-none",style:{color:t&&Jqe(t)?"#000":"#fff"},children:r})})}const _W={"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"},eVe={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 tD(t){if(!t)return null;if(_W[t])return _W[t];const e=t.split("-");if(e.length<2)return null;const n=e[1];return eVe[n]||null}function nD(t){return(t??.02).toFixed(3)}function NW({side:t}){const{mode:e}=ng(),n=e==="dark"?"#1a4d2e":"#e7f5e9";return i.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 oie(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 lie(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function cie({slot:t,index:e,activeStatus:n,filamentName:r,children:a}){const{t:s}=Dt(),[o,l]=w.useState(!1),[c,u]=w.useState("top"),d=w.useRef(null),m=w.useRef(null),p=w.useRef(null),f=!t.nozzle_diameter&&!t.nozzle_type,y=t.stat===1;w.useEffect(()=>{if(o&&d.current&&m.current){const C=d.current.getBoundingClientRect(),k=m.current.offsetHeight,T=C.top-56,D=window.innerHeight-C.bottom;TT?u("bottom"):u("top")}},[o]);const v=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},b=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const g=R4(t.filament_color),_=oie(t.nozzle_type,s),N=lie(t.nozzle_type,s);return i.jsxs("div",{ref:d,className:"relative",onMouseEnter:v,onMouseLeave:b,children:[a,o&&i.jsxs("div",{ref:m,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 @@ -8517,7 +8517,7 @@ ${o("inventory.assignProfileMismatchMessage",{spoolProfile:g.spoolProfile||o("co 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 tVe({leftSlot:t,rightSlot:e,activeNozzle:n,filamentInfo:r,children:a}){const{t:s}=Dt(),[o,l]=w.useState(!1),[c,u]=w.useState("top"),d=w.useRef(null),m=w.useRef(null),p=w.useRef(null);w.useEffect(()=>{if(o&&d.current&&m.current){const b=d.current.getBoundingClientRect(),g=m.current.offsetHeight,N=b.top-56,C=window.innerHeight-b.bottom;NN?u("bottom"):u("top")}},[o]);const f=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},y=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};if(w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]),!t&&!e)return i.jsx(i.Fragment,{children:a});const v=(b,g)=>{const _=n===g,N=oie(b.nozzle_type,s),C=lie(b.nozzle_type,s),k=RI(b.filament_color),P=b.filament_id?r?.[b.filament_id]?.name:void 0;return i.jsxs("div",{className:"flex-1 space-y-1.5",children:[i.jsx("div",{className:`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${_?"text-amber-400":"text-bambu-gray"}`,children:s(g==="L"?"common.left":"common.right")}),b.nozzle_diameter&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleDiameter")}),i.jsxs("span",{className:"text-xs text-white font-semibold",children:[b.nozzle_diameter," mm"]})]}),N&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleType")}),i.jsx("span",{className:"text-[10px] text-white font-semibold",children:N})]}),C&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleFlow")}),i.jsx("span",{className:"text-[10px] text-white font-semibold",children:C})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleStatus")}),i.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded ${_?"bg-green-900/50 text-green-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:s(_?"printers.nozzleActive":"printers.nozzleIdle")})]}),b.wear!=null&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleWear")}),i.jsxs("span",{className:"text-xs text-white font-semibold",children:[b.wear,"%"]})]}),g==="R"&&b.max_temp>0&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleMaxTemp")}),i.jsxs("span",{className:"text-xs text-white font-semibold",children:[b.max_temp,"°C"]})]}),g==="R"&&b.serial_number&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleSerial")}),i.jsx("span",{className:"text-[10px] text-white font-mono",children:b.serial_number})]}),(k||b.filament_type||b.filament_id)&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleFilament")}),i.jsxs("div",{className:"flex items-center gap-1",children:[k&&i.jsx("div",{className:"w-3 h-3 rounded-sm border border-white/20",style:{backgroundColor:k}}),i.jsx("span",{className:"text-[10px] text-white font-semibold truncate max-w-[100px]",children:P||b.filament_type||b.filament_id||""})]})]})]})};return i.jsxs("div",{ref:d,className:"relative flex-1",onMouseEnter:f,onMouseLeave:y,children:[a,o&&i.jsxs("div",{ref:m,className:` + `})]})]})}function tVe({leftSlot:t,rightSlot:e,activeNozzle:n,filamentInfo:r,children:a}){const{t:s}=Dt(),[o,l]=w.useState(!1),[c,u]=w.useState("top"),d=w.useRef(null),m=w.useRef(null),p=w.useRef(null);w.useEffect(()=>{if(o&&d.current&&m.current){const b=d.current.getBoundingClientRect(),g=m.current.offsetHeight,N=b.top-56,C=window.innerHeight-b.bottom;NN?u("bottom"):u("top")}},[o]);const f=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},y=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};if(w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]),!t&&!e)return i.jsx(i.Fragment,{children:a});const v=(b,g)=>{const _=n===g,N=oie(b.nozzle_type,s),C=lie(b.nozzle_type,s),k=R4(b.filament_color),P=b.filament_id?r?.[b.filament_id]?.name:void 0;return i.jsxs("div",{className:"flex-1 space-y-1.5",children:[i.jsx("div",{className:`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${_?"text-amber-400":"text-bambu-gray"}`,children:s(g==="L"?"common.left":"common.right")}),b.nozzle_diameter&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleDiameter")}),i.jsxs("span",{className:"text-xs text-white font-semibold",children:[b.nozzle_diameter," mm"]})]}),N&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleType")}),i.jsx("span",{className:"text-[10px] text-white font-semibold",children:N})]}),C&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleFlow")}),i.jsx("span",{className:"text-[10px] text-white font-semibold",children:C})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleStatus")}),i.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded ${_?"bg-green-900/50 text-green-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:s(_?"printers.nozzleActive":"printers.nozzleIdle")})]}),b.wear!=null&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleWear")}),i.jsxs("span",{className:"text-xs text-white font-semibold",children:[b.wear,"%"]})]}),g==="R"&&b.max_temp>0&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleMaxTemp")}),i.jsxs("span",{className:"text-xs text-white font-semibold",children:[b.max_temp,"°C"]})]}),g==="R"&&b.serial_number&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleSerial")}),i.jsx("span",{className:"text-[10px] text-white font-mono",children:b.serial_number})]}),(k||b.filament_type||b.filament_id)&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleFilament")}),i.jsxs("div",{className:"flex items-center gap-1",children:[k&&i.jsx("div",{className:"w-3 h-3 rounded-sm border border-white/20",style:{backgroundColor:k}}),i.jsx("span",{className:"text-[10px] text-white font-semibold truncate max-w-[100px]",children:P||b.filament_type||b.filament_id||""})]})]})]})};return i.jsxs("div",{ref:d,className:"relative flex-1",onMouseEnter:f,onMouseLeave:y,children:[a,o&&i.jsxs("div",{ref:m,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 @@ -8526,7 +8526,7 @@ ${o("inventory.assignProfileMismatchMessage",{spoolProfile:g.spoolProfile||o("co 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 nVe({slots:t,filamentInfo:e}){const{t:n}=Dt(),r=t.filter(l=>l.id>=2),a=6,s=r.length>0?Math.min(...r.map(l=>l.id)):16,o=Array.from({length:a},(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 i.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:[i.jsx("p",{className:"text-[9px] text-bambu-gray mb-1",children:n("printers.nozzleRack")}),i.jsx("div",{className:"flex gap-[3px] justify-center",children:o.map((l,c)=>{const u=!l.nozzle_diameter&&!l.nozzle_type,d=u?null:RI(l.filament_color),m=d?eie(l.filament_color):!1;return i.jsx(cie,{slot:l,index:c,filamentName:l.filament_id?e?.[l.filament_id]?.name:void 0,children:i.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:i.jsx("span",{className:`text-[10px] font-semibold ${u?"text-bambu-gray/30":m?"text-black/80":"text-white"}`,style:d&&!m?{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 kW({className:t}){return i.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:i.jsx("path",{d:"M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z",fill:"#C3C2C1"})})}function rVe({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z",fill:"#C3C2C1"}),i.jsx("path",{d:"M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z",fill:"#1F8FEB"})]})}function iVe({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z",fill:"#1F8FEB"}),i.jsx("path",{d:"M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z",fill:"#C3C2C1"})]})}function aVe({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"}),i.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function sVe({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function oVe({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function rD({className:t,color:e,isHeating:n}){const a={"text-orange-400":"#fb923c","text-blue-400":"#60a5fa","text-green-400":"#4ade80"}[e]||"#888",s=n?{filter:`drop-shadow(0 0 4px ${a}) drop-shadow(0 0 8px ${a})`}:{};return n?i.jsxs("svg",{className:t,style:s,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:a,rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:a}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:a,strokeWidth:"1",fill:"none"})]}):i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:a,strokeWidth:"1",fill:"none"}),i.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:a,strokeWidth:"1",fill:"none"})]})}function CW({humidity:t,goodThreshold:e=40,fairThreshold:n=60,onClick:r,compact:a}){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=kW:s<=l?d=rVe:d=iVe,i.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:[i.jsx(d,{className:a?"w-2.5 h-3":"w-3 h-4"}),i.jsxs("span",{className:`font-medium tabular-nums ${a?"text-[10px]":"text-xs"}`,style:{color:c},children:[s,"%"]})]})}function TW({temp:t,goodThreshold:e=28,fairThreshold:n=35,onClick:r,compact:a}){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=aVe):t<=o?(l="#d4a017",c="Fair",u=sVe):(l="#c62828",c="Bad",u=oVe),i.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:[i.jsx(u,{className:a?"w-2.5 h-3":"w-3 h-4"}),i.jsxs("span",{className:`tabular-nums text-right ${a?"text-[10px] w-8":"w-12"}`,style:{color:l},children:[t,"°C"]})]})}function Zc(t,e){const n=typeof t=="string"?parseInt(t,10):t,r=isNaN(n)?0:n,a=e===1,s=r>=128?r-128:r,o=String.fromCharCode(65+s);return a?`HT-${o}`:`AMS-${o}`}function iD(t){return t?!!(t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function lVe({url:t,printName:e}){const{t:n}=Dt(),[r,a]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(!1),u=w.useMemo(()=>{if(!t)return null;const d=t.includes("?")?"&":"?";return`${t}${d}v=${encodeURIComponent(e||Date.now().toString())}`},[t,e]);return w.useEffect(()=>{a(!1),o(!1)},[u]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:`w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${u&&r?"cursor-pointer":""}`,onClick:()=>u&&r&&c(!0),children:u&&!s?i.jsxs(i.Fragment,{children:[i.jsx("img",{src:u,alt:n("printers.printPreview"),className:`w-full h-full object-cover ${r?"block":"hidden"}`,onLoad:()=>a(!0),onError:()=>o(!0)}),!r&&i.jsx(ia,{className:"w-8 h-8 text-bambu-gray"})]}):i.jsx(ia,{className:"w-8 h-8 text-bambu-gray"})}),l&&u&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8",onClick:()=>c(!1),children:i.jsxs("div",{className:"relative max-w-2xl max-h-full",children:[i.jsx("img",{src:u,alt:n("printers.printPreview"),className:"max-w-full max-h-[80vh] rounded-lg shadow-2xl"}),e&&i.jsx("p",{className:"text-white text-center mt-4 text-lg",children:e})]})})]})}function cVe({printers:t}){const{t:e}=Dt(),n=sn(),[r,a]=w.useState(0);w.useEffect(()=>{let l=!1;const c=n.getQueryCache().subscribe(()=>{l||(l=!0,requestAnimationFrame(()=>{a(u=>u+1),l=!1}))});return()=>c()},[n]);const{counts:s,nextFinish:o}=w.useMemo(()=>{let l=0,c=0,u=0,d=0,m=0,p=null,f=null,y=0;return t?.forEach(v=>{const b=n.getQueryData(["printerStatus",v.id]);b===void 0?d++:b.connected?(b.hms_errors&&nk(b.hms_errors).length>0&&m++,b.state==="RUNNING"?(l++,b.remaining_time!=null&&b.remaining_time>0&&(f===null||b.remaining_time0?"bg-bambu-green":"bg-gray-500"}`}),i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white font-medium",children:s.idle})," ",e("printers.status.available").toLowerCase()]})]}),s.printing>0&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white font-medium",children:s.printing})," ",e("printers.status.printing").toLowerCase()]})]}),s.offline>0&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-gray-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white font-medium",children:s.offline})," ",e("printers.status.offline").toLowerCase()]})]}),s.problem>0&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-status-error"}),i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white font-medium",children:s.problem})," ",e("printers.status.problem").toLowerCase()]})]}),o&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-px h-4 bg-bambu-dark-tertiary"}),i.jsxs("div",{className:"flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"text-bambu-green font-medium",children:[e("printers.nextAvailable"),":"]}),i.jsx("span",{className:"text-white font-medium",children:o.name})]}),i.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto",children:[i.jsx("div",{className:"w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5",children:i.jsx("div",{className:"bg-bambu-green h-1.5 rounded-full transition-all",style:{width:`${o.progress}%`}})}),i.jsxs("span",{className:"text-white font-medium",children:[Math.round(o.progress),"%"]}),i.jsxs("span",{className:"text-bambu-gray",children:["(",Us(o.remainingMin*60),")"]})]})]})]})]}):null}function aD(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 t0(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",P1S:"P1S",P1P:"P1P",P2S:"P2S",A1:"A1","A1 Mini":"A1 Mini",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[t]||t:""}function AW({ams:t,printerId:e,label:n,amsLabels:r,canEdit:a,onSaved:s,children:o}){const{t:l}=Dt(),[c,u]=w.useState(!1),[d,m]=w.useState("top"),[p,f]=w.useState(""),[y,v]=w.useState(!1),[b,g]=w.useState(null),[_,N]=w.useState(!1),C=w.useRef(null),k=w.useRef(null),P=w.useRef(null);w.useEffect(()=>{c&&(f(r?.[t.id]??""),g(null),requestAnimationFrame(()=>{if(C.current&&k.current){const G=C.current.getBoundingClientRect(),z=G.top-56,Z=window.innerHeight-G.bottom;m(zz?"bottom":"top")}}))},[c,r,t.id]);const T=()=>{P.current&&clearTimeout(P.current),P.current=setTimeout(()=>u(!0),80)},D=()=>{P.current&&clearTimeout(P.current),_||(P.current=setTimeout(()=>u(!1),200))};w.useEffect(()=>()=>{P.current&&clearTimeout(P.current)},[]);const A=async()=>{if(a){v(!0),g(null);try{const G=p.trim();G?await ge.saveAmsLabel(e,t.id,G,t.serial_number):await ge.deleteAmsLabel(e,t.id,t.serial_number),s(),u(!1)}catch(G){g(G instanceof Error?G.message:String(G))}finally{v(!1)}}},R=async()=>{if(a){v(!0),g(null);try{await ge.deleteAmsLabel(e,t.id,t.serial_number),s(),u(!1)}catch(G){g(G instanceof Error?G.message:String(G))}finally{v(!1)}}};return i.jsxs("div",{ref:C,className:"relative inline-block",onMouseEnter:T,onMouseLeave:D,children:[o,c&&i.jsx("div",{ref:k,className:` + `})]})]})}function nVe({slots:t,filamentInfo:e}){const{t:n}=Dt(),r=t.filter(l=>l.id>=2),a=6,s=r.length>0?Math.min(...r.map(l=>l.id)):16,o=Array.from({length:a},(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 i.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:[i.jsx("p",{className:"text-[9px] text-bambu-gray mb-1",children:n("printers.nozzleRack")}),i.jsx("div",{className:"flex gap-[3px] justify-center",children:o.map((l,c)=>{const u=!l.nozzle_diameter&&!l.nozzle_type,d=u?null:R4(l.filament_color),m=d?eie(l.filament_color):!1;return i.jsx(cie,{slot:l,index:c,filamentName:l.filament_id?e?.[l.filament_id]?.name:void 0,children:i.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:i.jsx("span",{className:`text-[10px] font-semibold ${u?"text-bambu-gray/30":m?"text-black/80":"text-white"}`,style:d&&!m?{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 kW({className:t}){return i.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:i.jsx("path",{d:"M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z",fill:"#C3C2C1"})})}function rVe({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z",fill:"#C3C2C1"}),i.jsx("path",{d:"M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z",fill:"#1F8FEB"})]})}function iVe({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z",fill:"#1F8FEB"}),i.jsx("path",{d:"M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z",fill:"#C3C2C1"})]})}function aVe({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"}),i.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function sVe({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function oVe({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function rD({className:t,color:e,isHeating:n}){const a={"text-orange-400":"#fb923c","text-blue-400":"#60a5fa","text-green-400":"#4ade80"}[e]||"#888",s=n?{filter:`drop-shadow(0 0 4px ${a}) drop-shadow(0 0 8px ${a})`}:{};return n?i.jsxs("svg",{className:t,style:s,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:a,rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:a}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:a,strokeWidth:"1",fill:"none"})]}):i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:a,strokeWidth:"1",fill:"none"}),i.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:a,strokeWidth:"1",fill:"none"})]})}function CW({humidity:t,goodThreshold:e=40,fairThreshold:n=60,onClick:r,compact:a}){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=kW:s<=l?d=rVe:d=iVe,i.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:[i.jsx(d,{className:a?"w-2.5 h-3":"w-3 h-4"}),i.jsxs("span",{className:`font-medium tabular-nums ${a?"text-[10px]":"text-xs"}`,style:{color:c},children:[s,"%"]})]})}function TW({temp:t,goodThreshold:e=28,fairThreshold:n=35,onClick:r,compact:a}){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=aVe):t<=o?(l="#d4a017",c="Fair",u=sVe):(l="#c62828",c="Bad",u=oVe),i.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:[i.jsx(u,{className:a?"w-2.5 h-3":"w-3 h-4"}),i.jsxs("span",{className:`tabular-nums text-right ${a?"text-[10px] w-8":"w-12"}`,style:{color:l},children:[t,"°C"]})]})}function Zc(t,e){const n=typeof t=="string"?parseInt(t,10):t,r=isNaN(n)?0:n,a=e===1,s=r>=128?r-128:r,o=String.fromCharCode(65+s);return a?`HT-${o}`:`AMS-${o}`}function iD(t){return t?!!(t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function lVe({url:t,printName:e}){const{t:n}=Dt(),[r,a]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(!1),u=w.useMemo(()=>{if(!t)return null;const d=t.includes("?")?"&":"?";return`${t}${d}v=${encodeURIComponent(e||Date.now().toString())}`},[t,e]);return w.useEffect(()=>{a(!1),o(!1)},[u]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:`w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${u&&r?"cursor-pointer":""}`,onClick:()=>u&&r&&c(!0),children:u&&!s?i.jsxs(i.Fragment,{children:[i.jsx("img",{src:u,alt:n("printers.printPreview"),className:`w-full h-full object-cover ${r?"block":"hidden"}`,onLoad:()=>a(!0),onError:()=>o(!0)}),!r&&i.jsx(ia,{className:"w-8 h-8 text-bambu-gray"})]}):i.jsx(ia,{className:"w-8 h-8 text-bambu-gray"})}),l&&u&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8",onClick:()=>c(!1),children:i.jsxs("div",{className:"relative max-w-2xl max-h-full",children:[i.jsx("img",{src:u,alt:n("printers.printPreview"),className:"max-w-full max-h-[80vh] rounded-lg shadow-2xl"}),e&&i.jsx("p",{className:"text-white text-center mt-4 text-lg",children:e})]})})]})}function cVe({printers:t}){const{t:e}=Dt(),n=sn(),[r,a]=w.useState(0);w.useEffect(()=>{let l=!1;const c=n.getQueryCache().subscribe(()=>{l||(l=!0,requestAnimationFrame(()=>{a(u=>u+1),l=!1}))});return()=>c()},[n]);const{counts:s,nextFinish:o}=w.useMemo(()=>{let l=0,c=0,u=0,d=0,m=0,p=null,f=null,y=0;return t?.forEach(v=>{const b=n.getQueryData(["printerStatus",v.id]);b===void 0?d++:b.connected?(b.hms_errors&&nk(b.hms_errors).length>0&&m++,b.state==="RUNNING"?(l++,b.remaining_time!=null&&b.remaining_time>0&&(f===null||b.remaining_time0?"bg-bambu-green":"bg-gray-500"}`}),i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white font-medium",children:s.idle})," ",e("printers.status.available").toLowerCase()]})]}),s.printing>0&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white font-medium",children:s.printing})," ",e("printers.status.printing").toLowerCase()]})]}),s.offline>0&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-gray-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white font-medium",children:s.offline})," ",e("printers.status.offline").toLowerCase()]})]}),s.problem>0&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-status-error"}),i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white font-medium",children:s.problem})," ",e("printers.status.problem").toLowerCase()]})]}),o&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-px h-4 bg-bambu-dark-tertiary"}),i.jsxs("div",{className:"flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"text-bambu-green font-medium",children:[e("printers.nextAvailable"),":"]}),i.jsx("span",{className:"text-white font-medium",children:o.name})]}),i.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto",children:[i.jsx("div",{className:"w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5",children:i.jsx("div",{className:"bg-bambu-green h-1.5 rounded-full transition-all",style:{width:`${o.progress}%`}})}),i.jsxs("span",{className:"text-white font-medium",children:[Math.round(o.progress),"%"]}),i.jsxs("span",{className:"text-bambu-gray",children:["(",Us(o.remainingMin*60),")"]})]})]})]})]}):null}function aD(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 t0(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",P1S:"P1S",P1P:"P1P",P2S:"P2S",A1:"A1","A1 Mini":"A1 Mini",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[t]||t:""}function AW({ams:t,printerId:e,label:n,amsLabels:r,canEdit:a,onSaved:s,children:o}){const{t:l}=Dt(),[c,u]=w.useState(!1),[d,m]=w.useState("top"),[p,f]=w.useState(""),[y,v]=w.useState(!1),[b,g]=w.useState(null),[_,N]=w.useState(!1),C=w.useRef(null),k=w.useRef(null),P=w.useRef(null);w.useEffect(()=>{c&&(f(r?.[t.id]??""),g(null),requestAnimationFrame(()=>{if(C.current&&k.current){const G=C.current.getBoundingClientRect(),z=G.top-56,Z=window.innerHeight-G.bottom;m(zz?"bottom":"top")}}))},[c,r,t.id]);const T=()=>{P.current&&clearTimeout(P.current),P.current=setTimeout(()=>u(!0),80)},D=()=>{P.current&&clearTimeout(P.current),_||(P.current=setTimeout(()=>u(!1),200))};w.useEffect(()=>()=>{P.current&&clearTimeout(P.current)},[]);const A=async()=>{if(a){v(!0),g(null);try{const G=p.trim();G?await ge.saveAmsLabel(e,t.id,G,t.serial_number):await ge.deleteAmsLabel(e,t.id,t.serial_number),s(),u(!1)}catch(G){g(G instanceof Error?G.message:String(G))}finally{v(!1)}}},R=async()=>{if(a){v(!0),g(null);try{await ge.deleteAmsLabel(e,t.id,t.serial_number),s(),u(!1)}catch(G){g(G instanceof Error?G.message:String(G))}finally{v(!1)}}};return i.jsxs("div",{ref:C,className:"relative inline-block",onMouseEnter:T,onMouseLeave:D,children:[o,c&&i.jsx("div",{ref:k,className:` absolute left-0 z-50 ${d==="top"?"bottom-full mb-2":"top-full mt-2"} animate-in fade-in-0 zoom-in-95 duration-150 @@ -8538,17 +8538,17 @@ ${o("inventory.assignProfileMismatchMessage",{spoolProfile:g.spoolProfile||o("co flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${Gt&&k("printers:control")?Ot?"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:k("printers:control")?g(Ot?"printers.resume":"printers.pause"):g("printers.permission.noControl"),children:[Ot?i.jsx(Co,{className:"w-3 h-3"}):i.jsx(lT,{className:"w-3 h-3"}),g(Ot?"printers.resume":"printers.pause")]})]})]})]})})(),(Ut?.length>0||Qe.vt_tray.length>0)&&r==="expanded"&&(()=>{const ht=Ut.filter(ut=>ut.tray.length>1),Ot=Ut.filter(ut=>ut.tray.length===1),Gt=t.nozzle_count===2||Qe?.temperatures?.nozzle_2!==void 0;return i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:g("printers.filaments")}),i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),i.jsxs("div",{className:"space-y-3",children:[ht.length>0&&i.jsx("div",{className:"grid grid-cols-2 gap-3",children:ht.map(ut=>{const An=Tt[String(ut.id)],gr=ut.id>=128?ut.id-128:ut.id,Jn=An!==void 0?An:gr,Ca=Jn===1,Es=Jn===0;return i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx(AW,{ams:ut,printerId:t.id,label:Zc(ut.id,ut.tray.length),amsLabels:le,canEdit:k("printers:update"),onSaved:Le,children:i.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:le?.[ut.id]||Zc(ut.id,ut.tray.length)})}),Gt&&(Ca||Es)&&i.jsx(NW,{side:Ca?"L":"R"})]}),(ut.humidity!=null||ut.temp!=null)&&i.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[ut.humidity!=null&&i.jsx(CW,{humidity:ut.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>Pe({amsId:ut.id,amsLabel:Zc(ut.id,ut.tray.length),mode:"humidity"}),compact:!0}),ut.temp!=null&&i.jsx(TW,{temp:ut.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>Pe({amsId:ut.id,amsLabel:Zc(ut.id,ut.tray.length),mode:"temperature"}),compact:!0}),Qe.supports_drying&&(ut.module_type==="n3f"||ut.module_type==="n3s")&&k("printers:control")&&i.jsx("button",{disabled:!!(ut.dry_sf_reason?.length&&ut.dry_time===0),onClick:on=>{if(ut.dry_time>0)Fr.mutate(ut.id);else if(xe===ut.id)oe(null);else{const js=(ut.tray.find(ml=>ml.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Ds=b[js]||b.PLA,ul=ut.module_type;ve(js),me(Ds[ul]||Ds.n3f),we(ul==="n3s"?Ds.n3s_hours:Ds.n3f_hours),He(!1),F(ut.module_type),oe(ut.id);const dl=on.currentTarget.getBoundingClientRect();_e({top:dl.bottom+4,left:Math.max(8,dl.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ut.dry_time>0?"bg-amber-500/20 text-amber-400":ut.dry_sf_reason?.length?"bg-bambu-dark-tertiary/30 text-bambu-gray/50 cursor-not-allowed":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:ut.dry_time>0?g("printers.drying.stop"):ut.dry_sf_reason?.length?g("printers.drying.powerRequired"):g("printers.drying.start"),children:i.jsx(qp,{className:"w-3 h-3"})})]})]}),ut.dry_time>0&&i.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px]",children:[i.jsx(qp,{className:"w-3 h-3 text-amber-400 shrink-0"}),i.jsx("span",{className:"text-amber-400 font-medium",children:g("printers.drying.active")}),i.jsx("span",{className:"text-amber-300/70",children:g("printers.drying.timeRemaining",{time:ut.dry_time>=60?`${Math.floor(ut.dry_time/60)}h ${ut.dry_time%60}m`:`${ut.dry_time}m`})}),i.jsx("button",{onClick:()=>Fr.mutate(ut.id),disabled:Fr.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:g("printers.drying.stop"),children:i.jsx(Ht,{className:"w-3 h-3"})})]}),i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(on=>{const Pn=ut.tray[on]||ut.tray.find(Cn=>Cn.id===on),js=Pn?.tray_type&&Pn.remain>=0,Ds=!Pn?.tray_type,ul=ut.id*4+on,dl=Xt===ul,ml=Pn?.tray_info_idx?Ee?.[Pn.tray_info_idx]:null,Bi=ct?.[ul],$a=(Pn?.tray_uuid||Pn?.tag_uid||$p(t.serial_number,ut.id,on))?.toUpperCase(),ic=$a?l?.[$a]:void 0,cs=yN(ic),jo=d?.(t.id,ut.id,on),Uc=(()=>{const Cn=jo?.spool;return Cn&&Cn.label_weight>0&&Cn.weight_used!=null?Math.round(Math.max(0,Cn.label_weight-Cn.weight_used)/Cn.label_weight*100):null})(),ii=Uc===0&&js&&Pn.remain>0?null:Uc,Do=cs??ii??(js?Pn.remain:null),sp=cs!==null?"spoolman":ii!==null?"inventory":js?"ams":void 0,Pr=Pn?.tray_type?{vendor:iD(Pn)?"Bambu Lab":"Generic",profile:Bi?.preset_name||ml?.name||jo?.spool?.slicer_filament_name||Pn.tray_sub_brands||Pn.tray_type,colorName:tD(Pn.tray_id_name)||xN(Pn.tray_color),colorHex:Pn.tray_color||null,kFactor:nD(Pn.k),fillLevel:Do,trayUuid:Pn.tray_uuid||null,tagUid:Pn.tag_uid||null,fillSource:sp}:null,Fu=Ts?.amsId===ut.id&&Ts?.slotId===on,um=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ds?"opacity-50":""} ${dl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx(eD,{trayColor:Pn?.tray_color,trayType:Pn?.tray_type,isEmpty:Ds,slotNumber:on+1}),i.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Pn?.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Do!==null&&Do>=0&&Pn&&i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Do}%`,backgroundColor:ix(Do)}})})]});return i.jsxs("div",{className:"relative group",children:[Fu&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:i.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Qe?.state!=="RUNNING"&&i.jsx("button",{onClick:Cn=>{Cn.stopPropagation(),Eo(so?.amsId===ut.id&&so?.slotId===on?null:{amsId:ut.id,slotId:on})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:i.jsx(Nh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Qe?.state!=="RUNNING"&&so?.amsId===ut.id&&so?.slotId===on&&i.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:i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Cn=>{Cn.stopPropagation(),k("printers:ams_rfid")&&(As.mutate({amsId:ut.id,slotId:on}),Eo(null))},disabled:Fu||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[i.jsx(Sr,{className:`w-3 h-3 ${Fu?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Pr?i.jsx(Qj,{data:Pr,spoolman:{enabled:o,linkedSpoolId:$a?l?.[$a]?.id:void 0,spoolmanUrl:c,syncMode:u,onLinkSpool:o?()=>{const Cn=(Pr.trayUuid||Pr.tagUid||$p(t.serial_number,ut.id,on)).toUpperCase();Ve({tagUid:Pr.tagUid||Cn,trayUuid:Pr.trayUuid||"",printerId:t.id,amsId:ut.id,trayId:on})}:void 0,onUnlinkSpool:ic?.id?()=>fr.mutate(ic.id):void 0},inventory:o?void 0:(()=>{const Cn=d?.(t.id,ut.id,on);return{assignedSpool:Cn?.spool?{id:Cn.spool.id,material:Cn.spool.material,brand:Cn.spool.brand,color_name:Cn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Cn.spool.label_weight-Cn.spool.weight_used))}:null,onAssignSpool:Pr.vendor!=="Bambu Lab"?()=>Ce({printerId:t.id,amsId:ut.id,trayId:on,trayInfo:{type:Pn?.tray_type||Pr.profile,material:Pn?.tray_type??void 0,profile:Pr.profile,color:Pr.colorHex||"",location:`${Zc(ut.id,ut.tray.length)} Slot ${on+1}`}}):void 0,onUnassignSpool:Cn&&Pr.vendor!=="Bambu Lab"?()=>m?.(t.id,ut.id,on):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>nt({amsId:ut.id,trayId:on,trayCount:ut.tray.length,trayType:Pn?.tray_type||void 0,trayColor:Pn?.tray_color||void 0,traySubBrands:Pn?.tray_sub_brands||void 0,trayInfoIdx:Pn?.tray_info_idx||void 0,extruderId:An,caliIdx:Pn?.cali_idx,savedPresetId:Bi?.preset_id})},children:um}):i.jsx(Zj,{children:um})]},on)})})]},ut.id)})}),(Ot.length>0||Qe.vt_tray.length>0)&&i.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ot.map(ut=>{const An=Tt[String(ut.id)],gr=ut.id>=128?ut.id-128:ut.id,Jn=An!==void 0?An:gr,Ca=Jn===1,Es=Jn===0,on=ut.tray[0],Pn=on?.tray_type&&on.remain>=0,js=!on?.tray_type,Ds=Ex(ut.id,on?.id??0,!1),ul=Xt===Ds,dl=on?.tray_info_idx?Ee?.[on.tray_info_idx]:null,ml=ct?.[Ds],Bi=on?.id??0,$a=(on?.tray_uuid||on?.tag_uid||$p(t.serial_number,ut.id,Bi))?.toUpperCase(),ic=$a?l?.[$a]:void 0,cs=yN(ic),jo=d?.(t.id,ut.id,Bi),Uc=(()=>{const Cn=jo?.spool;return Cn&&Cn.label_weight>0&&Cn.weight_used!=null?Math.round(Math.max(0,Cn.label_weight-Cn.weight_used)/Cn.label_weight*100):null})(),ii=Uc===0&&Pn&&on.remain>0?null:Uc,Do=cs??ii??(Pn?on.remain:null),sp=cs!==null?"spoolman":ii!==null?"inventory":Pn?"ams":void 0,Pr=on?.tray_type?{vendor:iD(on)?"Bambu Lab":"Generic",profile:ml?.preset_name||dl?.name||jo?.spool?.slicer_filament_name||on.tray_sub_brands||on.tray_type,colorName:tD(on.tray_id_name)||xN(on.tray_color),colorHex:on.tray_color||null,kFactor:nD(on.k),fillLevel:Do,trayUuid:on.tray_uuid||null,tagUid:on.tag_uid||null,fillSource:sp}:null,Fu=Ts?.amsId===ut.id&&Ts?.slotId===Bi,um=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${js?"opacity-50":""} ${ul?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx(eD,{trayColor:on?.tray_color,trayType:on?.tray_type,isEmpty:js,slotNumber:1}),i.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:on?.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Do!==null&&Do>=0&&i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Do}%`,backgroundColor:ix(Do)}})})]});return i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[i.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[i.jsx(AW,{ams:ut,printerId:t.id,label:Zc(ut.id,ut.tray.length),amsLabels:le,canEdit:k("printers:update"),onSaved:Le,children:i.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:le?.[ut.id]||Zc(ut.id,ut.tray.length)})}),Gt&&(Ca||Es)&&i.jsx(NW,{side:Ca?"L":"R"}),Qe.supports_drying&&(ut.module_type==="n3f"||ut.module_type==="n3s")&&k("printers:control")&&i.jsx("div",{className:"relative ml-auto",children:i.jsx("button",{onClick:Cn=>{if(ut.dry_time>0)Fr.mutate(ut.id);else if(xe===ut.id)oe(null);else{const hy=(ut.tray.find(HA=>HA.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),op=b[hy]||b.PLA,Lu=ut.module_type;ve(hy),me(op[Lu]||op.n3f),we(Lu==="n3s"?op.n3s_hours:op.n3f_hours),He(!1),F(ut.module_type),oe(ut.id);const iS=Cn.currentTarget.getBoundingClientRect();_e({top:iS.bottom+4,left:Math.max(8,iS.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ut.dry_time>0?"bg-amber-500/20 text-amber-400":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:ut.dry_time>0?g("printers.drying.stop"):g("printers.drying.start"),children:i.jsx(qp,{className:"w-3 h-3"})})})]}),ut.dry_time>0&&i.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px] whitespace-nowrap overflow-hidden",children:[i.jsx(qp,{className:"w-3 h-3 text-amber-400 shrink-0"}),i.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:ut.dry_time>=60?`${Math.floor(ut.dry_time/60)}h ${ut.dry_time%60}m`:`${ut.dry_time}m`}),i.jsx("button",{onClick:()=>Fr.mutate(ut.id),disabled:Fr.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:g("printers.drying.stop"),children:i.jsx(Ht,{className:"w-3 h-3"})})]}),i.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[i.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[Fu&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:i.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Qe?.state!=="RUNNING"&&i.jsx("button",{onClick:Cn=>{Cn.stopPropagation(),Eo(so?.amsId===ut.id&&so?.slotId===Bi?null:{amsId:ut.id,slotId:Bi})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:i.jsx(Nh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Qe?.state!=="RUNNING"&&so?.amsId===ut.id&&so?.slotId===Bi&&i.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:i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Cn=>{Cn.stopPropagation(),k("printers:ams_rfid")&&(As.mutate({amsId:ut.id,slotId:Bi}),Eo(null))},disabled:Fu||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[i.jsx(Sr,{className:`w-3 h-3 ${Fu?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Pr?i.jsx(Qj,{data:Pr,spoolman:{enabled:o,linkedSpoolId:$a?l?.[$a]?.id:void 0,spoolmanUrl:c,syncMode:u,onLinkSpool:o?()=>{const Cn=(Pr.trayUuid||Pr.tagUid||$p(t.serial_number,ut.id,Bi)).toUpperCase();Ve({tagUid:Pr.tagUid||Cn,trayUuid:Pr.trayUuid||"",printerId:t.id,amsId:ut.id,trayId:Bi})}:void 0,onUnlinkSpool:ic?.id?()=>fr.mutate(ic.id):void 0},inventory:o?void 0:(()=>{const Cn=d?.(t.id,ut.id,Bi);return{assignedSpool:Cn?.spool?{id:Cn.spool.id,material:Cn.spool.material,brand:Cn.spool.brand,color_name:Cn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Cn.spool.label_weight-Cn.spool.weight_used))}:null,onAssignSpool:Pr.vendor!=="Bambu Lab"?()=>Ce({printerId:t.id,amsId:ut.id,trayId:Bi,trayInfo:{type:on?.tray_type||Pr.profile,material:on?.tray_type??void 0,profile:Pr.profile,color:Pr.colorHex||"",location:Zc(ut.id,ut.tray.length)}}):void 0,onUnassignSpool:Cn&&Pr.vendor!=="Bambu Lab"?()=>m?.(t.id,ut.id,Bi):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>nt({amsId:ut.id,trayId:Bi,trayCount:ut.tray.length,trayType:on?.tray_type||void 0,trayColor:on?.tray_color||void 0,traySubBrands:on?.tray_sub_brands||void 0,trayInfoIdx:on?.tray_info_idx||void 0,extruderId:An,caliIdx:on?.cali_idx,savedPresetId:ml?.preset_id})},children:um}):i.jsx(Zj,{children:um})]}),(ut.humidity!=null||ut.temp!=null)&&i.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[ut.temp!=null&&i.jsx(TW,{temp:ut.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>Pe({amsId:ut.id,amsLabel:Zc(ut.id,ut.tray.length),mode:"temperature"}),compact:!0}),ut.humidity!=null&&i.jsx(CW,{humidity:ut.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>Pe({amsId:ut.id,amsLabel:Zc(ut.id,ut.tray.length),mode:"humidity"}),compact:!0})]})]})]},ut.id)}),Qe.vt_tray.length>0&&i.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${Qe.vt_tray.length===1?"max-w-[50%]":""}`,children:[i.jsx("div",{className:"flex items-center gap-1 mb-2",children:i.jsx("span",{className:"text-[10px] text-white font-medium",children:g("printers.external")})}),i.jsx("div",{className:`grid ${Qe.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...Qe.vt_tray].sort((ut,An)=>(ut.id??254)-(An.id??254)).map(ut=>{const An=ut.id??254,gr=Gt&&Xt===254?An===254&&Qe.active_extruder===1||An===255&&Qe.active_extruder===0:Xt===An,Jn=An-254,Ca=Gt?g(An===254?"printers.extL":"printers.extR"):"",Es=ut.tray_info_idx?Ee?.[ut.tray_info_idx]:null,on=ct?.[1020+Jn],Pn=(ut.tray_uuid||ut.tag_uid||$p(t.serial_number,255,Jn))?.toUpperCase(),js=Pn?l?.[Pn]:void 0,Ds=yN(js),ul=d?.(t.id,255,Jn),dl=(()=>{const ii=ul?.spool;return ii&&ii.label_weight>0&&ii.weight_used!=null?Math.round(Math.max(0,ii.label_weight-ii.weight_used)/ii.label_weight*100):null})(),ml=ut.tray_type&&ut.remain>=0,Bi=dl===0&&ml&&ut.remain>0?null:dl,$a=Ds??Bi??(ml?ut.remain:null),ic=Ds!==null?"spoolman":Bi!==null?"inventory":ml?"ams":void 0,cs={vendor:iD(ut)?"Bambu Lab":"Generic",profile:on?.preset_name||Es?.name||ul?.spool?.slicer_filament_name||ut.tray_sub_brands||ut.tray_type||"Unknown",colorName:tD(ut.tray_id_name)||xN(ut.tray_color),colorHex:ut.tray_color||null,kFactor:nD(ut.k),fillLevel:$a,trayUuid:ut.tray_uuid||null,tagUid:ut.tag_uid||null,fillSource:ic},jo=!ut.tray_type,Uc=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${jo?"opacity-50":""} ${gr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx(eD,{trayColor:ut.tray_color,trayType:ut.tray_type,isEmpty:jo,slotNumber:Jn+1}),i.jsx("div",{className:`text-[9px] font-bold truncate ${jo?"text-white/40":"text-white"}`,children:ut.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:$a!==null&&$a>=0&&!jo&&i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${$a}%`,backgroundColor:ix($a)}})}),Ca&&i.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:Ca})]});return i.jsx("div",{className:"relative group",children:jo?i.jsx(Zj,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>nt({amsId:255,trayId:Jn,trayCount:1,extruderId:Gt?An===254?1:0:void 0})},inventory:o?void 0:{onAssignSpool:()=>Ce({printerId:t.id,amsId:255,trayId:Jn,trayInfo:{type:"",color:"",location:Ca||g("printers.external")}})},children:Uc}):i.jsx(Qj,{data:cs,spoolman:{enabled:o,linkedSpoolId:Pn?l?.[Pn]?.id:void 0,spoolmanUrl:c,syncMode:u,onLinkSpool:o?()=>{const ii=(cs.trayUuid||cs.tagUid||$p(t.serial_number,255,Jn)).toUpperCase();Ve({tagUid:cs.tagUid||ii,trayUuid:cs.trayUuid||"",printerId:t.id,amsId:255,trayId:Jn})}:void 0,onUnlinkSpool:js?.id?()=>fr.mutate(js.id):void 0},inventory:o?void 0:(()=>{const ii=d?.(t.id,255,Jn);return{assignedSpool:ii?.spool?{id:ii.spool.id,material:ii.spool.material,brand:ii.spool.brand,color_name:ii.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(ii.spool.label_weight-ii.spool.weight_used))}:null,onAssignSpool:()=>Ce({printerId:t.id,amsId:255,trayId:Jn,trayInfo:{type:ut.tray_type||cs.profile,material:ut.tray_type??void 0,profile:cs.profile,color:cs.colorHex||"",location:Ca||g("printers.external")}}),onUnassignSpool:ii?()=>m?.(t.id,255,Jn):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>nt({amsId:255,trayId:Jn,trayCount:1,trayType:ut.tray_type||void 0,trayColor:ut.tray_color||void 0,traySubBrands:ut.tray_sub_brands||void 0,trayInfoIdx:ut.tray_info_idx||void 0,extruderId:Gt?An===254?1:0:void 0,caliIdx:ut.cali_idx,savedPresetId:on?.preset_id})},children:Uc})},An)})})]})]})]})]})})()]}),tn&&r==="expanded"&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsx(Pc,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"text-sm text-white truncate",children:tn.name}),kn&&i.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${kn.state==="ON"?"bg-bambu-green/20 text-bambu-green":kn.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[kn.state||"?",kn.state==="ON"&&kn.energy?.power!=null&&i.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",kn.energy.power,"W"]})]})]}),i.jsx("div",{className:"flex-1"}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("button",{onClick:()=>de(!0),disabled:Ua.isPending||kn?.state==="ON"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?kn?.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:k("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[i.jsx(em,{className:"w-3 h-3"}),"On"]}),i.jsxs("button",{onClick:()=>V(!0),disabled:Ua.isPending||kn?.state==="OFF"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?kn?.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:k("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[i.jsx(cT,{className:"w-3 h-3"}),"Off"]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx("span",{className:`text-xs hidden sm:inline ${tn.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:tn.auto_off_executed?"Auto-off done":"Auto-off"}),i.jsx("button",{onClick:()=>ap.mutate(!tn.auto_off),disabled:ap.isPending||tn.auto_off_executed||!k("smart_plugs:control"),title:k("smart_plugs:control")?tn.auto_off_executed?g("printers.autoOffExecuted"):g("printers.autoOffAfterPrint"):g("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${k("smart_plugs:control")?tn.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":tn.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:i.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${tn.auto_off||tn.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),wn&&wn.length>0&&i.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[i.jsx(vw,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:wn.map(ht=>{const Ot=ht.ha_entity_id?.startsWith("script.");return i.jsxs("button",{onClick:()=>Ui.mutate({id:ht.id,action:Ot?"on":"toggle"}),disabled:Ui.isPending,title:`${Ot?"Run":"Toggle"} ${ht.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:[i.jsx(Co,{className:"w-2.5 h-2.5"}),ht.name]},ht.id)})})]})]}),r==="expanded"&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>Du.mutate(!Qe?.chamber_light),disabled:!Qe?.connected||Du.isPending||!k("printers:control"),title:k("printers:control")?Qe?.chamber_light?g("printers.chamberLightOff"):g("printers.chamberLightOn"):g("printers.permission.noControl"),className:Qe?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:i.jsx(PO,{on:Qe?.chamber_light??!1,className:`w-4 h-4 ${Qe?.chamber_light?"text-yellow-400":""}`})}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>{if(f==="embedded"&&y)y(t.id,t.name);else{const ht=localStorage.getItem("cameraWindowState"),Ot=ht?JSON.parse(ht):{width:640,height:400},Gt=[`width=${Ot.width}`,`height=${Ot.height}`,Ot.left!==void 0?`left=${Ot.left}`:"",Ot.top!==void 0?`top=${Ot.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,Gt)}},disabled:!Qe?.connected||!k("camera:view"),title:k("camera:view")?g(f==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):g("printers.permission.noCamera"),children:i.jsx(QL,{className:"w-4 h-4"})}),i.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[i.jsx(ze,{variant:"secondary",size:"sm",onClick:Ic,disabled:!Qe?.connected||ll.isPending||!k("printers:update"),title:k("printers:update")?t.plate_detection_enabled?g("printers.plateDetection.enabledClick"):g("printers.plateDetection.disabledClick"):g("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:ll.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(BN,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:rc,disabled:!Qe?.connected||Nt||!k("printers:update"),title:k("printers:update")?g("printers.plateDetection.manageCalibration"):g("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Nt?i.jsx(ft,{className:"w-3 h-3 animate-spin"}):i.jsx(In,{className:"w-3 h-3"})})]}),i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>J(!0),disabled:!dt||!k("printers:files"),title:k("printers:files")?g("printers.browseFiles"):g("printers.permission.noFiles"),children:[i.jsx(Vx,{className:"w-4 h-4"}),g("printers.files")]}),dt&&Qe?.state!=="RUNNING"&&Qe?.state!=="PAUSE"&&i.jsxs(ze,{size:"sm",onClick:()=>$(!0),disabled:!k("printers:control"),title:k("printers:control")?g("common.print"):g("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[i.jsx(_r,{className:"w-4 h-4"}),g("common.print")]})]})]}),I&&i.jsx(cMe,{printerId:t.id,printerName:t.name,onClose:()=>J(!1)}),O&&i.jsx(nie,{folderId:null,onClose:()=>$(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:ht=>{const Ot=ht.name.toLowerCase();if(!Ot.endsWith(".gcode")&&!Ot.includes(".gcode."))return g("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:ht=>{const Ot=ht.metadata?.sliced_for_model,Gt=t0(t.model);if(Ot&&Gt&&Ot.toLowerCase()!==Gt.toLowerCase())return ge.deleteLibraryFile(ht.id).catch(()=>{}),g("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:Ot,printerModel:Gt});be({id:ht.id,filename:ht.filename})}}),ce&&i.jsx(xu,{mode:"reprint",libraryFileId:ce.id,archiveName:ce.filename,initialSelectedPrinterIds:[t.id],onClose:()=>be(null),onSuccess:()=>be(null)}),ae&&i.jsx(fMe,{printerId:t.id,printerName:t.name,onClose:()=>Y(!1)}),ee&&i.jsx(Zqe,{printer:t,status:Qe,totalPrintHours:n?.total_print_hours,onClose:ie}),mt&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>ao(),children:i.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:ht=>ht.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[mt.needs_calibration?i.jsx(BN,{className:"w-5 h-5 text-blue-500"}):mt.is_empty?i.jsx(pr,{className:"w-5 h-5 text-green-500"}):i.jsx(Vi,{className:"w-5 h-5 text-yellow-500"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),mt.reference_count!==void 0&&mt.max_references&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[mt.reference_count,"/",mt.max_references," refs"]})]}),i.jsx("button",{onClick:()=>ao(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[mt.needs_calibration?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[i.jsx("p",{className:"font-medium text-blue-400",children:g("printers.plateDetection.calibrationRequired")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationInstructions")}})]}),i.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[i.jsx("p",{children:g("printers.plateDetection.calibrationDescription")}),i.jsx("p",{dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationTip")}})]})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`p-3 rounded-lg ${mt.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[i.jsx("p",{className:`font-medium ${mt.is_empty?"text-green-400":"text-yellow-400"}`,children:mt.is_empty?g("printers.plateDetection.plateEmpty"):g("printers.plateDetection.objectsDetected")}),i.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[g("printers.plateDetection.confidence"),": ",Math.round(mt.confidence*100),"% | ",g("printers.plateDetection.difference"),": ",mt.difference_percent.toFixed(1),"%"]})]}),mt.debug_image_url&&i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:g("printers.plateDetection.analysisPreview")}),i.jsx("img",{src:mt.debug_image_url,alt:g("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:g("printers.plateDetection.analysisLegend")})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:mt.message})]}),Ps&&Ps.references.length>0&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-sm font-medium text-white mb-2",children:g("printers.plateDetection.savedReferences",{count:Ps.references.length,max:Ps.max_references})}),i.jsx("div",{className:"grid grid-cols-5 gap-2",children:Ps.references.map(ht=>i.jsxs("div",{className:"relative group",children:[i.jsx("img",{src:ge.getPlateReferenceThumbnailUrl(t.id,ht.index),alt:ht.label||`Reference ${ht.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),i.jsx("button",{onClick:()=>un(ht.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:g("printers.plateDetection.deleteReference"),children:i.jsx(Ht,{className:"w-3 h-3 text-white"})}),ka?.index===ht.index?i.jsx("input",{type:"text",value:ka.label,onChange:Ot=>cl({...ka,label:Ot.target.value}),onBlur:()=>Xi(ht.index,ka.label),onKeyDown:Ot=>{Ot.key==="Enter"&&Xi(ht.index,ka.label),Ot.key==="Escape"&&cl(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:g("printers.plateDetection.labelPlaceholder")}):i.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>cl({index:ht.index,label:ht.label}),title:ht.label?g("printers.plateDetection.clickToEdit",{label:ht.label}):g("printers.plateDetection.clickToAddLabel"),children:ht.label||i.jsx("span",{className:"italic opacity-50",children:g("printers.noLabel")})}),i.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:ht.timestamp?Qn(ht.timestamp)?.toLocaleDateString()??"":""})]},ht.index))})]}),!mt.needs_calibration&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:g("printers.roi.title")}),qt?i.jsxs("div",{className:"flex gap-1",children:[i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>Kt(null),disabled:Qt,children:g("common.cancel")}),i.jsx(ze,{size:"sm",onClick:lm,disabled:Qt,children:Qt?i.jsx(ft,{className:"w-3 h-3 animate-spin"}):g("common.save")})]}):i.jsxs(ze,{variant:"ghost",size:"sm",onClick:()=>Kt(mt.roi||{x:.15,y:.35,w:.7,h:.55}),children:[i.jsx(Yi,{className:"w-3 h-3 mr-1"}),g("common.edit")]})]}),qt?i.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.xStart")}),i.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:qt.x,onChange:ht=>Kt({...qt,x:parseFloat(ht.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(qt.x*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.yStart")}),i.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:qt.y,onChange:ht=>Kt({...qt,y:parseFloat(ht.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(qt.y*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.width")}),i.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:qt.w,onChange:ht=>Kt({...qt,w:parseFloat(ht.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(qt.w*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.height")}),i.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:qt.h,onChange:ht=>Kt({...qt,h:parseFloat(ht.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(qt.h*100),"%"]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:g("printers.roi.instruction")})]}):i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((mt.roi?.x||.15)*100),"%, Y=",Math.round((mt.roi?.y||.35)*100),"%, W=",Math.round((mt.roi?.w||.7)*100),"%, H=",Math.round((mt.roi?.h||.55)*100),"%"]})]})]}),i.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:mt.needs_calibration?i.jsxs(i.Fragment,{children:[i.jsx(ze,{variant:"ghost",onClick:()=>ao(),children:g("common.cancel")}),i.jsx(ze,{onClick:()=>om(),disabled:rt,children:rt?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):i.jsxs(i.Fragment,{children:[i.jsx(ze,{variant:"ghost",onClick:()=>om(),disabled:rt,children:rt?"Adding...":`Add Reference (${Ps?.references.length||0}/${Ps?.max_references||5})`}),i.jsx(ze,{onClick:()=>ao(),children:"Close"})]})})]})}),ue&&tn&&i.jsx(Nn,{title:g("printers.confirm.powerOnTitle"),message:g("printers.confirm.powerOnMessage",{name:t.name}),confirmText:g("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Ua.mutate("on"),de(!1)},onCancel:()=>de(!1)}),he&&tn&&i.jsx(Nn,{title:g("printers.confirm.powerOffTitle"),message:Qe?.state==="RUNNING"?g("printers.confirm.powerOffWarning",{name:t.name}):g("printers.confirm.powerOffMessage",{name:t.name}),confirmText:g("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Ua.mutate("off"),V(!1)},onCancel:()=>V(!1)}),pe&&i.jsx(Nn,{title:g("printers.confirm.stopTitle"),message:g("printers.confirm.stopMessage",{name:t.name}),confirmText:g("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{ju.mutate(),Te(!1)},onCancel:()=>Te(!1)}),q&&i.jsx(Nn,{title:g("printers.confirm.pauseTitle"),message:g("printers.confirm.pauseMessage",{name:t.name}),confirmText:g("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{cg.mutate(),X(!1)},onCancel:()=>X(!1)}),U&&i.jsx(Nn,{title:g("printers.confirm.resumeTitle"),message:g("printers.confirm.resumeMessage",{name:t.name}),confirmText:g("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{tc.mutate(),K(!1)},onCancel:()=>K(!1)}),i.jsx(MO,{printerId:t.id,isOpen:H,onClose:()=>re(!1)}),ne&&i.jsx(xMe,{printerName:t.name,errors:Qe?.hms_errors||[],onClose:()=>se(!1),printerId:t.id,hasPermission:k}),We&&i.jsx(Aqe,{isOpen:!!We,onClose:()=>Pe(null),printerId:t.id,printerName:t.name,amsId:We.amsId,amsLabel:We.amsLabel,initialMode:We.mode,thresholds:s}),Ke&&i.jsx(Pqe,{isOpen:!!Ke,onClose:()=>Ve(null),tagUid:Ke.tagUid,trayUuid:Ke.trayUuid,printerId:Ke.printerId,amsId:Ke.amsId,trayId:Ke.trayId}),ke&&i.jsx(Mqe,{isOpen:!!ke,onClose:()=>Ce(null),printerId:ke.printerId,amsId:ke.amsId,trayId:ke.trayId,trayInfo:ke.trayInfo}),$e&&i.jsx(tie,{isOpen:!!$e,onClose:()=>nt(null),printerId:t.id,slotInfo:$e,printerModel:t0(t.model)||void 0,onSuccess:()=>{_.invalidateQueries({queryKey:["slotPresets",t.id]}),_.invalidateQueries({queryKey:["printerStatus",t.id]})}}),z&&i.jsx(mVe,{printer:t,onClose:()=>Z(!1)}),xt&&De&&i.jsx(dVe,{printer:t,firmwareInfo:De,onClose:()=>vt(!1)}),so&&i.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Eo(null)}),xe!==null&&Oe&&(()=>{const ht=L==="n3s"?85:65,Ot=35,Gt=ht+10;return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>oe(null)}),i.jsxs("div",{className:"fixed z-[101] w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden",style:{top:Oe.top,left:Oe.left},onClick:ut=>ut.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[i.jsx(qp,{className:"w-3.5 h-3.5 text-amber-400"}),i.jsx("span",{className:"text-xs text-white font-medium",children:g("printers.drying.start")})]}),i.jsxs("div",{className:"px-3 py-2.5 space-y-2.5",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:g("printers.filaments")}),i.jsx("select",{value:te,onChange:ut=>{const An=ut.target.value;ve(An);const gr=b[An];gr&&(me(gr[L==="n3s"?"n3s":"n3f"]),we(L==="n3s"?gr.n3s_hours:gr.n3f_hours))},className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs focus:outline-none focus:border-amber-500/50",children:Object.keys(b).map(ut=>i.jsx("option",{value:ut,children:ut},ut))})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-1",children:[i.jsx("label",{className:"text-[10px] text-bambu-gray",children:g("printers.drying.temperature")}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("input",{type:"number",min:45,max:ht,value:fe,onChange:ut=>me(Math.min(ht,Math.max(45,Number(ut.target.value)||45))),className:"w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),i.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),i.jsx("input",{type:"range",min:Ot,max:Gt,value:fe,onChange:ut=>me(Math.min(ht,Math.max(45,Number(ut.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),i.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[i.jsx("span",{children:"45°C"}),i.jsxs("span",{children:[ht,"°C"]})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-1",children:[i.jsx("label",{className:"text-[10px] text-bambu-gray",children:g("printers.drying.duration")}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("input",{type:"number",min:1,max:24,value:je,onChange:ut=>we(Math.min(24,Math.max(1,Number(ut.target.value)||1))),className:"w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),i.jsx("span",{className:"text-[10px] text-bambu-gray",children:g("printers.drying.hours")})]})]}),i.jsx("input",{type:"range",min:1,max:24,value:je,onChange:ut=>we(Number(ut.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),i.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[i.jsx("span",{children:"1h"}),i.jsx("span",{children:"24h"})]})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:Fe,onChange:ut=>He(ut.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),i.jsx("span",{className:"text-[11px] text-bambu-gray",children:g("printers.drying.rotateTray")})]})]}),i.jsx("div",{className:"px-3 pb-3",children:i.jsx("button",{onClick:()=>{xe!==null&&bi.mutate({amsId:xe,temp:fe,duration:je,filament:te,rotateTray:Fe})},disabled:bi.isPending,className:"w-full py-1.5 bg-amber-500 hover:bg-amber-400 text-white text-xs font-medium rounded-lg transition-colors disabled:opacity-50",children:bi.isPending?g("printers.drying.startingDrying"):g("printers.drying.start")})})]})]})})()]})}function uVe({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Dt(),[a,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,u]=w.useState([]),[d,m]=w.useState(""),[p,f]=w.useState(!1),[y,v]=w.useState(!1),[b,g]=w.useState([]),[_,N]=w.useState(""),[C,k]=w.useState({scanned:0,total:0});w.useEffect(()=>{Vc.getInfo().then(A=>{v(A.is_docker),A.subnets.length>0&&(g(A.subnets),N(A.subnets[0]))}).catch(()=>{})},[]);const P=c.filter(A=>!n.includes(A.serial)),T=async()=>{m(""),u([]),l(!0),f(!1),k({scanned:0,total:0});try{if(y){await Vc.startSubnetScan(_);const A=setInterval(async()=>{try{const R=await Vc.getScanStatus();k({scanned:R.scanned,total:R.total});const G=await Vc.getDiscoveredPrinters();u(G),R.running||(clearInterval(A),l(!1),f(!0))}catch(R){console.error("Failed to get scan status:",R)}},500)}else{await Vc.startDiscovery(10);const A=setInterval(async()=>{try{const R=await Vc.getDiscoveredPrinters();u(R)}catch(R){console.error("Failed to get discovered printers:",R)}},1e3);setTimeout(async()=>{clearInterval(A);try{await Vc.stopDiscovery()}catch{}l(!1),f(!0);try{const R=await Vc.getDiscoveredPrinters();u(R)}catch(R){console.error("Failed to get final discovered printers:",R)}},1e4)}}catch(A){console.error("Failed to start discovery:",A),m(A instanceof Error?A.message:r("printers.discovery.failedToStart")),l(!1),f(!0)}},D=A=>{const R=A.serial.startsWith("unknown-")?"":A.serial;s({...a,name:A.name||"",serial_number:R,ip_address:A.ip_address,model:t0(A.model)}),u([])};return w.useEffect(()=>()=>{Vc.stopDiscovery().catch(()=>{}),Vc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const A=R=>{R.key==="Escape"&&t()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:i.jsx(Pt,{className:"w-full max-w-md",onClick:A=>A.stopPropagation(),children:i.jsxs(Et,{children:[i.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),i.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[y&&i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),b.length>0?i.jsx("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:A=>N(A.target.value),disabled:o,children:b.map(A=>i.jsx("option",{value:A,children:A},A))}):i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:A=>N(A.target.value),placeholder:"192.168.1.0/24",disabled:o}),i.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),i.jsx(ze,{type:"button",variant:"secondary",onClick:T,disabled:o,className:"w-full",children:o?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),y&&C.total>0?r("printers.discovery.scanProgress",{scanned:C.scanned,total:C.total}):r("printers.discovery.scanning")]}):i.jsxs(i.Fragment,{children:[i.jsx(Rr,{className:"w-4 h-4"}),r(y?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),d&&i.jsx("div",{className:"mt-2 text-sm text-red-400",children:d}),P.length>0&&i.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:P.map(A=>i.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:()=>D(A),children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"font-medium text-white text-sm truncate",children:A.name||A.serial}),i.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[t0(A.model)||r("printers.discovery.unknown")," • ",A.ip_address,A.serial.startsWith("unknown-")&&i.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),i.jsx(In,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},A.serial))}),o&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(y?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(y?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&P.length===0&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),i.jsxs("form",{onSubmit:A=>{A.preventDefault(),e(a)},className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),i.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:a.name,onChange:A=>s({...a,name:A.target.value}),placeholder:r("printers.modal.myPrinter")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),i.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:a.ip_address,onChange:A=>s({...a,ip_address:A.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),i.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:a.serial_number,onChange:A=>s({...a,serial_number:A.target.value}),placeholder:"01P00A000000000"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),i.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:a.access_code,onChange:A=>s({...a,access_code:A.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),i.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:a.model||"",onChange:A=>s({...a,model:A.target.value}),children:[i.jsx("option",{value:"",children:r("printers.modal.selectModel")}),i.jsxs("optgroup",{label:"H2 Series",children:[i.jsx("option",{value:"H2C",children:"H2C"}),i.jsx("option",{value:"H2D",children:"H2D"}),i.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),i.jsx("option",{value:"H2S",children:"H2S"})]}),i.jsxs("optgroup",{label:"X1 Series",children:[i.jsx("option",{value:"X1E",children:"X1E"}),i.jsx("option",{value:"X1C",children:"X1 Carbon"}),i.jsx("option",{value:"X1",children:"X1"})]}),i.jsxs("optgroup",{label:"P Series",children:[i.jsx("option",{value:"P2S",children:"P2S"}),i.jsx("option",{value:"P1S",children:"P1S"}),i.jsx("option",{value:"P1P",children:"P1P"})]}),i.jsxs("optgroup",{label:"A1 Series",children:[i.jsx("option",{value:"A1",children:"A1"}),i.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),i.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:a.location||"",onChange:A=>s({...a,location:A.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"auto_archive",checked:a.auto_archive,onChange:A=>s({...a,auto_archive:A.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),i.jsxs("div",{className:"flex gap-3 pt-4",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsx(ze,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function dVe({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Dt(),a=sn(),{showToast:s}=bn(),{hasPermission:o}=Ar(),l=o("firmware:update"),[c,u]=w.useState(null),[d,m]=w.useState(!1),[p,f]=w.useState(null),{data:y,isLoading:v}=et({queryKey:["firmwarePrepare",t.id],queryFn:()=>nN.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),b=gt({mutationFn:()=>nN.startUpload(t.id),onSuccess:()=>{m(!0);const _=setInterval(async()=>{try{const N=await nN.getUploadStatus(t.id);u(N),(N.status==="complete"||N.status==="error")&&(clearInterval(_),f(null),m(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),a.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(_)},onError:_=>{s(r("printers.firmwareModal.uploadFailed",{error:_.message}),"error"),m(!1)}});w.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const g=()=>{u(null),b.mutate()};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:i.jsx(Pt,{className:"w-full max-w-md mx-4",children:i.jsxs(Et,{children:[i.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[i.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?i.jsx(fi,{className:"w-5 h-5 text-orange-400"}):i.jsx(pr,{className:"w-5 h-5 text-status-ok"})}),i.jsxs("div",{className:"flex-1",children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[i.jsxs("div",{className:"flex justify-between items-center text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),i.jsx("span",{className:`font-mono ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&i.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[i.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),i.jsx("span",{className:"text-orange-400 font-mono",children:e.latest_version})]}),e.release_notes&&i.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[i.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),i.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:e.release_notes})]})]}),e.update_available?v?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):y&&!d&&!c?i.jsx("div",{className:"mb-4",children:y.can_proceed?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[i.jsx(ia,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):i.jsx("div",{className:"space-y-1",children:y.errors.map((_,N)=>i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(Li,{className:"w-4 h-4 flex-shrink-0"}),_]},N))})}):null:null,(d||c)&&c&&i.jsxs("div",{className:"mb-4",children:[i.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),i.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),i.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:i.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}%`}})}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&i.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[i.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),i.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),i.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),i.jsxs("div",{className:"flex gap-2 justify-end",children:[i.jsx(ze,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),y?.can_proceed&&!d&&c?.status!=="complete"&&l&&i.jsx(ze,{onClick:g,disabled:b.isPending,children:b.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):i.jsxs(i.Fragment,{children:[i.jsx(fi,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function mVe({printer:t,onClose:e}){const{t:n}=Dt(),r=sn(),{showToast:a}=bn(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=gt({mutationFn:u=>ge.updatePrinter(t.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:u=>a(u.message||n("printers.toast.failedToUpdate"),"error")});w.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 i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:i.jsx(Pt,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:i.jsxs(Et,{children:[i.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),i.jsxs("form",{onSubmit:c,className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),i.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")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),i.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),i.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}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),i.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")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),i.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:[i.jsx("option",{value:"",children:n("printers.modal.selectModel")}),i.jsxs("optgroup",{label:"H2 Series",children:[i.jsx("option",{value:"H2C",children:"H2C"}),i.jsx("option",{value:"H2D",children:"H2D"}),i.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),i.jsx("option",{value:"H2S",children:"H2S"})]}),i.jsxs("optgroup",{label:"X1 Series",children:[i.jsx("option",{value:"X1E",children:"X1E"}),i.jsx("option",{value:"X1C",children:"X1 Carbon"}),i.jsx("option",{value:"X1",children:"X1"})]}),i.jsxs("optgroup",{label:"P Series",children:[i.jsx("option",{value:"P2S",children:"P2S"}),i.jsx("option",{value:"P1S",children:"P1S"}),i.jsx("option",{value:"P1P",children:"P1P"})]}),i.jsxs("optgroup",{label:"A1 Series",children:[i.jsx("option",{value:"A1",children:"A1"}),i.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),i.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")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.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"}),i.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),i.jsxs("div",{className:"flex gap-3 pt-4",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),i.jsx(ze,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function hVe(t){const{data:e}=et({queryKey:["printerStatus",t],queryFn:()=>ge.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function pVe({printer:t,plug:e,onPowerOn:n,isPowering:r}){const a=hVe(t.id),{data:s}=et({queryKey:["smartPlugStatus",e.id],queryFn:()=>ge.getSmartPlugStatus(e.id),refetchInterval:1e4});return a?i.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&i.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||"?"})]}),i.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:[i.jsx(em,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function fVe(){const{t}=Dt(),[e,n]=w.useState(!1),[r,a]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[u,d]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,y]=w.useState(()=>{const re=localStorage.getItem("printerCardSize");return re?parseInt(re,10):2}),v=f===1?"compact":"expanded",b=sn(),{showToast:g}=bn(),{hasPermission:_}=Ar(),[N,C]=w.useState(()=>{const re=localStorage.getItem("openEmbeddedCameras");if(re)try{const O=JSON.parse(re);return new Map(O.map($=>[$.id,$]))}catch{return new Map}return new Map});w.useEffect(()=>{const re=Array.from(N.values());re.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(re)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:k,isLoading:P}=et({queryKey:["printers"],queryFn:ge.getPrinters}),{data:T}=et({queryKey:["settings"],queryFn:ge.getSettings}),D=w.useMemo(()=>{if(T?.drying_presets)try{const re=JSON.parse(T.drying_presets);if(typeof re=="object"&&re!==null&&Object.keys(re).length>0)return{...OF,...re}}catch{}return OF},[T?.drying_presets]);w.useEffect(()=>{T?.camera_view_mode==="window"&&N.size>0&&C(new Map)},[T?.camera_view_mode,N.size]);const{data:A}=et({queryKey:["smart-plugs"],queryFn:ge.getSmartPlugs}),{data:R}=et({queryKey:["maintenanceOverview"],queryFn:ge.getMaintenanceOverview,staleTime:60*1e3}),{data:G}=et({queryKey:["spoolman-status"],queryFn:ge.getSpoolmanStatus,staleTime:60*1e3}),z=G?.enabled&&G?.connected,{data:Z}=et({queryKey:["spoolman-settings"],queryFn:ge.getSpoolmanSettings,enabled:!!z,staleTime:60*1e3}),I=Z?.spoolman_sync_mode,{data:J}=et({queryKey:["unlinked-spools"],queryFn:ge.getUnlinkedSpools,enabled:!!z,staleTime:30*1e3}),ae=J&&J.length>0,{data:Y}=et({queryKey:["linked-spools"],queryFn:ge.getLinkedSpools,enabled:!!z,staleTime:30*1e3}),ue=Y?.linked,{data:de}=et({queryKey:["spool-assignments"],queryFn:()=>ge.getAssignments(),enabled:_("inventory:view_assignments"),staleTime:30*1e3}),he=gt({mutationFn:({printerId:re,amsId:O,trayId:$})=>ge.unassignSpool(re,O,$),onSuccess:()=>{b.invalidateQueries({queryKey:["spool-assignments"]})}}),V=(re,O,$)=>de?.find(ee=>ee.printer_id===re&&ee.ams_id===Number(O)&&ee.tray_id===Number($)),ne=R?.reduce((re,O)=>(re[O.printer_id]={due_count:O.due_count,warning_count:O.warning_count,total_print_hours:O.total_print_hours},re),{})||{},se=A?.reduce((re,O)=>(O.printer_id&&(re[O.printer_id]=O),re),{})||{},pe=gt({mutationFn:ge.createPrinter,onSuccess:()=>{b.invalidateQueries({queryKey:["printers"]}),b.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:re=>g(re.message||t("printers.toast.failedToAdd"),"error")}),Te=gt({mutationFn:re=>ge.controlSmartPlug(re,"on"),onSuccess:()=>{b.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),q=()=>{const re=!r;a(re),localStorage.setItem("hideDisconnectedPrinters",String(re))},X=re=>{d(re),localStorage.setItem("printerSortBy",re)},j=()=>{const re=!m;p(re),localStorage.setItem("printerSortAsc",String(re))},E=()=>{switch(f){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"}},U=["S","M","L","XL"],K=w.useMemo(()=>{if(!k)return[];const re=[...k];switch(u){case"name":re.sort((O,$)=>O.name.localeCompare($.name));break;case"model":re.sort((O,$)=>(O.model||"").localeCompare($.model||""));break;case"location":re.sort((O,$)=>{const ee=O.location||"",W=$.location||"";return!ee&&W?1:ee&&!W?-1:ee.localeCompare(W)||O.name.localeCompare($.name)});break;case"status":re.sort((O,$)=>{const ee=b.getQueryData(["printerStatus",O.id]),W=b.getQueryData(["printerStatus",$.id]),ie=ce=>ce?.connected?(ce.hms_errors?nk(ce.hms_errors):[]).length>0?0:ce.state==="RUNNING"?1:2:3;return ie(ee)-ie(W)});break}return m||re.reverse(),re},[k,u,m,b]),H=w.useMemo(()=>{if(u!=="location")return null;const re={};return K.forEach(O=>{const $=O.location||"Ungrouped";re[$]||(re[$]=[]),re[$].push(O)}),re},[u,K]);return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),i.jsx(cVe,{printers:k})]}),i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("select",{value:u,onChange:re=>X(re.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:[i.jsx("option",{value:"name",children:t("printers.sort.name")}),i.jsx("option",{value:"status",children:t("printers.sort.status")}),i.jsx("option",{value:"model",children:t("printers.sort.model")}),i.jsx("option",{value:"location",children:t("printers.sort.location")})]}),i.jsx("button",{onClick:j,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?i.jsx(Af,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(cx,{className:"w-4 h-4 text-bambu-gray"})})]}),i.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:U.map((re,O)=>{const $=O+1,ee=f===$;return i.jsx("button",{onClick:()=>{y($),localStorage.setItem("printerCardSize",String($))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${O===0?"rounded-l-lg":""} ${O===U.length-1?"rounded-r-lg":""} ${ee?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(re==="S"?"printers.cardSize.small":re==="M"?"printers.cardSize.medium":re==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:re},re)})}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:r,onChange:q,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(se).length>0&&i.jsxs("div",{className:"relative",children:[i.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:[i.jsx(em,{className:"w-4 h-4"}),t("printers.powerOn"),i.jsx(In,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),i.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:[i.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),k?.filter(re=>se[re.id]).map(re=>i.jsx(pVe,{printer:re,plug:se[re.id],onPowerOn:O=>{c(O),Te.mutate(O)},isPowering:l===se[re.id]?.id},re.id)),k?.filter(re=>se[re.id]).length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),i.jsxs(ze,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[i.jsx(ir,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),P?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):k?.length===0?i.jsx(Pt,{children:i.jsxs(Et,{className:"text-center py-12",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),i.jsxs(ze,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[i.jsx(ir,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):H?i.jsx("div",{className:"space-y-6",children:Object.entries(H).map(([re,O])=>i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),re,i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",O.length,")"]})]}),i.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${E()}`,children:O.map($=>i.jsx(PW,{printer:$,hideIfDisconnected:r,maintenanceInfo:ne[$.id],viewMode:v,cardSize:f,amsThresholds:T?{humidityGood:Number(T.ams_humidity_good)||40,humidityFair:Number(T.ams_humidity_fair)||60,tempGood:Number(T.ams_temp_good)||28,tempFair:Number(T.ams_temp_fair)||35}:void 0,spoolmanEnabled:z,hasUnlinkedSpools:ae,linkedSpools:ue,spoolmanUrl:G?.url,spoolmanSyncMode:I,onGetAssignment:V,onUnassignSpool:(ee,W,ie)=>he.mutate({printerId:ee,amsId:W,trayId:ie}),timeFormat:T?.time_format||"system",cameraViewMode:T?.camera_view_mode||"window",onOpenEmbeddedCamera:(ee,W)=>C(ie=>new Map(ie).set(ee,{id:ee,name:W})),checkPrinterFirmware:T?.check_printer_firmware!==!1,dryingPresets:D},$.id))})]},re))}):i.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${E()}`,children:K.map(re=>i.jsx(PW,{printer:re,hideIfDisconnected:r,maintenanceInfo:ne[re.id],viewMode:v,cardSize:f,spoolmanEnabled:z,hasUnlinkedSpools:ae,linkedSpools:ue,spoolmanUrl:G?.url,spoolmanSyncMode:I,onGetAssignment:V,onUnassignSpool:(O,$,ee)=>he.mutate({printerId:O,amsId:$,trayId:ee}),amsThresholds:T?{humidityGood:Number(T.ams_humidity_good)||40,humidityFair:Number(T.ams_humidity_fair)||60,tempGood:Number(T.ams_temp_good)||28,tempFair:Number(T.ams_temp_fair)||35}:void 0,timeFormat:T?.time_format||"system",cameraViewMode:T?.camera_view_mode||"window",onOpenEmbeddedCamera:(O,$)=>C(ee=>new Map(ee).set(O,{id:O,name:$})),checkPrinterFirmware:T?.check_printer_firmware!==!1,dryingPresets:D},re.id))}),e&&i.jsx(uVe,{onClose:()=>n(!1),onAdd:re=>pe.mutate(re),existingSerials:k?.map(re=>re.serial_number)||[]}),Array.from(N.values()).map((re,O)=>i.jsx(pMe,{printerId:re.id,printerName:re.name,viewerIndex:O,onClose:()=>C($=>{const ee=new Map($);return ee.delete(re.id),ee})},re.id))]})}function gVe(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function of(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:gVe()==="macos"?n=`bambustudioopen://${encodeURIComponent(t)}`:n=`bambustudio://open?file=${t}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}const MW=768;function uie(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${MW-1}px)`),r=a=>{e(a.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function LI({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:a}){const{t:s}=Dt(),{data:o}=et({queryKey:["settings"],queryFn:ge.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[u,d]=w.useState(null),[m,p]=w.useState(null),[f,y]=w.useState(!0),[v,b]=w.useState(null),[g,_]=w.useState(!1),[N,C]=w.useState(null),[k,P]=w.useState(0),[T,D]=w.useState(!1),[A,R]=w.useState(null),[G,z]=w.useState(!1),[Z,I]=w.useState(!1),J=w.useRef(null),ae=w.useRef(null),Y=10,ue=160,de=240,he=.35;w.useEffect(()=>{const xe=oe=>{oe.key==="Escape"&&a()};return window.addEventListener("keydown",xe),()=>window.removeEventListener("keydown",xe)},[a]),w.useEffect(()=>{if(y(!0),c){const xe=(r||"").toLowerCase(),oe=xe==="3mf"||xe==="stl",L=xe==="gcode"||xe==="3mf";p({has_model:oe,has_gcode:L,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d(oe?"3d":L?"gcode":null),y(!1);return}if(!t){p(null),d(null),y(!1);return}ge.getArchiveCapabilities(t).then(xe=>{p(xe),xe.has_model?d("3d"):xe.has_gcode&&d("gcode"),y(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d("3d"),y(!1)})},[t,r,c]),w.useEffect(()=>{if(_(!0),C(null),P(0),c){const xe=(r||"").toLowerCase();if(!e||xe!=="3mf"){b(null),_(!1);return}ge.getLibraryFilePlates(e).then(oe=>b(oe)).catch(()=>b(null)).finally(()=>_(!1));return}if(!t){b(null),_(!1);return}ge.getArchivePlates(t).then(xe=>b(xe)).catch(()=>b(null)).finally(()=>_(!1))},[t,r,c,e]);const V=w.useMemo(()=>v?.plates??[],[v]),ne=(v?.is_multi_plate??!1)&&V.length>1,se=T&&ne,pe=N==null?null:V.find(xe=>xe.index===N)??null,Te=xe=>xe.object_count??xe.objects?.length??0,q=V.reduce((xe,oe)=>xe+Te(oe),0),X=pe?Te(pe):q,j=pe?s("modelViewer.plateNumber",{number:pe.index}):s("modelViewer.allPlates"),E=V.length>0,U=w.useRef(null),K=w.useRef(null),[H,re]=w.useState(10),[O,$]=w.useState(3),ee=V.length>H,W=Math.max(1,Math.ceil(V.length/H)),ie=ee?V.slice(k*H,(k+1)*H):V;w.useEffect(()=>{if(!se){re(10),$(3);return}const xe=U.current,oe=K.current;if(!xe||!oe)return;let L=0;const F=()=>{const fe=oe.clientWidth,je=Math.floor(fe/210),we=Math.max(3,Math.min(5,je||3));$(ye=>ye===we?ye:we);const Fe=window.getComputedStyle(xe),He=Number.parseFloat(Fe.rowGap||"0"),_e=xe.querySelector("button")?.getBoundingClientRect().height??44,Ae=oe.clientHeight,Me=Math.max(1,Math.floor((Ae+He)/(_e+He)))*we,Xe=Math.max(1,Me-1);re(ye=>ye===Xe?ye:Xe)},te=()=>{L&&cancelAnimationFrame(L),L=requestAnimationFrame(F)};te();const ve=new ResizeObserver(te);return ve.observe(oe),ve.observe(xe),()=>{L&&cancelAnimationFrame(L),ve.disconnect()}},[se,V.length]),w.useEffect(()=>{if(!ee){P(0);return}P(xe=>Math.min(xe,W-1))},[V.length,ee,W]),w.useEffect(()=>{if(!ee||N==null)return;const xe=V.findIndex(L=>L.index===N);if(xe<0)return;const oe=Math.floor(xe/H);P(L=>L===oe?L:oe)},[V,H,N,ee]),w.useEffect(()=>{if(!se){R(null),I(!1);return}if(Z)return;const xe=J.current,oe=ae.current;if(!xe||!oe)return;const L=xe.clientHeight;if(!L)return;const F=Math.max(de,L*he),te=Math.max(ue,L-Y-F),ve=Math.min(oe.scrollHeight,te);R(Math.max(ue,ve))},[se,Z,V.length,k,Y,ue,de,he]),w.useEffect(()=>{if(!G)return;const xe=L=>{const F=J.current;if(!F)return;const te=F.getBoundingClientRect(),ve=te.height;if(!ve)return;const fe=Math.max(de,ve*he),me=Math.max(ue,ve-Y-fe),je=Math.min(me,Math.max(ue,L.clientY-te.top));R(je)},oe=()=>{z(!1),I(!0)};return document.addEventListener("mousemove",xe),document.addEventListener("mouseup",oe),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",xe),document.removeEventListener("mouseup",oe),document.body.style.cursor="",document.body.style.userSelect=""}},[G,Y,ue,de,he]);const ce=c?(r||"").toLowerCase()==="3mf":!0,be=async()=>{if(!ce)return;const xe=n||"model";try{if(c){const{token:oe}=await ge.createLibrarySlicerToken(e),L=ge.getLibrarySlicerDownloadUrl(e,oe,xe);of(`${window.location.origin}${L}`,l)}else{const{token:oe}=await ge.createArchiveSlicerToken(t),L=ge.getArchiveSlicerDownloadUrl(t,oe,xe);of(`${window.location.origin}${L}`,l)}}catch{if(c){const oe=`${window.location.origin}${ge.getLibraryFileDownloadUrl(e)}`;of(oe,l)}else{const oe=`${window.location.origin}${ge.getArchiveForSlicer(t,xe)}`;of(oe,l)}}};return i.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${T?"p-0":"p-8"}`,onClick:a,children:i.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${T?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:xe=>xe.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),E&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[j,": ",s("modelViewer.objectCount",{count:X})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(ze,{variant:"secondary",size:"sm",onClick:be,disabled:!ce,children:[i.jsx(ni,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>D(xe=>!xe),title:T?"Exit fullscreen":"Enter fullscreen",children:T?i.jsx(WL,{className:"w-4 h-4"}):i.jsx(oT,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:a,children:i.jsx(Ht,{className:"w-5 h-5"})})]})]}),m&&i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[i.jsxs("button",{onClick:()=>m.has_model&&d("3d"),disabled:!m.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":m.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(ia,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!m.has_model&&i.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),i.jsxs("button",{onClick:()=>m.has_gcode&&d("gcode"),disabled:!m.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":m.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(mpe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!m.has_gcode&&i.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),i.jsx("div",{className:"flex-1 overflow-hidden p-4",children:f?i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})}):u==="3d"&&m?i.jsxs("div",{ref:J,className:`w-full h-full flex flex-col ${se?"gap-0 min-h-0":"gap-3"}`,children:[ne&&i.jsxs("div",{ref:ae,style:se&&A!=null?{height:A}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${se?"flex flex-col shrink-0":""}`,children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[i.jsx(Gi,{className:"w-4 h-4"}),s("modelViewer.plates"),g&&i.jsx(ft,{className:"w-3 h-3 animate-spin"})]}),i.jsxs("div",{className:se?"flex flex-col min-h-0 flex-1":void 0,children:[i.jsx("div",{ref:K,className:se?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:i.jsxs("div",{ref:U,className:se?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:se?{gridTemplateColumns:`repeat(${O}, minmax(0, 1fr))`}:void 0,children:[i.jsxs("button",{type:"button",onClick:()=>C(null),className:`flex items-center rounded-lg border text-left transition-colors ${se?"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:[i.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${se?"w-8 h-8":"w-10 h-10"}`,children:i.jsx(Gi,{className:`${se?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:`${se?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),i.jsx("p",{className:`${se?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:V.length})})]}),N==null&&i.jsx(Zr,{className:`${se?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),ie.map(xe=>i.jsxs("button",{type:"button",onClick:()=>C(xe.index),className:`flex items-center rounded-lg border text-left transition-colors ${se?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===xe.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[xe.has_thumbnail&&xe.thumbnail_url?i.jsx("img",{src:xe.thumbnail_url,alt:`Plate ${xe.index}`,className:`${se?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):i.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${se?"w-8 h-8":"w-10 h-10"}`,children:i.jsx(Gi,{className:`${se?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:`${se?"text-xs":"text-sm"} text-white font-medium truncate`,children:xe.name||s("modelViewer.plateNumber",{number:xe.index})}),i.jsx("p",{className:`${se?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:xe.object_count??xe.objects?.length??0})})]}),N===xe.index&&i.jsx(Zr,{className:`${se?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},xe.index))]})}),(pe||ee)&&i.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[pe&&i.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[i.jsx("span",{children:s("modelViewer.plateNumber",{number:pe.index})}),pe.print_time_seconds!=null&&i.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(pe.print_time_seconds/60)})}),pe.filament_used_grams!=null&&i.jsxs("span",{children:[pe.filament_used_grams.toFixed(1)," g"]}),pe.filaments.length>0&&i.jsx("span",{children:s("modelViewer.filamentCount",{count:pe.filaments.length})})]}),ee&&i.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${pe?"ml-auto":""}`,children:[i.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:k+1,total:W})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{type:"button",onClick:()=>P(xe=>Math.max(xe-1,0)),disabled:k===0,className:`px-2 py-1 rounded border text-xs ${k===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let oe=Math.max(0,k-Math.floor(2.5));const L=Math.min(W,oe+5);L-oe<5&&(oe=Math.max(0,L-5));const F=Array.from({length:L-oe},(te,ve)=>oe+ve);return i.jsxs(i.Fragment,{children:[oe>0&&i.jsx("button",{type:"button",onClick:()=>P(0),className:`px-2 py-1 rounded border text-xs ${k===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),oe>1&&i.jsx("span",{className:"px-1",children:"…"}),F.map(te=>i.jsx("button",{type:"button",onClick:()=>P(te),className:`px-2 py-1 rounded border text-xs ${k===te?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:te+1},te)),LP(W-1),className:`px-2 py-1 rounded border text-xs ${k===W-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:W})]})})(),i.jsx("button",{type:"button",onClick:()=>P(xe=>Math.min(xe+1,W-1)),disabled:k>=W-1,className:`px-2 py-1 rounded border text-xs ${k>=W-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")})]})]})]})]})]}),se&&i.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:xe=>{xe.preventDefault(),z(!0),I(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${G?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),i.jsx("div",{className:`flex-1 ${se?"min-h-0":""}`,children:i.jsx(tZ,{url:c?ge.getLibraryFileDownloadUrl(e):m.has_source?ge.getSource3mfDownloadUrl(t):ge.getArchiveDownload(t),fileType:r,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):u==="gcode"&&m?i.jsx(OZ,{gcodeUrl:c?ge.getLibraryFileGcodeUrl(e):ge.getArchiveGcode(t),filamentColors:m.filament_colors,className:"w-full h-full"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}function bVe({onClose:t,initialFiles:e}){const{t:n}=Dt(),r=sn(),{showToast:a}=bn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(k=>k.name.endsWith(".3mf")).map(k=>({file:k,status:"pending"}))||[]),[c,u]=w.useState(!1),[d,m]=w.useState(null);w.useEffect(()=>{const k=P=>{P.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]);const p=gt({mutationFn:k=>ge.uploadArchivesBulk(k),onSuccess:k=>{m(k),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(P=>P.map(T=>{const D=k.results.find(R=>R.filename===T.file.name),A=k.errors.find(R=>R.filename===T.file.name);return D?{...T,status:"success",archiveId:D.id}:A?{...T,status:"error",error:A.error}:T})),k.failed===0?a(`${k.uploaded} file${k.uploaded!==1?"s":""} uploaded`):k.uploaded===0?a(`Failed to upload ${k.failed} file${k.failed!==1?"s":""}`,"error"):a(`${k.uploaded} uploaded, ${k.failed} failed`,"warning")},onError:()=>{l(k=>k.map(P=>({...P,status:"error",error:"Upload failed"}))),a("Upload failed","error")}}),f=w.useCallback(k=>{k.preventDefault(),u(!0)},[]),y=w.useCallback(k=>{k.preventDefault(),u(!1)},[]),v=w.useCallback(k=>{k.preventDefault(),u(!1);const P=Array.from(k.dataTransfer.files).filter(T=>T.name.endsWith(".3mf"));P.length>0&&l(T=>[...T,...P.map(D=>({file:D,status:"pending"}))])},[]),b=w.useCallback(k=>{const P=Array.from(k.target.files||[]).filter(T=>T.name.endsWith(".3mf"));P.length>0&&l(T=>[...T,...P.map(D=>({file:D,status:"pending"}))]),s.current&&(s.current.value="")},[]),g=w.useCallback(k=>{l(P=>P.filter((T,D)=>D!==k))},[]),_=()=>{if(o.length===0)return;const k=o.filter(P=>P.status==="pending");k.length!==0&&(l(P=>P.map(T=>T.status==="pending"?{...T,status:"uploading"}:T)),p.mutate(k.map(P=>P.file)))},N=o.filter(k=>k.status==="pending").length,C=p.isPending;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:i.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"p-4",children:i.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:f,onDragLeave:y,onDrop:v,children:[i.jsx(yi,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),i.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),i.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),i.jsx(ze,{variant:"secondary",onClick:()=>s.current?.click(),disabled:C,children:n("uploadModal.browseFiles")}),i.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:b})]})}),i.jsx("div",{className:"px-4 pb-4",children:i.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&i.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:i.jsx("div",{className:"space-y-2",children:o.map((k,P)=>i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[i.jsx(iT,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"flex-1 text-white text-sm truncate",children:k.file.name}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[(k.file.size/(1024*1024)).toFixed(1)," MB"]}),k.status==="pending"&&i.jsx("button",{onClick:()=>g(P),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:C,children:i.jsx(Ht,{className:"w-4 h-4"})}),k.status==="uploading"&&i.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"}),k.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-bambu-green"}),k.status==="error"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-red-400",children:k.error}),i.jsx(Li,{className:"w-4 h-4 text-red-400"})]})]},`${k.file.name}-${P}`))})}),d&&i.jsx("div",{className:"px-4 pb-4",children:i.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"text-bambu-green",children:d.uploaded})," ",n("uploadModal.uploaded"),d.failed>0&&i.jsxs(i.Fragment,{children:[", ",i.jsx("span",{className:"text-red-400",children:d.failed})," ",n("uploadModal.failed")]})]})})}),i.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(ze,{variant:"secondary",onClick:t,className:"flex-1",children:n(d?"common.close":"common.cancel")}),!d&&i.jsx(ze,{onClick:_,disabled:N===0||C,className:"flex-1",children:C?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(yi,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const xVe=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],yVe=["completed","failed","aborted","printing"];function die({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Dt();w.useEffect(()=>{const E=U=>{U.key==="Escape"&&e()};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[e]);const a=sn(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[u,d]=w.useState(t.project_id??null),[m,p]=w.useState(t.notes||""),[f,y]=w.useState(t.tags||""),[v,b]=w.useState(t.failure_reason||""),[g,_]=w.useState(t.status),[N,C]=w.useState(t.quantity??1),[k,P]=w.useState(t.photos||[]),[T,D]=w.useState(t.external_url||""),[A,R]=w.useState(!1),[G,z]=w.useState(!1),Z=w.useRef(null),I=w.useRef(null),J=w.useRef(null),{data:ae}=et({queryKey:["printers"],queryFn:ge.getPrinters}),{data:Y}=et({queryKey:["projects"],queryFn:()=>ge.getProjects()}),{data:ue}=et({queryKey:["tags"],queryFn:ge.getTags,enabled:n.length===0}),de=n.length>0?n:ue?.map(E=>E.name)||[],he=f.split(",").map(E=>E.trim()).filter(Boolean),V=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ne=de.filter(E=>!he.includes(E)&&(V===""||E.toLowerCase().includes(V))),se=E=>{let U;if(V&&!de.includes(V)?U=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(K=>K.trim()).filter(Boolean):[]:U=he,!U.includes(E)){const K=[...U,E].join(", ");y(K)}J.current!==null&&clearTimeout(J.current),Z.current?.focus()},pe=E=>{const U=he.filter(K=>K!==E).join(", ");y(U)},Te=gt({mutationFn:E=>ge.updateArchive(t.id,E),onSuccess:()=>{a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["projects"]}),e()}}),q=async E=>{const U=E.target.files?.[0];if(U){R(!0);try{const K=await ge.uploadArchivePhoto(t.id,U);P(K.photos),a.invalidateQueries({queryKey:["archives"]})}catch(K){console.error("Failed to upload photo:",K)}finally{R(!1),I.current&&(I.current.value="")}}},X=async E=>{try{const U=await ge.deleteArchivePhoto(t.id,E);P(U.photos||[]),a.invalidateQueries({queryKey:["archives"]})}catch(U){console.error("Failed to delete photo:",U)}},j=E=>{E.preventDefault();const U={print_name:s||void 0,printer_id:l,project_id:u,notes:m||void 0,tags:f||void 0,quantity:N,external_url:T||null};g!==t.status&&(U.status=g),g==="failed"||g==="aborted"?U.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(U.failure_reason=null),Te.mutate(U)};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:i.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:E=>E.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:j,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),i.jsx("input",{type:"text",value:s,onChange:E=>o(E.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")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),i.jsxs("select",{value:l??"",onChange:E=>c(E.target.value?Number(E.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:[i.jsx("option",{value:"",children:r("editArchive.noPrinter")}),ae?.map(E=>i.jsx("option",{value:E.id,children:E.name},E.id))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(vs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),i.jsxs("select",{value:u??"",onChange:E=>d(E.target.value?Number(E.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:[i.jsx("option",{value:"",children:r("editArchive.noProject")}),Y?.map(E=>i.jsx("option",{value:E.id,children:E.name},E.id))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(yfe,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),i.jsx("input",{type:"number",min:1,value:N,onChange:E=>C(Math.max(1,parseInt(E.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"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),i.jsx("textarea",{value:m,onChange:E=>p(E.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")})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(Gx,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),i.jsx("input",{type:"url",value:T,onChange:E=>D(E.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/..."}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),he.length>0&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:he.map(E=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[i.jsx(Hd,{className:"w-3 h-3"}),E,i.jsx("button",{type:"button",onClick:()=>pe(E),className:"ml-0.5 text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-3 h-3"})})]},E))}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{ref:Z,type:"text",value:f,onChange:E=>y(E.target.value),onFocus:()=>{J.current!==null&&clearTimeout(J.current),z(!0)},onBlur:()=>{J.current=window.setTimeout(()=>z(!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:he.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),G&&ne.length>0&&i.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:[i.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[V?r("editArchive.matchingTags",{query:V}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),i.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ne.map(E=>i.jsx("button",{type:"button",onClick:()=>se(E),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:E},E))})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),i.jsx("select",{value:g,onChange:E=>{_(E.target.value),E.target.value==="completed"&&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:yVe.map(E=>i.jsx("option",{value:E,children:r(`editArchive.statuses.${E}`)},E))})]}),(g==="failed"||g==="aborted")&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),i.jsxs("select",{value:v,onChange:E=>b(E.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:[i.jsx("option",{value:"",children:r("editArchive.selectReason")}),xVe.map(E=>i.jsx("option",{value:r(`editArchive.failureReasons.${E}`),children:r(`editArchive.failureReasons.${E}`)},E))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(dx,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),i.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[k.map(E=>i.jsxs("div",{className:"relative group",children:[i.jsx("img",{src:ge.getArchivePhotoUrl(t.id,E),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),i.jsx("button",{type:"button",onClick:()=>X(E),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx(nn,{className:"w-3 h-3 text-white"})})]},E)),i.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:[i.jsx("input",{ref:I,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:q,className:"hidden",disabled:A}),A?i.jsx(ft,{className:"w-6 h-6 text-bambu-gray animate-spin"}):i.jsx(ir,{className:"w-6 h-6 text-bambu-gray"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),i.jsxs(ze,{type:"submit",disabled:Te.isPending,className:"flex-1",children:[i.jsx(as,{className:"w-4 h-4"}),Te.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function mie({x:t,y:e,items:n,onClose:r}){const a=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,u]=w.useState({x:t,y:e,visible:!1}),[d,m]=w.useState(!1),[p,f]=w.useState({});w.useEffect(()=>{const b=N=>{a.current&&!a.current.contains(N.target)&&r()},g=N=>{N.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",b),document.addEventListener("keydown",g),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",g),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(a.current){a.current.style.visibility="hidden",a.current.style.display="block";const b=a.current.getBoundingClientRect(),g=window.innerWidth,_=window.innerHeight,N=8;let C=t,k=e;t+b.width>g-N&&(C=Math.max(N,g-b.width-N)),C_-N&&(k=Math.max(N,_-b.height-N)),kP),u({x:C,y:k,visible:!0})}},[t,e]);const y=(b,g)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=g.getBoundingClientRect(),N=window.innerHeight,C=300,T=N-_.top-8C;f(D=>({...D,[b]:T?"bottom":"top"})),o(b)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return i.jsx("div",{ref:a,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((b,g)=>{if(b.divider)return i.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},g);const _=b.submenu&&b.submenu.length>0;return i.jsxs("div",{className:"relative",onMouseEnter:N=>_&&y(g,N.currentTarget),onMouseLeave:()=>_&&v(),children:[i.jsxs("button",{onMouseEnter:N=>_&&y(g,N.currentTarget.parentElement),onClick:()=>{_?o(s===g?null:g):b.disabled||(b.onClick(),r())},disabled:b.disabled,title:b.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===g?"bg-bambu-dark-tertiary":""}`,children:[b.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),i.jsx("span",{className:"flex-1",children:b.label}),_&&i.jsx(fa,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===g&&i.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[g]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:b.submenu.map((N,C)=>i.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&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:N.icon}),N.label]},C))})]},g)})})}function vVe({selectedIds:t,existingTags:e,onClose:n}){const r=sn(),{showToast:a}=bn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[u,d]=w.useState("add");w.useEffect(()=>{const v=b=>{b.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const m=gt({mutationFn:async()=>{const v=Array.from(l);let b=0;for(const g of t)try{const _=await ge.getArchive(g),N=_.tags?_.tags.split(",").map(k=>k.trim()).filter(Boolean):[];let C;u==="add"?C=[...new Set([...N,...v])]:C=N.filter(k=>!l.has(k)),await ge.updateArchive(g,{tags:C.join(", ")}),b++}catch(_){throw console.error(`Failed to update archive ${g}:`,_),new Error(`Failed on archive ${g}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:b,mode:u,tags:v}},onSuccess:({count:v,mode:b,tags:g})=>{r.invalidateQueries({queryKey:["archives"]}),a(`${b==="add"?"Added":"Removed"} ${g.length} tag${g.length!==1?"s":""} ${b==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{a(v.message||"Failed to update tags","error")}}),p=v=>{c(b=>{const g=new Set(b);return g.has(v)?g.delete(v):g.add(v),g})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},y=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-md",children:i.jsxs(Et,{className:"p-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Hd,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:u==="add"?"Add Tags":"Remove Tags"})]}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:[u==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{size:"sm",variant:u==="add"?"primary":"secondary",onClick:()=>d("add"),children:"Add Tags"}),i.jsx(ze,{size:"sm",variant:u==="remove"?"primary":"secondary",onClick:()=>d("remove"),children:"Remove Tags"})]}),u==="add"&&i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:y}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:i.jsx(ir,{className:"w-4 h-4"})})]}),e.length>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>i.jsx("button",{onClick:()=>p(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&i.jsxs("div",{children:[i.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",u==="add"?"add":"remove",":"]}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>i.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${u==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,i.jsx("button",{onClick:()=>p(v),className:"hover:opacity-70",children:i.jsx(Ht,{className:"w-3 h-3"})})]},v))})]})]}),i.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(ze,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),i.jsx(ze,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):i.jsxs(i.Fragment,{children:[i.jsx(Hd,{className:"w-4 h-4"}),u==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function wVe({selectedIds:t,onClose:e}){const n=sn(),{showToast:r}=bn(),{data:a,isLoading:s}=et({queryKey:["projects"],queryFn:()=>ge.getProjects()});w.useEffect(()=>{const d=m=>{m.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=gt({mutationFn:async d=>(await ge.addArchivesToProject(d,t),d),onSuccess:d=>{const m=a?.find(p=>p.id===d);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${m?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=gt({mutationFn:async()=>{for(const d of t)await ge.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 i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:i.jsxs(Et,{className:"p-0 flex flex-col min-h-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(vs,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:u,children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):i.jsxs("div",{className:"space-y-2",children:[i.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:[i.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:i.jsx(Vi,{className:"w-4 h-4 text-red-400"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),i.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&i.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),a&&a.length>0&&i.jsxs("div",{className:"flex items-center gap-2 py-2",children:[i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),a?.map(d=>i.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:[i.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:i.jsx(vs,{className:"w-4 h-4",style:{color:d.color||"rgb(var(--bambu-green))"}})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium truncate",children:d.name}),i.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&&i.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},d.id)),(!a||a.length===0)&&i.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),i.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:i.jsx(ze,{variant:"secondary",onClick:e,className:"flex-1",disabled:u,children:"Cancel"})})]})})})}function SVe(t,e){return new Date(t,e+1,0).getDate()}function _Ve(t,e){return new Date(t,e,1).getDay()}const NVe=["January","February","March","April","May","June","July","August","September","October","November","December"],kVe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function CVe({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[a,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,u]=w.useState(null),[d,m]=w.useState(null),p=w.useMemo(()=>{const k=new Map;return t.forEach(P=>{const T=Qn(P.completed_at||P.created_at)||new Date,D=`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`,A=k.get(D)||[];A.push(P),k.set(D,A)}),k},[t]),f=SVe(o,a),y=_Ve(o,a),v=()=>{a===0?(s(11),l(o-1)):s(a-1)},b=()=>{a===11?(s(0),l(o+1)):s(a+1)},g=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let k=0;k{k!==c&&m(null),u(k)};return i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[i.jsxs("div",{className:"flex-1",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Cc,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white",children:[NVe[a]," ",o]}),i.jsx("button",{onClick:g,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"})]}),i.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(fa,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:kVe.map(k=>i.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:k},k))}),i.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((k,P)=>{if(k===null)return i.jsx("div",{className:"aspect-square"},`empty-${P}`);const T=`${o}-${String(a+1).padStart(2,"0")}-${String(k).padStart(2,"0")}`,D=p.get(T)||[],A=D.length>0,R=k===r.getDate()&&a===r.getMonth()&&o===r.getFullYear(),G=T===c,z=D.filter(I=>I.status==="completed").length,Z=D.filter(I=>I.status==="failed").length;return i.jsxs("button",{onClick:()=>C(G?null:T),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${G?"bg-bambu-green text-white":R?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":A?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[i.jsx("span",{className:`text-sm font-medium ${R&&!G?"text-bambu-green":""}`,children:k}),A&&i.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${Z>0&&z===0?"bg-red-400":Z>0?"bg-yellow-400":"bg-green-400"}`}),i.jsx("span",{className:"text-xs font-medium",children:D.length})]})]},k)})}),i.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(k=>{const P=Qn(k.completed_at||k.created_at)||new Date;return P.getMonth()===a&&P.getFullYear()===o}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(k=>{const P=Qn(k.completed_at||k.created_at)||new Date;return P.getMonth()===a&&P.getFullYear()===o&&k.status==="completed"}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(k=>{const P=Qn(k.completed_at||k.created_at)||new Date;return P.getMonth()===a&&P.getFullYear()===o&&k.status==="failed"}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),i.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?i.jsxs(i.Fragment,{children:[i.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?i.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:N.map(k=>{const P=k.id===d||k.id===n;return i.jsxs("button",{onClick:()=>{m(k.id),e?.(k)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${P?"":"hover:bg-bambu-dark-tertiary"}`,style:P?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[k.thumbnail_path?i.jsx("img",{src:ge.getArchiveThumbnail(k.id),alt:"",className:"w-12 h-12 rounded object-cover"}):i.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:k.print_name||k.filename}),i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx("span",{className:k.status==="failed"?"text-red-400":"text-green-400",children:k.status==="failed"?"Failed":"Completed"}),k.filament_color&&i.jsx("div",{className:"flex gap-0.5",children:k.filament_color.split(",").map((T,D)=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:T}},D))})]})]})]},k.id)})}):i.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):i.jsx("div",{className:"text-center py-8",children:i.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function hie({archiveId:t,archiveName:e,onClose:n}){const r=ge.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const a=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-6 flex flex-col items-center",children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),i.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:i.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),i.jsxs(ze,{onClick:a,className:"w-full",children:[i.jsx(fi,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function pie({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:a}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const f=y=>{y.key==="Escape"&&r(),y.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),y.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r,n.length]),w.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=ge.getArchivePhotoUrl(t,u),m=()=>{const f=document.createElement("a");f.href=d,f.download=`${e}_photo_${s+1}.jpg`,f.click()},p=()=>{a&&c(!0)};return i.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[i.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(ze,{variant:"secondary",size:"sm",onClick:m,children:[i.jsx(fi,{className:"w-4 h-4"}),"Download"]}),a&&i.jsx(ze,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:i.jsx(nn,{className:"w-4 h-4"})}),i.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-6 h-6"})})]})]}),i.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&i.jsx("button",{onClick:()=>o(f=>f-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:i.jsx(Cc,{className:"w-8 h-8 text-white"})}),i.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(f=>f+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:i.jsx(fa,{className:"w-8 h-8 text-white"})})]}),n.length>1&&i.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,y)=>i.jsx("button",{onClick:()=>o(y),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${y===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:i.jsx("img",{src:ge.getArchivePhotoUrl(t,f),alt:`Thumbnail ${y+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&i.jsx(Nn,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{a?.(u),c(!1)},onCancel:()=>c(!1)})]})}const{entries:fie,setPrototypeOf:EW,isFrozen:TVe,getPrototypeOf:AVe,getOwnPropertyDescriptor:PVe}=Object;let{freeze:Qs,seal:Ql,create:vN}=Object,{apply:IF,construct:zF}=typeof Reflect<"u"&&Reflect;Qs||(Qs=function(e){return e});Ql||(Ql=function(e){return e});IF||(IF=function(e,n){for(var r=arguments.length,a=new Array(r>2?r-2:0),s=2;s1?n-1:0),a=1;a1?n-1:0),a=1;a2&&arguments[2]!==void 0?arguments[2]:wN;EW&&EW(t,null);let r=e.length;for(;r--;){let a=e[r];if(typeof a=="string"){const s=n(a);s!==a&&(TVe(e)||(e[r]=s),a=s)}t[a]=!0}return t}function FVe(t){for(let e=0;e/gm),UVe=Ql(/\$\{[\w\W]*/gm),BVe=Ql(/^data-[\-\w.\u00B7-\uFFFF]+$/),HVe=Ql(/^aria-[\-\w]+$/),gie=Ql(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),$Ve=Ql(/^(?:\w+script|data):/i),qVe=Ql(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),bie=Ql(/^html$/i),VVe=Ql(/^[a-z][.\w]*(-[.\w]+)+$/i);var OW=Object.freeze({__proto__:null,ARIA_ATTR:HVe,ATTR_WHITESPACE:qVe,CUSTOM_ELEMENT:VVe,DATA_ATTR:BVe,DOCTYPE_NAME:bie,ERB_EXPR:zVe,IS_ALLOWED_URI:gie,IS_SCRIPT_OR_DATA:$Ve,MUSTACHE_EXPR:IVe,TMPLIT_EXPR:UVe});const Tv={element:1,text:3,progressingInstruction:7,comment:8,document:9},GVe=function(){return typeof window>"u"?null:window},WVe=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const a="data-tt-policy-suffix";n&&n.hasAttribute(a)&&(r=n.getAttribute(a));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},IW=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function xie(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:GVe();const e=Ze=>xie(Ze);if(e.version="3.3.3",e.removed=[],!t||!t.document||t.document.nodeType!==Tv.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const r=n,a=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:u,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,y=c.prototype,v=Cv(y,"cloneNode"),b=Cv(y,"remove"),g=Cv(y,"nextSibling"),_=Cv(y,"childNodes"),N=Cv(y,"parentNode");if(typeof o=="function"){const Ze=n.createElement("template");Ze.content&&Ze.content.ownerDocument&&(n=Ze.content.ownerDocument)}let C,k="";const{implementation:P,createNodeIterator:T,createDocumentFragment:D,getElementsByTagName:A}=n,{importNode:R}=r;let G=IW();e.isSupported=typeof fie=="function"&&typeof N=="function"&&P&&P.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:z,ERB_EXPR:Z,TMPLIT_EXPR:I,DATA_ATTR:J,ARIA_ATTR:ae,IS_SCRIPT_OR_DATA:Y,ATTR_WHITESPACE:ue,CUSTOM_ELEMENT:de}=OW;let{IS_ALLOWED_URI:he}=OW,V=null;const ne=er({},[...DW,...lD,...cD,...uD,...RW]);let se=null;const pe=er({},[...FW,...dD,...LW,...R1]);let Te=Object.seal(vN(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),q=null,X=null;const j=Object.seal(vN(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let E=!0,U=!0,K=!1,H=!0,re=!1,O=!0,$=!1,ee=!1,W=!1,ie=!1,ce=!1,be=!1,xe=!0,oe=!1;const L="user-content-";let F=!0,te=!1,ve={},fe=null;const me=er({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let je=null;const we=er({},["audio","video","img","source","image","track"]);let Fe=null;const He=er({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Oe="http://www.w3.org/1998/Math/MathML",_e="http://www.w3.org/2000/svg",Ae="http://www.w3.org/1999/xhtml";let Be=Ae,Me=!1,Xe=null;const ye=er({},[Oe,_e,Ae],sD);let We=er({},["mi","mo","mn","ms","mtext"]),Pe=er({},["annotation-xml"]);const Ke=er({},["title","style","font","a","script"]);let Ve=null;const ke=["application/xhtml+xml","text/html"],Ce="text/html";let $e=null,nt=null;const xt=n.createElement("form"),vt=function(Ee){return Ee instanceof RegExp||Ee instanceof Function},mt=function(){let Ee=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(nt&&nt===Ee)){if((!Ee||typeof Ee!="object")&&(Ee={}),Ee=Jc(Ee),Ve=ke.indexOf(Ee.PARSER_MEDIA_TYPE)===-1?Ce:Ee.PARSER_MEDIA_TYPE,$e=Ve==="application/xhtml+xml"?sD:wN,V=Vo(Ee,"ALLOWED_TAGS")?er({},Ee.ALLOWED_TAGS,$e):ne,se=Vo(Ee,"ALLOWED_ATTR")?er({},Ee.ALLOWED_ATTR,$e):pe,Xe=Vo(Ee,"ALLOWED_NAMESPACES")?er({},Ee.ALLOWED_NAMESPACES,sD):ye,Fe=Vo(Ee,"ADD_URI_SAFE_ATTR")?er(Jc(He),Ee.ADD_URI_SAFE_ATTR,$e):He,je=Vo(Ee,"ADD_DATA_URI_TAGS")?er(Jc(we),Ee.ADD_DATA_URI_TAGS,$e):we,fe=Vo(Ee,"FORBID_CONTENTS")?er({},Ee.FORBID_CONTENTS,$e):me,q=Vo(Ee,"FORBID_TAGS")?er({},Ee.FORBID_TAGS,$e):Jc({}),X=Vo(Ee,"FORBID_ATTR")?er({},Ee.FORBID_ATTR,$e):Jc({}),ve=Vo(Ee,"USE_PROFILES")?Ee.USE_PROFILES:!1,E=Ee.ALLOW_ARIA_ATTR!==!1,U=Ee.ALLOW_DATA_ATTR!==!1,K=Ee.ALLOW_UNKNOWN_PROTOCOLS||!1,H=Ee.ALLOW_SELF_CLOSE_IN_ATTR!==!1,re=Ee.SAFE_FOR_TEMPLATES||!1,O=Ee.SAFE_FOR_XML!==!1,$=Ee.WHOLE_DOCUMENT||!1,ie=Ee.RETURN_DOM||!1,ce=Ee.RETURN_DOM_FRAGMENT||!1,be=Ee.RETURN_TRUSTED_TYPE||!1,W=Ee.FORCE_BODY||!1,xe=Ee.SANITIZE_DOM!==!1,oe=Ee.SANITIZE_NAMED_PROPS||!1,F=Ee.KEEP_CONTENT!==!1,te=Ee.IN_PLACE||!1,he=Ee.ALLOWED_URI_REGEXP||gie,Be=Ee.NAMESPACE||Ae,We=Ee.MATHML_TEXT_INTEGRATION_POINTS||We,Pe=Ee.HTML_INTEGRATION_POINTS||Pe,Te=Ee.CUSTOM_ELEMENT_HANDLING||{},Ee.CUSTOM_ELEMENT_HANDLING&&vt(Ee.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Te.tagNameCheck=Ee.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Ee.CUSTOM_ELEMENT_HANDLING&&vt(Ee.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Te.attributeNameCheck=Ee.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Ee.CUSTOM_ELEMENT_HANDLING&&typeof Ee.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Te.allowCustomizedBuiltInElements=Ee.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),re&&(U=!1),ce&&(ie=!0),ve&&(V=er({},RW),se=vN(null),ve.html===!0&&(er(V,DW),er(se,FW)),ve.svg===!0&&(er(V,lD),er(se,dD),er(se,R1)),ve.svgFilters===!0&&(er(V,cD),er(se,dD),er(se,R1)),ve.mathMl===!0&&(er(V,uD),er(se,LW),er(se,R1))),Vo(Ee,"ADD_TAGS")||(j.tagCheck=null),Vo(Ee,"ADD_ATTR")||(j.attributeCheck=null),Ee.ADD_TAGS&&(typeof Ee.ADD_TAGS=="function"?j.tagCheck=Ee.ADD_TAGS:(V===ne&&(V=Jc(V)),er(V,Ee.ADD_TAGS,$e))),Ee.ADD_ATTR&&(typeof Ee.ADD_ATTR=="function"?j.attributeCheck=Ee.ADD_ATTR:(se===pe&&(se=Jc(se)),er(se,Ee.ADD_ATTR,$e))),Ee.ADD_URI_SAFE_ATTR&&er(Fe,Ee.ADD_URI_SAFE_ATTR,$e),Ee.FORBID_CONTENTS&&(fe===me&&(fe=Jc(fe)),er(fe,Ee.FORBID_CONTENTS,$e)),Ee.ADD_FORBID_CONTENTS&&(fe===me&&(fe=Jc(fe)),er(fe,Ee.ADD_FORBID_CONTENTS,$e)),F&&(V["#text"]=!0),$&&er(V,["html","head","body"]),V.table&&(er(V,["tbody"]),delete q.tbody),Ee.TRUSTED_TYPES_POLICY){if(typeof Ee.TRUSTED_TYPES_POLICY.createHTML!="function")throw kv('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ee.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw kv('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');C=Ee.TRUSTED_TYPES_POLICY,k=C.createHTML("")}else C===void 0&&(C=WVe(f,a)),C!==null&&typeof k=="string"&&(k=C.createHTML(""));Qs&&Qs(Ee),nt=Ee}},qe=er({},[...lD,...cD,...LVe]),Nt=er({},[...uD,...OVe]),_t=function(Ee){let ct=N(Ee);(!ct||!ct.tagName)&&(ct={namespaceURI:Be,tagName:"template"});const le=wN(Ee.tagName),Le=wN(ct.tagName);return Xe[Ee.namespaceURI]?Ee.namespaceURI===_e?ct.namespaceURI===Ae?le==="svg":ct.namespaceURI===Oe?le==="svg"&&(Le==="annotation-xml"||We[Le]):!!qe[le]:Ee.namespaceURI===Oe?ct.namespaceURI===Ae?le==="math":ct.namespaceURI===_e?le==="math"&&Pe[Le]:!!Nt[le]:Ee.namespaceURI===Ae?ct.namespaceURI===_e&&!Pe[Le]||ct.namespaceURI===Oe&&!We[Le]?!1:!Nt[le]&&(Ke[le]||!qe[le]):!!(Ve==="application/xhtml+xml"&&Xe[Ee.namespaceURI]):!1},rt=function(Ee){_v(e.removed,{element:Ee});try{N(Ee).removeChild(Ee)}catch{b(Ee)}},Rt=function(Ee,ct){try{_v(e.removed,{attribute:ct.getAttributeNode(Ee),from:ct})}catch{_v(e.removed,{attribute:null,from:ct})}if(ct.removeAttribute(Ee),Ee==="is")if(ie||ce)try{rt(ct)}catch{}else try{ct.setAttribute(Ee,"")}catch{}},qt=function(Ee){let ct=null,le=null;if(W)Ee=""+Ee;else{const Ge=oD(Ee,/^[\r\n\t ]+/);le=Ge&&Ge[0]}Ve==="application/xhtml+xml"&&Be===Ae&&(Ee=''+Ee+"");const Le=C?C.createHTML(Ee):Ee;if(Be===Ae)try{ct=new p().parseFromString(Le,Ve)}catch{}if(!ct||!ct.documentElement){ct=P.createDocument(Be,"template",null);try{ct.documentElement.innerHTML=Me?k:Le}catch{}}const Ye=ct.body||ct.documentElement;return Ee&&le&&Ye.insertBefore(n.createTextNode(le),Ye.childNodes[0]||null),Be===Ae?A.call(ct,$?"html":"body")[0]:$?ct.documentElement:Ye},Kt=function(Ee){return T.call(Ee.ownerDocument||Ee,Ee,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},Qt=function(Ee){return Ee instanceof m&&(typeof Ee.nodeName!="string"||typeof Ee.textContent!="string"||typeof Ee.removeChild!="function"||!(Ee.attributes instanceof d)||typeof Ee.removeAttribute!="function"||typeof Ee.setAttribute!="function"||typeof Ee.namespaceURI!="string"||typeof Ee.insertBefore!="function"||typeof Ee.hasChildNodes!="function")},mn=function(Ee){return typeof l=="function"&&Ee instanceof l};function hn(Ze,Ee,ct){D1(Ze,le=>{le.call(e,Ee,ct,nt)})}const Hn=function(Ee){let ct=null;if(hn(G.beforeSanitizeElements,Ee,null),Qt(Ee))return rt(Ee),!0;const le=$e(Ee.nodeName);if(hn(G.uponSanitizeElement,Ee,{tagName:le,allowedTags:V}),O&&Ee.hasChildNodes()&&!mn(Ee.firstElementChild)&&Ls(/<[/\w!]/g,Ee.innerHTML)&&Ls(/<[/\w!]/g,Ee.textContent)||Ee.nodeType===Tv.progressingInstruction||O&&Ee.nodeType===Tv.comment&&Ls(/<[/\w]/g,Ee.data))return rt(Ee),!0;if(!(j.tagCheck instanceof Function&&j.tagCheck(le))&&(!V[le]||q[le])){if(!q[le]&&De(le)&&(Te.tagNameCheck instanceof RegExp&&Ls(Te.tagNameCheck,le)||Te.tagNameCheck instanceof Function&&Te.tagNameCheck(le)))return!1;if(F&&!fe[le]){const Le=N(Ee)||Ee.parentNode,Ye=_(Ee)||Ee.childNodes;if(Ye&&Le){const Ge=Ye.length;for(let Ie=Ge-1;Ie>=0;--Ie){const pt=v(Ye[Ie],!0);pt.__removalCount=(Ee.__removalCount||0)+1,Le.insertBefore(pt,g(Ee))}}}return rt(Ee),!0}return Ee instanceof c&&!_t(Ee)||(le==="noscript"||le==="noembed"||le==="noframes")&&Ls(/<\/no(script|embed|frames)/i,Ee.innerHTML)?(rt(Ee),!0):(re&&Ee.nodeType===Tv.text&&(ct=Ee.textContent,D1([z,Z,I],Le=>{ct=Nv(ct,Le," ")}),Ee.textContent!==ct&&(_v(e.removed,{element:Ee.cloneNode()}),Ee.textContent=ct)),hn(G.afterSanitizeElements,Ee,null),!1)},Qe=function(Ee,ct,le){if(X[ct]||xe&&(ct==="id"||ct==="name")&&(le in n||le in xt))return!1;if(!(U&&!X[ct]&&Ls(J,ct))){if(!(E&&Ls(ae,ct))){if(!(j.attributeCheck instanceof Function&&j.attributeCheck(ct,Ee))){if(!se[ct]||X[ct]){if(!(De(Ee)&&(Te.tagNameCheck instanceof RegExp&&Ls(Te.tagNameCheck,Ee)||Te.tagNameCheck instanceof Function&&Te.tagNameCheck(Ee))&&(Te.attributeNameCheck instanceof RegExp&&Ls(Te.attributeNameCheck,ct)||Te.attributeNameCheck instanceof Function&&Te.attributeNameCheck(ct,Ee))||ct==="is"&&Te.allowCustomizedBuiltInElements&&(Te.tagNameCheck instanceof RegExp&&Ls(Te.tagNameCheck,le)||Te.tagNameCheck instanceof Function&&Te.tagNameCheck(le))))return!1}else if(!Fe[ct]){if(!Ls(he,Nv(le,ue,""))){if(!((ct==="src"||ct==="xlink:href"||ct==="href")&&Ee!=="script"&&jVe(le,"data:")===0&&je[Ee])){if(!(K&&!Ls(Y,Nv(le,ue,"")))){if(le)return!1}}}}}}}return!0},De=function(Ee){return Ee!=="annotation-xml"&&oD(Ee,de)},ot=function(Ee){hn(G.beforeSanitizeAttributes,Ee,null);const{attributes:ct}=Ee;if(!ct||Qt(Ee))return;const le={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:se,forceKeepAttr:void 0};let Le=ct.length;for(;Le--;){const Ye=ct[Le],{name:Ge,namespaceURI:Ie,value:pt}=Ye,dt=$e(Ge),Je=pt;let Tt=Ge==="value"?Je:DVe(Je);if(le.attrName=dt,le.attrValue=Tt,le.keepAttr=!0,le.forceKeepAttr=void 0,hn(G.uponSanitizeAttribute,Ee,le),Tt=le.attrValue,oe&&(dt==="id"||dt==="name")&&(Rt(Ge,Ee),Tt=L+Tt),O&&Ls(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Tt)){Rt(Ge,Ee);continue}if(dt==="attributename"&&oD(Tt,"href")){Rt(Ge,Ee);continue}if(le.forceKeepAttr)continue;if(!le.keepAttr){Rt(Ge,Ee);continue}if(!H&&Ls(/\/>/i,Tt)){Rt(Ge,Ee);continue}re&&D1([z,Z,I],Ut=>{Tt=Nv(Tt,Ut," ")});const zt=$e(Ee.nodeName);if(!Qe(zt,dt,Tt)){Rt(Ge,Ee);continue}if(C&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Ie)switch(f.getAttributeType(zt,dt)){case"TrustedHTML":{Tt=C.createHTML(Tt);break}case"TrustedScriptURL":{Tt=C.createScriptURL(Tt);break}}if(Tt!==Je)try{Ie?Ee.setAttributeNS(Ie,Ge,Tt):Ee.setAttribute(Ge,Tt),Qt(Ee)?rt(Ee):jW(e.removed)}catch{Rt(Ge,Ee)}}hn(G.afterSanitizeAttributes,Ee,null)},st=function Ze(Ee){let ct=null;const le=Kt(Ee);for(hn(G.beforeSanitizeShadowDOM,Ee,null);ct=le.nextNode();)hn(G.uponSanitizeShadowNode,ct,null),Hn(ct),ot(ct),ct.content instanceof s&&Ze(ct.content);hn(G.afterSanitizeShadowDOM,Ee,null)};return e.sanitize=function(Ze){let Ee=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ct=null,le=null,Le=null,Ye=null;if(Me=!Ze,Me&&(Ze=""),typeof Ze!="string"&&!mn(Ze))if(typeof Ze.toString=="function"){if(Ze=Ze.toString(),typeof Ze!="string")throw kv("dirty is not a string, aborting")}else throw kv("toString is not a function");if(!e.isSupported)return Ze;if(ee||mt(Ee),e.removed=[],typeof Ze=="string"&&(te=!1),te){if(Ze.nodeName){const pt=$e(Ze.nodeName);if(!V[pt]||q[pt])throw kv("root node is forbidden and cannot be sanitized in-place")}}else if(Ze instanceof l)ct=qt(""),le=ct.ownerDocument.importNode(Ze,!0),le.nodeType===Tv.element&&le.nodeName==="BODY"||le.nodeName==="HTML"?ct=le:ct.appendChild(le);else{if(!ie&&!re&&!$&&Ze.indexOf("<")===-1)return C&&be?C.createHTML(Ze):Ze;if(ct=qt(Ze),!ct)return ie?null:be?k:""}ct&&W&&rt(ct.firstChild);const Ge=Kt(te?Ze:ct);for(;Le=Ge.nextNode();)Hn(Le),ot(Le),Le.content instanceof s&&st(Le.content);if(te)return Ze;if(ie){if(ce)for(Ye=D.call(ct.ownerDocument);ct.firstChild;)Ye.appendChild(ct.firstChild);else Ye=ct;return(se.shadowroot||se.shadowrootmode)&&(Ye=R.call(r,Ye,!0)),Ye}let Ie=$?ct.outerHTML:ct.innerHTML;return $&&V["!doctype"]&&ct.ownerDocument&&ct.ownerDocument.doctype&&ct.ownerDocument.doctype.name&&Ls(bie,ct.ownerDocument.doctype.name)&&(Ie=" + `,title:k("printers:control")?g(Ot?"printers.resume":"printers.pause"):g("printers.permission.noControl"),children:[Ot?i.jsx(Co,{className:"w-3 h-3"}):i.jsx(lT,{className:"w-3 h-3"}),g(Ot?"printers.resume":"printers.pause")]})]})]})]})})(),(Ut?.length>0||Qe.vt_tray.length>0)&&r==="expanded"&&(()=>{const ht=Ut.filter(ut=>ut.tray.length>1),Ot=Ut.filter(ut=>ut.tray.length===1),Gt=t.nozzle_count===2||Qe?.temperatures?.nozzle_2!==void 0;return i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:g("printers.filaments")}),i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),i.jsxs("div",{className:"space-y-3",children:[ht.length>0&&i.jsx("div",{className:"grid grid-cols-2 gap-3",children:ht.map(ut=>{const An=Tt[String(ut.id)],gr=ut.id>=128?ut.id-128:ut.id,Jn=An!==void 0?An:gr,Ca=Jn===1,Es=Jn===0;return i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx(AW,{ams:ut,printerId:t.id,label:Zc(ut.id,ut.tray.length),amsLabels:le,canEdit:k("printers:update"),onSaved:Le,children:i.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:le?.[ut.id]||Zc(ut.id,ut.tray.length)})}),Gt&&(Ca||Es)&&i.jsx(NW,{side:Ca?"L":"R"})]}),(ut.humidity!=null||ut.temp!=null)&&i.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[ut.humidity!=null&&i.jsx(CW,{humidity:ut.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>Pe({amsId:ut.id,amsLabel:Zc(ut.id,ut.tray.length),mode:"humidity"}),compact:!0}),ut.temp!=null&&i.jsx(TW,{temp:ut.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>Pe({amsId:ut.id,amsLabel:Zc(ut.id,ut.tray.length),mode:"temperature"}),compact:!0}),Qe.supports_drying&&(ut.module_type==="n3f"||ut.module_type==="n3s")&&k("printers:control")&&i.jsx("button",{disabled:!!(ut.dry_sf_reason?.length&&ut.dry_time===0),onClick:on=>{if(ut.dry_time>0)Fr.mutate(ut.id);else if(xe===ut.id)oe(null);else{const js=(ut.tray.find(ml=>ml.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Ds=b[js]||b.PLA,ul=ut.module_type;ve(js),me(Ds[ul]||Ds.n3f),we(ul==="n3s"?Ds.n3s_hours:Ds.n3f_hours),He(!1),F(ut.module_type),oe(ut.id);const dl=on.currentTarget.getBoundingClientRect();_e({top:dl.bottom+4,left:Math.max(8,dl.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ut.dry_time>0?"bg-amber-500/20 text-amber-400":ut.dry_sf_reason?.length?"bg-bambu-dark-tertiary/30 text-bambu-gray/50 cursor-not-allowed":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:ut.dry_time>0?g("printers.drying.stop"):ut.dry_sf_reason?.length?g("printers.drying.powerRequired"):g("printers.drying.start"),children:i.jsx(qp,{className:"w-3 h-3"})})]})]}),ut.dry_time>0&&i.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px]",children:[i.jsx(qp,{className:"w-3 h-3 text-amber-400 shrink-0"}),i.jsx("span",{className:"text-amber-400 font-medium",children:g("printers.drying.active")}),i.jsx("span",{className:"text-amber-300/70",children:g("printers.drying.timeRemaining",{time:ut.dry_time>=60?`${Math.floor(ut.dry_time/60)}h ${ut.dry_time%60}m`:`${ut.dry_time}m`})}),i.jsx("button",{onClick:()=>Fr.mutate(ut.id),disabled:Fr.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:g("printers.drying.stop"),children:i.jsx(Ht,{className:"w-3 h-3"})})]}),i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(on=>{const Pn=ut.tray[on]||ut.tray.find(Cn=>Cn.id===on),js=Pn?.tray_type&&Pn.remain>=0,Ds=!Pn?.tray_type,ul=ut.id*4+on,dl=Xt===ul,ml=Pn?.tray_info_idx?Ee?.[Pn.tray_info_idx]:null,Bi=ct?.[ul],$a=(Pn?.tray_uuid||Pn?.tag_uid||$p(t.serial_number,ut.id,on))?.toUpperCase(),ic=$a?l?.[$a]:void 0,cs=yN(ic),jo=d?.(t.id,ut.id,on),Uc=(()=>{const Cn=jo?.spool;return Cn&&Cn.label_weight>0&&Cn.weight_used!=null?Math.round(Math.max(0,Cn.label_weight-Cn.weight_used)/Cn.label_weight*100):null})(),ii=Uc===0&&js&&Pn.remain>0?null:Uc,Do=cs??ii??(js?Pn.remain:null),sp=cs!==null?"spoolman":ii!==null?"inventory":js?"ams":void 0,Pr=Pn?.tray_type?{vendor:iD(Pn)?"Bambu Lab":"Generic",profile:Bi?.preset_name||ml?.name||jo?.spool?.slicer_filament_name||Pn.tray_sub_brands||Pn.tray_type,colorName:tD(Pn.tray_id_name)||xN(Pn.tray_color),colorHex:Pn.tray_color||null,kFactor:nD(Pn.k),fillLevel:Do,trayUuid:Pn.tray_uuid||null,tagUid:Pn.tag_uid||null,fillSource:sp}:null,Fu=Ts?.amsId===ut.id&&Ts?.slotId===on,um=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ds?"opacity-50":""} ${dl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx(eD,{trayColor:Pn?.tray_color,trayType:Pn?.tray_type,isEmpty:Ds,slotNumber:on+1}),i.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Pn?.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Do!==null&&Do>=0&&Pn&&i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Do}%`,backgroundColor:ix(Do)}})})]});return i.jsxs("div",{className:"relative group",children:[Fu&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:i.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Qe?.state!=="RUNNING"&&i.jsx("button",{onClick:Cn=>{Cn.stopPropagation(),Eo(so?.amsId===ut.id&&so?.slotId===on?null:{amsId:ut.id,slotId:on})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:i.jsx(Nh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Qe?.state!=="RUNNING"&&so?.amsId===ut.id&&so?.slotId===on&&i.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:i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Cn=>{Cn.stopPropagation(),k("printers:ams_rfid")&&(As.mutate({amsId:ut.id,slotId:on}),Eo(null))},disabled:Fu||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[i.jsx(Sr,{className:`w-3 h-3 ${Fu?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Pr?i.jsx(Q2,{data:Pr,spoolman:{enabled:o,linkedSpoolId:$a?l?.[$a]?.id:void 0,spoolmanUrl:c,syncMode:u,onLinkSpool:o?()=>{const Cn=(Pr.trayUuid||Pr.tagUid||$p(t.serial_number,ut.id,on)).toUpperCase();Ve({tagUid:Pr.tagUid||Cn,trayUuid:Pr.trayUuid||"",printerId:t.id,amsId:ut.id,trayId:on})}:void 0,onUnlinkSpool:ic?.id?()=>fr.mutate(ic.id):void 0},inventory:o?void 0:(()=>{const Cn=d?.(t.id,ut.id,on);return{assignedSpool:Cn?.spool?{id:Cn.spool.id,material:Cn.spool.material,brand:Cn.spool.brand,color_name:Cn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Cn.spool.label_weight-Cn.spool.weight_used))}:null,onAssignSpool:Pr.vendor!=="Bambu Lab"?()=>Ce({printerId:t.id,amsId:ut.id,trayId:on,trayInfo:{type:Pn?.tray_type||Pr.profile,material:Pn?.tray_type??void 0,profile:Pr.profile,color:Pr.colorHex||"",location:`${Zc(ut.id,ut.tray.length)} Slot ${on+1}`}}):void 0,onUnassignSpool:Cn&&Pr.vendor!=="Bambu Lab"?()=>m?.(t.id,ut.id,on):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>nt({amsId:ut.id,trayId:on,trayCount:ut.tray.length,trayType:Pn?.tray_type||void 0,trayColor:Pn?.tray_color||void 0,traySubBrands:Pn?.tray_sub_brands||void 0,trayInfoIdx:Pn?.tray_info_idx||void 0,extruderId:An,caliIdx:Pn?.cali_idx,savedPresetId:Bi?.preset_id})},children:um}):i.jsx(Z2,{children:um})]},on)})})]},ut.id)})}),(Ot.length>0||Qe.vt_tray.length>0)&&i.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ot.map(ut=>{const An=Tt[String(ut.id)],gr=ut.id>=128?ut.id-128:ut.id,Jn=An!==void 0?An:gr,Ca=Jn===1,Es=Jn===0,on=ut.tray[0],Pn=on?.tray_type&&on.remain>=0,js=!on?.tray_type,Ds=Ex(ut.id,on?.id??0,!1),ul=Xt===Ds,dl=on?.tray_info_idx?Ee?.[on.tray_info_idx]:null,ml=ct?.[Ds],Bi=on?.id??0,$a=(on?.tray_uuid||on?.tag_uid||$p(t.serial_number,ut.id,Bi))?.toUpperCase(),ic=$a?l?.[$a]:void 0,cs=yN(ic),jo=d?.(t.id,ut.id,Bi),Uc=(()=>{const Cn=jo?.spool;return Cn&&Cn.label_weight>0&&Cn.weight_used!=null?Math.round(Math.max(0,Cn.label_weight-Cn.weight_used)/Cn.label_weight*100):null})(),ii=Uc===0&&Pn&&on.remain>0?null:Uc,Do=cs??ii??(Pn?on.remain:null),sp=cs!==null?"spoolman":ii!==null?"inventory":Pn?"ams":void 0,Pr=on?.tray_type?{vendor:iD(on)?"Bambu Lab":"Generic",profile:ml?.preset_name||dl?.name||jo?.spool?.slicer_filament_name||on.tray_sub_brands||on.tray_type,colorName:tD(on.tray_id_name)||xN(on.tray_color),colorHex:on.tray_color||null,kFactor:nD(on.k),fillLevel:Do,trayUuid:on.tray_uuid||null,tagUid:on.tag_uid||null,fillSource:sp}:null,Fu=Ts?.amsId===ut.id&&Ts?.slotId===Bi,um=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${js?"opacity-50":""} ${ul?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx(eD,{trayColor:on?.tray_color,trayType:on?.tray_type,isEmpty:js,slotNumber:1}),i.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:on?.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Do!==null&&Do>=0&&i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Do}%`,backgroundColor:ix(Do)}})})]});return i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[i.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[i.jsx(AW,{ams:ut,printerId:t.id,label:Zc(ut.id,ut.tray.length),amsLabels:le,canEdit:k("printers:update"),onSaved:Le,children:i.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:le?.[ut.id]||Zc(ut.id,ut.tray.length)})}),Gt&&(Ca||Es)&&i.jsx(NW,{side:Ca?"L":"R"}),Qe.supports_drying&&(ut.module_type==="n3f"||ut.module_type==="n3s")&&k("printers:control")&&i.jsx("div",{className:"relative ml-auto",children:i.jsx("button",{onClick:Cn=>{if(ut.dry_time>0)Fr.mutate(ut.id);else if(xe===ut.id)oe(null);else{const hy=(ut.tray.find(HA=>HA.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),op=b[hy]||b.PLA,Lu=ut.module_type;ve(hy),me(op[Lu]||op.n3f),we(Lu==="n3s"?op.n3s_hours:op.n3f_hours),He(!1),F(ut.module_type),oe(ut.id);const iS=Cn.currentTarget.getBoundingClientRect();_e({top:iS.bottom+4,left:Math.max(8,iS.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ut.dry_time>0?"bg-amber-500/20 text-amber-400":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:ut.dry_time>0?g("printers.drying.stop"):g("printers.drying.start"),children:i.jsx(qp,{className:"w-3 h-3"})})})]}),ut.dry_time>0&&i.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px] whitespace-nowrap overflow-hidden",children:[i.jsx(qp,{className:"w-3 h-3 text-amber-400 shrink-0"}),i.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:ut.dry_time>=60?`${Math.floor(ut.dry_time/60)}h ${ut.dry_time%60}m`:`${ut.dry_time}m`}),i.jsx("button",{onClick:()=>Fr.mutate(ut.id),disabled:Fr.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:g("printers.drying.stop"),children:i.jsx(Ht,{className:"w-3 h-3"})})]}),i.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[i.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[Fu&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:i.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Qe?.state!=="RUNNING"&&i.jsx("button",{onClick:Cn=>{Cn.stopPropagation(),Eo(so?.amsId===ut.id&&so?.slotId===Bi?null:{amsId:ut.id,slotId:Bi})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:i.jsx(Nh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Qe?.state!=="RUNNING"&&so?.amsId===ut.id&&so?.slotId===Bi&&i.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:i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Cn=>{Cn.stopPropagation(),k("printers:ams_rfid")&&(As.mutate({amsId:ut.id,slotId:Bi}),Eo(null))},disabled:Fu||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[i.jsx(Sr,{className:`w-3 h-3 ${Fu?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Pr?i.jsx(Q2,{data:Pr,spoolman:{enabled:o,linkedSpoolId:$a?l?.[$a]?.id:void 0,spoolmanUrl:c,syncMode:u,onLinkSpool:o?()=>{const Cn=(Pr.trayUuid||Pr.tagUid||$p(t.serial_number,ut.id,Bi)).toUpperCase();Ve({tagUid:Pr.tagUid||Cn,trayUuid:Pr.trayUuid||"",printerId:t.id,amsId:ut.id,trayId:Bi})}:void 0,onUnlinkSpool:ic?.id?()=>fr.mutate(ic.id):void 0},inventory:o?void 0:(()=>{const Cn=d?.(t.id,ut.id,Bi);return{assignedSpool:Cn?.spool?{id:Cn.spool.id,material:Cn.spool.material,brand:Cn.spool.brand,color_name:Cn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Cn.spool.label_weight-Cn.spool.weight_used))}:null,onAssignSpool:Pr.vendor!=="Bambu Lab"?()=>Ce({printerId:t.id,amsId:ut.id,trayId:Bi,trayInfo:{type:on?.tray_type||Pr.profile,material:on?.tray_type??void 0,profile:Pr.profile,color:Pr.colorHex||"",location:Zc(ut.id,ut.tray.length)}}):void 0,onUnassignSpool:Cn&&Pr.vendor!=="Bambu Lab"?()=>m?.(t.id,ut.id,Bi):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>nt({amsId:ut.id,trayId:Bi,trayCount:ut.tray.length,trayType:on?.tray_type||void 0,trayColor:on?.tray_color||void 0,traySubBrands:on?.tray_sub_brands||void 0,trayInfoIdx:on?.tray_info_idx||void 0,extruderId:An,caliIdx:on?.cali_idx,savedPresetId:ml?.preset_id})},children:um}):i.jsx(Z2,{children:um})]}),(ut.humidity!=null||ut.temp!=null)&&i.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[ut.temp!=null&&i.jsx(TW,{temp:ut.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>Pe({amsId:ut.id,amsLabel:Zc(ut.id,ut.tray.length),mode:"temperature"}),compact:!0}),ut.humidity!=null&&i.jsx(CW,{humidity:ut.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>Pe({amsId:ut.id,amsLabel:Zc(ut.id,ut.tray.length),mode:"humidity"}),compact:!0})]})]})]},ut.id)}),Qe.vt_tray.length>0&&i.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${Qe.vt_tray.length===1?"max-w-[50%]":""}`,children:[i.jsx("div",{className:"flex items-center gap-1 mb-2",children:i.jsx("span",{className:"text-[10px] text-white font-medium",children:g("printers.external")})}),i.jsx("div",{className:`grid ${Qe.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...Qe.vt_tray].sort((ut,An)=>(ut.id??254)-(An.id??254)).map(ut=>{const An=ut.id??254,gr=Gt&&Xt===254?An===254&&Qe.active_extruder===1||An===255&&Qe.active_extruder===0:Xt===An,Jn=An-254,Ca=Gt?g(An===254?"printers.extL":"printers.extR"):"",Es=ut.tray_info_idx?Ee?.[ut.tray_info_idx]:null,on=ct?.[1020+Jn],Pn=(ut.tray_uuid||ut.tag_uid||$p(t.serial_number,255,Jn))?.toUpperCase(),js=Pn?l?.[Pn]:void 0,Ds=yN(js),ul=d?.(t.id,255,Jn),dl=(()=>{const ii=ul?.spool;return ii&&ii.label_weight>0&&ii.weight_used!=null?Math.round(Math.max(0,ii.label_weight-ii.weight_used)/ii.label_weight*100):null})(),ml=ut.tray_type&&ut.remain>=0,Bi=dl===0&&ml&&ut.remain>0?null:dl,$a=Ds??Bi??(ml?ut.remain:null),ic=Ds!==null?"spoolman":Bi!==null?"inventory":ml?"ams":void 0,cs={vendor:iD(ut)?"Bambu Lab":"Generic",profile:on?.preset_name||Es?.name||ul?.spool?.slicer_filament_name||ut.tray_sub_brands||ut.tray_type||"Unknown",colorName:tD(ut.tray_id_name)||xN(ut.tray_color),colorHex:ut.tray_color||null,kFactor:nD(ut.k),fillLevel:$a,trayUuid:ut.tray_uuid||null,tagUid:ut.tag_uid||null,fillSource:ic},jo=!ut.tray_type,Uc=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${jo?"opacity-50":""} ${gr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx(eD,{trayColor:ut.tray_color,trayType:ut.tray_type,isEmpty:jo,slotNumber:Jn+1}),i.jsx("div",{className:`text-[9px] font-bold truncate ${jo?"text-white/40":"text-white"}`,children:ut.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:$a!==null&&$a>=0&&!jo&&i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${$a}%`,backgroundColor:ix($a)}})}),Ca&&i.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:Ca})]});return i.jsx("div",{className:"relative group",children:jo?i.jsx(Z2,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>nt({amsId:255,trayId:Jn,trayCount:1,extruderId:Gt?An===254?1:0:void 0})},inventory:o?void 0:{onAssignSpool:()=>Ce({printerId:t.id,amsId:255,trayId:Jn,trayInfo:{type:"",color:"",location:Ca||g("printers.external")}})},children:Uc}):i.jsx(Q2,{data:cs,spoolman:{enabled:o,linkedSpoolId:Pn?l?.[Pn]?.id:void 0,spoolmanUrl:c,syncMode:u,onLinkSpool:o?()=>{const ii=(cs.trayUuid||cs.tagUid||$p(t.serial_number,255,Jn)).toUpperCase();Ve({tagUid:cs.tagUid||ii,trayUuid:cs.trayUuid||"",printerId:t.id,amsId:255,trayId:Jn})}:void 0,onUnlinkSpool:js?.id?()=>fr.mutate(js.id):void 0},inventory:o?void 0:(()=>{const ii=d?.(t.id,255,Jn);return{assignedSpool:ii?.spool?{id:ii.spool.id,material:ii.spool.material,brand:ii.spool.brand,color_name:ii.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(ii.spool.label_weight-ii.spool.weight_used))}:null,onAssignSpool:()=>Ce({printerId:t.id,amsId:255,trayId:Jn,trayInfo:{type:ut.tray_type||cs.profile,material:ut.tray_type??void 0,profile:cs.profile,color:cs.colorHex||"",location:Ca||g("printers.external")}}),onUnassignSpool:ii?()=>m?.(t.id,255,Jn):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>nt({amsId:255,trayId:Jn,trayCount:1,trayType:ut.tray_type||void 0,trayColor:ut.tray_color||void 0,traySubBrands:ut.tray_sub_brands||void 0,trayInfoIdx:ut.tray_info_idx||void 0,extruderId:Gt?An===254?1:0:void 0,caliIdx:ut.cali_idx,savedPresetId:on?.preset_id})},children:Uc})},An)})})]})]})]})]})})()]}),tn&&r==="expanded"&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsx(Pc,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"text-sm text-white truncate",children:tn.name}),kn&&i.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${kn.state==="ON"?"bg-bambu-green/20 text-bambu-green":kn.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[kn.state||"?",kn.state==="ON"&&kn.energy?.power!=null&&i.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",kn.energy.power,"W"]})]})]}),i.jsx("div",{className:"flex-1"}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("button",{onClick:()=>de(!0),disabled:Ua.isPending||kn?.state==="ON"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?kn?.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:k("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[i.jsx(em,{className:"w-3 h-3"}),"On"]}),i.jsxs("button",{onClick:()=>V(!0),disabled:Ua.isPending||kn?.state==="OFF"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?kn?.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:k("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[i.jsx(cT,{className:"w-3 h-3"}),"Off"]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx("span",{className:`text-xs hidden sm:inline ${tn.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:tn.auto_off_executed?"Auto-off done":"Auto-off"}),i.jsx("button",{onClick:()=>ap.mutate(!tn.auto_off),disabled:ap.isPending||tn.auto_off_executed||!k("smart_plugs:control"),title:k("smart_plugs:control")?tn.auto_off_executed?g("printers.autoOffExecuted"):g("printers.autoOffAfterPrint"):g("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${k("smart_plugs:control")?tn.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":tn.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:i.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${tn.auto_off||tn.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),wn&&wn.length>0&&i.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[i.jsx(vw,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:wn.map(ht=>{const Ot=ht.ha_entity_id?.startsWith("script.");return i.jsxs("button",{onClick:()=>Ui.mutate({id:ht.id,action:Ot?"on":"toggle"}),disabled:Ui.isPending,title:`${Ot?"Run":"Toggle"} ${ht.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:[i.jsx(Co,{className:"w-2.5 h-2.5"}),ht.name]},ht.id)})})]})]}),r==="expanded"&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>Du.mutate(!Qe?.chamber_light),disabled:!Qe?.connected||Du.isPending||!k("printers:control"),title:k("printers:control")?Qe?.chamber_light?g("printers.chamberLightOff"):g("printers.chamberLightOn"):g("printers.permission.noControl"),className:Qe?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:i.jsx(PO,{on:Qe?.chamber_light??!1,className:`w-4 h-4 ${Qe?.chamber_light?"text-yellow-400":""}`})}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>{if(f==="embedded"&&y)y(t.id,t.name);else{const ht=localStorage.getItem("cameraWindowState"),Ot=ht?JSON.parse(ht):{width:640,height:400},Gt=[`width=${Ot.width}`,`height=${Ot.height}`,Ot.left!==void 0?`left=${Ot.left}`:"",Ot.top!==void 0?`top=${Ot.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,Gt)}},disabled:!Qe?.connected||!k("camera:view"),title:k("camera:view")?g(f==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):g("printers.permission.noCamera"),children:i.jsx(QL,{className:"w-4 h-4"})}),i.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[i.jsx(ze,{variant:"secondary",size:"sm",onClick:Ic,disabled:!Qe?.connected||ll.isPending||!k("printers:update"),title:k("printers:update")?t.plate_detection_enabled?g("printers.plateDetection.enabledClick"):g("printers.plateDetection.disabledClick"):g("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:ll.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(BN,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:rc,disabled:!Qe?.connected||Nt||!k("printers:update"),title:k("printers:update")?g("printers.plateDetection.manageCalibration"):g("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Nt?i.jsx(ft,{className:"w-3 h-3 animate-spin"}):i.jsx(In,{className:"w-3 h-3"})})]}),i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>J(!0),disabled:!dt||!k("printers:files"),title:k("printers:files")?g("printers.browseFiles"):g("printers.permission.noFiles"),children:[i.jsx(Vx,{className:"w-4 h-4"}),g("printers.files")]}),dt&&Qe?.state!=="RUNNING"&&Qe?.state!=="PAUSE"&&i.jsxs(ze,{size:"sm",onClick:()=>$(!0),disabled:!k("printers:control"),title:k("printers:control")?g("common.print"):g("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[i.jsx(_r,{className:"w-4 h-4"}),g("common.print")]})]})]}),I&&i.jsx(cMe,{printerId:t.id,printerName:t.name,onClose:()=>J(!1)}),O&&i.jsx(nie,{folderId:null,onClose:()=>$(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:ht=>{const Ot=ht.name.toLowerCase();if(!Ot.endsWith(".gcode")&&!Ot.includes(".gcode."))return g("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:ht=>{const Ot=ht.metadata?.sliced_for_model,Gt=t0(t.model);if(Ot&&Gt&&Ot.toLowerCase()!==Gt.toLowerCase())return ge.deleteLibraryFile(ht.id).catch(()=>{}),g("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:Ot,printerModel:Gt});be({id:ht.id,filename:ht.filename})}}),ce&&i.jsx(xu,{mode:"reprint",libraryFileId:ce.id,archiveName:ce.filename,initialSelectedPrinterIds:[t.id],onClose:()=>be(null),onSuccess:()=>be(null)}),ae&&i.jsx(fMe,{printerId:t.id,printerName:t.name,onClose:()=>Y(!1)}),ee&&i.jsx(Zqe,{printer:t,status:Qe,totalPrintHours:n?.total_print_hours,onClose:ie}),mt&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>ao(),children:i.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:ht=>ht.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[mt.needs_calibration?i.jsx(BN,{className:"w-5 h-5 text-blue-500"}):mt.is_empty?i.jsx(pr,{className:"w-5 h-5 text-green-500"}):i.jsx(Vi,{className:"w-5 h-5 text-yellow-500"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),mt.reference_count!==void 0&&mt.max_references&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[mt.reference_count,"/",mt.max_references," refs"]})]}),i.jsx("button",{onClick:()=>ao(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[mt.needs_calibration?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[i.jsx("p",{className:"font-medium text-blue-400",children:g("printers.plateDetection.calibrationRequired")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationInstructions")}})]}),i.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[i.jsx("p",{children:g("printers.plateDetection.calibrationDescription")}),i.jsx("p",{dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationTip")}})]})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`p-3 rounded-lg ${mt.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[i.jsx("p",{className:`font-medium ${mt.is_empty?"text-green-400":"text-yellow-400"}`,children:mt.is_empty?g("printers.plateDetection.plateEmpty"):g("printers.plateDetection.objectsDetected")}),i.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[g("printers.plateDetection.confidence"),": ",Math.round(mt.confidence*100),"% | ",g("printers.plateDetection.difference"),": ",mt.difference_percent.toFixed(1),"%"]})]}),mt.debug_image_url&&i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:g("printers.plateDetection.analysisPreview")}),i.jsx("img",{src:mt.debug_image_url,alt:g("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:g("printers.plateDetection.analysisLegend")})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:mt.message})]}),Ps&&Ps.references.length>0&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-sm font-medium text-white mb-2",children:g("printers.plateDetection.savedReferences",{count:Ps.references.length,max:Ps.max_references})}),i.jsx("div",{className:"grid grid-cols-5 gap-2",children:Ps.references.map(ht=>i.jsxs("div",{className:"relative group",children:[i.jsx("img",{src:ge.getPlateReferenceThumbnailUrl(t.id,ht.index),alt:ht.label||`Reference ${ht.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),i.jsx("button",{onClick:()=>un(ht.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:g("printers.plateDetection.deleteReference"),children:i.jsx(Ht,{className:"w-3 h-3 text-white"})}),ka?.index===ht.index?i.jsx("input",{type:"text",value:ka.label,onChange:Ot=>cl({...ka,label:Ot.target.value}),onBlur:()=>Xi(ht.index,ka.label),onKeyDown:Ot=>{Ot.key==="Enter"&&Xi(ht.index,ka.label),Ot.key==="Escape"&&cl(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:g("printers.plateDetection.labelPlaceholder")}):i.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>cl({index:ht.index,label:ht.label}),title:ht.label?g("printers.plateDetection.clickToEdit",{label:ht.label}):g("printers.plateDetection.clickToAddLabel"),children:ht.label||i.jsx("span",{className:"italic opacity-50",children:g("printers.noLabel")})}),i.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:ht.timestamp?Qn(ht.timestamp)?.toLocaleDateString()??"":""})]},ht.index))})]}),!mt.needs_calibration&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:g("printers.roi.title")}),qt?i.jsxs("div",{className:"flex gap-1",children:[i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>Kt(null),disabled:Qt,children:g("common.cancel")}),i.jsx(ze,{size:"sm",onClick:lm,disabled:Qt,children:Qt?i.jsx(ft,{className:"w-3 h-3 animate-spin"}):g("common.save")})]}):i.jsxs(ze,{variant:"ghost",size:"sm",onClick:()=>Kt(mt.roi||{x:.15,y:.35,w:.7,h:.55}),children:[i.jsx(Yi,{className:"w-3 h-3 mr-1"}),g("common.edit")]})]}),qt?i.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.xStart")}),i.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:qt.x,onChange:ht=>Kt({...qt,x:parseFloat(ht.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(qt.x*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.yStart")}),i.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:qt.y,onChange:ht=>Kt({...qt,y:parseFloat(ht.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(qt.y*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.width")}),i.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:qt.w,onChange:ht=>Kt({...qt,w:parseFloat(ht.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(qt.w*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.height")}),i.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:qt.h,onChange:ht=>Kt({...qt,h:parseFloat(ht.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(qt.h*100),"%"]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:g("printers.roi.instruction")})]}):i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((mt.roi?.x||.15)*100),"%, Y=",Math.round((mt.roi?.y||.35)*100),"%, W=",Math.round((mt.roi?.w||.7)*100),"%, H=",Math.round((mt.roi?.h||.55)*100),"%"]})]})]}),i.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:mt.needs_calibration?i.jsxs(i.Fragment,{children:[i.jsx(ze,{variant:"ghost",onClick:()=>ao(),children:g("common.cancel")}),i.jsx(ze,{onClick:()=>om(),disabled:rt,children:rt?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):i.jsxs(i.Fragment,{children:[i.jsx(ze,{variant:"ghost",onClick:()=>om(),disabled:rt,children:rt?"Adding...":`Add Reference (${Ps?.references.length||0}/${Ps?.max_references||5})`}),i.jsx(ze,{onClick:()=>ao(),children:"Close"})]})})]})}),ue&&tn&&i.jsx(Nn,{title:g("printers.confirm.powerOnTitle"),message:g("printers.confirm.powerOnMessage",{name:t.name}),confirmText:g("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Ua.mutate("on"),de(!1)},onCancel:()=>de(!1)}),he&&tn&&i.jsx(Nn,{title:g("printers.confirm.powerOffTitle"),message:Qe?.state==="RUNNING"?g("printers.confirm.powerOffWarning",{name:t.name}):g("printers.confirm.powerOffMessage",{name:t.name}),confirmText:g("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Ua.mutate("off"),V(!1)},onCancel:()=>V(!1)}),pe&&i.jsx(Nn,{title:g("printers.confirm.stopTitle"),message:g("printers.confirm.stopMessage",{name:t.name}),confirmText:g("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{ju.mutate(),Te(!1)},onCancel:()=>Te(!1)}),q&&i.jsx(Nn,{title:g("printers.confirm.pauseTitle"),message:g("printers.confirm.pauseMessage",{name:t.name}),confirmText:g("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{cg.mutate(),X(!1)},onCancel:()=>X(!1)}),U&&i.jsx(Nn,{title:g("printers.confirm.resumeTitle"),message:g("printers.confirm.resumeMessage",{name:t.name}),confirmText:g("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{tc.mutate(),K(!1)},onCancel:()=>K(!1)}),i.jsx(MO,{printerId:t.id,isOpen:H,onClose:()=>re(!1)}),ne&&i.jsx(xMe,{printerName:t.name,errors:Qe?.hms_errors||[],onClose:()=>se(!1),printerId:t.id,hasPermission:k}),We&&i.jsx(Aqe,{isOpen:!!We,onClose:()=>Pe(null),printerId:t.id,printerName:t.name,amsId:We.amsId,amsLabel:We.amsLabel,initialMode:We.mode,thresholds:s}),Ke&&i.jsx(Pqe,{isOpen:!!Ke,onClose:()=>Ve(null),tagUid:Ke.tagUid,trayUuid:Ke.trayUuid,printerId:Ke.printerId,amsId:Ke.amsId,trayId:Ke.trayId}),ke&&i.jsx(Mqe,{isOpen:!!ke,onClose:()=>Ce(null),printerId:ke.printerId,amsId:ke.amsId,trayId:ke.trayId,trayInfo:ke.trayInfo}),$e&&i.jsx(tie,{isOpen:!!$e,onClose:()=>nt(null),printerId:t.id,slotInfo:$e,printerModel:t0(t.model)||void 0,onSuccess:()=>{_.invalidateQueries({queryKey:["slotPresets",t.id]}),_.invalidateQueries({queryKey:["printerStatus",t.id]})}}),z&&i.jsx(mVe,{printer:t,onClose:()=>Z(!1)}),xt&&De&&i.jsx(dVe,{printer:t,firmwareInfo:De,onClose:()=>vt(!1)}),so&&i.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Eo(null)}),xe!==null&&Oe&&(()=>{const ht=L==="n3s"?85:65,Ot=35,Gt=ht+10;return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>oe(null)}),i.jsxs("div",{className:"fixed z-[101] w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden",style:{top:Oe.top,left:Oe.left},onClick:ut=>ut.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[i.jsx(qp,{className:"w-3.5 h-3.5 text-amber-400"}),i.jsx("span",{className:"text-xs text-white font-medium",children:g("printers.drying.start")})]}),i.jsxs("div",{className:"px-3 py-2.5 space-y-2.5",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:g("printers.filaments")}),i.jsx("select",{value:te,onChange:ut=>{const An=ut.target.value;ve(An);const gr=b[An];gr&&(me(gr[L==="n3s"?"n3s":"n3f"]),we(L==="n3s"?gr.n3s_hours:gr.n3f_hours))},className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs focus:outline-none focus:border-amber-500/50",children:Object.keys(b).map(ut=>i.jsx("option",{value:ut,children:ut},ut))})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-1",children:[i.jsx("label",{className:"text-[10px] text-bambu-gray",children:g("printers.drying.temperature")}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("input",{type:"number",min:45,max:ht,value:fe,onChange:ut=>me(Math.min(ht,Math.max(45,Number(ut.target.value)||45))),className:"w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),i.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),i.jsx("input",{type:"range",min:Ot,max:Gt,value:fe,onChange:ut=>me(Math.min(ht,Math.max(45,Number(ut.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),i.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[i.jsx("span",{children:"45°C"}),i.jsxs("span",{children:[ht,"°C"]})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-1",children:[i.jsx("label",{className:"text-[10px] text-bambu-gray",children:g("printers.drying.duration")}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("input",{type:"number",min:1,max:24,value:je,onChange:ut=>we(Math.min(24,Math.max(1,Number(ut.target.value)||1))),className:"w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),i.jsx("span",{className:"text-[10px] text-bambu-gray",children:g("printers.drying.hours")})]})]}),i.jsx("input",{type:"range",min:1,max:24,value:je,onChange:ut=>we(Number(ut.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),i.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[i.jsx("span",{children:"1h"}),i.jsx("span",{children:"24h"})]})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:Fe,onChange:ut=>He(ut.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),i.jsx("span",{className:"text-[11px] text-bambu-gray",children:g("printers.drying.rotateTray")})]})]}),i.jsx("div",{className:"px-3 pb-3",children:i.jsx("button",{onClick:()=>{xe!==null&&bi.mutate({amsId:xe,temp:fe,duration:je,filament:te,rotateTray:Fe})},disabled:bi.isPending,className:"w-full py-1.5 bg-amber-500 hover:bg-amber-400 text-white text-xs font-medium rounded-lg transition-colors disabled:opacity-50",children:bi.isPending?g("printers.drying.startingDrying"):g("printers.drying.start")})})]})]})})()]})}function uVe({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Dt(),[a,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,u]=w.useState([]),[d,m]=w.useState(""),[p,f]=w.useState(!1),[y,v]=w.useState(!1),[b,g]=w.useState([]),[_,N]=w.useState(""),[C,k]=w.useState({scanned:0,total:0});w.useEffect(()=>{Vc.getInfo().then(A=>{v(A.is_docker),A.subnets.length>0&&(g(A.subnets),N(A.subnets[0]))}).catch(()=>{})},[]);const P=c.filter(A=>!n.includes(A.serial)),T=async()=>{m(""),u([]),l(!0),f(!1),k({scanned:0,total:0});try{if(y){await Vc.startSubnetScan(_);const A=setInterval(async()=>{try{const R=await Vc.getScanStatus();k({scanned:R.scanned,total:R.total});const G=await Vc.getDiscoveredPrinters();u(G),R.running||(clearInterval(A),l(!1),f(!0))}catch(R){console.error("Failed to get scan status:",R)}},500)}else{await Vc.startDiscovery(10);const A=setInterval(async()=>{try{const R=await Vc.getDiscoveredPrinters();u(R)}catch(R){console.error("Failed to get discovered printers:",R)}},1e3);setTimeout(async()=>{clearInterval(A);try{await Vc.stopDiscovery()}catch{}l(!1),f(!0);try{const R=await Vc.getDiscoveredPrinters();u(R)}catch(R){console.error("Failed to get final discovered printers:",R)}},1e4)}}catch(A){console.error("Failed to start discovery:",A),m(A instanceof Error?A.message:r("printers.discovery.failedToStart")),l(!1),f(!0)}},D=A=>{const R=A.serial.startsWith("unknown-")?"":A.serial;s({...a,name:A.name||"",serial_number:R,ip_address:A.ip_address,model:t0(A.model)}),u([])};return w.useEffect(()=>()=>{Vc.stopDiscovery().catch(()=>{}),Vc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const A=R=>{R.key==="Escape"&&t()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:i.jsx(Pt,{className:"w-full max-w-md",onClick:A=>A.stopPropagation(),children:i.jsxs(Et,{children:[i.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),i.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[y&&i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),b.length>0?i.jsx("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:A=>N(A.target.value),disabled:o,children:b.map(A=>i.jsx("option",{value:A,children:A},A))}):i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:A=>N(A.target.value),placeholder:"192.168.1.0/24",disabled:o}),i.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),i.jsx(ze,{type:"button",variant:"secondary",onClick:T,disabled:o,className:"w-full",children:o?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),y&&C.total>0?r("printers.discovery.scanProgress",{scanned:C.scanned,total:C.total}):r("printers.discovery.scanning")]}):i.jsxs(i.Fragment,{children:[i.jsx(Rr,{className:"w-4 h-4"}),r(y?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),d&&i.jsx("div",{className:"mt-2 text-sm text-red-400",children:d}),P.length>0&&i.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:P.map(A=>i.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:()=>D(A),children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"font-medium text-white text-sm truncate",children:A.name||A.serial}),i.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[t0(A.model)||r("printers.discovery.unknown")," • ",A.ip_address,A.serial.startsWith("unknown-")&&i.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),i.jsx(In,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},A.serial))}),o&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(y?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(y?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&P.length===0&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),i.jsxs("form",{onSubmit:A=>{A.preventDefault(),e(a)},className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),i.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:a.name,onChange:A=>s({...a,name:A.target.value}),placeholder:r("printers.modal.myPrinter")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),i.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:a.ip_address,onChange:A=>s({...a,ip_address:A.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),i.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:a.serial_number,onChange:A=>s({...a,serial_number:A.target.value}),placeholder:"01P00A000000000"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),i.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:a.access_code,onChange:A=>s({...a,access_code:A.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),i.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:a.model||"",onChange:A=>s({...a,model:A.target.value}),children:[i.jsx("option",{value:"",children:r("printers.modal.selectModel")}),i.jsxs("optgroup",{label:"H2 Series",children:[i.jsx("option",{value:"H2C",children:"H2C"}),i.jsx("option",{value:"H2D",children:"H2D"}),i.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),i.jsx("option",{value:"H2S",children:"H2S"})]}),i.jsxs("optgroup",{label:"X1 Series",children:[i.jsx("option",{value:"X1E",children:"X1E"}),i.jsx("option",{value:"X1C",children:"X1 Carbon"}),i.jsx("option",{value:"X1",children:"X1"})]}),i.jsxs("optgroup",{label:"P Series",children:[i.jsx("option",{value:"P2S",children:"P2S"}),i.jsx("option",{value:"P1S",children:"P1S"}),i.jsx("option",{value:"P1P",children:"P1P"})]}),i.jsxs("optgroup",{label:"A1 Series",children:[i.jsx("option",{value:"A1",children:"A1"}),i.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),i.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:a.location||"",onChange:A=>s({...a,location:A.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"auto_archive",checked:a.auto_archive,onChange:A=>s({...a,auto_archive:A.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),i.jsxs("div",{className:"flex gap-3 pt-4",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsx(ze,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function dVe({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Dt(),a=sn(),{showToast:s}=bn(),{hasPermission:o}=Ar(),l=o("firmware:update"),[c,u]=w.useState(null),[d,m]=w.useState(!1),[p,f]=w.useState(null),{data:y,isLoading:v}=et({queryKey:["firmwarePrepare",t.id],queryFn:()=>nN.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),b=gt({mutationFn:()=>nN.startUpload(t.id),onSuccess:()=>{m(!0);const _=setInterval(async()=>{try{const N=await nN.getUploadStatus(t.id);u(N),(N.status==="complete"||N.status==="error")&&(clearInterval(_),f(null),m(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),a.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(_)},onError:_=>{s(r("printers.firmwareModal.uploadFailed",{error:_.message}),"error"),m(!1)}});w.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const g=()=>{u(null),b.mutate()};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:i.jsx(Pt,{className:"w-full max-w-md mx-4",children:i.jsxs(Et,{children:[i.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[i.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?i.jsx(fi,{className:"w-5 h-5 text-orange-400"}):i.jsx(pr,{className:"w-5 h-5 text-status-ok"})}),i.jsxs("div",{className:"flex-1",children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[i.jsxs("div",{className:"flex justify-between items-center text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),i.jsx("span",{className:`font-mono ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&i.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[i.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),i.jsx("span",{className:"text-orange-400 font-mono",children:e.latest_version})]}),e.release_notes&&i.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[i.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),i.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:e.release_notes})]})]}),e.update_available?v?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):y&&!d&&!c?i.jsx("div",{className:"mb-4",children:y.can_proceed?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[i.jsx(ia,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):i.jsx("div",{className:"space-y-1",children:y.errors.map((_,N)=>i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(Li,{className:"w-4 h-4 flex-shrink-0"}),_]},N))})}):null:null,(d||c)&&c&&i.jsxs("div",{className:"mb-4",children:[i.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),i.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),i.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:i.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}%`}})}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&i.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[i.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),i.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),i.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),i.jsxs("div",{className:"flex gap-2 justify-end",children:[i.jsx(ze,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),y?.can_proceed&&!d&&c?.status!=="complete"&&l&&i.jsx(ze,{onClick:g,disabled:b.isPending,children:b.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):i.jsxs(i.Fragment,{children:[i.jsx(fi,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function mVe({printer:t,onClose:e}){const{t:n}=Dt(),r=sn(),{showToast:a}=bn(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=gt({mutationFn:u=>ge.updatePrinter(t.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:u=>a(u.message||n("printers.toast.failedToUpdate"),"error")});w.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 i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:i.jsx(Pt,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:i.jsxs(Et,{children:[i.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),i.jsxs("form",{onSubmit:c,className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),i.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")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),i.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),i.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}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),i.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")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),i.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:[i.jsx("option",{value:"",children:n("printers.modal.selectModel")}),i.jsxs("optgroup",{label:"H2 Series",children:[i.jsx("option",{value:"H2C",children:"H2C"}),i.jsx("option",{value:"H2D",children:"H2D"}),i.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),i.jsx("option",{value:"H2S",children:"H2S"})]}),i.jsxs("optgroup",{label:"X1 Series",children:[i.jsx("option",{value:"X1E",children:"X1E"}),i.jsx("option",{value:"X1C",children:"X1 Carbon"}),i.jsx("option",{value:"X1",children:"X1"})]}),i.jsxs("optgroup",{label:"P Series",children:[i.jsx("option",{value:"P2S",children:"P2S"}),i.jsx("option",{value:"P1S",children:"P1S"}),i.jsx("option",{value:"P1P",children:"P1P"})]}),i.jsxs("optgroup",{label:"A1 Series",children:[i.jsx("option",{value:"A1",children:"A1"}),i.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),i.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")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.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"}),i.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),i.jsxs("div",{className:"flex gap-3 pt-4",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),i.jsx(ze,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function hVe(t){const{data:e}=et({queryKey:["printerStatus",t],queryFn:()=>ge.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function pVe({printer:t,plug:e,onPowerOn:n,isPowering:r}){const a=hVe(t.id),{data:s}=et({queryKey:["smartPlugStatus",e.id],queryFn:()=>ge.getSmartPlugStatus(e.id),refetchInterval:1e4});return a?i.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&i.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||"?"})]}),i.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:[i.jsx(em,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function fVe(){const{t}=Dt(),[e,n]=w.useState(!1),[r,a]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[u,d]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,y]=w.useState(()=>{const re=localStorage.getItem("printerCardSize");return re?parseInt(re,10):2}),v=f===1?"compact":"expanded",b=sn(),{showToast:g}=bn(),{hasPermission:_}=Ar(),[N,C]=w.useState(()=>{const re=localStorage.getItem("openEmbeddedCameras");if(re)try{const O=JSON.parse(re);return new Map(O.map($=>[$.id,$]))}catch{return new Map}return new Map});w.useEffect(()=>{const re=Array.from(N.values());re.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(re)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:k,isLoading:P}=et({queryKey:["printers"],queryFn:ge.getPrinters}),{data:T}=et({queryKey:["settings"],queryFn:ge.getSettings}),D=w.useMemo(()=>{if(T?.drying_presets)try{const re=JSON.parse(T.drying_presets);if(typeof re=="object"&&re!==null&&Object.keys(re).length>0)return{...OF,...re}}catch{}return OF},[T?.drying_presets]);w.useEffect(()=>{T?.camera_view_mode==="window"&&N.size>0&&C(new Map)},[T?.camera_view_mode,N.size]);const{data:A}=et({queryKey:["smart-plugs"],queryFn:ge.getSmartPlugs}),{data:R}=et({queryKey:["maintenanceOverview"],queryFn:ge.getMaintenanceOverview,staleTime:60*1e3}),{data:G}=et({queryKey:["spoolman-status"],queryFn:ge.getSpoolmanStatus,staleTime:60*1e3}),z=G?.enabled&&G?.connected,{data:Z}=et({queryKey:["spoolman-settings"],queryFn:ge.getSpoolmanSettings,enabled:!!z,staleTime:60*1e3}),I=Z?.spoolman_sync_mode,{data:J}=et({queryKey:["unlinked-spools"],queryFn:ge.getUnlinkedSpools,enabled:!!z,staleTime:30*1e3}),ae=J&&J.length>0,{data:Y}=et({queryKey:["linked-spools"],queryFn:ge.getLinkedSpools,enabled:!!z,staleTime:30*1e3}),ue=Y?.linked,{data:de}=et({queryKey:["spool-assignments"],queryFn:()=>ge.getAssignments(),enabled:_("inventory:view_assignments"),staleTime:30*1e3}),he=gt({mutationFn:({printerId:re,amsId:O,trayId:$})=>ge.unassignSpool(re,O,$),onSuccess:()=>{b.invalidateQueries({queryKey:["spool-assignments"]})}}),V=(re,O,$)=>de?.find(ee=>ee.printer_id===re&&ee.ams_id===Number(O)&&ee.tray_id===Number($)),ne=R?.reduce((re,O)=>(re[O.printer_id]={due_count:O.due_count,warning_count:O.warning_count,total_print_hours:O.total_print_hours},re),{})||{},se=A?.reduce((re,O)=>(O.printer_id&&(re[O.printer_id]=O),re),{})||{},pe=gt({mutationFn:ge.createPrinter,onSuccess:()=>{b.invalidateQueries({queryKey:["printers"]}),b.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:re=>g(re.message||t("printers.toast.failedToAdd"),"error")}),Te=gt({mutationFn:re=>ge.controlSmartPlug(re,"on"),onSuccess:()=>{b.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),q=()=>{const re=!r;a(re),localStorage.setItem("hideDisconnectedPrinters",String(re))},X=re=>{d(re),localStorage.setItem("printerSortBy",re)},j=()=>{const re=!m;p(re),localStorage.setItem("printerSortAsc",String(re))},E=()=>{switch(f){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"}},U=["S","M","L","XL"],K=w.useMemo(()=>{if(!k)return[];const re=[...k];switch(u){case"name":re.sort((O,$)=>O.name.localeCompare($.name));break;case"model":re.sort((O,$)=>(O.model||"").localeCompare($.model||""));break;case"location":re.sort((O,$)=>{const ee=O.location||"",W=$.location||"";return!ee&&W?1:ee&&!W?-1:ee.localeCompare(W)||O.name.localeCompare($.name)});break;case"status":re.sort((O,$)=>{const ee=b.getQueryData(["printerStatus",O.id]),W=b.getQueryData(["printerStatus",$.id]),ie=ce=>ce?.connected?(ce.hms_errors?nk(ce.hms_errors):[]).length>0?0:ce.state==="RUNNING"?1:2:3;return ie(ee)-ie(W)});break}return m||re.reverse(),re},[k,u,m,b]),H=w.useMemo(()=>{if(u!=="location")return null;const re={};return K.forEach(O=>{const $=O.location||"Ungrouped";re[$]||(re[$]=[]),re[$].push(O)}),re},[u,K]);return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),i.jsx(cVe,{printers:k})]}),i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("select",{value:u,onChange:re=>X(re.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:[i.jsx("option",{value:"name",children:t("printers.sort.name")}),i.jsx("option",{value:"status",children:t("printers.sort.status")}),i.jsx("option",{value:"model",children:t("printers.sort.model")}),i.jsx("option",{value:"location",children:t("printers.sort.location")})]}),i.jsx("button",{onClick:j,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?i.jsx(Af,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(cx,{className:"w-4 h-4 text-bambu-gray"})})]}),i.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:U.map((re,O)=>{const $=O+1,ee=f===$;return i.jsx("button",{onClick:()=>{y($),localStorage.setItem("printerCardSize",String($))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${O===0?"rounded-l-lg":""} ${O===U.length-1?"rounded-r-lg":""} ${ee?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(re==="S"?"printers.cardSize.small":re==="M"?"printers.cardSize.medium":re==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:re},re)})}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:r,onChange:q,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(se).length>0&&i.jsxs("div",{className:"relative",children:[i.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:[i.jsx(em,{className:"w-4 h-4"}),t("printers.powerOn"),i.jsx(In,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),i.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:[i.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),k?.filter(re=>se[re.id]).map(re=>i.jsx(pVe,{printer:re,plug:se[re.id],onPowerOn:O=>{c(O),Te.mutate(O)},isPowering:l===se[re.id]?.id},re.id)),k?.filter(re=>se[re.id]).length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),i.jsxs(ze,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[i.jsx(ir,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),P?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):k?.length===0?i.jsx(Pt,{children:i.jsxs(Et,{className:"text-center py-12",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),i.jsxs(ze,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[i.jsx(ir,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):H?i.jsx("div",{className:"space-y-6",children:Object.entries(H).map(([re,O])=>i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),re,i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",O.length,")"]})]}),i.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${E()}`,children:O.map($=>i.jsx(PW,{printer:$,hideIfDisconnected:r,maintenanceInfo:ne[$.id],viewMode:v,cardSize:f,amsThresholds:T?{humidityGood:Number(T.ams_humidity_good)||40,humidityFair:Number(T.ams_humidity_fair)||60,tempGood:Number(T.ams_temp_good)||28,tempFair:Number(T.ams_temp_fair)||35}:void 0,spoolmanEnabled:z,hasUnlinkedSpools:ae,linkedSpools:ue,spoolmanUrl:G?.url,spoolmanSyncMode:I,onGetAssignment:V,onUnassignSpool:(ee,W,ie)=>he.mutate({printerId:ee,amsId:W,trayId:ie}),timeFormat:T?.time_format||"system",cameraViewMode:T?.camera_view_mode||"window",onOpenEmbeddedCamera:(ee,W)=>C(ie=>new Map(ie).set(ee,{id:ee,name:W})),checkPrinterFirmware:T?.check_printer_firmware!==!1,dryingPresets:D},$.id))})]},re))}):i.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${E()}`,children:K.map(re=>i.jsx(PW,{printer:re,hideIfDisconnected:r,maintenanceInfo:ne[re.id],viewMode:v,cardSize:f,spoolmanEnabled:z,hasUnlinkedSpools:ae,linkedSpools:ue,spoolmanUrl:G?.url,spoolmanSyncMode:I,onGetAssignment:V,onUnassignSpool:(O,$,ee)=>he.mutate({printerId:O,amsId:$,trayId:ee}),amsThresholds:T?{humidityGood:Number(T.ams_humidity_good)||40,humidityFair:Number(T.ams_humidity_fair)||60,tempGood:Number(T.ams_temp_good)||28,tempFair:Number(T.ams_temp_fair)||35}:void 0,timeFormat:T?.time_format||"system",cameraViewMode:T?.camera_view_mode||"window",onOpenEmbeddedCamera:(O,$)=>C(ee=>new Map(ee).set(O,{id:O,name:$})),checkPrinterFirmware:T?.check_printer_firmware!==!1,dryingPresets:D},re.id))}),e&&i.jsx(uVe,{onClose:()=>n(!1),onAdd:re=>pe.mutate(re),existingSerials:k?.map(re=>re.serial_number)||[]}),Array.from(N.values()).map((re,O)=>i.jsx(pMe,{printerId:re.id,printerName:re.name,viewerIndex:O,onClose:()=>C($=>{const ee=new Map($);return ee.delete(re.id),ee})},re.id))]})}function gVe(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function of(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:gVe()==="macos"?n=`bambustudioopen://${encodeURIComponent(t)}`:n=`bambustudio://open?file=${t}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}const MW=768;function uie(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${MW-1}px)`),r=a=>{e(a.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function L4({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:a}){const{t:s}=Dt(),{data:o}=et({queryKey:["settings"],queryFn:ge.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[u,d]=w.useState(null),[m,p]=w.useState(null),[f,y]=w.useState(!0),[v,b]=w.useState(null),[g,_]=w.useState(!1),[N,C]=w.useState(null),[k,P]=w.useState(0),[T,D]=w.useState(!1),[A,R]=w.useState(null),[G,z]=w.useState(!1),[Z,I]=w.useState(!1),J=w.useRef(null),ae=w.useRef(null),Y=10,ue=160,de=240,he=.35;w.useEffect(()=>{const xe=oe=>{oe.key==="Escape"&&a()};return window.addEventListener("keydown",xe),()=>window.removeEventListener("keydown",xe)},[a]),w.useEffect(()=>{if(y(!0),c){const xe=(r||"").toLowerCase(),oe=xe==="3mf"||xe==="stl",L=xe==="gcode"||xe==="3mf";p({has_model:oe,has_gcode:L,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d(oe?"3d":L?"gcode":null),y(!1);return}if(!t){p(null),d(null),y(!1);return}ge.getArchiveCapabilities(t).then(xe=>{p(xe),xe.has_model?d("3d"):xe.has_gcode&&d("gcode"),y(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d("3d"),y(!1)})},[t,r,c]),w.useEffect(()=>{if(_(!0),C(null),P(0),c){const xe=(r||"").toLowerCase();if(!e||xe!=="3mf"){b(null),_(!1);return}ge.getLibraryFilePlates(e).then(oe=>b(oe)).catch(()=>b(null)).finally(()=>_(!1));return}if(!t){b(null),_(!1);return}ge.getArchivePlates(t).then(xe=>b(xe)).catch(()=>b(null)).finally(()=>_(!1))},[t,r,c,e]);const V=w.useMemo(()=>v?.plates??[],[v]),ne=(v?.is_multi_plate??!1)&&V.length>1,se=T&&ne,pe=N==null?null:V.find(xe=>xe.index===N)??null,Te=xe=>xe.object_count??xe.objects?.length??0,q=V.reduce((xe,oe)=>xe+Te(oe),0),X=pe?Te(pe):q,j=pe?s("modelViewer.plateNumber",{number:pe.index}):s("modelViewer.allPlates"),E=V.length>0,U=w.useRef(null),K=w.useRef(null),[H,re]=w.useState(10),[O,$]=w.useState(3),ee=V.length>H,W=Math.max(1,Math.ceil(V.length/H)),ie=ee?V.slice(k*H,(k+1)*H):V;w.useEffect(()=>{if(!se){re(10),$(3);return}const xe=U.current,oe=K.current;if(!xe||!oe)return;let L=0;const F=()=>{const fe=oe.clientWidth,je=Math.floor(fe/210),we=Math.max(3,Math.min(5,je||3));$(ye=>ye===we?ye:we);const Fe=window.getComputedStyle(xe),He=Number.parseFloat(Fe.rowGap||"0"),_e=xe.querySelector("button")?.getBoundingClientRect().height??44,Ae=oe.clientHeight,Me=Math.max(1,Math.floor((Ae+He)/(_e+He)))*we,Xe=Math.max(1,Me-1);re(ye=>ye===Xe?ye:Xe)},te=()=>{L&&cancelAnimationFrame(L),L=requestAnimationFrame(F)};te();const ve=new ResizeObserver(te);return ve.observe(oe),ve.observe(xe),()=>{L&&cancelAnimationFrame(L),ve.disconnect()}},[se,V.length]),w.useEffect(()=>{if(!ee){P(0);return}P(xe=>Math.min(xe,W-1))},[V.length,ee,W]),w.useEffect(()=>{if(!ee||N==null)return;const xe=V.findIndex(L=>L.index===N);if(xe<0)return;const oe=Math.floor(xe/H);P(L=>L===oe?L:oe)},[V,H,N,ee]),w.useEffect(()=>{if(!se){R(null),I(!1);return}if(Z)return;const xe=J.current,oe=ae.current;if(!xe||!oe)return;const L=xe.clientHeight;if(!L)return;const F=Math.max(de,L*he),te=Math.max(ue,L-Y-F),ve=Math.min(oe.scrollHeight,te);R(Math.max(ue,ve))},[se,Z,V.length,k,Y,ue,de,he]),w.useEffect(()=>{if(!G)return;const xe=L=>{const F=J.current;if(!F)return;const te=F.getBoundingClientRect(),ve=te.height;if(!ve)return;const fe=Math.max(de,ve*he),me=Math.max(ue,ve-Y-fe),je=Math.min(me,Math.max(ue,L.clientY-te.top));R(je)},oe=()=>{z(!1),I(!0)};return document.addEventListener("mousemove",xe),document.addEventListener("mouseup",oe),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",xe),document.removeEventListener("mouseup",oe),document.body.style.cursor="",document.body.style.userSelect=""}},[G,Y,ue,de,he]);const ce=c?(r||"").toLowerCase()==="3mf":!0,be=async()=>{if(!ce)return;const xe=n||"model";try{if(c){const{token:oe}=await ge.createLibrarySlicerToken(e),L=ge.getLibrarySlicerDownloadUrl(e,oe,xe);of(`${window.location.origin}${L}`,l)}else{const{token:oe}=await ge.createArchiveSlicerToken(t),L=ge.getArchiveSlicerDownloadUrl(t,oe,xe);of(`${window.location.origin}${L}`,l)}}catch{if(c){const oe=`${window.location.origin}${ge.getLibraryFileDownloadUrl(e)}`;of(oe,l)}else{const oe=`${window.location.origin}${ge.getArchiveForSlicer(t,xe)}`;of(oe,l)}}};return i.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${T?"p-0":"p-8"}`,onClick:a,children:i.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${T?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:xe=>xe.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),E&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[j,": ",s("modelViewer.objectCount",{count:X})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(ze,{variant:"secondary",size:"sm",onClick:be,disabled:!ce,children:[i.jsx(ni,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>D(xe=>!xe),title:T?"Exit fullscreen":"Enter fullscreen",children:T?i.jsx(WL,{className:"w-4 h-4"}):i.jsx(oT,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:a,children:i.jsx(Ht,{className:"w-5 h-5"})})]})]}),m&&i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[i.jsxs("button",{onClick:()=>m.has_model&&d("3d"),disabled:!m.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":m.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(ia,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!m.has_model&&i.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),i.jsxs("button",{onClick:()=>m.has_gcode&&d("gcode"),disabled:!m.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":m.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(mpe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!m.has_gcode&&i.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),i.jsx("div",{className:"flex-1 overflow-hidden p-4",children:f?i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})}):u==="3d"&&m?i.jsxs("div",{ref:J,className:`w-full h-full flex flex-col ${se?"gap-0 min-h-0":"gap-3"}`,children:[ne&&i.jsxs("div",{ref:ae,style:se&&A!=null?{height:A}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${se?"flex flex-col shrink-0":""}`,children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[i.jsx(Gi,{className:"w-4 h-4"}),s("modelViewer.plates"),g&&i.jsx(ft,{className:"w-3 h-3 animate-spin"})]}),i.jsxs("div",{className:se?"flex flex-col min-h-0 flex-1":void 0,children:[i.jsx("div",{ref:K,className:se?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:i.jsxs("div",{ref:U,className:se?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:se?{gridTemplateColumns:`repeat(${O}, minmax(0, 1fr))`}:void 0,children:[i.jsxs("button",{type:"button",onClick:()=>C(null),className:`flex items-center rounded-lg border text-left transition-colors ${se?"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:[i.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${se?"w-8 h-8":"w-10 h-10"}`,children:i.jsx(Gi,{className:`${se?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:`${se?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),i.jsx("p",{className:`${se?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:V.length})})]}),N==null&&i.jsx(Zr,{className:`${se?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),ie.map(xe=>i.jsxs("button",{type:"button",onClick:()=>C(xe.index),className:`flex items-center rounded-lg border text-left transition-colors ${se?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===xe.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[xe.has_thumbnail&&xe.thumbnail_url?i.jsx("img",{src:xe.thumbnail_url,alt:`Plate ${xe.index}`,className:`${se?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):i.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${se?"w-8 h-8":"w-10 h-10"}`,children:i.jsx(Gi,{className:`${se?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:`${se?"text-xs":"text-sm"} text-white font-medium truncate`,children:xe.name||s("modelViewer.plateNumber",{number:xe.index})}),i.jsx("p",{className:`${se?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:xe.object_count??xe.objects?.length??0})})]}),N===xe.index&&i.jsx(Zr,{className:`${se?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},xe.index))]})}),(pe||ee)&&i.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[pe&&i.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[i.jsx("span",{children:s("modelViewer.plateNumber",{number:pe.index})}),pe.print_time_seconds!=null&&i.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(pe.print_time_seconds/60)})}),pe.filament_used_grams!=null&&i.jsxs("span",{children:[pe.filament_used_grams.toFixed(1)," g"]}),pe.filaments.length>0&&i.jsx("span",{children:s("modelViewer.filamentCount",{count:pe.filaments.length})})]}),ee&&i.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${pe?"ml-auto":""}`,children:[i.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:k+1,total:W})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{type:"button",onClick:()=>P(xe=>Math.max(xe-1,0)),disabled:k===0,className:`px-2 py-1 rounded border text-xs ${k===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let oe=Math.max(0,k-Math.floor(2.5));const L=Math.min(W,oe+5);L-oe<5&&(oe=Math.max(0,L-5));const F=Array.from({length:L-oe},(te,ve)=>oe+ve);return i.jsxs(i.Fragment,{children:[oe>0&&i.jsx("button",{type:"button",onClick:()=>P(0),className:`px-2 py-1 rounded border text-xs ${k===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),oe>1&&i.jsx("span",{className:"px-1",children:"…"}),F.map(te=>i.jsx("button",{type:"button",onClick:()=>P(te),className:`px-2 py-1 rounded border text-xs ${k===te?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:te+1},te)),LP(W-1),className:`px-2 py-1 rounded border text-xs ${k===W-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:W})]})})(),i.jsx("button",{type:"button",onClick:()=>P(xe=>Math.min(xe+1,W-1)),disabled:k>=W-1,className:`px-2 py-1 rounded border text-xs ${k>=W-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")})]})]})]})]})]}),se&&i.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:xe=>{xe.preventDefault(),z(!0),I(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${G?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),i.jsx("div",{className:`flex-1 ${se?"min-h-0":""}`,children:i.jsx(tZ,{url:c?ge.getLibraryFileDownloadUrl(e):m.has_source?ge.getSource3mfDownloadUrl(t):ge.getArchiveDownload(t),fileType:r,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):u==="gcode"&&m?i.jsx(OZ,{gcodeUrl:c?ge.getLibraryFileGcodeUrl(e):ge.getArchiveGcode(t),filamentColors:m.filament_colors,className:"w-full h-full"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}function bVe({onClose:t,initialFiles:e}){const{t:n}=Dt(),r=sn(),{showToast:a}=bn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(k=>k.name.endsWith(".3mf")).map(k=>({file:k,status:"pending"}))||[]),[c,u]=w.useState(!1),[d,m]=w.useState(null);w.useEffect(()=>{const k=P=>{P.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]);const p=gt({mutationFn:k=>ge.uploadArchivesBulk(k),onSuccess:k=>{m(k),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(P=>P.map(T=>{const D=k.results.find(R=>R.filename===T.file.name),A=k.errors.find(R=>R.filename===T.file.name);return D?{...T,status:"success",archiveId:D.id}:A?{...T,status:"error",error:A.error}:T})),k.failed===0?a(`${k.uploaded} file${k.uploaded!==1?"s":""} uploaded`):k.uploaded===0?a(`Failed to upload ${k.failed} file${k.failed!==1?"s":""}`,"error"):a(`${k.uploaded} uploaded, ${k.failed} failed`,"warning")},onError:()=>{l(k=>k.map(P=>({...P,status:"error",error:"Upload failed"}))),a("Upload failed","error")}}),f=w.useCallback(k=>{k.preventDefault(),u(!0)},[]),y=w.useCallback(k=>{k.preventDefault(),u(!1)},[]),v=w.useCallback(k=>{k.preventDefault(),u(!1);const P=Array.from(k.dataTransfer.files).filter(T=>T.name.endsWith(".3mf"));P.length>0&&l(T=>[...T,...P.map(D=>({file:D,status:"pending"}))])},[]),b=w.useCallback(k=>{const P=Array.from(k.target.files||[]).filter(T=>T.name.endsWith(".3mf"));P.length>0&&l(T=>[...T,...P.map(D=>({file:D,status:"pending"}))]),s.current&&(s.current.value="")},[]),g=w.useCallback(k=>{l(P=>P.filter((T,D)=>D!==k))},[]),_=()=>{if(o.length===0)return;const k=o.filter(P=>P.status==="pending");k.length!==0&&(l(P=>P.map(T=>T.status==="pending"?{...T,status:"uploading"}:T)),p.mutate(k.map(P=>P.file)))},N=o.filter(k=>k.status==="pending").length,C=p.isPending;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:i.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"p-4",children:i.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:f,onDragLeave:y,onDrop:v,children:[i.jsx(yi,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),i.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),i.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),i.jsx(ze,{variant:"secondary",onClick:()=>s.current?.click(),disabled:C,children:n("uploadModal.browseFiles")}),i.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:b})]})}),i.jsx("div",{className:"px-4 pb-4",children:i.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&i.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:i.jsx("div",{className:"space-y-2",children:o.map((k,P)=>i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[i.jsx(iT,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"flex-1 text-white text-sm truncate",children:k.file.name}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[(k.file.size/(1024*1024)).toFixed(1)," MB"]}),k.status==="pending"&&i.jsx("button",{onClick:()=>g(P),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:C,children:i.jsx(Ht,{className:"w-4 h-4"})}),k.status==="uploading"&&i.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"}),k.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-bambu-green"}),k.status==="error"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-red-400",children:k.error}),i.jsx(Li,{className:"w-4 h-4 text-red-400"})]})]},`${k.file.name}-${P}`))})}),d&&i.jsx("div",{className:"px-4 pb-4",children:i.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"text-bambu-green",children:d.uploaded})," ",n("uploadModal.uploaded"),d.failed>0&&i.jsxs(i.Fragment,{children:[", ",i.jsx("span",{className:"text-red-400",children:d.failed})," ",n("uploadModal.failed")]})]})})}),i.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(ze,{variant:"secondary",onClick:t,className:"flex-1",children:n(d?"common.close":"common.cancel")}),!d&&i.jsx(ze,{onClick:_,disabled:N===0||C,className:"flex-1",children:C?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(yi,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const xVe=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],yVe=["completed","failed","aborted","printing"];function die({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Dt();w.useEffect(()=>{const E=U=>{U.key==="Escape"&&e()};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[e]);const a=sn(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[u,d]=w.useState(t.project_id??null),[m,p]=w.useState(t.notes||""),[f,y]=w.useState(t.tags||""),[v,b]=w.useState(t.failure_reason||""),[g,_]=w.useState(t.status),[N,C]=w.useState(t.quantity??1),[k,P]=w.useState(t.photos||[]),[T,D]=w.useState(t.external_url||""),[A,R]=w.useState(!1),[G,z]=w.useState(!1),Z=w.useRef(null),I=w.useRef(null),J=w.useRef(null),{data:ae}=et({queryKey:["printers"],queryFn:ge.getPrinters}),{data:Y}=et({queryKey:["projects"],queryFn:()=>ge.getProjects()}),{data:ue}=et({queryKey:["tags"],queryFn:ge.getTags,enabled:n.length===0}),de=n.length>0?n:ue?.map(E=>E.name)||[],he=f.split(",").map(E=>E.trim()).filter(Boolean),V=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ne=de.filter(E=>!he.includes(E)&&(V===""||E.toLowerCase().includes(V))),se=E=>{let U;if(V&&!de.includes(V)?U=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(K=>K.trim()).filter(Boolean):[]:U=he,!U.includes(E)){const K=[...U,E].join(", ");y(K)}J.current!==null&&clearTimeout(J.current),Z.current?.focus()},pe=E=>{const U=he.filter(K=>K!==E).join(", ");y(U)},Te=gt({mutationFn:E=>ge.updateArchive(t.id,E),onSuccess:()=>{a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["projects"]}),e()}}),q=async E=>{const U=E.target.files?.[0];if(U){R(!0);try{const K=await ge.uploadArchivePhoto(t.id,U);P(K.photos),a.invalidateQueries({queryKey:["archives"]})}catch(K){console.error("Failed to upload photo:",K)}finally{R(!1),I.current&&(I.current.value="")}}},X=async E=>{try{const U=await ge.deleteArchivePhoto(t.id,E);P(U.photos||[]),a.invalidateQueries({queryKey:["archives"]})}catch(U){console.error("Failed to delete photo:",U)}},j=E=>{E.preventDefault();const U={print_name:s||void 0,printer_id:l,project_id:u,notes:m||void 0,tags:f||void 0,quantity:N,external_url:T||null};g!==t.status&&(U.status=g),g==="failed"||g==="aborted"?U.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(U.failure_reason=null),Te.mutate(U)};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:i.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:E=>E.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:j,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),i.jsx("input",{type:"text",value:s,onChange:E=>o(E.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")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),i.jsxs("select",{value:l??"",onChange:E=>c(E.target.value?Number(E.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:[i.jsx("option",{value:"",children:r("editArchive.noPrinter")}),ae?.map(E=>i.jsx("option",{value:E.id,children:E.name},E.id))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(vs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),i.jsxs("select",{value:u??"",onChange:E=>d(E.target.value?Number(E.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:[i.jsx("option",{value:"",children:r("editArchive.noProject")}),Y?.map(E=>i.jsx("option",{value:E.id,children:E.name},E.id))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(yfe,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),i.jsx("input",{type:"number",min:1,value:N,onChange:E=>C(Math.max(1,parseInt(E.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"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),i.jsx("textarea",{value:m,onChange:E=>p(E.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")})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(Gx,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),i.jsx("input",{type:"url",value:T,onChange:E=>D(E.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/..."}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),he.length>0&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:he.map(E=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[i.jsx(Hd,{className:"w-3 h-3"}),E,i.jsx("button",{type:"button",onClick:()=>pe(E),className:"ml-0.5 text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-3 h-3"})})]},E))}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{ref:Z,type:"text",value:f,onChange:E=>y(E.target.value),onFocus:()=>{J.current!==null&&clearTimeout(J.current),z(!0)},onBlur:()=>{J.current=window.setTimeout(()=>z(!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:he.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),G&&ne.length>0&&i.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:[i.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[V?r("editArchive.matchingTags",{query:V}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),i.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ne.map(E=>i.jsx("button",{type:"button",onClick:()=>se(E),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:E},E))})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),i.jsx("select",{value:g,onChange:E=>{_(E.target.value),E.target.value==="completed"&&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:yVe.map(E=>i.jsx("option",{value:E,children:r(`editArchive.statuses.${E}`)},E))})]}),(g==="failed"||g==="aborted")&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),i.jsxs("select",{value:v,onChange:E=>b(E.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:[i.jsx("option",{value:"",children:r("editArchive.selectReason")}),xVe.map(E=>i.jsx("option",{value:r(`editArchive.failureReasons.${E}`),children:r(`editArchive.failureReasons.${E}`)},E))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(dx,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),i.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[k.map(E=>i.jsxs("div",{className:"relative group",children:[i.jsx("img",{src:ge.getArchivePhotoUrl(t.id,E),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),i.jsx("button",{type:"button",onClick:()=>X(E),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx(nn,{className:"w-3 h-3 text-white"})})]},E)),i.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:[i.jsx("input",{ref:I,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:q,className:"hidden",disabled:A}),A?i.jsx(ft,{className:"w-6 h-6 text-bambu-gray animate-spin"}):i.jsx(ir,{className:"w-6 h-6 text-bambu-gray"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),i.jsxs(ze,{type:"submit",disabled:Te.isPending,className:"flex-1",children:[i.jsx(as,{className:"w-4 h-4"}),Te.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function mie({x:t,y:e,items:n,onClose:r}){const a=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,u]=w.useState({x:t,y:e,visible:!1}),[d,m]=w.useState(!1),[p,f]=w.useState({});w.useEffect(()=>{const b=N=>{a.current&&!a.current.contains(N.target)&&r()},g=N=>{N.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",b),document.addEventListener("keydown",g),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",g),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(a.current){a.current.style.visibility="hidden",a.current.style.display="block";const b=a.current.getBoundingClientRect(),g=window.innerWidth,_=window.innerHeight,N=8;let C=t,k=e;t+b.width>g-N&&(C=Math.max(N,g-b.width-N)),C_-N&&(k=Math.max(N,_-b.height-N)),kP),u({x:C,y:k,visible:!0})}},[t,e]);const y=(b,g)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=g.getBoundingClientRect(),N=window.innerHeight,C=300,T=N-_.top-8C;f(D=>({...D,[b]:T?"bottom":"top"})),o(b)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return i.jsx("div",{ref:a,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((b,g)=>{if(b.divider)return i.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},g);const _=b.submenu&&b.submenu.length>0;return i.jsxs("div",{className:"relative",onMouseEnter:N=>_&&y(g,N.currentTarget),onMouseLeave:()=>_&&v(),children:[i.jsxs("button",{onMouseEnter:N=>_&&y(g,N.currentTarget.parentElement),onClick:()=>{_?o(s===g?null:g):b.disabled||(b.onClick(),r())},disabled:b.disabled,title:b.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===g?"bg-bambu-dark-tertiary":""}`,children:[b.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),i.jsx("span",{className:"flex-1",children:b.label}),_&&i.jsx(fa,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===g&&i.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[g]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:b.submenu.map((N,C)=>i.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&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:N.icon}),N.label]},C))})]},g)})})}function vVe({selectedIds:t,existingTags:e,onClose:n}){const r=sn(),{showToast:a}=bn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[u,d]=w.useState("add");w.useEffect(()=>{const v=b=>{b.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const m=gt({mutationFn:async()=>{const v=Array.from(l);let b=0;for(const g of t)try{const _=await ge.getArchive(g),N=_.tags?_.tags.split(",").map(k=>k.trim()).filter(Boolean):[];let C;u==="add"?C=[...new Set([...N,...v])]:C=N.filter(k=>!l.has(k)),await ge.updateArchive(g,{tags:C.join(", ")}),b++}catch(_){throw console.error(`Failed to update archive ${g}:`,_),new Error(`Failed on archive ${g}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:b,mode:u,tags:v}},onSuccess:({count:v,mode:b,tags:g})=>{r.invalidateQueries({queryKey:["archives"]}),a(`${b==="add"?"Added":"Removed"} ${g.length} tag${g.length!==1?"s":""} ${b==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{a(v.message||"Failed to update tags","error")}}),p=v=>{c(b=>{const g=new Set(b);return g.has(v)?g.delete(v):g.add(v),g})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},y=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-md",children:i.jsxs(Et,{className:"p-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Hd,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:u==="add"?"Add Tags":"Remove Tags"})]}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:[u==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{size:"sm",variant:u==="add"?"primary":"secondary",onClick:()=>d("add"),children:"Add Tags"}),i.jsx(ze,{size:"sm",variant:u==="remove"?"primary":"secondary",onClick:()=>d("remove"),children:"Remove Tags"})]}),u==="add"&&i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:y}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:i.jsx(ir,{className:"w-4 h-4"})})]}),e.length>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>i.jsx("button",{onClick:()=>p(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&i.jsxs("div",{children:[i.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",u==="add"?"add":"remove",":"]}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>i.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${u==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,i.jsx("button",{onClick:()=>p(v),className:"hover:opacity-70",children:i.jsx(Ht,{className:"w-3 h-3"})})]},v))})]})]}),i.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(ze,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),i.jsx(ze,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):i.jsxs(i.Fragment,{children:[i.jsx(Hd,{className:"w-4 h-4"}),u==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function wVe({selectedIds:t,onClose:e}){const n=sn(),{showToast:r}=bn(),{data:a,isLoading:s}=et({queryKey:["projects"],queryFn:()=>ge.getProjects()});w.useEffect(()=>{const d=m=>{m.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=gt({mutationFn:async d=>(await ge.addArchivesToProject(d,t),d),onSuccess:d=>{const m=a?.find(p=>p.id===d);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${m?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=gt({mutationFn:async()=>{for(const d of t)await ge.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 i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:i.jsxs(Et,{className:"p-0 flex flex-col min-h-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(vs,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:u,children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):i.jsxs("div",{className:"space-y-2",children:[i.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:[i.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:i.jsx(Vi,{className:"w-4 h-4 text-red-400"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),i.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&i.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),a&&a.length>0&&i.jsxs("div",{className:"flex items-center gap-2 py-2",children:[i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),a?.map(d=>i.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:[i.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:i.jsx(vs,{className:"w-4 h-4",style:{color:d.color||"rgb(var(--bambu-green))"}})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium truncate",children:d.name}),i.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&&i.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},d.id)),(!a||a.length===0)&&i.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),i.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:i.jsx(ze,{variant:"secondary",onClick:e,className:"flex-1",disabled:u,children:"Cancel"})})]})})})}function SVe(t,e){return new Date(t,e+1,0).getDate()}function _Ve(t,e){return new Date(t,e,1).getDay()}const NVe=["January","February","March","April","May","June","July","August","September","October","November","December"],kVe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function CVe({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[a,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,u]=w.useState(null),[d,m]=w.useState(null),p=w.useMemo(()=>{const k=new Map;return t.forEach(P=>{const T=Qn(P.completed_at||P.created_at)||new Date,D=`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`,A=k.get(D)||[];A.push(P),k.set(D,A)}),k},[t]),f=SVe(o,a),y=_Ve(o,a),v=()=>{a===0?(s(11),l(o-1)):s(a-1)},b=()=>{a===11?(s(0),l(o+1)):s(a+1)},g=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let k=0;k{k!==c&&m(null),u(k)};return i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[i.jsxs("div",{className:"flex-1",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Cc,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white",children:[NVe[a]," ",o]}),i.jsx("button",{onClick:g,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"})]}),i.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(fa,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:kVe.map(k=>i.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:k},k))}),i.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((k,P)=>{if(k===null)return i.jsx("div",{className:"aspect-square"},`empty-${P}`);const T=`${o}-${String(a+1).padStart(2,"0")}-${String(k).padStart(2,"0")}`,D=p.get(T)||[],A=D.length>0,R=k===r.getDate()&&a===r.getMonth()&&o===r.getFullYear(),G=T===c,z=D.filter(I=>I.status==="completed").length,Z=D.filter(I=>I.status==="failed").length;return i.jsxs("button",{onClick:()=>C(G?null:T),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${G?"bg-bambu-green text-white":R?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":A?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[i.jsx("span",{className:`text-sm font-medium ${R&&!G?"text-bambu-green":""}`,children:k}),A&&i.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${Z>0&&z===0?"bg-red-400":Z>0?"bg-yellow-400":"bg-green-400"}`}),i.jsx("span",{className:"text-xs font-medium",children:D.length})]})]},k)})}),i.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(k=>{const P=Qn(k.completed_at||k.created_at)||new Date;return P.getMonth()===a&&P.getFullYear()===o}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(k=>{const P=Qn(k.completed_at||k.created_at)||new Date;return P.getMonth()===a&&P.getFullYear()===o&&k.status==="completed"}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(k=>{const P=Qn(k.completed_at||k.created_at)||new Date;return P.getMonth()===a&&P.getFullYear()===o&&k.status==="failed"}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),i.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?i.jsxs(i.Fragment,{children:[i.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?i.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:N.map(k=>{const P=k.id===d||k.id===n;return i.jsxs("button",{onClick:()=>{m(k.id),e?.(k)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${P?"":"hover:bg-bambu-dark-tertiary"}`,style:P?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[k.thumbnail_path?i.jsx("img",{src:ge.getArchiveThumbnail(k.id),alt:"",className:"w-12 h-12 rounded object-cover"}):i.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:k.print_name||k.filename}),i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx("span",{className:k.status==="failed"?"text-red-400":"text-green-400",children:k.status==="failed"?"Failed":"Completed"}),k.filament_color&&i.jsx("div",{className:"flex gap-0.5",children:k.filament_color.split(",").map((T,D)=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:T}},D))})]})]})]},k.id)})}):i.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):i.jsx("div",{className:"text-center py-8",children:i.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function hie({archiveId:t,archiveName:e,onClose:n}){const r=ge.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const a=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-6 flex flex-col items-center",children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),i.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:i.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),i.jsxs(ze,{onClick:a,className:"w-full",children:[i.jsx(fi,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function pie({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:a}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const f=y=>{y.key==="Escape"&&r(),y.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),y.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r,n.length]),w.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=ge.getArchivePhotoUrl(t,u),m=()=>{const f=document.createElement("a");f.href=d,f.download=`${e}_photo_${s+1}.jpg`,f.click()},p=()=>{a&&c(!0)};return i.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[i.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(ze,{variant:"secondary",size:"sm",onClick:m,children:[i.jsx(fi,{className:"w-4 h-4"}),"Download"]}),a&&i.jsx(ze,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:i.jsx(nn,{className:"w-4 h-4"})}),i.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-6 h-6"})})]})]}),i.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&i.jsx("button",{onClick:()=>o(f=>f-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:i.jsx(Cc,{className:"w-8 h-8 text-white"})}),i.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(f=>f+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:i.jsx(fa,{className:"w-8 h-8 text-white"})})]}),n.length>1&&i.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,y)=>i.jsx("button",{onClick:()=>o(y),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${y===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:i.jsx("img",{src:ge.getArchivePhotoUrl(t,f),alt:`Thumbnail ${y+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&i.jsx(Nn,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{a?.(u),c(!1)},onCancel:()=>c(!1)})]})}const{entries:fie,setPrototypeOf:EW,isFrozen:TVe,getPrototypeOf:AVe,getOwnPropertyDescriptor:PVe}=Object;let{freeze:Qs,seal:Ql,create:vN}=Object,{apply:IF,construct:zF}=typeof Reflect<"u"&&Reflect;Qs||(Qs=function(e){return e});Ql||(Ql=function(e){return e});IF||(IF=function(e,n){for(var r=arguments.length,a=new Array(r>2?r-2:0),s=2;s1?n-1:0),a=1;a1?n-1:0),a=1;a2&&arguments[2]!==void 0?arguments[2]:wN;EW&&EW(t,null);let r=e.length;for(;r--;){let a=e[r];if(typeof a=="string"){const s=n(a);s!==a&&(TVe(e)||(e[r]=s),a=s)}t[a]=!0}return t}function FVe(t){for(let e=0;e/gm),UVe=Ql(/\$\{[\w\W]*/gm),BVe=Ql(/^data-[\-\w.\u00B7-\uFFFF]+$/),HVe=Ql(/^aria-[\-\w]+$/),gie=Ql(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),$Ve=Ql(/^(?:\w+script|data):/i),qVe=Ql(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),bie=Ql(/^html$/i),VVe=Ql(/^[a-z][.\w]*(-[.\w]+)+$/i);var OW=Object.freeze({__proto__:null,ARIA_ATTR:HVe,ATTR_WHITESPACE:qVe,CUSTOM_ELEMENT:VVe,DATA_ATTR:BVe,DOCTYPE_NAME:bie,ERB_EXPR:zVe,IS_ALLOWED_URI:gie,IS_SCRIPT_OR_DATA:$Ve,MUSTACHE_EXPR:IVe,TMPLIT_EXPR:UVe});const Tv={element:1,text:3,progressingInstruction:7,comment:8,document:9},GVe=function(){return typeof window>"u"?null:window},WVe=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const a="data-tt-policy-suffix";n&&n.hasAttribute(a)&&(r=n.getAttribute(a));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},IW=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function xie(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:GVe();const e=Ze=>xie(Ze);if(e.version="3.3.3",e.removed=[],!t||!t.document||t.document.nodeType!==Tv.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const r=n,a=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:u,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,y=c.prototype,v=Cv(y,"cloneNode"),b=Cv(y,"remove"),g=Cv(y,"nextSibling"),_=Cv(y,"childNodes"),N=Cv(y,"parentNode");if(typeof o=="function"){const Ze=n.createElement("template");Ze.content&&Ze.content.ownerDocument&&(n=Ze.content.ownerDocument)}let C,k="";const{implementation:P,createNodeIterator:T,createDocumentFragment:D,getElementsByTagName:A}=n,{importNode:R}=r;let G=IW();e.isSupported=typeof fie=="function"&&typeof N=="function"&&P&&P.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:z,ERB_EXPR:Z,TMPLIT_EXPR:I,DATA_ATTR:J,ARIA_ATTR:ae,IS_SCRIPT_OR_DATA:Y,ATTR_WHITESPACE:ue,CUSTOM_ELEMENT:de}=OW;let{IS_ALLOWED_URI:he}=OW,V=null;const ne=er({},[...DW,...lD,...cD,...uD,...RW]);let se=null;const pe=er({},[...FW,...dD,...LW,...R1]);let Te=Object.seal(vN(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),q=null,X=null;const j=Object.seal(vN(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let E=!0,U=!0,K=!1,H=!0,re=!1,O=!0,$=!1,ee=!1,W=!1,ie=!1,ce=!1,be=!1,xe=!0,oe=!1;const L="user-content-";let F=!0,te=!1,ve={},fe=null;const me=er({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let je=null;const we=er({},["audio","video","img","source","image","track"]);let Fe=null;const He=er({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Oe="http://www.w3.org/1998/Math/MathML",_e="http://www.w3.org/2000/svg",Ae="http://www.w3.org/1999/xhtml";let Be=Ae,Me=!1,Xe=null;const ye=er({},[Oe,_e,Ae],sD);let We=er({},["mi","mo","mn","ms","mtext"]),Pe=er({},["annotation-xml"]);const Ke=er({},["title","style","font","a","script"]);let Ve=null;const ke=["application/xhtml+xml","text/html"],Ce="text/html";let $e=null,nt=null;const xt=n.createElement("form"),vt=function(Ee){return Ee instanceof RegExp||Ee instanceof Function},mt=function(){let Ee=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(nt&&nt===Ee)){if((!Ee||typeof Ee!="object")&&(Ee={}),Ee=Jc(Ee),Ve=ke.indexOf(Ee.PARSER_MEDIA_TYPE)===-1?Ce:Ee.PARSER_MEDIA_TYPE,$e=Ve==="application/xhtml+xml"?sD:wN,V=Vo(Ee,"ALLOWED_TAGS")?er({},Ee.ALLOWED_TAGS,$e):ne,se=Vo(Ee,"ALLOWED_ATTR")?er({},Ee.ALLOWED_ATTR,$e):pe,Xe=Vo(Ee,"ALLOWED_NAMESPACES")?er({},Ee.ALLOWED_NAMESPACES,sD):ye,Fe=Vo(Ee,"ADD_URI_SAFE_ATTR")?er(Jc(He),Ee.ADD_URI_SAFE_ATTR,$e):He,je=Vo(Ee,"ADD_DATA_URI_TAGS")?er(Jc(we),Ee.ADD_DATA_URI_TAGS,$e):we,fe=Vo(Ee,"FORBID_CONTENTS")?er({},Ee.FORBID_CONTENTS,$e):me,q=Vo(Ee,"FORBID_TAGS")?er({},Ee.FORBID_TAGS,$e):Jc({}),X=Vo(Ee,"FORBID_ATTR")?er({},Ee.FORBID_ATTR,$e):Jc({}),ve=Vo(Ee,"USE_PROFILES")?Ee.USE_PROFILES:!1,E=Ee.ALLOW_ARIA_ATTR!==!1,U=Ee.ALLOW_DATA_ATTR!==!1,K=Ee.ALLOW_UNKNOWN_PROTOCOLS||!1,H=Ee.ALLOW_SELF_CLOSE_IN_ATTR!==!1,re=Ee.SAFE_FOR_TEMPLATES||!1,O=Ee.SAFE_FOR_XML!==!1,$=Ee.WHOLE_DOCUMENT||!1,ie=Ee.RETURN_DOM||!1,ce=Ee.RETURN_DOM_FRAGMENT||!1,be=Ee.RETURN_TRUSTED_TYPE||!1,W=Ee.FORCE_BODY||!1,xe=Ee.SANITIZE_DOM!==!1,oe=Ee.SANITIZE_NAMED_PROPS||!1,F=Ee.KEEP_CONTENT!==!1,te=Ee.IN_PLACE||!1,he=Ee.ALLOWED_URI_REGEXP||gie,Be=Ee.NAMESPACE||Ae,We=Ee.MATHML_TEXT_INTEGRATION_POINTS||We,Pe=Ee.HTML_INTEGRATION_POINTS||Pe,Te=Ee.CUSTOM_ELEMENT_HANDLING||{},Ee.CUSTOM_ELEMENT_HANDLING&&vt(Ee.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Te.tagNameCheck=Ee.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Ee.CUSTOM_ELEMENT_HANDLING&&vt(Ee.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Te.attributeNameCheck=Ee.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Ee.CUSTOM_ELEMENT_HANDLING&&typeof Ee.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Te.allowCustomizedBuiltInElements=Ee.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),re&&(U=!1),ce&&(ie=!0),ve&&(V=er({},RW),se=vN(null),ve.html===!0&&(er(V,DW),er(se,FW)),ve.svg===!0&&(er(V,lD),er(se,dD),er(se,R1)),ve.svgFilters===!0&&(er(V,cD),er(se,dD),er(se,R1)),ve.mathMl===!0&&(er(V,uD),er(se,LW),er(se,R1))),Vo(Ee,"ADD_TAGS")||(j.tagCheck=null),Vo(Ee,"ADD_ATTR")||(j.attributeCheck=null),Ee.ADD_TAGS&&(typeof Ee.ADD_TAGS=="function"?j.tagCheck=Ee.ADD_TAGS:(V===ne&&(V=Jc(V)),er(V,Ee.ADD_TAGS,$e))),Ee.ADD_ATTR&&(typeof Ee.ADD_ATTR=="function"?j.attributeCheck=Ee.ADD_ATTR:(se===pe&&(se=Jc(se)),er(se,Ee.ADD_ATTR,$e))),Ee.ADD_URI_SAFE_ATTR&&er(Fe,Ee.ADD_URI_SAFE_ATTR,$e),Ee.FORBID_CONTENTS&&(fe===me&&(fe=Jc(fe)),er(fe,Ee.FORBID_CONTENTS,$e)),Ee.ADD_FORBID_CONTENTS&&(fe===me&&(fe=Jc(fe)),er(fe,Ee.ADD_FORBID_CONTENTS,$e)),F&&(V["#text"]=!0),$&&er(V,["html","head","body"]),V.table&&(er(V,["tbody"]),delete q.tbody),Ee.TRUSTED_TYPES_POLICY){if(typeof Ee.TRUSTED_TYPES_POLICY.createHTML!="function")throw kv('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ee.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw kv('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');C=Ee.TRUSTED_TYPES_POLICY,k=C.createHTML("")}else C===void 0&&(C=WVe(f,a)),C!==null&&typeof k=="string"&&(k=C.createHTML(""));Qs&&Qs(Ee),nt=Ee}},qe=er({},[...lD,...cD,...LVe]),Nt=er({},[...uD,...OVe]),_t=function(Ee){let ct=N(Ee);(!ct||!ct.tagName)&&(ct={namespaceURI:Be,tagName:"template"});const le=wN(Ee.tagName),Le=wN(ct.tagName);return Xe[Ee.namespaceURI]?Ee.namespaceURI===_e?ct.namespaceURI===Ae?le==="svg":ct.namespaceURI===Oe?le==="svg"&&(Le==="annotation-xml"||We[Le]):!!qe[le]:Ee.namespaceURI===Oe?ct.namespaceURI===Ae?le==="math":ct.namespaceURI===_e?le==="math"&&Pe[Le]:!!Nt[le]:Ee.namespaceURI===Ae?ct.namespaceURI===_e&&!Pe[Le]||ct.namespaceURI===Oe&&!We[Le]?!1:!Nt[le]&&(Ke[le]||!qe[le]):!!(Ve==="application/xhtml+xml"&&Xe[Ee.namespaceURI]):!1},rt=function(Ee){_v(e.removed,{element:Ee});try{N(Ee).removeChild(Ee)}catch{b(Ee)}},Rt=function(Ee,ct){try{_v(e.removed,{attribute:ct.getAttributeNode(Ee),from:ct})}catch{_v(e.removed,{attribute:null,from:ct})}if(ct.removeAttribute(Ee),Ee==="is")if(ie||ce)try{rt(ct)}catch{}else try{ct.setAttribute(Ee,"")}catch{}},qt=function(Ee){let ct=null,le=null;if(W)Ee=""+Ee;else{const Ge=oD(Ee,/^[\r\n\t ]+/);le=Ge&&Ge[0]}Ve==="application/xhtml+xml"&&Be===Ae&&(Ee=''+Ee+"");const Le=C?C.createHTML(Ee):Ee;if(Be===Ae)try{ct=new p().parseFromString(Le,Ve)}catch{}if(!ct||!ct.documentElement){ct=P.createDocument(Be,"template",null);try{ct.documentElement.innerHTML=Me?k:Le}catch{}}const Ye=ct.body||ct.documentElement;return Ee&&le&&Ye.insertBefore(n.createTextNode(le),Ye.childNodes[0]||null),Be===Ae?A.call(ct,$?"html":"body")[0]:$?ct.documentElement:Ye},Kt=function(Ee){return T.call(Ee.ownerDocument||Ee,Ee,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},Qt=function(Ee){return Ee instanceof m&&(typeof Ee.nodeName!="string"||typeof Ee.textContent!="string"||typeof Ee.removeChild!="function"||!(Ee.attributes instanceof d)||typeof Ee.removeAttribute!="function"||typeof Ee.setAttribute!="function"||typeof Ee.namespaceURI!="string"||typeof Ee.insertBefore!="function"||typeof Ee.hasChildNodes!="function")},mn=function(Ee){return typeof l=="function"&&Ee instanceof l};function hn(Ze,Ee,ct){D1(Ze,le=>{le.call(e,Ee,ct,nt)})}const Hn=function(Ee){let ct=null;if(hn(G.beforeSanitizeElements,Ee,null),Qt(Ee))return rt(Ee),!0;const le=$e(Ee.nodeName);if(hn(G.uponSanitizeElement,Ee,{tagName:le,allowedTags:V}),O&&Ee.hasChildNodes()&&!mn(Ee.firstElementChild)&&Ls(/<[/\w!]/g,Ee.innerHTML)&&Ls(/<[/\w!]/g,Ee.textContent)||Ee.nodeType===Tv.progressingInstruction||O&&Ee.nodeType===Tv.comment&&Ls(/<[/\w]/g,Ee.data))return rt(Ee),!0;if(!(j.tagCheck instanceof Function&&j.tagCheck(le))&&(!V[le]||q[le])){if(!q[le]&&De(le)&&(Te.tagNameCheck instanceof RegExp&&Ls(Te.tagNameCheck,le)||Te.tagNameCheck instanceof Function&&Te.tagNameCheck(le)))return!1;if(F&&!fe[le]){const Le=N(Ee)||Ee.parentNode,Ye=_(Ee)||Ee.childNodes;if(Ye&&Le){const Ge=Ye.length;for(let Ie=Ge-1;Ie>=0;--Ie){const pt=v(Ye[Ie],!0);pt.__removalCount=(Ee.__removalCount||0)+1,Le.insertBefore(pt,g(Ee))}}}return rt(Ee),!0}return Ee instanceof c&&!_t(Ee)||(le==="noscript"||le==="noembed"||le==="noframes")&&Ls(/<\/no(script|embed|frames)/i,Ee.innerHTML)?(rt(Ee),!0):(re&&Ee.nodeType===Tv.text&&(ct=Ee.textContent,D1([z,Z,I],Le=>{ct=Nv(ct,Le," ")}),Ee.textContent!==ct&&(_v(e.removed,{element:Ee.cloneNode()}),Ee.textContent=ct)),hn(G.afterSanitizeElements,Ee,null),!1)},Qe=function(Ee,ct,le){if(X[ct]||xe&&(ct==="id"||ct==="name")&&(le in n||le in xt))return!1;if(!(U&&!X[ct]&&Ls(J,ct))){if(!(E&&Ls(ae,ct))){if(!(j.attributeCheck instanceof Function&&j.attributeCheck(ct,Ee))){if(!se[ct]||X[ct]){if(!(De(Ee)&&(Te.tagNameCheck instanceof RegExp&&Ls(Te.tagNameCheck,Ee)||Te.tagNameCheck instanceof Function&&Te.tagNameCheck(Ee))&&(Te.attributeNameCheck instanceof RegExp&&Ls(Te.attributeNameCheck,ct)||Te.attributeNameCheck instanceof Function&&Te.attributeNameCheck(ct,Ee))||ct==="is"&&Te.allowCustomizedBuiltInElements&&(Te.tagNameCheck instanceof RegExp&&Ls(Te.tagNameCheck,le)||Te.tagNameCheck instanceof Function&&Te.tagNameCheck(le))))return!1}else if(!Fe[ct]){if(!Ls(he,Nv(le,ue,""))){if(!((ct==="src"||ct==="xlink:href"||ct==="href")&&Ee!=="script"&&jVe(le,"data:")===0&&je[Ee])){if(!(K&&!Ls(Y,Nv(le,ue,"")))){if(le)return!1}}}}}}}return!0},De=function(Ee){return Ee!=="annotation-xml"&&oD(Ee,de)},ot=function(Ee){hn(G.beforeSanitizeAttributes,Ee,null);const{attributes:ct}=Ee;if(!ct||Qt(Ee))return;const le={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:se,forceKeepAttr:void 0};let Le=ct.length;for(;Le--;){const Ye=ct[Le],{name:Ge,namespaceURI:Ie,value:pt}=Ye,dt=$e(Ge),Je=pt;let Tt=Ge==="value"?Je:DVe(Je);if(le.attrName=dt,le.attrValue=Tt,le.keepAttr=!0,le.forceKeepAttr=void 0,hn(G.uponSanitizeAttribute,Ee,le),Tt=le.attrValue,oe&&(dt==="id"||dt==="name")&&(Rt(Ge,Ee),Tt=L+Tt),O&&Ls(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Tt)){Rt(Ge,Ee);continue}if(dt==="attributename"&&oD(Tt,"href")){Rt(Ge,Ee);continue}if(le.forceKeepAttr)continue;if(!le.keepAttr){Rt(Ge,Ee);continue}if(!H&&Ls(/\/>/i,Tt)){Rt(Ge,Ee);continue}re&&D1([z,Z,I],Ut=>{Tt=Nv(Tt,Ut," ")});const zt=$e(Ee.nodeName);if(!Qe(zt,dt,Tt)){Rt(Ge,Ee);continue}if(C&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Ie)switch(f.getAttributeType(zt,dt)){case"TrustedHTML":{Tt=C.createHTML(Tt);break}case"TrustedScriptURL":{Tt=C.createScriptURL(Tt);break}}if(Tt!==Je)try{Ie?Ee.setAttributeNS(Ie,Ge,Tt):Ee.setAttribute(Ge,Tt),Qt(Ee)?rt(Ee):jW(e.removed)}catch{Rt(Ge,Ee)}}hn(G.afterSanitizeAttributes,Ee,null)},st=function Ze(Ee){let ct=null;const le=Kt(Ee);for(hn(G.beforeSanitizeShadowDOM,Ee,null);ct=le.nextNode();)hn(G.uponSanitizeShadowNode,ct,null),Hn(ct),ot(ct),ct.content instanceof s&&Ze(ct.content);hn(G.afterSanitizeShadowDOM,Ee,null)};return e.sanitize=function(Ze){let Ee=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ct=null,le=null,Le=null,Ye=null;if(Me=!Ze,Me&&(Ze=""),typeof Ze!="string"&&!mn(Ze))if(typeof Ze.toString=="function"){if(Ze=Ze.toString(),typeof Ze!="string")throw kv("dirty is not a string, aborting")}else throw kv("toString is not a function");if(!e.isSupported)return Ze;if(ee||mt(Ee),e.removed=[],typeof Ze=="string"&&(te=!1),te){if(Ze.nodeName){const pt=$e(Ze.nodeName);if(!V[pt]||q[pt])throw kv("root node is forbidden and cannot be sanitized in-place")}}else if(Ze instanceof l)ct=qt(""),le=ct.ownerDocument.importNode(Ze,!0),le.nodeType===Tv.element&&le.nodeName==="BODY"||le.nodeName==="HTML"?ct=le:ct.appendChild(le);else{if(!ie&&!re&&!$&&Ze.indexOf("<")===-1)return C&&be?C.createHTML(Ze):Ze;if(ct=qt(Ze),!ct)return ie?null:be?k:""}ct&&W&&rt(ct.firstChild);const Ge=Kt(te?Ze:ct);for(;Le=Ge.nextNode();)Hn(Le),ot(Le),Le.content instanceof s&&st(Le.content);if(te)return Ze;if(ie){if(ce)for(Ye=D.call(ct.ownerDocument);ct.firstChild;)Ye.appendChild(ct.firstChild);else Ye=ct;return(se.shadowroot||se.shadowrootmode)&&(Ye=R.call(r,Ye,!0)),Ye}let Ie=$?ct.outerHTML:ct.innerHTML;return $&&V["!doctype"]&&ct.ownerDocument&&ct.ownerDocument.doctype&&ct.ownerDocument.doctype.name&&Ls(bie,ct.ownerDocument.doctype.name)&&(Ie=" `+Ie),re&&D1([z,Z,I],pt=>{Ie=Nv(Ie,pt," ")}),C&&be?C.createHTML(Ie):Ie},e.setConfig=function(){let Ze=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};mt(Ze),ee=!0},e.clearConfig=function(){nt=null,ee=!1},e.isValidAttribute=function(Ze,Ee,ct){nt||mt({});const le=$e(Ze),Le=$e(Ee);return Qe(le,Le,ct)},e.addHook=function(Ze,Ee){typeof Ee=="function"&&_v(G[Ze],Ee)},e.removeHook=function(Ze,Ee){if(Ee!==void 0){const ct=MVe(G[Ze],Ee);return ct===-1?void 0:EVe(G[Ze],ct,1)[0]}return jW(G[Ze])},e.removeHooks=function(Ze){G[Ze]=[]},e.removeAllHooks=function(){G=IW()},e}var yie=xie();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 vie(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let a=t.child(r),s=e.child(r);if(a==s){n+=a.nodeSize;continue}if(!a.sameMarkup(s))return n;if(a.isText&&a.text!=s.text){for(let o=0;a.text[o]==s.text[o];o++)n++;return n}if(a.content.size||s.content.size){let o=vie(a.content,s.content,n+1);if(o!=null)return o}n+=a.nodeSize}}function wie(t,e,n,r){for(let a=t.childCount,s=e.childCount;;){if(a==0||s==0)return a==s?null:{a:n,b:r};let o=t.child(--a),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,a+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,a+d)}l=u}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,a){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?a?typeof a=="function"?a(l):a: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,a=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(a[a.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),a+=l.nodeSize),o=c}return new Bt(r,a)}cutByIndex(e,n){return e==n?Bt.empty:e==0&&n==this.content.length?this:new Bt(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let a=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return a[e]=n,new Bt(a,s)}addToStart(e){return new Bt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Bt(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 a=this.child(n),s=r+a.nodeSize;if(s>=e)return s==e?F1(n+1,s):F1(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 Bt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Bt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Bt.empty;let n,r=0;for(let a=0;athis.type.rank&&(n||(n=e.slice(0,a)),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-a.type.rank),n}};Yr.none=[];class aC extends Error{}class Zt{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=_ie(this.content,e+this.openStart,n);return r&&new Zt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new Zt(Sie(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 Zt.empty;let r=n.openStart||0,a=n.openEnd||0;if(typeof r!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Zt(Bt.fromJSON(e,n.content),r,a)}static maxOpen(e,n=!0){let r=0,a=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)a++;return new Zt(e,r,a)}}Zt.empty=new Zt(Bt.empty,0,0);function Sie(t,e,n){let{index:r,offset:a}=t.findIndex(e),s=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(a==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(Sie(s.content,e-a-1,n-a-1)))}function _ie(t,e,n,r){let{index:a,offset:s}=t.findIndex(e),o=t.maybeChild(a);if(s==e||o.isText)return r&&!r.canReplace(a,a,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=_ie(o.content,e-s-1,n,o);return l&&t.replaceChild(a,o.copy(l))}function KVe(t,e,n){if(n.openStart>t.depth)throw new aC("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new aC("Inconsistent open depths");return Nie(t,e,n,0)}function Nie(t,e,n,r){let a=t.index(r),s=t.node(r);if(a==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function n0(t,e,n,r){let a=(e||t).node(n),s=0,o=e?e.index(n):a.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(vf(t.nodeAfter,r),s++));for(let l=s;la&&BF(t,e,a+1),o=r.depth>a&&BF(n,r,a+1),l=[];return n0(null,t,a,l),s&&o&&e.index(a)==n.index(a)?(kie(s,o),vf(wf(s,Cie(t,e,n,r,a+1)),l)):(s&&vf(wf(s,sC(t,e,a+1)),l),n0(e,n,a,l),o&&vf(wf(o,sC(n,r,a+1)),l)),n0(r,null,a,l),new Bt(l)}function sC(t,e,n){let r=[];if(n0(null,t,n,r),t.depth>n){let a=BF(t,e,n+1);vf(wf(a,sC(t,e,n+1)),r)}return n0(e,null,n,r),new Bt(r)}function YVe(t,e){let n=e.depth-t.openStart,a=e.node(n).copy(t.content);for(let s=n-1;s>=0;s--)a=e.node(s).copy(Bt.from(a));return{start:a.resolveNoCache(t.openStart+n),end:a.resolveNoCache(a.content.size-t.openEnd-n)}}class J0{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],a=e.child(n);return r?e.child(n).cut(r):a}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],a=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 oC(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=[],a=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),u=s-c;if(r.push(o,l,a+c),!u||(o=o.child(l),o.isText))break;s=u-1,a+=c+1}return new J0(n,r,s)}static resolveCached(e,n){let r=zW.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(a=!0),!a)),a}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()+")"),Tie(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=Bt.empty,a=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,a,s),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=a;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 a=Bt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,a,r);return s.type.checkAttrs(s.attrs),s}}kc.prototype.text=void 0;class lC extends kc{constructor(e,n,r,a){if(super(e,n,null,a),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Tie(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 lC(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new lC(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 Tie(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Kf{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new JVe(e,n);if(r.next==null)return Kf.empty;let a=Aie(r);r.next&&r.err("Unexpected trailing text");let s=s7e(a7e(a));return o7e(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 a=0;a{let s=a+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` `)}}Kf.empty=new Kf(!0);class JVe{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 Aie(t){let e=[];do e.push(e7e(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function e7e(t){let e=[];do e.push(t7e(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function t7e(t){let e=i7e(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=n7e(t,e);else break;return e}function UW(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function n7e(t,e){let n=UW(t),r=n;return t.eat(",")&&(t.next!="}"?r=UW(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function r7e(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let a=[];for(let s in n){let o=n[s];o.isInGroup(e)&&a.push(o)}return a.length==0&&t.err("No node type or group '"+e+"' found"),a}function i7e(t){if(t.eat("(")){let e=Aie(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=r7e(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 a7e(t){let e=[[]];return a(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 a(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;a(u,l=n())}else if(o.type=="star"){let c=n();return r(l,c),a(s(o.expr,c),c),[r(c)]}else if(o.type=="plus"){let c=n();return a(s(o.expr,l),c),a(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||a.push([l,u=[]]),u.indexOf(d)==-1&&u.push(d)})})});let s=e[r.join(",")]=new Kf(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:Eie(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new kc(this,this.computeAttrs(e),Bt.from(n),Yr.setFrom(r))}createChecked(e=null,n,r){return n=Bt.from(n),this.checkContent(n),new kc(this,this.computeAttrs(e),n,Yr.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=Bt.from(n),n.size){let o=this.contentMatch.fillBefore(n);if(!o)return null;n=o.append(n)}let a=this.contentMatch.matchFragment(n),s=a&&a.fillBefore(Bt.empty,!0);return s?new kc(this,e,n.append(s),Yr.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 Rie(s,n,o));let a=n.spec.topNode||"doc";if(!r[a])throw new RangeError("Schema is missing its top node type ('"+a+"')");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 l7e(t,e,n){let r=n.split("|");return a=>{let s=a===null?"null":typeof a;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${s}`)}}class c7e{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?l7e(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class yA{constructor(e,n,r,a){this.name=e,this.rank=n,this.schema=r,this.spec=a,this.attrs=Die(e,a.attrs),this.excluded=null;let s=Mie(this.attrs);this.instance=s?new Yr(this,s):null}create(e=null){return!e&&this.instance?this.instance:new Yr(this,Eie(this.attrs,e))}static compile(e,n){let r=Object.create(null),a=0;return e.forEach((s,o)=>r[s]=new yA(s,a++,n,o)),r}removeFromSet(e){for(var n=0;n-1}}class Fie{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let a in e)n[a]=e[a];n.nodes=Za.from(e.nodes),n.marks=Za.from(e.marks||{}),this.nodes=HW.compile(this.spec.nodes,this),this.marks=yA.compile(this.spec.marks,this);let r=Object.create(null);for(let a in this.nodes){if(a in this.marks)throw new RangeError(a+" can not be both a node and a mark");let s=this.nodes[a],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Kf.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?$W(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let a in this.marks){let s=this.marks[a],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:$W(this,o.split(" "))}this.nodeFromJSON=a=>kc.fromJSON(this,a),this.markFromJSON=a=>Yr.fromJSON(this,a),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,a){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof HW){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,a)}text(e,n){let r=this.nodes.text;return new lC(r,r.defaultAttrs,e,Yr.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 $W(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 u7e(t){return t.tag!=null}function d7e(t){return t.style!=null}let r0=class HF{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(u7e(a))this.tags.push(a);else if(d7e(a)){let s=/[^=]*/.exec(a.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(a)}}),this.normalizeLists=!this.tags.some(a=>{if(!/^(ul|ol)\b/.test(a.tag)||!a.node)return!1;let s=e.nodes[a.node];return s.contentMatch.matchType(s)})}parse(e,n={}){let r=new VW(this,n,!1);return r.addAll(e,Yr.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new VW(this,n,!0);return r.addAll(e,Yr.none,n.from,n.to),Zt.maxOpen(r.finish())}matchTag(e,n,r){for(let a=r?this.tags.indexOf(r)+1:0;ae.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(a){let s=a.priority==null?50:a.priority,o=0;for(;o{r(o=GW(o)),o.mark||o.ignore||o.clearMark||(o.mark=a)})}for(let a in e.nodes){let s=e.nodes[a].spec.parseDOM;s&&s.forEach(o=>{r(o=GW(o)),o.node||o.ignore||o.mark||(o.node=a)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new HF(e,HF.schemaRules(e)))}};const Lie={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},m7e={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Oie={ol:!0,ul:!0},ew=1,$F=2,i0=4;function qW(t,e,n){return e!=null?(e?ew:0)|(e==="full"?$F:0):t&&t.whitespace=="pre"?ew|$F:n&~i0}class L1{constructor(e,n,r,a,s,o){this.type=e,this.attrs=n,this.marks=r,this.solid=a,this.options=o,this.content=[],this.activeMarks=Yr.none,this.match=s||(o&i0?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Bt.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,a;return(a=r.findWrapping(e.type))?(this.match=r,a):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&ew)){let r=this.content[this.content.length-1],a;if(r&&r.isText&&(a=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==a[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-a[0].length))}}let n=Bt.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(Bt.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&&!Lie.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class VW{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let a=n.topNode,s,o=qW(null,n.preserveWhitespace,0)|(r?i0:0);a?s=new L1(a.type,a.attrs,Yr.none,!0,n.topMatch||a.type.contentMatch,o):r?s=new L1(null,null,Yr.none,!0,null,o):s=new L1(e.schema.topNodeType,null,Yr.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,a=this.top,s=a.options&$F?"full":this.localPreserveWS||(a.options&ew)>0,{schema:o}=this.parser;if(s==="full"||a.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,a){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(a)this.addElement(e,r,a);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,a){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=a==null?null:e.childNodes[a];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,n);this.findAtPoint(e,s)}findPlace(e,n,r){let a,s;for(let o=this.open,l=0;o>=0;o--){let c=this.nodes[o],u=c.findWrapping(e);if(u&&(!a||a.length>u.length+l)&&(a=u,s=c,!u.length))break;if(c.solid){if(r)break;l+=2}}if(!a)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(u.type):WW(u.type,e))?(c=u.addToSet(c),!1):!0),this.nodes.push(new L1(e,n,c,a,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|=ew)}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 a=r.length-1;a>=0;a--)e+=r[a].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,a=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(a?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&&a?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 h7e(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Oie.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function p7e(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function GW(t){let e={};for(let n in t)e[n]=t[n];return e}function WW(t,e){let n=e.schema.nodes;for(let r in n){let a=n[r];if(!a.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;a--){let s=this.serializeMark(e.marks[a],e.isInline,n);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,n,r={}){let a=this.marks[e.type.name];return a&&SN(hD(r),a(e,n),null,e.attrs)}static renderSpec(e,n,r=null,a){return SN(e,n,r,a)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new og(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=KW(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return KW(e.marks)}}function KW(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function hD(t){return t.document||window.document}const YW=new WeakMap;function f7e(t){let e=YW.get(t);return e===void 0&&YW.set(t,e=g7e(t)),e}function g7e(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 a=0;a-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=a.indexOf(" ");o>0&&(n=a.slice(0,o),a=a.slice(o+1));let l,c=n?t.createElementNS(n,a):t.createElement(a),u=e[1],d=1;if(u&&typeof u=="object"&&u.nodeType==null&&!Array.isArray(u)){d=2;for(let m in u)if(u[m]!=null){let p=m.indexOf(" ");p>0?c.setAttributeNS(m.slice(0,p),m.slice(p+1),u[m]):m=="style"&&c.style?c.style.cssText=u[m]:c.setAttribute(m,u[m])}}for(let m=d;md)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:f,contentDOM:y}=SN(t,p,n,r);if(c.appendChild(f),y){if(l)throw new RangeError("Multiple content holes");l=y}}}return{dom:c,contentDOM:l}}const Iie=65535,zie=Math.pow(2,16);function b7e(t,e){return t+e*zie}function XW(t){return t&Iie}function x7e(t){return(t-(t&Iie))/zie}const Uie=1,Bie=2,_N=4,Hie=8;class qF{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&Hie)>0}get deletedBefore(){return(this.delInfo&(Uie|_N))>0}get deletedAfter(){return(this.delInfo&(Bie|_N))>0}get deletedAcross(){return(this.delInfo&_N)>0}}class Xo{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&Xo.empty)return Xo.empty}recover(e){let n=0,r=XW(e);if(!this.inverted)for(let a=0;ae)break;let u=this.ranges[l+s],d=this.ranges[l+o],m=c+u;if(e<=m){let p=u?e==c?-1:e==m?1:n:n,f=c+a+(p<0?0:d);if(r)return f;let y=e==(n<0?c:m)?null:b7e(l/3,e-c),v=e==c?Bie:e==m?Uie:_N;return(n<0?e!=c:e!=m)&&(v|=Hie),new qF(f,v,y)}a+=d-u}return r?e+a:new qF(e+a,0,null)}touches(e,n){let r=0,a=XW(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==a*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 a=0,s=0;a=0;n--){let a=e.getMirror(n);this.appendMap(e._maps[n].invert(),a!=null&&a>n?r-a-1:void 0)}}invert(){let e=new tw;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)),a),n.openStart,n.openEnd);return sa.fromReplace(e,this.from,this.to,s)}invert(){return new _c(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 yh(n.pos,r.pos,this.mark)}merge(e){return e instanceof yh&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new yh(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 yh(n.from,n.to,e.markFromJSON(n.mark))}}ks.jsonID("addMark",yh);class _c extends ks{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 Zt(OI(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),e),n.openStart,n.openEnd);return sa.fromReplace(e,this.from,this.to,r)}invert(){return new yh(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 _c(n.pos,r.pos,this.mark)}merge(e){return e instanceof _c&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new _c(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 _c(n.from,n.to,e.markFromJSON(n.mark))}}ks.jsonID("removeMark",_c);class vh extends ks{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return sa.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return sa.fromReplace(e,this.pos,this.pos+1,new Zt(Bt.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 a=0;ar.pos?null:new La(n.pos,r.pos,a,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 La(n.from,n.to,n.gapFrom,n.gapTo,Zt.fromJSON(e,n.slice),n.insert,!!n.structure)}}ks.jsonID("replaceAround",La);function VF(t,e,n){let r=t.resolve(e),a=n-e,s=r.depth;for(;a>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,a--;if(a>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;a>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,a--}}return!1}function y7e(t,e,n,r){let a=[],s=[],o,l;t.doc.nodesBetween(e,n,(c,u,d)=>{if(!c.isInline)return;let m=c.marks;if(!r.isInSet(m)&&d.type.allowsMarkType(r.type)){let p=Math.max(u,e),f=Math.min(u+c.nodeSize,n),y=r.addToSet(m);for(let v=0;vt.step(c)),s.forEach(c=>t.step(c))}function v7e(t,e,n,r){let a=[],s=0;t.doc.nodesBetween(e,n,(o,l)=>{if(!o.isInline)return;s++;let c=null;if(r instanceof yA){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 _c(o.from,o.to,o.style)))}function II(t,e,n,r=n.contentMatch,a=!0){let s=t.doc.nodeAt(e),o=[],l=e+1;for(let c=0;c=0;c--)t.step(o[c])}function w7e(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function cy(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,a=0,s=0;;--r){let o=t.$from.node(r),l=t.$from.index(r)+a,c=t.$to.indexAfter(r)-s;if(rn;y--)v||r.index(y)>0?(v=!0,d=Bt.from(r.node(y).copy(d)),m++):c--;let p=Bt.empty,f=0;for(let y=s,v=!1;y>n;y--)v||a.after(y+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=Bt.from(n[o].type.create(n[o].attrs,r))}let a=e.start,s=e.end;t.step(new La(a,s,a,s,new Zt(r,0,0),n.length,!0))}function C7e(t,e,n,r,a){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 a=="function"?a(o):a;if(o.isTextblock&&!o.hasMarkup(r,c)&&T7e(t.doc,t.mapping.slice(s).map(l),r)){let u=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",y=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!y?u=!1:!f&&y&&(u=!0)}u===!1&&qie(t,o,l,s),II(t,t.mapping.slice(s).map(l,1),r,void 0,u===null);let d=t.mapping.slice(s),m=d.map(l,1),p=d.map(l+o.nodeSize,1);return t.step(new La(m,p,m+1,p-1,new Zt(Bt.from(r.create(c,null,o.marks)),0,0),1,!0)),u===!0&&$ie(t,o,l,s),!1}})}function $ie(t,e,n,r){e.forEach((a,s)=>{if(a.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(a.text);){let c=t.mapping.slice(r).map(n+1+s+o.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function qie(t,e,n,r){e.forEach((a,s)=>{if(a.type==a.type.schema.linebreakReplacement){let o=t.mapping.slice(r).map(n+1+s);t.replaceWith(o,o+1,e.type.schema.text(` -`))}})}function T7e(t,e,n){let r=t.resolve(e),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function A7e(t,e,n,r,a){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,a||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 La(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new Zt(Bt.from(o),0,0),1,!0))}function Od(t,e,n=1,r){let a=t.resolve(e),s=a.depth-n,o=r&&r[r.length-1]||a.parent;if(s<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!o.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let u=a.depth-1,d=n-2;u>s;u--,d--){let m=a.node(u),p=a.index(u);if(m.type.spec.isolating)return!1;let f=m.content.cutByIndex(p,m.childCount),y=r&&r[d+1];y&&(f=f.replaceChild(0,y.type.create(y.attrs)));let v=r&&r[d]||m;if(!m.canReplace(p+1,m.childCount)||!v.type.validContent(f))return!1}let l=a.indexAfter(s),c=r&&r[0];return a.node(s).canReplaceWith(l,l,c?c.type:a.node(s+1).type)}function P7e(t,e,n=1,r){let a=t.doc.resolve(e),s=Bt.empty,o=Bt.empty;for(let l=a.depth,c=a.depth-n,u=n-1;l>c;l--,u--){s=Bt.from(a.node(l).copy(s));let d=r&&r[u];o=Bt.from(d?d.type.create(d.attrs,o):a.node(l).copy(o))}t.step(new Ra(e,e,new Zt(s.append(o),n,n),!0))}function tp(t,e){let n=t.resolve(e),r=n.index();return Vie(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function M7e(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let a=0;a0?(s=r.node(a+1),l++,o=r.node(a).maybeChild(l)):(s=r.node(a).maybeChild(l-1),o=r.node(a+1)),s&&!s.isTextblock&&Vie(s,o)&&r.node(a).canReplace(l,l+1))return e;if(a==0)break;e=n<0?r.before(a):r.after(a)}}function E7e(t,e,n){let r=null,{linebreakReplacement:a}=t.doc.type.schema,s=t.doc.resolve(e-n),o=s.node().type;if(a&&o.inlineContent){let d=o.whitespace=="pre",m=!!o.contentMatch.matchType(a);d&&!m?r=!1:!d&&m&&(r=!0)}let l=t.steps.length;if(r===!1){let d=t.doc.resolve(e+n);qie(t,d.node(),d.before(),l)}o.inlineContent&&II(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 Ra(u,c.map(e+n,-1),Zt.empty,!0)),r===!0){let d=t.doc.resolve(u);$ie(t,d.node(),d.before(),t.steps.length)}return t}function j7e(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 a=r.depth-1;a>=0;a--){let s=r.index(a);if(r.node(a).canReplaceWith(s,s,n))return r.before(a+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let a=r.depth-1;a>=0;a--){let s=r.indexAfter(a);if(r.node(a).canReplaceWith(s,s,n))return r.after(a+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,a);else{let m=u.contentMatchAt(c).findWrapping(a.firstChild.type);d=m&&u.canReplaceWith(c,c,m[0])}if(d)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function wA(t,e,n=e,r=Zt.empty){if(e==n&&!r.size)return null;let a=t.resolve(e),s=t.resolve(n);return Wie(a,s,r)?new Ra(e,n,r):new D7e(a,s,r).fit()}function Wie(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class D7e{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=Bt.empty;for(let a=0;a<=e.depth;a++){let s=e.node(a);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(a))})}for(let a=e.depth;a>0;a--)this.placed=Bt.from(e.node(a).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,a=this.close(e<0?this.$to:r.doc.resolve(e));if(!a)return null;let s=this.placed,o=r.depth,l=a.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let c=new Zt(s,o,l);return e>-1?new La(r.pos,e,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Ra(r.pos,a.pos,c):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,a=this.unplaced.openEnd;r1&&(a=0),s.type.spec.isolating&&a<=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 a,s=null;r?(s=fD(this.unplaced.content,r-1).firstChild,a=s.content):a=this.unplaced.content;let o=a.firstChild;for(let l=this.depth;l>=0;l--){let{type:c,match:u}=this.frontier[l],d,m=null;if(n==1&&(o?u.matchType(o.type)||(m=u.fillBefore(Bt.from(o),!1)):s&&c.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:m};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,a=fD(e,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new Zt(e,n+1,Math.max(r,a.size+n>=e.size-r?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:r}=this.unplaced,a=fD(e,n);if(a.childCount<=1&&n>0){let s=e.size-n<=n+a.size;this.unplaced=new Zt(zv(e,n-1,1),n-1,s?n-1:r)}else this.unplaced=new Zt(zv(e,n,1),n,r)}placeNodes({sliceDepth:e,frontierDepth:n,parent:r,inject:a,wrap:s}){for(;this.depth>n;)this.closeFrontierNode();if(s)for(let v=0;v1||c==0||v.content.size)&&(m=b,d.push(Kie(v.mark(p.allowedMarks(v.marks)),u==1?c:0,u==l.childCount?f:-1)))}let y=u==l.childCount;y||(f=-1),this.placed=Uv(this.placed,n,Bt.from(d)),this.frontier[n].match=m,y&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let v=0,b=l;v1&&a==this.$to.end(--r);)++a;return a}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:a}=this.frontier[n],s=n=0;l--){let{match:c,type:u}=this.frontier[l],d=gD(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=Uv(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let a=e.node(r),s=a.type.contentMatch.fillBefore(a.content,!0,e.index(r));this.openFrontierNode(a.type,a.attrs,s)}return e}openFrontierNode(e,n=null,r){let a=this.frontier[this.depth];a.match=a.match.matchType(e),this.placed=Uv(this.placed,this.depth,Bt.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Bt.empty,!0);n.childCount&&(this.placed=Uv(this.placed,this.frontier.length,n))}}function zv(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(zv(t.firstChild.content,e-1,n)))}function Uv(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Uv(t.lastChild.content,e-1,n)))}function fD(t,e){for(let n=0;n1&&(r=r.replaceChild(0,Kie(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(Bt.empty,!0)))),t.copy(r)}function gD(t,e,n,r,a){let s=t.node(e),o=a?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&&!R7e(n,s.content,o)?l:null}function R7e(t,e,n){for(let r=n;r0;p--,f--){let y=a.node(p).type.spec;if(y.defining||y.definingAsContext||y.isolating)break;o.indexOf(p)>-1?l=p:a.before(p)==f&&o.splice(1,0,-p)}let c=o.indexOf(l),u=[],d=r.openStart;for(let p=r.content,f=0;;f++){let y=p.firstChild;if(u.push(y),f==r.openStart)break;p=y.content}for(let p=d-1;p>=0;p--){let f=u[p],y=F7e(f.type);if(y&&!f.sameMarkup(a.node(Math.abs(l)-1)))d=p;else if(y||!f.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let f=(p+d+1)%(r.openStart+1),y=u[f];if(y)for(let v=0;v=0&&(t.replace(e,n,r),!(t.steps.length>m));p--){let f=o[p];f<0||(e=a.before(f),n=s.after(f))}}function Yie(t,e,n,r,a){if(er){let s=a.contentMatchAt(0),o=s.fillBefore(t).append(t);t=o.append(s.matchFragment(o).fillBefore(Bt.empty,!0))}return t}function O7e(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let a=j7e(t.doc,e,r.type);a!=null&&(e=n=a)}t.replaceRange(e,n,new Zt(Bt.from(r),0,0))}function I7e(t,e,n){let r=t.doc.resolve(e),a=t.doc.resolve(n),s=Xie(r,a);for(let o=0;o0&&(c||r.node(l-1).canReplace(r.index(l-1),a.indexAfter(l-1))))return t.delete(r.before(l),a.after(l))}for(let o=1;o<=r.depth&&o<=a.depth;o++)if(e-r.start(o)==r.depth-o&&n>r.end(o)&&a.end(o)-n!=a.depth-o&&r.start(o-1)==a.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),a.index(o-1)))return t.delete(r.before(o),n);t.delete(e,n)}function Xie(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let a=r;a>=0;a--){let s=t.start(a);if(se.pos+(e.depth-a)||t.node(a).type.spec.isolating||e.node(a).type.spec.isolating)break;(s==e.start(a)||a==t.depth&&a==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&a&&e.start(a-1)==s-1)&&n.push(a)}return n}class ax extends ks{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 sa.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 a=n.type.create(r,null,n.marks);return sa.fromReplace(e,this.pos,this.pos+1,new Zt(Bt.from(a),0,n.isLeaf?0:1))}getMap(){return Xo.empty}invert(e){return new ax(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 ax(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 ax(n.pos,n.attr,n.value)}}ks.jsonID("attr",ax);class nw extends ks{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let a in e.attrs)n[a]=e.attrs[a];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return sa.ok(r)}getMap(){return Xo.empty}invert(e){return new nw(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 nw(n.attr,n.value)}}ks.jsonID("docAttr",nw);let jx=class extends Error{};jx=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};jx.prototype=Object.create(Error.prototype);jx.prototype.constructor=jx;jx.prototype.name="TransformError";class Qie{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new tw}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new jx(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,n=-1e9;for(let r=0;r{e=Math.min(e,l),n=Math.max(n,c)})}return e==1e9?null:{from:e,to:n}}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,r=Zt.empty){let a=wA(this.doc,e,n,r);return a&&this.step(a),this}replaceWith(e,n,r){return this.replace(e,n,new Zt(Bt.from(r),0,0))}delete(e,n){return this.replace(e,n,Zt.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return L7e(this,e,n,r),this}replaceRangeWith(e,n,r){return O7e(this,e,n,r),this}deleteRange(e,n){return I7e(this,e,n),this}lift(e,n){return S7e(this,e,n),this}join(e,n=1){return E7e(this,e,n),this}wrap(e,n){return k7e(this,e,n),this}setBlockType(e,n=e,r,a=null){return C7e(this,e,n,r,a),this}setNodeMarkup(e,n,r=null,a){return A7e(this,e,n,r,a),this}setNodeAttribute(e,n,r){return this.step(new ax(e,n,r)),this}setDocAttribute(e,n){return this.step(new nw(e,n)),this}addNodeMark(e,n){return this.step(new vh(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 Yr)n.isInSet(r.marks)&&this.step(new Yf(e,n));else{let a=r.marks,s,o=[];for(;s=n.isInSet(a);)o.push(new Yf(e,s)),a=s.removeFromSet(a);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,n=1,r){return P7e(this,e,n,r),this}addMark(e,n,r){return y7e(this,e,n,r),this}removeMark(e,n,r){return v7e(this,e,n,r),this}clearIncompatible(e,n,r){return II(this,e,n,r),this}}const bD=Object.create(null);class Kn{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new z7e(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?Fb(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):Fb(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 nl(e.node(0))}static atStart(e){return Fb(e,e,0,0,1)||new nl(e)}static atEnd(e){return Fb(e,e,e.content.size,e.childCount,-1)||new nl(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=bD[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 bD)throw new RangeError("Duplicate use of selection JSON ID "+e);return bD[e]=n,n.prototype.jsonID=e,n}getBookmark(){return Dn.between(this.$anchor,this.$head).getBookmark()}}Kn.prototype.visible=!0;class z7e{constructor(e,n){this.$from=e,this.$to=n}}let ZW=!1;function JW(t){!ZW&&!t.parent.inlineContent&&(ZW=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class Dn extends Kn{constructor(e,n=e){JW(e),JW(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 Kn.near(r);let a=e.resolve(n.map(this.anchor));return new Dn(a.parent.inlineContent?a:r,r)}replace(e,n=Zt.empty){if(super.replace(e,n),n==Zt.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof Dn&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new SA(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 Dn(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let a=e.resolve(n);return new this(a,r==n?a:e.resolve(r))}static between(e,n,r){let a=e.pos-n.pos;if((!r||a)&&(r=a>=0?1:-1),!n.parent.inlineContent){let s=Kn.findFrom(n,r,!0)||Kn.findFrom(n,-r,!0);if(s)n=s.$head;else return Kn.near(n,r)}return e.parent.inlineContent||(a==0?e=n:(e=(Kn.findFrom(e,-r,!0)||Kn.findFrom(e,r,!0)).$anchor,e.pos0?0:1);a>0?o=0;o+=a){let l=e.child(o);if(l.isAtom){if(!s&&yn.isSelectable(l))return yn.create(t,n-(a<0?l.nodeSize:0))}else{let c=Fb(t,l,n+a,a<0?l.childCount:0,a,s);if(c)return c}n+=l.nodeSize*a}return null}function eK(t,e,n){let r=t.steps.length-1;if(r{o==null&&(o=d)}),t.setSelection(Kn.near(t.doc.resolve(o),n))}const tK=1,O1=2,nK=4;class B7e extends Qie{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 Yr.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)||Yr.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let a=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(a.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,a.text(e,s)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(Kn.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|=nK,this}get scrolledIntoView(){return(this.updated&nK)>0}}function rK(t,e){return!e||!t?t:t.bind(e)}class Bv{constructor(e,n,r){this.name=e,this.init=rK(n.init,r),this.apply=rK(n.apply,r)}}const H7e=[new Bv("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new Bv("selection",{init(t,e){return t.selection||Kn.atStart(e.doc)},apply(t){return t.selection}}),new Bv("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new Bv("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class xD{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=H7e.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 Bv(r.key,r.spec.state,r))})}}class Vb{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 a=e[r],s=a.spec.state;s&&s.toJSON&&(n[r]=s.toJSON.call(a,this[a.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 a=new xD(e.schema,e.plugins),s=new Vb(a);return a.fields.forEach(o=>{if(o.name=="doc")s.doc=kc.fromJSON(e.schema,n.doc);else if(o.name=="selection")s.selection=Kn.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 Zie(t,e,n){for(let r in t){let a=t[r];a instanceof Function?a=a.bind(e):r=="handleDOMEvents"&&(a=Zie(a,e,{})),n[r]=a}return n}class _i{constructor(e){this.spec=e,this.props={},e.props&&Zie(e.props,this,this.props),this.key=e.key?e.key.key:Jie("plugin")}getState(e){return e[this.key]}}const yD=Object.create(null);function Jie(t){return t in yD?t+"$"+ ++yD[t]:(yD[t]=0,t+"$")}class Na{constructor(e="key"){this.key=Jie(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const BI=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function eae(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const tae=(t,e,n)=>{let r=eae(t,n);if(!r)return!1;let a=HI(r);if(!a){let o=r.blockRange(),l=o&&cy(o);return l==null?!1:(e&&e(t.tr.lift(o,l).scrollIntoView()),!0)}let s=a.nodeBefore;if(uae(t,a,e,-1))return!0;if(r.parent.content.size==0&&(Dx(s,"end")||yn.isSelectable(s)))for(let o=r.depth;;o--){let l=wA(t.doc,r.before(o),r.after(o),Zt.empty);if(l&&l.slice.size1)break}return s.isAtom&&a.depth==r.depth-1?(e&&e(t.tr.delete(a.pos-s.nodeSize,a.pos).scrollIntoView()),!0):!1},$7e=(t,e,n)=>{let r=eae(t,n);if(!r)return!1;let a=HI(r);return a?nae(t,a,e):!1},q7e=(t,e,n)=>{let r=iae(t,n);if(!r)return!1;let a=$I(r);return a?nae(t,a,e):!1};function nae(t,e,n){let r=e.nodeBefore,a=r,s=e.pos-1;for(;!a.isTextblock;s--){if(a.type.spec.isolating)return!1;let d=a.lastChild;if(!d)return!1;a=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=wA(t.doc,s,c,Zt.empty);if(!u||u.from!=s||u instanceof Ra&&u.slice.size>=c-s)return!1;if(n){let d=t.tr.step(u);d.setSelection(Dn.create(d.doc,s)),n(d.scrollIntoView())}return!0}function Dx(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 rae=(t,e,n)=>{let{$head:r,empty:a}=t.selection,s=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;s=HI(r)}let o=s&&s.nodeBefore;return!o||!yn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(yn.create(t.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function HI(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 iae(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset{let r=iae(t,n);if(!r)return!1;let a=$I(r);if(!a)return!1;let s=a.nodeAfter;if(uae(t,a,e,1))return!0;if(r.parent.content.size==0&&(Dx(s,"start")||yn.isSelectable(s))){let o=wA(t.doc,r.before(),r.after(),Zt.empty);if(o&&o.slice.size{let{$head:r,empty:a}=t.selection,s=r;if(!a)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 yn,a;if(r){if(n.node.isTextblock||!tp(t.doc,n.from))return!1;a=n.from}else if(a=vA(t.doc,n.from,-1),a==null)return!1;if(e){let s=t.tr.join(a);r&&s.setSelection(yn.create(s.doc,a-t.doc.resolve(a).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},G7e=(t,e)=>{let n=t.selection,r;if(n instanceof yn){if(n.node.isTextblock||!tp(t.doc,n.to))return!1;r=n.to}else if(r=vA(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},W7e=(t,e)=>{let{$from:n,$to:r}=t.selection,a=n.blockRange(r),s=a&&cy(a);return s==null?!1:(e&&e(t.tr.lift(a,s).scrollIntoView()),!0)},oae=(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 qI(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 a=n.node(-1),s=n.indexAfter(-1),o=qI(a.contentMatchAt(s));if(!o||!a.canReplaceWith(s,s,o))return!1;if(e){let l=n.after(),c=t.tr.replaceWith(l,l,o.createAndFill());c.setSelection(Kn.near(c.doc.resolve(l),1)),e(c.scrollIntoView())}return!0},lae=(t,e)=>{let n=t.selection,{$from:r,$to:a}=n;if(n instanceof nl||r.parent.inlineContent||a.parent.inlineContent)return!1;let s=qI(a.parent.contentMatchAt(a.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&a.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(Od(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),a=r&&cy(r);return a==null?!1:(e&&e(t.tr.lift(r,a).scrollIntoView()),!0)};function Y7e(t){return(e,n)=>{let{$from:r,$to:a}=e.selection;if(e.selection instanceof yn&&e.selection.node.isBlock)return!r.parentOffset||!Od(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 f=r.depth;;f--)if(r.node(f).isBlock){c=r.end(f)==r.pos+(r.depth-f),u=r.start(f)==r.pos-(r.depth-f),l=qI(r.node(f-1).contentMatchAt(r.indexAfter(f-1))),s.unshift(c&&l?{type:l}:null),o=f;break}else{if(f==1)return!1;s.unshift(null)}let d=e.tr;(e.selection instanceof Dn||e.selection instanceof nl)&&d.deleteSelection();let m=d.mapping.map(r.pos),p=Od(d.doc,m,s.length,s);if(p||(s[0]=l?{type:l}:null,p=Od(d.doc,m,s.length,s)),!p)return!1;if(d.split(m,s.length,s),!c&&u&&r.node(o).type!=l){let f=d.mapping.map(r.before(o)),y=d.doc.resolve(f);l&&r.node(o-1).canReplaceWith(y.index(),y.index()+1,l)&&d.setNodeMarkup(d.mapping.map(r.before(o)),l)}return n&&n(d.scrollIntoView()),!0}}const X7e=Y7e(),Q7e=(t,e)=>{let{$from:n,to:r}=t.selection,a,s=n.sharedDepth(r);return s==0?!1:(a=n.before(s),e&&e(t.tr.setSelection(yn.create(t.doc,a))),!0)};function Z7e(t,e,n){let r=e.nodeBefore,a=e.nodeAfter,s=e.index();return!r||!a||!r.type.compatibleContent(a.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)||!(a.isTextblock||tp(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function uae(t,e,n,r){let a=e.nodeBefore,s=e.nodeAfter,o,l,c=a.type.spec.isolating||s.type.spec.isolating;if(!c&&Z7e(t,e,n))return!0;let u=!c&&e.parent.canReplace(e.index(),e.index()+1);if(u&&(o=(l=a.contentMatchAt(a.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(n){let f=e.pos+s.nodeSize,y=Bt.empty;for(let g=o.length-1;g>=0;g--)y=Bt.from(o[g].create(null,y));y=Bt.from(a.copy(y));let v=t.tr.step(new La(e.pos-1,f,e.pos,f,new Zt(y,1,0),o.length,!0)),b=v.doc.resolve(f+2*o.length);b.nodeAfter&&b.nodeAfter.type==a.type&&tp(v.doc,b.pos)&&v.join(b.pos),n(v.scrollIntoView())}return!0}let d=s.type.spec.isolating||r>0&&c?null:Kn.findFrom(e,1),m=d&&d.$from.blockRange(d.$to),p=m&&cy(m);if(p!=null&&p>=e.depth)return n&&n(t.tr.lift(m,p).scrollIntoView()),!0;if(u&&Dx(s,"start",!0)&&Dx(a,"end")){let f=a,y=[];for(;y.push(f),!f.isTextblock;)f=f.lastChild;let v=s,b=1;for(;!v.isTextblock;v=v.firstChild)b++;if(f.canReplace(f.childCount,f.childCount,v.content)){if(n){let g=Bt.empty;for(let N=y.length-1;N>=0;N--)g=Bt.from(y[N].copy(g));let _=t.tr.step(new La(e.pos-y.length,e.pos+s.nodeSize,e.pos+b,e.pos+s.nodeSize-b,new Zt(g,y.length,0),0,!0));n(_.scrollIntoView())}return!0}}return!1}function dae(t){return function(e,n){let r=e.selection,a=t<0?r.$from:r.$to,s=a.depth;for(;a.node(s).isInline;){if(!s)return!1;s--}return a.node(s).isTextblock?(n&&n(e.tr.setSelection(Dn.create(e.doc,t<0?a.start(s):a.end(s)))),!0):!1}}const J7e=dae(-1),eGe=dae(1);function tGe(t,e=null){return function(n,r){let{$from:a,$to:s}=n.selection,o=a.blockRange(s),l=o&&zI(o,t,e);return l?(r&&r(n.tr.wrap(o,l).scrollIntoView()),!0):!1}}function iK(t,e=null){return function(n,r){let a=!1;for(let s=0;s{if(a)return!1;if(!(!c.isTextblock||c.hasMarkup(t,e)))if(c.type==t)a=!0;else{let d=n.doc.resolve(u),m=d.index();a=d.parent.canReplaceWith(m,m+1,t)}})}if(!a)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 oC(c,c,e.depth),e.endIndex=0;d--)s=Bt.from(n[d].type.create(n[d].attrs,s));t.step(new La(e.start-(r?2:0),e.end,e.start,e.end,new Zt(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?sGe(e,n,t,s):oGe(e,n,s):!0:!1}}function sGe(t,e,n,r){let a=t.tr,s=r.end,o=r.$to.end(r.depth);sv;y--)f-=a.child(y).nodeSize,r.delete(f-1,f+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==a.childCount,u=s.node(-1),d=s.index(-1);if(!u.canReplace(d+(l?0:1),d+1,o.content.append(c?Bt.empty:Bt.from(a))))return!1;let m=s.pos,p=m+o.nodeSize;return r.step(new La(m-(l?1:0),p+(c?1:0),m+1,p-1,new Zt((l?Bt.empty:Bt.from(a.copy(Bt.empty))).append(c?Bt.empty:Bt.from(a.copy(Bt.empty))),l?0:1,c?0:1),l?0:1)),e(r.scrollIntoView()),!0}function lGe(t){return function(e,n){let{$from:r,$to:a}=e.selection,s=r.blockRange(a,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=Bt.from(u?t.create():null),m=new Zt(Bt.from(t.create(null,Bt.from(l.type.create(null,d)))),u?3:1,0),p=s.start,f=s.end;n(e.tr.step(new La(p-(u?3:1),f,p,f,m,1,!0)).scrollIntoView())}return!0}}const rs=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},Rx=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let GF=null;const bd=function(t,e,n){let r=GF||(GF=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},cGe=function(){GF=null},Xf=function(t,e,n,r){return n&&(aK(t,e,n,r,-1)||aK(t,e,n,r,1))},uGe=/^(img|br|input|textarea|hr)$/i;function aK(t,e,n,r,a){for(var s;;){if(t==n&&e==r)return!0;if(e==(a<0?0:Ol(t))){let o=t.parentNode;if(!o||o.nodeType!=1||Qw(t)||uGe.test(t.nodeName)||t.contentEditable=="false")return!1;e=rs(t)+(a<0?0:1),t=o}else if(t.nodeType==1){let o=t.childNodes[e+(a<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=a;else return!1;else t=o,e=a<0?Ol(t):0}else return!1}}function Ol(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function dGe(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=Ol(t)}else if(t.parentNode&&!Qw(t))e=rs(t),t=t.parentNode;else return null}}function mGe(t,e){for(;;){if(t.nodeType==3&&e2),El=Fx||(Nu?/Mac/.test(Nu.platform):!1),pae=Nu?/Win/.test(Nu.platform):!1,Pd=/Android \d/.test(np),Zw=!!sK&&"webkitFontSmoothing"in sK.documentElement.style,gGe=Zw?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function bGe(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 ud(t,e){return typeof t=="number"?t:t[e]}function xGe(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 oK(t,e,n){let r=t.someProp("scrollThreshold")||0,a=t.someProp("scrollMargin")||5,s=t.dom.ownerDocument;for(let o=n||t.dom;o;){if(o.nodeType!=1){o=Rx(o);continue}let l=o,c=l==s.body,u=c?bGe(s):xGe(l),d=0,m=0;if(e.topu.bottom-ud(r,"bottom")&&(m=e.bottom-e.top>u.bottom-u.top?e.top+ud(a,"top")-u.top:e.bottom-u.bottom+ud(a,"bottom")),e.leftu.right-ud(r,"right")&&(d=e.right-u.right+ud(a,"right")),d||m)if(c)s.defaultView.scrollBy(d,m);else{let f=l.scrollLeft,y=l.scrollTop;m&&(l.scrollTop+=m),d&&(l.scrollLeft+=d);let v=l.scrollLeft-f,b=l.scrollTop-y;e={left:e.left-v,top:e.top-b,right:e.right-v,bottom:e.bottom-b}}let p=c?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(p))break;o=p=="absolute"?o.offsetParent:Rx(o)}}function yGe(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,a;for(let s=(e.left+e.right)/2,o=n+1;o=n-20){r=l,a=c.top;break}}return{refDOM:r,refTop:a,stack:fae(t.dom)}}function fae(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=Rx(r));return e}function vGe({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;gae(n,r==0?0:r-e)}function gae(t,e){for(let n=0;n=l){o=Math.max(y.bottom,o),l=Math.min(y.top,l);let v=y.left>e.left?y.left-e.left:y.right=(y.left+y.right)/2?1:0));continue}}else y.top>e.top&&!c&&y.left<=e.left&&y.right>=e.left&&(c=d,u={left:Math.max(y.left,Math.min(y.right,e.left)),top:y.top});!n&&(e.left>=y.right&&e.top>=y.top||e.left>=y.left&&e.top>=y.bottom)&&(s=m+1)}}return!n&&c&&(n=c,a=u,r=0),n&&n.nodeType==3?SGe(n,a):!n||r&&n.nodeType==1?{node:t,offset:s}:bae(n,a)}function SGe(t,e){let n=t.nodeValue.length,r=document.createRange(),a;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),a||{node:t,offset:0}}function GI(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function _Ge(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,a,s)}function kGe(t,e,n,r){let a=-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?a=l.posBefore:(!o&&c.right-1?a:t.docView.posFromDOM(e,n,-1)}function xae(t,e,n){let r=t.childNodes.length;if(r&&n.tope.top&&a++}let u;Zw&&a&&r.nodeType==1&&(u=r.childNodes[a-1]).nodeType==1&&u.contentEditable=="false"&&u.getBoundingClientRect().top>=e.top&&a--,r==t.dom&&a==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=t.state.doc.content.size:(a==0||r.nodeType!=1||r.childNodes[a-1].nodeName!="BR")&&(l=kGe(t,r,a,e))}l==null&&(l=NGe(t,o,e));let c=t.docView.nearestDesc(o,!0);return{pos:l,inside:c?c.posAtStart-c.border:-1}}function lK(t){return t.top=0&&a==r.nodeValue.length?(c--,d=1):n<0?c--:u++,Av(Km(bd(r,c,u),d),d<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&a&&(n<0||a==Ol(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return vD(c.getBoundingClientRect(),!1)}if(s==null&&a=0)}if(s==null&&a&&(n<0||a==Ol(r))){let c=r.childNodes[a-1],u=c.nodeType==3?bd(c,Ol(c)-(o?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(u)return Av(Km(u,1),!1)}if(s==null&&a=0)}function Av(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 vD(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 vae(t,e,n){let r=t.state,a=t.root.activeElement;r!=e&&t.updateState(e),a!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),a!=t.dom&&a&&a.focus()}}function AGe(t,e,n){let r=e.selection,a=n=="up"?r.$from:r.$to;return vae(t,e,()=>{let{node:s}=t.docView.domFromPos(a.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=yae(t,a.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=bd(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 PGe=/[\u0590-\u08ac]/;function MGe(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let a=r.parentOffset,s=!a,o=a==r.parent.content.size,l=t.domSelection();return l?!PGe.test(r.parent.textContent)||!l.modify?n=="left"||n=="backward"?s:o:vae(t,e,()=>{let{focusNode:c,focusOffset:u,anchorNode:d,anchorOffset:m}=t.domSelectionRange(),p=l.caretBidiLevel;l.modify("move",n,"character");let f=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:y,focusOffset:v}=t.domSelectionRange(),b=y&&!f.contains(y.nodeType==1?y:y.parentNode)||c==y&&u==v;try{l.collapse(d,m),c&&(c!=d||u!=m)&&l.extend&&l.extend(c,u)}catch{}return p!=null&&(l.caretBidiLevel=p),b}):r.pos==r.start()||r.pos==r.end()}let cK=null,uK=null,dK=!1;function EGe(t,e,n){return cK==e&&uK==n?dK:(cK=e,uK=n,dK=n=="up"||n=="down"?AGe(t,e,n):MGe(t,e,n))}const $l=0,mK=1,lf=2,ku=3;class Jw{constructor(e,n,r,a){this.parent=e,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=$l,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;nrs(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))a=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let s=e;;s=s.parentNode){if(s==this.dom){a=!1;break}if(s.previousSibling)break}if(a==null&&n==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){a=!0;break}if(s.nextSibling)break}}return a??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,a=e;a;a=a.parentNode){let s=this.getDesc(a),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 a=e;a;a=a.parentNode){let s=this.getDesc(a);if(s)return s.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;ne||o instanceof Sae){a=e-s;break}s=l}if(a)return this.children[r].domFromPos(a-this.children[r].border,n);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof wae&&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?rs(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 m=l;m>0;m--){let p=this.children[m-1];if(p.size&&p.dom.parentNode==this.contentDOM&&!p.emptyChildAt(1)){a=rs(p.dom)+1;break}e-=p.size}a==-1&&(a=0)}if(a>-1&&(u>n||l==this.children.length-1)){n=u;for(let d=l+1;dy&&on){let y=l;l=c,c=y}let f=document.createRange();f.setEnd(c.node,c.offset),f.setStart(l.node,l.offset),u.removeAllRanges(),u.addRange(f)}}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,a=0;a=r:er){let l=r+s.border,c=o-s.border;if(e>=l&&n<=c){this.dirty=e==r||n==o?lf:mK,e==l&&n==c&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=ku:s.markDirty(e-l,n-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?lf:ku}r=o}this.dirty=lf}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?lf:mK;n.dirty{if(!s)return a;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==$l&&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 jGe extends Jw{constructor(e,n,r,a){super(e,[],n,null),this.textDOM=r,this.text=a}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Qf extends Jw{constructor(e,n,r,a,s){super(e,[],r,a),this.mark=n,this.spec=s}static create(e,n,r,a){let s=a.nodeViews[n.type.name],o=s&&s(n,a,r);return(!o||!o.dom)&&(o=og.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new Qf(e,n,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&ku||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=ku&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=$l){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=QF(s,0,e,r));for(let l=0;l{if(!c)return o;if(c.parent)return c.parent.posBeforeChild(c)},r,a),d=u&&u.dom,m=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:m}=og.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!m&&!n.isText&&d.nodeName!="BR"&&(d.hasAttribute("contenteditable")||(d.contentEditable="false"),n.type.spec.draggable&&(d.draggable=!0));let p=d;return d=kae(d,r,n),u?c=new DGe(e,n,r,a,d,m||null,p,u,s,o+1):n.isText?new NA(e,n,r,a,d,p,s):new Oh(e,n,r,a,d,m||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=()=>Bt.empty)}return e}matchesNode(e,n,r){return this.dirty==$l&&e.eq(this.node)&&cC(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,a=n,s=e.composing?this.localCompositionInfo(e,n):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,c=new FGe(this,o&&o.node,e);IGe(this.node,this.innerDeco,(u,d,m)=>{u.spec.marks?c.syncToMarks(u.spec.marks,r,e,d):u.type.side>=0&&!m&&c.syncToMarks(d==this.node.childCount?Yr.none:this.node.child(d).marks,r,e,d),c.placeWidget(u,e,a)},(u,d,m,p)=>{c.syncToMarks(u.marks,r,e,p);let f;c.findNodeMatch(u,d,m,p)||l&&e.state.selection.from>a&&e.state.selection.to-1&&c.updateNodeAt(u,d,m,f,e)||c.updateNextNode(u,d,m,e,p,a)||c.addNode(u,d,m,e,a),a+=u.nodeSize}),c.syncToMarks([],r,e,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==lf)&&(o&&this.protectLocalComposition(e,o),_ae(this.contentDOM,this.children,e),Fx&&zGe(this.dom))}localCompositionInfo(e,n){let{from:r,to:a}=e.state.selection;if(!(e.state.selection instanceof Dn)||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=UGe(this.node.content,o,r-n,a-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:a}){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 jGe(this,s,n,a);e.input.compositionNodes.push(o),this.children=QF(this.children,r,r+a.length,e,o)}update(e,n,r,a){return this.dirty==ku||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,a),!0)}updateInner(e,n,r,a){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(a,this.posAtStart),this.dirty=$l}updateOuterDeco(e){if(cC(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Nae(this.dom,this.nodeDOM,XF(this.outerDeco,this.node,n),XF(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 hK(t,e,n,r,a){kae(r,e,t);let s=new Oh(void 0,t,e,n,r,r,r,a,0);return s.contentDOM&&s.updateChildren(a,0),s}class NA extends Oh{constructor(e,n,r,a,s,o,l){super(e,n,r,a,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,a){return this.dirty==ku||this.dirty!=$l&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=$l||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,a.trackWrites==this.nodeDOM&&(a.trackWrites=null)),this.node=e,this.dirty=$l,!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 a=this.node.cut(e,n),s=document.createTextNode(a.text);return new NA(this.parent,a,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=ku)}get domAtom(){return!1}isText(e){return this.node.text==e}}class Sae extends Jw{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==$l&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class DGe extends Oh{constructor(e,n,r,a,s,o,l,c,u,d){super(e,n,r,a,s,o,l,u,d),this.spec=c}update(e,n,r,a){if(this.dirty==ku)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,a),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,a)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,a){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,a)}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 _ae(t,e,n){let r=t.firstChild,a=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)c>this.index&&(this.changed=!0,this.destroyBetween(this.index,c)),this.top=this.top.children[this.index];else{let d=Qf.create(this.top,e[o],n,r);this.top.children.splice(this.index,0,d),this.top=d,this.changed=!0}this.index=0,o++}}findNodeMatch(e,n,r,a){let s=-1,o;if(a>=this.preMatch.index&&(o=this.preMatch.matches[a-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 Qf)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(a-1))break;--a,s.set(l,a),o.push(l)}}return{index:a,matched:s,matches:o.reverse()}}function OGe(t,e){return t.type.side-e.type.side}function IGe(t,e,n,r){let a=e.locals(t),s=0;if(a.length==0){for(let u=0;us;)l.push(a[o++]);let y=s+p.nodeSize;if(p.isText){let b=y;o!b.inline):l.slice();r(p,v,e.forChild(s,p),f),s=y}}function zGe(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 UGe(t,e,n,r){for(let a=0,s=0;a=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 QF(t,e,n,r,a){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 WI(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let a=t.docView.nearestDesc(n.focusNode),s=a&&a.size==0,o=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(o<0)return null;let l=r.resolve(o),c,u;if(_A(n)){for(c=o;a&&!a.node;)a=a.parent;let m=a.node;if(a&&m.isAtom&&yn.isSelectable(m)&&a.parent&&!(m.isInline&&hGe(n.focusNode,n.focusOffset,a.dom))){let p=a.posBefore;u=new yn(o==p?l:r.resolve(p))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let m=o,p=o;for(let f=0;f{(n.anchorNode!=r||n.anchorOffset!=a)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Cae(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function HGe(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,rs(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&No&&Lh<=11&&(n.disabled=!0,n.disabled=!1)}function Tae(t,e){if(e instanceof yn){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(xK(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else xK(t)}function xK(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function KI(t,e,n,r){return t.someProp("createSelectionBetween",a=>a(t,e,n))||Dn.between(e,n,r)}function yK(t){return t.editable&&!t.hasFocus()?!1:Aae(t)}function Aae(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 $Ge(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Xf(e.node,e.offset,n.anchorNode,n.anchorOffset)}function ZF(t,e){let{$anchor:n,$head:r}=t.selection,a=e>0?n.max(r):n.min(r),s=a.parent.inlineContent?a.depth?t.doc.resolve(e>0?a.after():a.before()):null:a;return s&&Kn.findFrom(s,e)}function eh(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function vK(t,e,n){let r=t.state.selection;if(r instanceof Dn)if(n.indexOf("s")>-1){let{$head:a}=r,s=a.textOffset?null:e<0?a.nodeBefore:a.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=t.state.doc.resolve(a.pos+s.nodeSize*(e<0?-1:1));return eh(t,new Dn(r.$anchor,o))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let a=ZF(t.state,e);return a&&a instanceof yn?eh(t,a):!1}else if(!(El&&n.indexOf("m")>-1)){let a=r.$head,s=a.textOffset?null:e<0?a.nodeBefore:a.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?a.pos-s.nodeSize:a.pos;return s.isAtom||(o=t.docView.descAt(l))&&!o.contentDOM?yn.isSelectable(s)?eh(t,new yn(e<0?t.state.doc.resolve(a.pos-s.nodeSize):a)):Zw?eh(t,new Dn(t.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof yn&&r.node.isInline)return eh(t,new Dn(e>0?r.$to:r.$from));{let a=ZF(t.state,e);return a?eh(t,a):!1}}}function uC(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function s0(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function Cb(t,e){return e<0?qGe(t):VGe(t)}function qGe(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let a,s,o=!1;for(Hl&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let l=n.childNodes[r-1];if(s0(l,-1))a=n,s=--r;else if(l.nodeType==3)n=l,r=n.nodeValue.length;else break}}else{if(Pae(n))break;{let l=n.previousSibling;for(;l&&s0(l,-1);)a=n.parentNode,s=rs(l),l=l.previousSibling;if(l)n=l,r=uC(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}o?JF(t,n,r):a&&JF(t,a,s)}function VGe(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let a=uC(n),s,o;for(;;)if(r{t.state==a&&Id(t)},50)}function wK(t,e){let n=t.state.doc.resolve(e);if(!(ss||pae)&&n.parent.inlineContent){let a=t.coordsAtPos(e);if(e>n.start()){let s=t.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>a.top&&o1)return s.lefta.top&&o1)return s.left>a.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function SK(t,e,n){let r=t.state.selection;if(r instanceof Dn&&!r.empty||n.indexOf("s")>-1||El&&n.indexOf("m")>-1)return!1;let{$from:a,$to:s}=r;if(!a.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let o=ZF(t.state,e);if(o&&o instanceof yn)return eh(t,o)}if(!a.parent.inlineContent){let o=e<0?a:s,l=r instanceof nl?Kn.near(o,e):Kn.findFrom(o,e);return l?eh(t,l):!1}return!1}function _K(t,e){if(!(t.state.selection instanceof Dn))return!0;let{$head:n,$anchor:r,empty:a}=t.state.selection;if(!n.sameParent(r))return!0;if(!a)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 NK(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function KGe(t){if(!Ss||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;NK(t,r,"true"),setTimeout(()=>NK(t,r,"false"),20)}return!1}function YGe(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function XGe(t,e){let n=e.keyCode,r=YGe(e);if(n==8||El&&n==72&&r=="c")return _K(t,-1)||Cb(t,-1);if(n==46&&!e.shiftKey||El&&n==68&&r=="c")return _K(t,1)||Cb(t,1);if(n==13||n==27)return!0;if(n==37||El&&n==66&&r=="c"){let a=n==37?wK(t,t.state.selection.from)=="ltr"?-1:1:-1;return vK(t,a,r)||Cb(t,a)}else if(n==39||El&&n==70&&r=="c"){let a=n==39?wK(t,t.state.selection.from)=="ltr"?1:-1:1;return vK(t,a,r)||Cb(t,a)}else{if(n==38||El&&n==80&&r=="c")return SK(t,-1,r)||Cb(t,-1);if(n==40||El&&n==78&&r=="c")return KGe(t)||SK(t,1,r)||Cb(t,1);if(r==(El?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function YI(t,e){t.someProp("transformCopied",f=>{e=f(e,t)});let n=[],{content:r,openStart:a,openEnd:s}=e;for(;a>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){a--,s--;let f=r.firstChild;n.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let o=t.someProp("clipboardSerializer")||og.fromSchema(t.state.schema),l=Fae(),c=l.createElement("div");c.appendChild(o.serializeFragment(r,{document:l}));let u=c.firstChild,d,m=0;for(;u&&u.nodeType==1&&(d=Rae[u.nodeName.toLowerCase()]);){for(let f=d.length-1;f>=0;f--){let y=l.createElement(d[f]);for(;c.firstChild;)y.appendChild(c.firstChild);c.appendChild(y),m++}u=c.firstChild}u&&u.nodeType==1&&u.setAttribute("data-pm-slice",`${a} ${s}${m?` -${m}`:""} ${JSON.stringify(n)}`);let p=t.someProp("clipboardTextSerializer",f=>f(e,t))||e.content.textBetween(0,e.content.size,` +`),n)}ignoreFallback(e,n){e.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"),n,!0)}readStyles(e,n){let r=e.style;if(r&&r.length)for(let a=0;a!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,a){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(a)this.addElement(e,r,a);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,a){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=a==null?null:e.childNodes[a];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,n);this.findAtPoint(e,s)}findPlace(e,n,r){let a,s;for(let o=this.open,l=0;o>=0;o--){let c=this.nodes[o],u=c.findWrapping(e);if(u&&(!a||a.length>u.length+l)&&(a=u,s=c,!u.length))break;if(c.solid){if(r)break;l+=2}}if(!a)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(u.type):WW(u.type,e))?(c=u.addToSet(c),!1):!0),this.nodes.push(new L1(e,n,c,a,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|=ew)}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 a=r.length-1;a>=0;a--)e+=r[a].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,a=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(a?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&&a?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 h7e(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Oie.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function p7e(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function GW(t){let e={};for(let n in t)e[n]=t[n];return e}function WW(t,e){let n=e.schema.nodes;for(let r in n){let a=n[r];if(!a.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;a--){let s=this.serializeMark(e.marks[a],e.isInline,n);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,n,r={}){let a=this.marks[e.type.name];return a&&SN(hD(r),a(e,n),null,e.attrs)}static renderSpec(e,n,r=null,a){return SN(e,n,r,a)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new og(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=KW(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return KW(e.marks)}}function KW(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function hD(t){return t.document||window.document}const YW=new WeakMap;function f7e(t){let e=YW.get(t);return e===void 0&&YW.set(t,e=g7e(t)),e}function g7e(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 a=0;a-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=a.indexOf(" ");o>0&&(n=a.slice(0,o),a=a.slice(o+1));let l,c=n?t.createElementNS(n,a):t.createElement(a),u=e[1],d=1;if(u&&typeof u=="object"&&u.nodeType==null&&!Array.isArray(u)){d=2;for(let m in u)if(u[m]!=null){let p=m.indexOf(" ");p>0?c.setAttributeNS(m.slice(0,p),m.slice(p+1),u[m]):m=="style"&&c.style?c.style.cssText=u[m]:c.setAttribute(m,u[m])}}for(let m=d;md)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:f,contentDOM:y}=SN(t,p,n,r);if(c.appendChild(f),y){if(l)throw new RangeError("Multiple content holes");l=y}}}return{dom:c,contentDOM:l}}const Iie=65535,zie=Math.pow(2,16);function b7e(t,e){return t+e*zie}function XW(t){return t&Iie}function x7e(t){return(t-(t&Iie))/zie}const Uie=1,Bie=2,_N=4,Hie=8;class qF{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&Hie)>0}get deletedBefore(){return(this.delInfo&(Uie|_N))>0}get deletedAfter(){return(this.delInfo&(Bie|_N))>0}get deletedAcross(){return(this.delInfo&_N)>0}}class Xo{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&Xo.empty)return Xo.empty}recover(e){let n=0,r=XW(e);if(!this.inverted)for(let a=0;ae)break;let u=this.ranges[l+s],d=this.ranges[l+o],m=c+u;if(e<=m){let p=u?e==c?-1:e==m?1:n:n,f=c+a+(p<0?0:d);if(r)return f;let y=e==(n<0?c:m)?null:b7e(l/3,e-c),v=e==c?Bie:e==m?Uie:_N;return(n<0?e!=c:e!=m)&&(v|=Hie),new qF(f,v,y)}a+=d-u}return r?e+a:new qF(e+a,0,null)}touches(e,n){let r=0,a=XW(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==a*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 a=0,s=0;a=0;n--){let a=e.getMirror(n);this.appendMap(e._maps[n].invert(),a!=null&&a>n?r-a-1:void 0)}}invert(){let e=new tw;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)),a),n.openStart,n.openEnd);return sa.fromReplace(e,this.from,this.to,s)}invert(){return new _c(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 yh(n.pos,r.pos,this.mark)}merge(e){return e instanceof yh&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new yh(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 yh(n.from,n.to,e.markFromJSON(n.mark))}}ks.jsonID("addMark",yh);class _c extends ks{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 Zt(O4(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),e),n.openStart,n.openEnd);return sa.fromReplace(e,this.from,this.to,r)}invert(){return new yh(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 _c(n.pos,r.pos,this.mark)}merge(e){return e instanceof _c&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new _c(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 _c(n.from,n.to,e.markFromJSON(n.mark))}}ks.jsonID("removeMark",_c);class vh extends ks{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return sa.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return sa.fromReplace(e,this.pos,this.pos+1,new Zt(Bt.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 a=0;ar.pos?null:new La(n.pos,r.pos,a,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 La(n.from,n.to,n.gapFrom,n.gapTo,Zt.fromJSON(e,n.slice),n.insert,!!n.structure)}}ks.jsonID("replaceAround",La);function VF(t,e,n){let r=t.resolve(e),a=n-e,s=r.depth;for(;a>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,a--;if(a>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;a>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,a--}}return!1}function y7e(t,e,n,r){let a=[],s=[],o,l;t.doc.nodesBetween(e,n,(c,u,d)=>{if(!c.isInline)return;let m=c.marks;if(!r.isInSet(m)&&d.type.allowsMarkType(r.type)){let p=Math.max(u,e),f=Math.min(u+c.nodeSize,n),y=r.addToSet(m);for(let v=0;vt.step(c)),s.forEach(c=>t.step(c))}function v7e(t,e,n,r){let a=[],s=0;t.doc.nodesBetween(e,n,(o,l)=>{if(!o.isInline)return;s++;let c=null;if(r instanceof yA){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 _c(o.from,o.to,o.style)))}function I4(t,e,n,r=n.contentMatch,a=!0){let s=t.doc.nodeAt(e),o=[],l=e+1;for(let c=0;c=0;c--)t.step(o[c])}function w7e(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function cy(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,a=0,s=0;;--r){let o=t.$from.node(r),l=t.$from.index(r)+a,c=t.$to.indexAfter(r)-s;if(rn;y--)v||r.index(y)>0?(v=!0,d=Bt.from(r.node(y).copy(d)),m++):c--;let p=Bt.empty,f=0;for(let y=s,v=!1;y>n;y--)v||a.after(y+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=Bt.from(n[o].type.create(n[o].attrs,r))}let a=e.start,s=e.end;t.step(new La(a,s,a,s,new Zt(r,0,0),n.length,!0))}function C7e(t,e,n,r,a){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 a=="function"?a(o):a;if(o.isTextblock&&!o.hasMarkup(r,c)&&T7e(t.doc,t.mapping.slice(s).map(l),r)){let u=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",y=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!y?u=!1:!f&&y&&(u=!0)}u===!1&&qie(t,o,l,s),I4(t,t.mapping.slice(s).map(l,1),r,void 0,u===null);let d=t.mapping.slice(s),m=d.map(l,1),p=d.map(l+o.nodeSize,1);return t.step(new La(m,p,m+1,p-1,new Zt(Bt.from(r.create(c,null,o.marks)),0,0),1,!0)),u===!0&&$ie(t,o,l,s),!1}})}function $ie(t,e,n,r){e.forEach((a,s)=>{if(a.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(a.text);){let c=t.mapping.slice(r).map(n+1+s+o.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function qie(t,e,n,r){e.forEach((a,s)=>{if(a.type==a.type.schema.linebreakReplacement){let o=t.mapping.slice(r).map(n+1+s);t.replaceWith(o,o+1,e.type.schema.text(` +`))}})}function T7e(t,e,n){let r=t.resolve(e),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function A7e(t,e,n,r,a){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,a||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 La(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new Zt(Bt.from(o),0,0),1,!0))}function Od(t,e,n=1,r){let a=t.resolve(e),s=a.depth-n,o=r&&r[r.length-1]||a.parent;if(s<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!o.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let u=a.depth-1,d=n-2;u>s;u--,d--){let m=a.node(u),p=a.index(u);if(m.type.spec.isolating)return!1;let f=m.content.cutByIndex(p,m.childCount),y=r&&r[d+1];y&&(f=f.replaceChild(0,y.type.create(y.attrs)));let v=r&&r[d]||m;if(!m.canReplace(p+1,m.childCount)||!v.type.validContent(f))return!1}let l=a.indexAfter(s),c=r&&r[0];return a.node(s).canReplaceWith(l,l,c?c.type:a.node(s+1).type)}function P7e(t,e,n=1,r){let a=t.doc.resolve(e),s=Bt.empty,o=Bt.empty;for(let l=a.depth,c=a.depth-n,u=n-1;l>c;l--,u--){s=Bt.from(a.node(l).copy(s));let d=r&&r[u];o=Bt.from(d?d.type.create(d.attrs,o):a.node(l).copy(o))}t.step(new Ra(e,e,new Zt(s.append(o),n,n),!0))}function tp(t,e){let n=t.resolve(e),r=n.index();return Vie(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function M7e(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let a=0;a0?(s=r.node(a+1),l++,o=r.node(a).maybeChild(l)):(s=r.node(a).maybeChild(l-1),o=r.node(a+1)),s&&!s.isTextblock&&Vie(s,o)&&r.node(a).canReplace(l,l+1))return e;if(a==0)break;e=n<0?r.before(a):r.after(a)}}function E7e(t,e,n){let r=null,{linebreakReplacement:a}=t.doc.type.schema,s=t.doc.resolve(e-n),o=s.node().type;if(a&&o.inlineContent){let d=o.whitespace=="pre",m=!!o.contentMatch.matchType(a);d&&!m?r=!1:!d&&m&&(r=!0)}let l=t.steps.length;if(r===!1){let d=t.doc.resolve(e+n);qie(t,d.node(),d.before(),l)}o.inlineContent&&I4(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 Ra(u,c.map(e+n,-1),Zt.empty,!0)),r===!0){let d=t.doc.resolve(u);$ie(t,d.node(),d.before(),t.steps.length)}return t}function j7e(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 a=r.depth-1;a>=0;a--){let s=r.index(a);if(r.node(a).canReplaceWith(s,s,n))return r.before(a+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let a=r.depth-1;a>=0;a--){let s=r.indexAfter(a);if(r.node(a).canReplaceWith(s,s,n))return r.after(a+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,a);else{let m=u.contentMatchAt(c).findWrapping(a.firstChild.type);d=m&&u.canReplaceWith(c,c,m[0])}if(d)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function wA(t,e,n=e,r=Zt.empty){if(e==n&&!r.size)return null;let a=t.resolve(e),s=t.resolve(n);return Wie(a,s,r)?new Ra(e,n,r):new D7e(a,s,r).fit()}function Wie(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class D7e{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=Bt.empty;for(let a=0;a<=e.depth;a++){let s=e.node(a);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(a))})}for(let a=e.depth;a>0;a--)this.placed=Bt.from(e.node(a).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,a=this.close(e<0?this.$to:r.doc.resolve(e));if(!a)return null;let s=this.placed,o=r.depth,l=a.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let c=new Zt(s,o,l);return e>-1?new La(r.pos,e,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Ra(r.pos,a.pos,c):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,a=this.unplaced.openEnd;r1&&(a=0),s.type.spec.isolating&&a<=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 a,s=null;r?(s=fD(this.unplaced.content,r-1).firstChild,a=s.content):a=this.unplaced.content;let o=a.firstChild;for(let l=this.depth;l>=0;l--){let{type:c,match:u}=this.frontier[l],d,m=null;if(n==1&&(o?u.matchType(o.type)||(m=u.fillBefore(Bt.from(o),!1)):s&&c.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:m};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,a=fD(e,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new Zt(e,n+1,Math.max(r,a.size+n>=e.size-r?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:r}=this.unplaced,a=fD(e,n);if(a.childCount<=1&&n>0){let s=e.size-n<=n+a.size;this.unplaced=new Zt(zv(e,n-1,1),n-1,s?n-1:r)}else this.unplaced=new Zt(zv(e,n,1),n,r)}placeNodes({sliceDepth:e,frontierDepth:n,parent:r,inject:a,wrap:s}){for(;this.depth>n;)this.closeFrontierNode();if(s)for(let v=0;v1||c==0||v.content.size)&&(m=b,d.push(Kie(v.mark(p.allowedMarks(v.marks)),u==1?c:0,u==l.childCount?f:-1)))}let y=u==l.childCount;y||(f=-1),this.placed=Uv(this.placed,n,Bt.from(d)),this.frontier[n].match=m,y&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let v=0,b=l;v1&&a==this.$to.end(--r);)++a;return a}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:a}=this.frontier[n],s=n=0;l--){let{match:c,type:u}=this.frontier[l],d=gD(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=Uv(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let a=e.node(r),s=a.type.contentMatch.fillBefore(a.content,!0,e.index(r));this.openFrontierNode(a.type,a.attrs,s)}return e}openFrontierNode(e,n=null,r){let a=this.frontier[this.depth];a.match=a.match.matchType(e),this.placed=Uv(this.placed,this.depth,Bt.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Bt.empty,!0);n.childCount&&(this.placed=Uv(this.placed,this.frontier.length,n))}}function zv(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(zv(t.firstChild.content,e-1,n)))}function Uv(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Uv(t.lastChild.content,e-1,n)))}function fD(t,e){for(let n=0;n1&&(r=r.replaceChild(0,Kie(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(Bt.empty,!0)))),t.copy(r)}function gD(t,e,n,r,a){let s=t.node(e),o=a?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&&!R7e(n,s.content,o)?l:null}function R7e(t,e,n){for(let r=n;r0;p--,f--){let y=a.node(p).type.spec;if(y.defining||y.definingAsContext||y.isolating)break;o.indexOf(p)>-1?l=p:a.before(p)==f&&o.splice(1,0,-p)}let c=o.indexOf(l),u=[],d=r.openStart;for(let p=r.content,f=0;;f++){let y=p.firstChild;if(u.push(y),f==r.openStart)break;p=y.content}for(let p=d-1;p>=0;p--){let f=u[p],y=F7e(f.type);if(y&&!f.sameMarkup(a.node(Math.abs(l)-1)))d=p;else if(y||!f.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let f=(p+d+1)%(r.openStart+1),y=u[f];if(y)for(let v=0;v=0&&(t.replace(e,n,r),!(t.steps.length>m));p--){let f=o[p];f<0||(e=a.before(f),n=s.after(f))}}function Yie(t,e,n,r,a){if(er){let s=a.contentMatchAt(0),o=s.fillBefore(t).append(t);t=o.append(s.matchFragment(o).fillBefore(Bt.empty,!0))}return t}function O7e(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let a=j7e(t.doc,e,r.type);a!=null&&(e=n=a)}t.replaceRange(e,n,new Zt(Bt.from(r),0,0))}function I7e(t,e,n){let r=t.doc.resolve(e),a=t.doc.resolve(n),s=Xie(r,a);for(let o=0;o0&&(c||r.node(l-1).canReplace(r.index(l-1),a.indexAfter(l-1))))return t.delete(r.before(l),a.after(l))}for(let o=1;o<=r.depth&&o<=a.depth;o++)if(e-r.start(o)==r.depth-o&&n>r.end(o)&&a.end(o)-n!=a.depth-o&&r.start(o-1)==a.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),a.index(o-1)))return t.delete(r.before(o),n);t.delete(e,n)}function Xie(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let a=r;a>=0;a--){let s=t.start(a);if(se.pos+(e.depth-a)||t.node(a).type.spec.isolating||e.node(a).type.spec.isolating)break;(s==e.start(a)||a==t.depth&&a==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&a&&e.start(a-1)==s-1)&&n.push(a)}return n}class ax extends ks{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 sa.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 a=n.type.create(r,null,n.marks);return sa.fromReplace(e,this.pos,this.pos+1,new Zt(Bt.from(a),0,n.isLeaf?0:1))}getMap(){return Xo.empty}invert(e){return new ax(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 ax(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 ax(n.pos,n.attr,n.value)}}ks.jsonID("attr",ax);class nw extends ks{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let a in e.attrs)n[a]=e.attrs[a];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return sa.ok(r)}getMap(){return Xo.empty}invert(e){return new nw(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 nw(n.attr,n.value)}}ks.jsonID("docAttr",nw);let jx=class extends Error{};jx=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};jx.prototype=Object.create(Error.prototype);jx.prototype.constructor=jx;jx.prototype.name="TransformError";class Qie{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new tw}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new jx(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,n=-1e9;for(let r=0;r{e=Math.min(e,l),n=Math.max(n,c)})}return e==1e9?null:{from:e,to:n}}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,r=Zt.empty){let a=wA(this.doc,e,n,r);return a&&this.step(a),this}replaceWith(e,n,r){return this.replace(e,n,new Zt(Bt.from(r),0,0))}delete(e,n){return this.replace(e,n,Zt.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return L7e(this,e,n,r),this}replaceRangeWith(e,n,r){return O7e(this,e,n,r),this}deleteRange(e,n){return I7e(this,e,n),this}lift(e,n){return S7e(this,e,n),this}join(e,n=1){return E7e(this,e,n),this}wrap(e,n){return k7e(this,e,n),this}setBlockType(e,n=e,r,a=null){return C7e(this,e,n,r,a),this}setNodeMarkup(e,n,r=null,a){return A7e(this,e,n,r,a),this}setNodeAttribute(e,n,r){return this.step(new ax(e,n,r)),this}setDocAttribute(e,n){return this.step(new nw(e,n)),this}addNodeMark(e,n){return this.step(new vh(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 Yr)n.isInSet(r.marks)&&this.step(new Yf(e,n));else{let a=r.marks,s,o=[];for(;s=n.isInSet(a);)o.push(new Yf(e,s)),a=s.removeFromSet(a);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,n=1,r){return P7e(this,e,n,r),this}addMark(e,n,r){return y7e(this,e,n,r),this}removeMark(e,n,r){return v7e(this,e,n,r),this}clearIncompatible(e,n,r){return I4(this,e,n,r),this}}const bD=Object.create(null);class Kn{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new z7e(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?Fb(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):Fb(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 nl(e.node(0))}static atStart(e){return Fb(e,e,0,0,1)||new nl(e)}static atEnd(e){return Fb(e,e,e.content.size,e.childCount,-1)||new nl(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=bD[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 bD)throw new RangeError("Duplicate use of selection JSON ID "+e);return bD[e]=n,n.prototype.jsonID=e,n}getBookmark(){return Dn.between(this.$anchor,this.$head).getBookmark()}}Kn.prototype.visible=!0;class z7e{constructor(e,n){this.$from=e,this.$to=n}}let ZW=!1;function JW(t){!ZW&&!t.parent.inlineContent&&(ZW=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class Dn extends Kn{constructor(e,n=e){JW(e),JW(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 Kn.near(r);let a=e.resolve(n.map(this.anchor));return new Dn(a.parent.inlineContent?a:r,r)}replace(e,n=Zt.empty){if(super.replace(e,n),n==Zt.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof Dn&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new SA(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 Dn(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let a=e.resolve(n);return new this(a,r==n?a:e.resolve(r))}static between(e,n,r){let a=e.pos-n.pos;if((!r||a)&&(r=a>=0?1:-1),!n.parent.inlineContent){let s=Kn.findFrom(n,r,!0)||Kn.findFrom(n,-r,!0);if(s)n=s.$head;else return Kn.near(n,r)}return e.parent.inlineContent||(a==0?e=n:(e=(Kn.findFrom(e,-r,!0)||Kn.findFrom(e,r,!0)).$anchor,e.pos0?0:1);a>0?o=0;o+=a){let l=e.child(o);if(l.isAtom){if(!s&&yn.isSelectable(l))return yn.create(t,n-(a<0?l.nodeSize:0))}else{let c=Fb(t,l,n+a,a<0?l.childCount:0,a,s);if(c)return c}n+=l.nodeSize*a}return null}function eK(t,e,n){let r=t.steps.length-1;if(r{o==null&&(o=d)}),t.setSelection(Kn.near(t.doc.resolve(o),n))}const tK=1,O1=2,nK=4;class B7e extends Qie{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 Yr.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)||Yr.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let a=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(a.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,a.text(e,s)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(Kn.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|=nK,this}get scrolledIntoView(){return(this.updated&nK)>0}}function rK(t,e){return!e||!t?t:t.bind(e)}class Bv{constructor(e,n,r){this.name=e,this.init=rK(n.init,r),this.apply=rK(n.apply,r)}}const H7e=[new Bv("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new Bv("selection",{init(t,e){return t.selection||Kn.atStart(e.doc)},apply(t){return t.selection}}),new Bv("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new Bv("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class xD{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=H7e.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 Bv(r.key,r.spec.state,r))})}}class Vb{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 a=e[r],s=a.spec.state;s&&s.toJSON&&(n[r]=s.toJSON.call(a,this[a.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 a=new xD(e.schema,e.plugins),s=new Vb(a);return a.fields.forEach(o=>{if(o.name=="doc")s.doc=kc.fromJSON(e.schema,n.doc);else if(o.name=="selection")s.selection=Kn.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 Zie(t,e,n){for(let r in t){let a=t[r];a instanceof Function?a=a.bind(e):r=="handleDOMEvents"&&(a=Zie(a,e,{})),n[r]=a}return n}class _i{constructor(e){this.spec=e,this.props={},e.props&&Zie(e.props,this,this.props),this.key=e.key?e.key.key:Jie("plugin")}getState(e){return e[this.key]}}const yD=Object.create(null);function Jie(t){return t in yD?t+"$"+ ++yD[t]:(yD[t]=0,t+"$")}class Na{constructor(e="key"){this.key=Jie(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const B4=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function eae(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const tae=(t,e,n)=>{let r=eae(t,n);if(!r)return!1;let a=H4(r);if(!a){let o=r.blockRange(),l=o&&cy(o);return l==null?!1:(e&&e(t.tr.lift(o,l).scrollIntoView()),!0)}let s=a.nodeBefore;if(uae(t,a,e,-1))return!0;if(r.parent.content.size==0&&(Dx(s,"end")||yn.isSelectable(s)))for(let o=r.depth;;o--){let l=wA(t.doc,r.before(o),r.after(o),Zt.empty);if(l&&l.slice.size1)break}return s.isAtom&&a.depth==r.depth-1?(e&&e(t.tr.delete(a.pos-s.nodeSize,a.pos).scrollIntoView()),!0):!1},$7e=(t,e,n)=>{let r=eae(t,n);if(!r)return!1;let a=H4(r);return a?nae(t,a,e):!1},q7e=(t,e,n)=>{let r=iae(t,n);if(!r)return!1;let a=$4(r);return a?nae(t,a,e):!1};function nae(t,e,n){let r=e.nodeBefore,a=r,s=e.pos-1;for(;!a.isTextblock;s--){if(a.type.spec.isolating)return!1;let d=a.lastChild;if(!d)return!1;a=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=wA(t.doc,s,c,Zt.empty);if(!u||u.from!=s||u instanceof Ra&&u.slice.size>=c-s)return!1;if(n){let d=t.tr.step(u);d.setSelection(Dn.create(d.doc,s)),n(d.scrollIntoView())}return!0}function Dx(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 rae=(t,e,n)=>{let{$head:r,empty:a}=t.selection,s=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;s=H4(r)}let o=s&&s.nodeBefore;return!o||!yn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(yn.create(t.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function H4(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 iae(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset{let r=iae(t,n);if(!r)return!1;let a=$4(r);if(!a)return!1;let s=a.nodeAfter;if(uae(t,a,e,1))return!0;if(r.parent.content.size==0&&(Dx(s,"start")||yn.isSelectable(s))){let o=wA(t.doc,r.before(),r.after(),Zt.empty);if(o&&o.slice.size{let{$head:r,empty:a}=t.selection,s=r;if(!a)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 yn,a;if(r){if(n.node.isTextblock||!tp(t.doc,n.from))return!1;a=n.from}else if(a=vA(t.doc,n.from,-1),a==null)return!1;if(e){let s=t.tr.join(a);r&&s.setSelection(yn.create(s.doc,a-t.doc.resolve(a).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},G7e=(t,e)=>{let n=t.selection,r;if(n instanceof yn){if(n.node.isTextblock||!tp(t.doc,n.to))return!1;r=n.to}else if(r=vA(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},W7e=(t,e)=>{let{$from:n,$to:r}=t.selection,a=n.blockRange(r),s=a&&cy(a);return s==null?!1:(e&&e(t.tr.lift(a,s).scrollIntoView()),!0)},oae=(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 q4(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 a=n.node(-1),s=n.indexAfter(-1),o=q4(a.contentMatchAt(s));if(!o||!a.canReplaceWith(s,s,o))return!1;if(e){let l=n.after(),c=t.tr.replaceWith(l,l,o.createAndFill());c.setSelection(Kn.near(c.doc.resolve(l),1)),e(c.scrollIntoView())}return!0},lae=(t,e)=>{let n=t.selection,{$from:r,$to:a}=n;if(n instanceof nl||r.parent.inlineContent||a.parent.inlineContent)return!1;let s=q4(a.parent.contentMatchAt(a.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&a.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(Od(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),a=r&&cy(r);return a==null?!1:(e&&e(t.tr.lift(r,a).scrollIntoView()),!0)};function Y7e(t){return(e,n)=>{let{$from:r,$to:a}=e.selection;if(e.selection instanceof yn&&e.selection.node.isBlock)return!r.parentOffset||!Od(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 f=r.depth;;f--)if(r.node(f).isBlock){c=r.end(f)==r.pos+(r.depth-f),u=r.start(f)==r.pos-(r.depth-f),l=q4(r.node(f-1).contentMatchAt(r.indexAfter(f-1))),s.unshift(c&&l?{type:l}:null),o=f;break}else{if(f==1)return!1;s.unshift(null)}let d=e.tr;(e.selection instanceof Dn||e.selection instanceof nl)&&d.deleteSelection();let m=d.mapping.map(r.pos),p=Od(d.doc,m,s.length,s);if(p||(s[0]=l?{type:l}:null,p=Od(d.doc,m,s.length,s)),!p)return!1;if(d.split(m,s.length,s),!c&&u&&r.node(o).type!=l){let f=d.mapping.map(r.before(o)),y=d.doc.resolve(f);l&&r.node(o-1).canReplaceWith(y.index(),y.index()+1,l)&&d.setNodeMarkup(d.mapping.map(r.before(o)),l)}return n&&n(d.scrollIntoView()),!0}}const X7e=Y7e(),Q7e=(t,e)=>{let{$from:n,to:r}=t.selection,a,s=n.sharedDepth(r);return s==0?!1:(a=n.before(s),e&&e(t.tr.setSelection(yn.create(t.doc,a))),!0)};function Z7e(t,e,n){let r=e.nodeBefore,a=e.nodeAfter,s=e.index();return!r||!a||!r.type.compatibleContent(a.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)||!(a.isTextblock||tp(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function uae(t,e,n,r){let a=e.nodeBefore,s=e.nodeAfter,o,l,c=a.type.spec.isolating||s.type.spec.isolating;if(!c&&Z7e(t,e,n))return!0;let u=!c&&e.parent.canReplace(e.index(),e.index()+1);if(u&&(o=(l=a.contentMatchAt(a.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(n){let f=e.pos+s.nodeSize,y=Bt.empty;for(let g=o.length-1;g>=0;g--)y=Bt.from(o[g].create(null,y));y=Bt.from(a.copy(y));let v=t.tr.step(new La(e.pos-1,f,e.pos,f,new Zt(y,1,0),o.length,!0)),b=v.doc.resolve(f+2*o.length);b.nodeAfter&&b.nodeAfter.type==a.type&&tp(v.doc,b.pos)&&v.join(b.pos),n(v.scrollIntoView())}return!0}let d=s.type.spec.isolating||r>0&&c?null:Kn.findFrom(e,1),m=d&&d.$from.blockRange(d.$to),p=m&&cy(m);if(p!=null&&p>=e.depth)return n&&n(t.tr.lift(m,p).scrollIntoView()),!0;if(u&&Dx(s,"start",!0)&&Dx(a,"end")){let f=a,y=[];for(;y.push(f),!f.isTextblock;)f=f.lastChild;let v=s,b=1;for(;!v.isTextblock;v=v.firstChild)b++;if(f.canReplace(f.childCount,f.childCount,v.content)){if(n){let g=Bt.empty;for(let N=y.length-1;N>=0;N--)g=Bt.from(y[N].copy(g));let _=t.tr.step(new La(e.pos-y.length,e.pos+s.nodeSize,e.pos+b,e.pos+s.nodeSize-b,new Zt(g,y.length,0),0,!0));n(_.scrollIntoView())}return!0}}return!1}function dae(t){return function(e,n){let r=e.selection,a=t<0?r.$from:r.$to,s=a.depth;for(;a.node(s).isInline;){if(!s)return!1;s--}return a.node(s).isTextblock?(n&&n(e.tr.setSelection(Dn.create(e.doc,t<0?a.start(s):a.end(s)))),!0):!1}}const J7e=dae(-1),eGe=dae(1);function tGe(t,e=null){return function(n,r){let{$from:a,$to:s}=n.selection,o=a.blockRange(s),l=o&&z4(o,t,e);return l?(r&&r(n.tr.wrap(o,l).scrollIntoView()),!0):!1}}function iK(t,e=null){return function(n,r){let a=!1;for(let s=0;s{if(a)return!1;if(!(!c.isTextblock||c.hasMarkup(t,e)))if(c.type==t)a=!0;else{let d=n.doc.resolve(u),m=d.index();a=d.parent.canReplaceWith(m,m+1,t)}})}if(!a)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 oC(c,c,e.depth),e.endIndex=0;d--)s=Bt.from(n[d].type.create(n[d].attrs,s));t.step(new La(e.start-(r?2:0),e.end,e.start,e.end,new Zt(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?sGe(e,n,t,s):oGe(e,n,s):!0:!1}}function sGe(t,e,n,r){let a=t.tr,s=r.end,o=r.$to.end(r.depth);sv;y--)f-=a.child(y).nodeSize,r.delete(f-1,f+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==a.childCount,u=s.node(-1),d=s.index(-1);if(!u.canReplace(d+(l?0:1),d+1,o.content.append(c?Bt.empty:Bt.from(a))))return!1;let m=s.pos,p=m+o.nodeSize;return r.step(new La(m-(l?1:0),p+(c?1:0),m+1,p-1,new Zt((l?Bt.empty:Bt.from(a.copy(Bt.empty))).append(c?Bt.empty:Bt.from(a.copy(Bt.empty))),l?0:1,c?0:1),l?0:1)),e(r.scrollIntoView()),!0}function lGe(t){return function(e,n){let{$from:r,$to:a}=e.selection,s=r.blockRange(a,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=Bt.from(u?t.create():null),m=new Zt(Bt.from(t.create(null,Bt.from(l.type.create(null,d)))),u?3:1,0),p=s.start,f=s.end;n(e.tr.step(new La(p-(u?3:1),f,p,f,m,1,!0)).scrollIntoView())}return!0}}const rs=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},Rx=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let GF=null;const bd=function(t,e,n){let r=GF||(GF=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},cGe=function(){GF=null},Xf=function(t,e,n,r){return n&&(aK(t,e,n,r,-1)||aK(t,e,n,r,1))},uGe=/^(img|br|input|textarea|hr)$/i;function aK(t,e,n,r,a){for(var s;;){if(t==n&&e==r)return!0;if(e==(a<0?0:Ol(t))){let o=t.parentNode;if(!o||o.nodeType!=1||Qw(t)||uGe.test(t.nodeName)||t.contentEditable=="false")return!1;e=rs(t)+(a<0?0:1),t=o}else if(t.nodeType==1){let o=t.childNodes[e+(a<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=a;else return!1;else t=o,e=a<0?Ol(t):0}else return!1}}function Ol(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function dGe(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=Ol(t)}else if(t.parentNode&&!Qw(t))e=rs(t),t=t.parentNode;else return null}}function mGe(t,e){for(;;){if(t.nodeType==3&&e2),El=Fx||(Nu?/Mac/.test(Nu.platform):!1),pae=Nu?/Win/.test(Nu.platform):!1,Pd=/Android \d/.test(np),Zw=!!sK&&"webkitFontSmoothing"in sK.documentElement.style,gGe=Zw?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function bGe(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 ud(t,e){return typeof t=="number"?t:t[e]}function xGe(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 oK(t,e,n){let r=t.someProp("scrollThreshold")||0,a=t.someProp("scrollMargin")||5,s=t.dom.ownerDocument;for(let o=n||t.dom;o;){if(o.nodeType!=1){o=Rx(o);continue}let l=o,c=l==s.body,u=c?bGe(s):xGe(l),d=0,m=0;if(e.topu.bottom-ud(r,"bottom")&&(m=e.bottom-e.top>u.bottom-u.top?e.top+ud(a,"top")-u.top:e.bottom-u.bottom+ud(a,"bottom")),e.leftu.right-ud(r,"right")&&(d=e.right-u.right+ud(a,"right")),d||m)if(c)s.defaultView.scrollBy(d,m);else{let f=l.scrollLeft,y=l.scrollTop;m&&(l.scrollTop+=m),d&&(l.scrollLeft+=d);let v=l.scrollLeft-f,b=l.scrollTop-y;e={left:e.left-v,top:e.top-b,right:e.right-v,bottom:e.bottom-b}}let p=c?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(p))break;o=p=="absolute"?o.offsetParent:Rx(o)}}function yGe(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,a;for(let s=(e.left+e.right)/2,o=n+1;o=n-20){r=l,a=c.top;break}}return{refDOM:r,refTop:a,stack:fae(t.dom)}}function fae(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=Rx(r));return e}function vGe({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;gae(n,r==0?0:r-e)}function gae(t,e){for(let n=0;n=l){o=Math.max(y.bottom,o),l=Math.min(y.top,l);let v=y.left>e.left?y.left-e.left:y.right=(y.left+y.right)/2?1:0));continue}}else y.top>e.top&&!c&&y.left<=e.left&&y.right>=e.left&&(c=d,u={left:Math.max(y.left,Math.min(y.right,e.left)),top:y.top});!n&&(e.left>=y.right&&e.top>=y.top||e.left>=y.left&&e.top>=y.bottom)&&(s=m+1)}}return!n&&c&&(n=c,a=u,r=0),n&&n.nodeType==3?SGe(n,a):!n||r&&n.nodeType==1?{node:t,offset:s}:bae(n,a)}function SGe(t,e){let n=t.nodeValue.length,r=document.createRange(),a;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),a||{node:t,offset:0}}function G4(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function _Ge(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,a,s)}function kGe(t,e,n,r){let a=-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?a=l.posBefore:(!o&&c.right-1?a:t.docView.posFromDOM(e,n,-1)}function xae(t,e,n){let r=t.childNodes.length;if(r&&n.tope.top&&a++}let u;Zw&&a&&r.nodeType==1&&(u=r.childNodes[a-1]).nodeType==1&&u.contentEditable=="false"&&u.getBoundingClientRect().top>=e.top&&a--,r==t.dom&&a==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=t.state.doc.content.size:(a==0||r.nodeType!=1||r.childNodes[a-1].nodeName!="BR")&&(l=kGe(t,r,a,e))}l==null&&(l=NGe(t,o,e));let c=t.docView.nearestDesc(o,!0);return{pos:l,inside:c?c.posAtStart-c.border:-1}}function lK(t){return t.top=0&&a==r.nodeValue.length?(c--,d=1):n<0?c--:u++,Av(Km(bd(r,c,u),d),d<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&a&&(n<0||a==Ol(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return vD(c.getBoundingClientRect(),!1)}if(s==null&&a=0)}if(s==null&&a&&(n<0||a==Ol(r))){let c=r.childNodes[a-1],u=c.nodeType==3?bd(c,Ol(c)-(o?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(u)return Av(Km(u,1),!1)}if(s==null&&a=0)}function Av(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 vD(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 vae(t,e,n){let r=t.state,a=t.root.activeElement;r!=e&&t.updateState(e),a!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),a!=t.dom&&a&&a.focus()}}function AGe(t,e,n){let r=e.selection,a=n=="up"?r.$from:r.$to;return vae(t,e,()=>{let{node:s}=t.docView.domFromPos(a.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=yae(t,a.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=bd(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 PGe=/[\u0590-\u08ac]/;function MGe(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let a=r.parentOffset,s=!a,o=a==r.parent.content.size,l=t.domSelection();return l?!PGe.test(r.parent.textContent)||!l.modify?n=="left"||n=="backward"?s:o:vae(t,e,()=>{let{focusNode:c,focusOffset:u,anchorNode:d,anchorOffset:m}=t.domSelectionRange(),p=l.caretBidiLevel;l.modify("move",n,"character");let f=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:y,focusOffset:v}=t.domSelectionRange(),b=y&&!f.contains(y.nodeType==1?y:y.parentNode)||c==y&&u==v;try{l.collapse(d,m),c&&(c!=d||u!=m)&&l.extend&&l.extend(c,u)}catch{}return p!=null&&(l.caretBidiLevel=p),b}):r.pos==r.start()||r.pos==r.end()}let cK=null,uK=null,dK=!1;function EGe(t,e,n){return cK==e&&uK==n?dK:(cK=e,uK=n,dK=n=="up"||n=="down"?AGe(t,e,n):MGe(t,e,n))}const $l=0,mK=1,lf=2,ku=3;class Jw{constructor(e,n,r,a){this.parent=e,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=$l,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;nrs(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))a=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let s=e;;s=s.parentNode){if(s==this.dom){a=!1;break}if(s.previousSibling)break}if(a==null&&n==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){a=!0;break}if(s.nextSibling)break}}return a??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,a=e;a;a=a.parentNode){let s=this.getDesc(a),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 a=e;a;a=a.parentNode){let s=this.getDesc(a);if(s)return s.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;ne||o instanceof Sae){a=e-s;break}s=l}if(a)return this.children[r].domFromPos(a-this.children[r].border,n);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof wae&&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?rs(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 m=l;m>0;m--){let p=this.children[m-1];if(p.size&&p.dom.parentNode==this.contentDOM&&!p.emptyChildAt(1)){a=rs(p.dom)+1;break}e-=p.size}a==-1&&(a=0)}if(a>-1&&(u>n||l==this.children.length-1)){n=u;for(let d=l+1;dy&&on){let y=l;l=c,c=y}let f=document.createRange();f.setEnd(c.node,c.offset),f.setStart(l.node,l.offset),u.removeAllRanges(),u.addRange(f)}}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,a=0;a=r:er){let l=r+s.border,c=o-s.border;if(e>=l&&n<=c){this.dirty=e==r||n==o?lf:mK,e==l&&n==c&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=ku:s.markDirty(e-l,n-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?lf:ku}r=o}this.dirty=lf}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?lf:mK;n.dirty{if(!s)return a;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==$l&&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 jGe extends Jw{constructor(e,n,r,a){super(e,[],n,null),this.textDOM=r,this.text=a}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Qf extends Jw{constructor(e,n,r,a,s){super(e,[],r,a),this.mark=n,this.spec=s}static create(e,n,r,a){let s=a.nodeViews[n.type.name],o=s&&s(n,a,r);return(!o||!o.dom)&&(o=og.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new Qf(e,n,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&ku||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=ku&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=$l){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=QF(s,0,e,r));for(let l=0;l{if(!c)return o;if(c.parent)return c.parent.posBeforeChild(c)},r,a),d=u&&u.dom,m=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:m}=og.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!m&&!n.isText&&d.nodeName!="BR"&&(d.hasAttribute("contenteditable")||(d.contentEditable="false"),n.type.spec.draggable&&(d.draggable=!0));let p=d;return d=kae(d,r,n),u?c=new DGe(e,n,r,a,d,m||null,p,u,s,o+1):n.isText?new NA(e,n,r,a,d,p,s):new Oh(e,n,r,a,d,m||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=()=>Bt.empty)}return e}matchesNode(e,n,r){return this.dirty==$l&&e.eq(this.node)&&cC(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,a=n,s=e.composing?this.localCompositionInfo(e,n):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,c=new FGe(this,o&&o.node,e);IGe(this.node,this.innerDeco,(u,d,m)=>{u.spec.marks?c.syncToMarks(u.spec.marks,r,e,d):u.type.side>=0&&!m&&c.syncToMarks(d==this.node.childCount?Yr.none:this.node.child(d).marks,r,e,d),c.placeWidget(u,e,a)},(u,d,m,p)=>{c.syncToMarks(u.marks,r,e,p);let f;c.findNodeMatch(u,d,m,p)||l&&e.state.selection.from>a&&e.state.selection.to-1&&c.updateNodeAt(u,d,m,f,e)||c.updateNextNode(u,d,m,e,p,a)||c.addNode(u,d,m,e,a),a+=u.nodeSize}),c.syncToMarks([],r,e,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==lf)&&(o&&this.protectLocalComposition(e,o),_ae(this.contentDOM,this.children,e),Fx&&zGe(this.dom))}localCompositionInfo(e,n){let{from:r,to:a}=e.state.selection;if(!(e.state.selection instanceof Dn)||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=UGe(this.node.content,o,r-n,a-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:a}){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 jGe(this,s,n,a);e.input.compositionNodes.push(o),this.children=QF(this.children,r,r+a.length,e,o)}update(e,n,r,a){return this.dirty==ku||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,a),!0)}updateInner(e,n,r,a){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(a,this.posAtStart),this.dirty=$l}updateOuterDeco(e){if(cC(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Nae(this.dom,this.nodeDOM,XF(this.outerDeco,this.node,n),XF(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 hK(t,e,n,r,a){kae(r,e,t);let s=new Oh(void 0,t,e,n,r,r,r,a,0);return s.contentDOM&&s.updateChildren(a,0),s}class NA extends Oh{constructor(e,n,r,a,s,o,l){super(e,n,r,a,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,a){return this.dirty==ku||this.dirty!=$l&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=$l||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,a.trackWrites==this.nodeDOM&&(a.trackWrites=null)),this.node=e,this.dirty=$l,!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 a=this.node.cut(e,n),s=document.createTextNode(a.text);return new NA(this.parent,a,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=ku)}get domAtom(){return!1}isText(e){return this.node.text==e}}class Sae extends Jw{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==$l&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class DGe extends Oh{constructor(e,n,r,a,s,o,l,c,u,d){super(e,n,r,a,s,o,l,u,d),this.spec=c}update(e,n,r,a){if(this.dirty==ku)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,a),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,a)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,a){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,a)}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 _ae(t,e,n){let r=t.firstChild,a=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)c>this.index&&(this.changed=!0,this.destroyBetween(this.index,c)),this.top=this.top.children[this.index];else{let d=Qf.create(this.top,e[o],n,r);this.top.children.splice(this.index,0,d),this.top=d,this.changed=!0}this.index=0,o++}}findNodeMatch(e,n,r,a){let s=-1,o;if(a>=this.preMatch.index&&(o=this.preMatch.matches[a-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 Qf)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(a-1))break;--a,s.set(l,a),o.push(l)}}return{index:a,matched:s,matches:o.reverse()}}function OGe(t,e){return t.type.side-e.type.side}function IGe(t,e,n,r){let a=e.locals(t),s=0;if(a.length==0){for(let u=0;us;)l.push(a[o++]);let y=s+p.nodeSize;if(p.isText){let b=y;o!b.inline):l.slice();r(p,v,e.forChild(s,p),f),s=y}}function zGe(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 UGe(t,e,n,r){for(let a=0,s=0;a=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 QF(t,e,n,r,a){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 W4(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let a=t.docView.nearestDesc(n.focusNode),s=a&&a.size==0,o=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(o<0)return null;let l=r.resolve(o),c,u;if(_A(n)){for(c=o;a&&!a.node;)a=a.parent;let m=a.node;if(a&&m.isAtom&&yn.isSelectable(m)&&a.parent&&!(m.isInline&&hGe(n.focusNode,n.focusOffset,a.dom))){let p=a.posBefore;u=new yn(o==p?l:r.resolve(p))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let m=o,p=o;for(let f=0;f{(n.anchorNode!=r||n.anchorOffset!=a)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Cae(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function HGe(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,rs(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&No&&Lh<=11&&(n.disabled=!0,n.disabled=!1)}function Tae(t,e){if(e instanceof yn){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(xK(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else xK(t)}function xK(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function K4(t,e,n,r){return t.someProp("createSelectionBetween",a=>a(t,e,n))||Dn.between(e,n,r)}function yK(t){return t.editable&&!t.hasFocus()?!1:Aae(t)}function Aae(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 $Ge(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Xf(e.node,e.offset,n.anchorNode,n.anchorOffset)}function ZF(t,e){let{$anchor:n,$head:r}=t.selection,a=e>0?n.max(r):n.min(r),s=a.parent.inlineContent?a.depth?t.doc.resolve(e>0?a.after():a.before()):null:a;return s&&Kn.findFrom(s,e)}function eh(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function vK(t,e,n){let r=t.state.selection;if(r instanceof Dn)if(n.indexOf("s")>-1){let{$head:a}=r,s=a.textOffset?null:e<0?a.nodeBefore:a.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=t.state.doc.resolve(a.pos+s.nodeSize*(e<0?-1:1));return eh(t,new Dn(r.$anchor,o))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let a=ZF(t.state,e);return a&&a instanceof yn?eh(t,a):!1}else if(!(El&&n.indexOf("m")>-1)){let a=r.$head,s=a.textOffset?null:e<0?a.nodeBefore:a.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?a.pos-s.nodeSize:a.pos;return s.isAtom||(o=t.docView.descAt(l))&&!o.contentDOM?yn.isSelectable(s)?eh(t,new yn(e<0?t.state.doc.resolve(a.pos-s.nodeSize):a)):Zw?eh(t,new Dn(t.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof yn&&r.node.isInline)return eh(t,new Dn(e>0?r.$to:r.$from));{let a=ZF(t.state,e);return a?eh(t,a):!1}}}function uC(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function s0(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function Cb(t,e){return e<0?qGe(t):VGe(t)}function qGe(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let a,s,o=!1;for(Hl&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let l=n.childNodes[r-1];if(s0(l,-1))a=n,s=--r;else if(l.nodeType==3)n=l,r=n.nodeValue.length;else break}}else{if(Pae(n))break;{let l=n.previousSibling;for(;l&&s0(l,-1);)a=n.parentNode,s=rs(l),l=l.previousSibling;if(l)n=l,r=uC(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}o?JF(t,n,r):a&&JF(t,a,s)}function VGe(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let a=uC(n),s,o;for(;;)if(r{t.state==a&&Id(t)},50)}function wK(t,e){let n=t.state.doc.resolve(e);if(!(ss||pae)&&n.parent.inlineContent){let a=t.coordsAtPos(e);if(e>n.start()){let s=t.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>a.top&&o1)return s.lefta.top&&o1)return s.left>a.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function SK(t,e,n){let r=t.state.selection;if(r instanceof Dn&&!r.empty||n.indexOf("s")>-1||El&&n.indexOf("m")>-1)return!1;let{$from:a,$to:s}=r;if(!a.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let o=ZF(t.state,e);if(o&&o instanceof yn)return eh(t,o)}if(!a.parent.inlineContent){let o=e<0?a:s,l=r instanceof nl?Kn.near(o,e):Kn.findFrom(o,e);return l?eh(t,l):!1}return!1}function _K(t,e){if(!(t.state.selection instanceof Dn))return!0;let{$head:n,$anchor:r,empty:a}=t.state.selection;if(!n.sameParent(r))return!0;if(!a)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 NK(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function KGe(t){if(!Ss||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;NK(t,r,"true"),setTimeout(()=>NK(t,r,"false"),20)}return!1}function YGe(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function XGe(t,e){let n=e.keyCode,r=YGe(e);if(n==8||El&&n==72&&r=="c")return _K(t,-1)||Cb(t,-1);if(n==46&&!e.shiftKey||El&&n==68&&r=="c")return _K(t,1)||Cb(t,1);if(n==13||n==27)return!0;if(n==37||El&&n==66&&r=="c"){let a=n==37?wK(t,t.state.selection.from)=="ltr"?-1:1:-1;return vK(t,a,r)||Cb(t,a)}else if(n==39||El&&n==70&&r=="c"){let a=n==39?wK(t,t.state.selection.from)=="ltr"?1:-1:1;return vK(t,a,r)||Cb(t,a)}else{if(n==38||El&&n==80&&r=="c")return SK(t,-1,r)||Cb(t,-1);if(n==40||El&&n==78&&r=="c")return KGe(t)||SK(t,1,r)||Cb(t,1);if(r==(El?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function Y4(t,e){t.someProp("transformCopied",f=>{e=f(e,t)});let n=[],{content:r,openStart:a,openEnd:s}=e;for(;a>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){a--,s--;let f=r.firstChild;n.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let o=t.someProp("clipboardSerializer")||og.fromSchema(t.state.schema),l=Fae(),c=l.createElement("div");c.appendChild(o.serializeFragment(r,{document:l}));let u=c.firstChild,d,m=0;for(;u&&u.nodeType==1&&(d=Rae[u.nodeName.toLowerCase()]);){for(let f=d.length-1;f>=0;f--){let y=l.createElement(d[f]);for(;c.firstChild;)y.appendChild(c.firstChild);c.appendChild(y),m++}u=c.firstChild}u&&u.nodeType==1&&u.setAttribute("data-pm-slice",`${a} ${s}${m?` -${m}`:""} ${JSON.stringify(n)}`);let p=t.someProp("clipboardTextSerializer",f=>f(e,t))||e.content.textBetween(0,e.content.size,` `);return{dom:c,text:p,slice:e}}function Mae(t,e,n,r,a){let s=a.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 Zt(Bt.from(t.state.schema.text(e.replace(/\r\n?/g,` -`))),0,0),t.someProp("transformPasted",p=>{l=p(l,t,!0)}),l;let m=t.someProp("clipboardTextParser",p=>p(e,a,r,t));if(m)l=m;else{let p=a.marks(),{schema:f}=t.state,y=og.fromSchema(f);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(v=>{let b=o.appendChild(document.createElement("p"));v&&b.appendChild(y.serializeNode(f.text(v,p)))})}}else t.someProp("transformPastedHTML",m=>{n=m(n,t)}),o=e9e(n),Zw&&t9e(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 m=+d[3];m>0;m--){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")||r0.fromSchema(t.state.schema)).parseSlice(o,{preserveWhitespace:!!(c||d),context:a,ruleFromNode(p){return p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!QGe.test(p.parentNode.nodeName)?{ignore:!0}:null}})),d)l=n9e(kK(l,+d[1],+d[2]),d[4]);else if(l=Zt.maxOpen(ZGe(l.content,a),!0),l.openStart||l.openEnd){let m=0,p=0;for(let f=l.content.firstChild;m{l=m(l,t,c)}),l}const QGe=/^(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 ZGe(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let a=e.node(n).contentMatchAt(e.index(n)),s,o=[];if(t.forEach(l=>{if(!o)return;let c=a.findWrapping(l.type),u;if(!c)return o=null;if(u=o.length&&s.length&&jae(c,s,l,o[o.length-1],0))o[o.length-1]=u;else{o.length&&(o[o.length-1]=Dae(o[o.length-1],s.length));let d=Eae(l,c);o.push(d),a=a.matchType(d.type),s=c}}),o)return Bt.from(o)}return t}function Eae(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,Bt.from(t));return t}function jae(t,e,n,r,a){if(a1&&(s=0),a=n&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=a).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(Bt.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,o.copy(l))}function kK(t,e,n){return en})),SD.createHTML(t)):t}function e9e(t){let e=/^(\s*]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=Fae().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(t),a;if((a=r&&Rae[r[1].toLowerCase()])&&(t=a.map(s=>"<"+s+">").join("")+t+a.map(s=>"").reverse().join("")),n.innerHTML=JGe(t),a)for(let s=0;s=0;l-=2){let c=n.nodes[r[l]];if(!c||c.hasRequiredAttrs())break;a=Bt.from(c.create(r[l+1],a)),s++,o++}return new Zt(a,s,o)}const Js={},eo={},r9e={touchstart:!0,touchmove:!0};class i9e{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.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function a9e(t){for(let e in Js){let n=Js[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{o9e(t,r)&&!XI(t,r)&&(t.editable||!(r.type in eo))&&n(t,r)},r9e[e]?{passive:!0}:void 0)}Ss&&t.dom.addEventListener("input",()=>null),tL(t)}function wh(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function s9e(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 tL(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>XI(t,r))})}function XI(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function o9e(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 l9e(t,e){!XI(t,e)&&Js[e.type]&&(t.editable||!(e.type in eo))&&Js[e.type](t,e)}eo.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!Oae(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Pd&&ss&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),Fx&&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",a=>a(t,Xp(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||XGe(t,n)?n.preventDefault():wh(t,"key")};eo.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};eo.keypress=(t,e)=>{let n=e;if(Oae(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||El&&n.metaKey)return;if(t.someProp("handleKeyPress",a=>a(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof Dn)||!r.$from.sameParent(r.$to)){let a=String.fromCharCode(n.charCode),s=()=>t.state.tr.insertText(a).scrollIntoView();!/[\r\n]/.test(a)&&!t.someProp("handleTextInput",o=>o(t,r.$from.pos,r.$to.pos,a,s))&&t.dispatch(s()),n.preventDefault()}};function kA(t){return{left:t.clientX,top:t.clientY}}function c9e(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function QI(t,e,n,r,a){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),a,!0):l(t,n,s.node(o),s.before(o),a,!1)))return!0;return!1}function sx(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 u9e(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&yn.isSelectable(r)?(sx(t,new yn(n)),!0):!1}function d9e(t,e){if(e==-1)return!1;let n=t.state.selection,r,a;n instanceof yn&&(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(yn.isSelectable(l)){r&&n.$from.depth>0&&o>=n.$from.depth&&s.before(n.$from.depth+1)==n.$from.pos?a=s.before(n.$from.depth):a=s.before(o);break}}return a!=null?(sx(t,yn.create(t.state.doc,a)),!0):!1}function m9e(t,e,n,r,a){return QI(t,"handleClickOn",e,n,r)||t.someProp("handleClick",s=>s(t,e,r))||(a?d9e(t,n):u9e(t,n))}function h9e(t,e,n,r){return QI(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",a=>a(t,e,r))}function p9e(t,e,n,r){return QI(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",a=>a(t,e,r))||f9e(t,n,r)}function f9e(t,e,n){if(n.button!=0)return!1;let r=t.state.doc;if(e==-1)return r.inlineContent?(sx(t,Dn.create(r,0,r.content.size)),!0):!1;let a=r.resolve(e);for(let s=a.depth+1;s>0;s--){let o=s>a.depth?a.nodeAfter:a.node(s),l=a.before(s);if(o.inlineContent)sx(t,Dn.create(r,l+1,l+1+o.content.size));else if(yn.isSelectable(o))sx(t,yn.create(r,l));else continue;return!0}}function ZI(t){return dC(t)}const Lae=El?"metaKey":"ctrlKey";Js.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=ZI(t),a=Date.now(),s="singleClick";a-t.input.lastClick.time<500&&c9e(n,t.input.lastClick)&&!n[Lae]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?s="doubleClick":t.input.lastClick.type=="doubleClick"&&(s="tripleClick")),t.input.lastClick={time:a,x:n.clientX,y:n.clientY,type:s,button:n.button};let o=t.posAtCoords(kA(n));o&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new g9e(t,o,n,!!r)):(s=="doubleClick"?h9e:p9e)(t,o.pos,o.inside,n)?n.preventDefault():wh(t,"pointer"))};class g9e{constructor(e,n,r,a){this.view=e,this.pos=n,this.event=r,this.flushed=a,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!r[Lae],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=a?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 yn&&u.from<=o&&u.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Hl&&!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)),wh(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(()=>Id(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(kA(e))),this.updateAllowDefault(e),this.allowDefault||!n?wh(this.view,"pointer"):m9e(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Ss&&this.mightDrag&&!this.mightDrag.node.isAtom||ss&&!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)?(sx(this.view,Kn.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):wh(this.view,"pointer")}move(e){this.updateAllowDefault(e),wh(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)}}Js.touchstart=t=>{t.input.lastTouch=Date.now(),ZI(t),wh(t,"pointer")};Js.touchmove=t=>{t.input.lastTouch=Date.now(),wh(t,"pointer")};Js.contextmenu=t=>ZI(t);function Oae(t,e){return t.composing?!0:Ss&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const b9e=Pd?5e3:-1;eo.compositionstart=eo.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof Dn&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||ss&&pae&&x9e(t)))t.markCursor=t.state.storedMarks||n.marks(),dC(t,!0),t.markCursor=null;else if(dC(t,!e.selection.empty),Hl&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let a=r.focusNode,s=r.focusOffset;a&&a.nodeType==1&&s!=0;){let o=s<0?a.lastChild:a.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=t.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else a=o,s=-1}}t.input.composing=!0}Iae(t,b9e)};function x9e(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||e.nodeType!=1||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}eo.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.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,Iae(t,20))};function Iae(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>dC(t),e))}function zae(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=v9e());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function y9e(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=dGe(e.focusNode,e.focusOffset),r=mGe(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let a=r.pmViewDesc,s=t.domObserver.lastChangedTextNode;if(n==s||r==s)return s;if(!a||!a.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 v9e(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function dC(t,e=!1){if(!(Pd&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),zae(t),e||t.docView&&t.docView.dirty){let n=WI(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 w9e(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(),a=document.createRange();a.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(a),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}const rw=No&&Lh<15||Fx&&gGe<604;Js.copy=eo.cut=(t,e)=>{let n=e,r=t.state.selection,a=n.type=="cut";if(r.empty)return;let s=rw?null:n.clipboardData,o=r.content(),{dom:l,text:c}=YI(t,o);s?(n.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",c)):w9e(t,l),a&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function S9e(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function _9e(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 a=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?iw(t,r.value,null,a,e):iw(t,r.textContent,r.innerHTML,a,e)},50)}function iw(t,e,n,r,a){let s=Mae(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",c=>c(t,a,s||Zt.empty)))return!0;if(!s)return!1;let o=S9e(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 Uae(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," "):""}eo.paste=(t,e)=>{let n=e;if(t.composing&&!Pd)return;let r=rw?null:n.clipboardData,a=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&iw(t,Uae(r),r.getData("text/html"),a,n)?n.preventDefault():_9e(t,n)};class Bae{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}}const N9e=El?"altKey":"ctrlKey";function Hae(t,e){let n=t.someProp("dragCopies",r=>!r(e));return n??!e[N9e]}Js.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let a=t.state.selection,s=a.empty?null:t.posAtCoords(kA(n)),o;if(!(s&&s.pos>=a.from&&s.pos<=(a instanceof yn?a.to-1:a.to))){if(r&&r.mightDrag)o=yn.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let m=t.docView.nearestDesc(n.target,!0);m&&m.node.type.spec.draggable&&m!=t.docView&&(o=yn.create(t.state.doc,m.posBefore))}}let l=(o||t.state.selection).content(),{dom:c,text:u,slice:d}=YI(t,l);(!n.dataTransfer.files.length||!ss||hae>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(rw?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",rw||n.dataTransfer.setData("text/plain",u),t.dragging=new Bae(d,Hae(t,n),o)};Js.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};eo.dragover=eo.dragenter=(t,e)=>e.preventDefault();eo.drop=(t,e)=>{try{k9e(t,e,t.dragging)}finally{t.dragging=null}};function k9e(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(kA(e));if(!r)return;let a=t.state.doc.resolve(r.pos),s=n&&n.slice;s?t.someProp("transformPasted",f=>{s=f(s,t,!1)}):s=Mae(t,Uae(e.dataTransfer),rw?null:e.dataTransfer.getData("text/html"),!1,a);let o=!!(n&&Hae(t,e));if(t.someProp("handleDrop",f=>f(t,e,s||Zt.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Gie(t.state.doc,a.pos,s):a.pos;l==null&&(l=a.pos);let c=t.state.tr;if(o){let{node:f}=n;f?f.replace(c):c.deleteSelection()}let u=c.mapping.map(l),d=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,m=c.doc;if(d?c.replaceRangeWith(u,u,s.content.firstChild):c.replaceRange(u,u,s),c.doc.eq(m))return;let p=c.doc.resolve(u);if(d&&yn.isSelectable(s.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(s.content.firstChild))c.setSelection(new yn(p));else{let f=c.mapping.map(l);c.mapping.maps[c.mapping.maps.length-1].forEach((y,v,b,g)=>f=g),c.setSelection(KI(t,p,c.doc.resolve(f)))}t.focus(),t.dispatch(c.setMeta("uiEvent","drop"))}Js.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())&&Id(t)},20))};Js.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)};Js.beforeinput=(t,e)=>{if(ss&&Pd&&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,Xp(8,"Backspace")))))return;let{$cursor:a}=t.state.selection;a&&a.pos>0&&t.dispatch(t.state.tr.delete(a.pos-1,a.pos).scrollIntoView())},50)}};for(let t in eo)Js[t]=eo[t];function aw(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 mC{constructor(e,n){this.toDOM=e,this.spec=n||Sf,this.side=this.spec.side||0}map(e,n,r,a){let{pos:s,deleted:o}=e.mapResult(n.from+a,this.side<0?-1:1);return o?null:new qs(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof mC&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&aw(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Ih{constructor(e,n){this.attrs=e,this.spec=n||Sf}map(e,n,r,a){let s=e.map(n.from+a,this.spec.inclusiveStart?-1:1)-r,o=e.map(n.to+a,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new qs(s,o,this)}valid(e,n){return n.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+a,l.to+a))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,n-l,r,a+l,s)}}map(e,n,r){return this==bs||e.maps.length==0?this:this.mapInner(e,n,0,0,r||Sf)}mapInner(e,n,r,a,s){let o;for(let l=0;l{let u=c+r,d;if(d=qae(n,l,u)){for(a||(a=this.children.slice());sl&&m.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 Ih){let u=Math.max(s,c.from)-s,d=Math.min(o,c.to)-s;ua.map(e,n,Sf));return oh.from(r)}forChild(e,n){if(n.isLeaf)return xi.empty;let r=[];for(let a=0;an instanceof xi)?e:e.reduce((n,r)=>n.concat(r instanceof xi?r:r.members),[]))}}forEachSet(e){for(let n=0;n{let b=v-y-(f-p);for(let g=0;g_+d-m)continue;let N=l[g]+d-m;f>=N?l[g+1]=p<=N?-2:-1:p>=d&&b&&(l[g]+=b,l[g+1]+=b)}m+=b}),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),f=p-a,{index:y,offset:v}=r.content.findIndex(m),b=r.maybeChild(y);if(b&&v==m&&v+b.nodeSize==f){let g=l[u+2].mapInner(n,b,d+1,t[u]+s+1,o);g!=bs?(l[u]=m,l[u+1]=f,l[u+2]=g):(l[u+1]=-2,c=!0)}else c=!0}if(c){let u=T9e(l,t,e,n,a,s,o),d=hC(u,r,0,o);e=d.local;for(let m=0;mn&&o.to{let u=qae(t,l,c+n);if(u){s=!0;let d=hC(u,l,n+c+1,r);d!=bs&&a.push(c,c+l.nodeSize,d)}});let o=$ae(s?Vae(t):t,-n).sort(_f);for(let l=0;l0;)e++;t.splice(e,0,n)}function _D(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=bs&&e.push(r)}),t.cursorWrapper&&e.push(xi.create(t.state.doc,[t.cursorWrapper.deco])),oh.from(e)}const A9e={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},P9e=No&&Lh<=11;class M9e{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 E9e{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new M9e,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let a=0;aa.type=="childList"&&a.removedNodes.length||a.type=="characterData"&&a.oldValue.length>a.target.nodeValue.length)?this.flushSoon():Ss&&e.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),P9e&&(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,A9e)),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(yK(this.view)){if(this.suppressingSelectionUpdates)return Id(this.view);if(No&&Lh<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Xf(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=Rx(s))n.add(s);for(let s=e.anchorNode;s;s=Rx(s))if(n.has(s)){r=s;break}let a=r&&this.view.docView.nearestDesc(r);if(a&&a.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(),a=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&yK(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,c=[];if(e.editable)for(let d=0;dd.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let d of c)if(d.nodeName=="BR"&&d.parentNode){let m=d.nextSibling;m&&m.nodeType==1&&m.contentEditable=="false"&&d.parentNode.removeChild(d)}}else if(Hl&&c.length){let d=c.filter(m=>m.nodeName=="BR");if(d.length==2){let[m,p]=d;m.parentNode&&m.parentNode.parentNode==p.parentNode?p.remove():m.remove()}else{let{focusNode:m}=this.currentSelection;for(let p of d){let f=p.parentNode;f&&f.nodeName=="LI"&&(!m||R9e(e,m)!=f)&&p.remove()}}}let u=null;s<0&&a&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||a)&&(s>-1&&(e.docView.markDirty(s,o),j9e(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,F9e(e,c)),this.handleDOMChange(s,o,l,c),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Id(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;da;b--){let g=r.childNodes[b-1],_=g.pmViewDesc;if(g.nodeName=="BR"&&!_){s=b;break}if(!_||_.size)break}let m=t.state.doc,p=t.someProp("domParser")||r0.fromSchema(t.state.schema),f=m.resolve(o),y=null,v=p.parse(r,{topNode:f.parent,topMatch:f.parent.contentMatchAt(f.index()),topOpen:!0,from:a,to:s,preserveWhitespace:f.parent.type.whitespace=="pre"?"full":!0,findPositions:u,ruleFromNode:O9e,context:f});if(u&&u[0].pos!=null){let b=u[0].pos,g=u[1]&&u[1].pos;g==null&&(g=b),y={anchor:b+o,head:g+o}}return{doc:v,sel:y,from:o,to:l}}function O9e(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Ss&&/^(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||Ss&&/^(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 I9e=/^(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 z9e(t,e,n,r,a){let s=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let T=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,D=WI(t,T);if(D&&!t.state.selection.eq(D)){if(ss&&Pd&&t.input.lastKeyCode===13&&Date.now()-100R(t,Xp(13,"Enter"))))return;let A=t.state.tr.setSelection(D);T=="pointer"?A.setMeta("pointer",!0):T=="key"&&A.scrollIntoView(),s&&A.setMeta("composition",s),t.dispatch(A)}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=L9e(t,e,n),d=t.state.doc,m=d.slice(u.from,u.to),p,f;t.input.lastKeyCode===8&&Date.now()-100Date.now()-225||Pd)&&a.some(T=>T.nodeType==1&&!I9e.test(T.nodeName))&&(!y||y.endA>=y.endB)&&t.someProp("handleKeyDown",T=>T(t,Xp(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!y)if(r&&c instanceof Dn&&!c.empty&&c.$head.sameParent(c.$anchor)&&!t.composing&&!(u.sel&&u.sel.anchor!=u.sel.head))y={start:c.from,endA:c.to,endB:c.to};else{if(u.sel){let T=EK(t,t.state.doc,u.sel);if(T&&!T.eq(t.state.selection)){let D=t.state.tr.setSelection(T);s&&D.setMeta("composition",s),t.dispatch(D)}}return}t.state.selection.fromt.state.selection.from&&y.start<=t.state.selection.from+2&&t.state.selection.from>=u.from?y.start=t.state.selection.from:y.endA=t.state.selection.to-2&&t.state.selection.to<=u.to&&(y.endB+=t.state.selection.to-y.endA,y.endA=t.state.selection.to)),No&&Lh<=11&&y.endB==y.start+1&&y.endA==y.start&&y.start>u.from&&u.doc.textBetween(y.start-u.from-1,y.start-u.from+1)=="  "&&(y.start--,y.endA--,y.endB--);let v=u.doc.resolveNoCache(y.start-u.from),b=u.doc.resolveNoCache(y.endB-u.from),g=d.resolve(y.start),_=v.sameParent(b)&&v.parent.inlineContent&&g.end()>=y.endA;if((Fx&&t.input.lastIOSEnter>Date.now()-225&&(!_||a.some(T=>T.nodeName=="DIV"||T.nodeName=="P"))||!_&&v.posT(t,Xp(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>y.start&&B9e(d,y.start,y.endA,v,b)&&t.someProp("handleKeyDown",T=>T(t,Xp(8,"Backspace")))){Pd&&ss&&t.domObserver.suppressSelectionUpdates();return}ss&&y.endB==y.start&&(t.input.lastChromeDelete=Date.now()),Pd&&!_&&v.start()!=b.start()&&b.parentOffset==0&&v.depth==b.depth&&u.sel&&u.sel.anchor==u.sel.head&&u.sel.head==y.endA&&(y.endB-=2,b=u.doc.resolveNoCache(y.endB-u.from),setTimeout(()=>{t.someProp("handleKeyDown",function(T){return T(t,Xp(13,"Enter"))})},20));let N=y.start,C=y.endA,k=T=>{let D=T||t.state.tr.replace(N,C,u.doc.slice(y.start-u.from,y.endB-u.from));if(u.sel){let A=EK(t,D.doc,u.sel);A&&!(ss&&t.composing&&A.empty&&(y.start!=y.endB||t.input.lastChromeDeleteId(t),20));let T=k(t.state.tr.delete(N,C)),D=d.resolve(y.start).marksAcross(d.resolve(y.endA));D&&T.ensureMarks(D),t.dispatch(T)}else if(y.endA==y.endB&&(P=U9e(v.parent.content.cut(v.parentOffset,b.parentOffset),g.parent.content.cut(g.parentOffset,y.endA-g.start())))){let T=k(t.state.tr);P.type=="add"?T.addMark(N,C,P.mark):T.removeMark(N,C,P.mark),t.dispatch(T)}else if(v.parent.child(v.index()).isText&&v.index()==b.index()-(b.textOffset?0:1)){let T=v.parent.textBetween(v.parentOffset,b.parentOffset),D=()=>k(t.state.tr.insertText(T,N,C));t.someProp("handleTextInput",A=>A(t,N,C,T,D))||t.dispatch(D())}else t.dispatch(k());else t.dispatch(k())}function EK(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:KI(t,e.resolve(n.anchor),e.resolve(n.head))}function U9e(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,a=n,s=r,o,l,c;for(let d=0;dd.mark(l.addToSet(d.marks));else if(a.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||ND(o,!0,!1)0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,a++,e=!1;if(n){let s=t.node(r).maybeChild(t.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,a++}return a}function H9e(t,e,n,r,a){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(a=="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 Gae{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 i9e,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(OK),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=FK(this),RK(this),this.nodeViews=LK(this),this.docView=hK(this.state.doc,DK(this),_D(this),this.dom,this),this.domObserver=new E9e(this,(r,a,s,o)=>z9e(this,r,a,s,o)),this.domObserver.start(),a9e(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&&tL(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(OK),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 a=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(zae(this),o=!0),this.state=e;let l=a.plugins!=e.plugins||this._props.plugins!=n.plugins;if(l||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let f=LK(this);q9e(f,this.nodeViews)&&(this.nodeViews=f,s=!0)}(l||n.handleDOMEvents!=this._props.handleDOMEvents)&&tL(this),this.editable=FK(this),RK(this);let c=_D(this),u=DK(this),d=a.plugins!=e.plugins&&!a.doc.eq(e.doc)?"reset":e.scrollToSelection>a.scrollToSelection?"to selection":"preserve",m=s||!this.docView.matchesNode(e.doc,u,c);(m||!e.selection.eq(a.selection))&&(o=!0);let p=d=="preserve"&&o&&this.dom.style.overflowAnchor==null&&yGe(this);if(o){this.domObserver.stop();let f=m&&(No||ss)&&!this.composing&&!a.selection.empty&&!e.selection.empty&&$9e(a.selection,e.selection);if(m){let y=ss?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=y9e(this)),(s||!this.docView.update(e.doc,u,c,this))&&(this.docView.updateOuterDeco(u),this.docView.destroy(),this.docView=hK(e.doc,u,c,this.dom,this)),y&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}f||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&$Ge(this))?Id(this,f):(Tae(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(a),!((r=this.dragging)===null||r===void 0)&&r.node&&!a.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,a),d=="reset"?this.dom.scrollTop=0:d=="to selection"?this.scrollToSelection():p&&vGe(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 yn){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&oK(this,n.getBoundingClientRect(),e)}else oK(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&&(a=s)}this.dragging=new Bae(e.slice,e.move,a<0?void 0:yn.create(this.state.doc,a))}someProp(e,n){let r=this._props&&this._props[e],a;if(r!=null&&(a=n?n(r):r))return a;for(let o=0;on.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return CGe(this,e)}coordsAtPos(e,n=1){return yae(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 a=this.docView.posFromDOM(e,n,r);if(a==null)throw new RangeError("DOM position not inside the editor");return a}endOfTextblock(e,n){return EGe(this,n||this.state,e)}pasteHTML(e,n){return iw(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return iw(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return YI(this,e)}destroy(){this.docView&&(s9e(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],_D(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,cGe())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return l9e(this,e)}domSelectionRange(){let e=this.domSelection();return e?Ss&&this.root.nodeType===11&&pGe(this.dom.ownerDocument)==this.dom&&D9e(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}Gae.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function DK(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"),[qs.node(0,t.state.doc.content.size,e)]}function RK(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:qs.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function FK(t){return!t.someProp("editable",e=>e(t.state)===!1)}function $9e(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 LK(t){let e=Object.create(null);function n(r){for(let a in r)Object.prototype.hasOwnProperty.call(e,a)||(e[a]=r[a])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function q9e(t,e){let n=0,r=0;for(let a in t){if(t[a]!=e[a])return!0;n++}for(let a in e)r++;return n!=r}function OK(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 Wh={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:"'"},pC={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},V9e=typeof navigator<"u"&&/Mac/.test(navigator.platform),G9e=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var is=0;is<10;is++)Wh[48+is]=Wh[96+is]=String(is);for(var is=1;is<=24;is++)Wh[is+111]="F"+is;for(var is=65;is<=90;is++)Wh[is]=String.fromCharCode(is+32),pC[is]=String.fromCharCode(is);for(var kD in Wh)pC.hasOwnProperty(kD)||(pC[kD]=Wh[kD]);function W9e(t){var e=V9e&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||G9e&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?pC:Wh)[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 K9e=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),Y9e=typeof navigator<"u"&&/Win/.test(navigator.platform);function X9e(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let r,a,s,o;for(let l=0;l{for(var n in e)J9e(t,n,{get:e[n],enumerable:!0})};function CA(t){const{state:e,transaction:n}=t;let{selection:r}=n,{doc:a}=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 a},get tr(){return r=n.selection,a=n.doc,s=n.storedMarks,n}}}var TA=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:a}=n,s=this.buildProps(a);return Object.fromEntries(Object.entries(t).map(([o,l])=>[o,(...u)=>{const d=l(...u)(s);return!a.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(a),d}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,e=!0){const{rawCommands:n,editor:r,state:a}=this,{view:s}=r,o=[],l=!!t,c=t||a.tr,u=()=>(!l&&e&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&s.dispatch(c),o.every(m=>m===!0)),d={...Object.fromEntries(Object.entries(n).map(([m,p])=>[m,(...y)=>{const v=this.buildProps(c,e),b=p(...y)(v);return o.push(b),d}])),run:u};return d}createCan(t){const{rawCommands:e,state:n}=this,r=!1,a=t||n.tr,s=this.buildProps(a,r);return{...Object.fromEntries(Object.entries(e).map(([l,c])=>[l,(...u)=>c(...u)({...s,dispatch:void 0})])),chain:()=>this.createChain(a,r)}}buildProps(t,e=!0){const{rawCommands:n,editor:r,state:a}=this,{view:s}=r,o={tr:t,editor:r,view:s,state:CA({state:a,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}},Kae={};t5(Kae,{blur:()=>eWe,clearContent:()=>tWe,clearNodes:()=>nWe,command:()=>rWe,createParagraphNear:()=>iWe,cut:()=>aWe,deleteCurrentNode:()=>sWe,deleteNode:()=>oWe,deleteRange:()=>lWe,deleteSelection:()=>cWe,enter:()=>uWe,exitCode:()=>dWe,extendMarkRange:()=>mWe,first:()=>hWe,focus:()=>fWe,forEach:()=>gWe,insertContent:()=>bWe,insertContentAt:()=>vWe,joinBackward:()=>_We,joinDown:()=>SWe,joinForward:()=>NWe,joinItemBackward:()=>kWe,joinItemForward:()=>CWe,joinTextblockBackward:()=>TWe,joinTextblockForward:()=>AWe,joinUp:()=>wWe,keyboardShortcut:()=>MWe,lift:()=>EWe,liftEmptyBlock:()=>jWe,liftListItem:()=>DWe,newlineInCode:()=>RWe,resetAttributes:()=>FWe,scrollIntoView:()=>LWe,selectAll:()=>OWe,selectNodeBackward:()=>IWe,selectNodeForward:()=>zWe,selectParentNode:()=>UWe,selectTextblockEnd:()=>BWe,selectTextblockStart:()=>HWe,setContent:()=>$We,setMark:()=>cKe,setMeta:()=>uKe,setNode:()=>dKe,setNodeSelection:()=>mKe,setTextDirection:()=>hKe,setTextSelection:()=>pKe,sinkListItem:()=>fKe,splitBlock:()=>gKe,splitListItem:()=>bKe,toggleList:()=>xKe,toggleMark:()=>yKe,toggleNode:()=>vKe,toggleWrap:()=>wKe,undoInputRule:()=>SKe,unsetAllMarks:()=>_Ke,unsetMark:()=>NKe,unsetTextDirection:()=>kKe,updateAttributes:()=>CKe,wrapIn:()=>TKe,wrapInList:()=>AKe});var eWe=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window?.getSelection())==null||n.removeAllRanges())}),!0),tWe=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),nWe=()=>({state:t,tr:e,dispatch:n})=>{const{selection:r}=e,{ranges:a}=r;return n&&a.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,m=u.resolve(d.map(c)),p=u.resolve(d.map(c+l.nodeSize)),f=m.blockRange(p);if(!f)return;const y=cy(f);if(l.type.isTextblock){const{defaultType:v}=m.parent.contentMatchAt(m.index());e.setNodeMarkup(f.start,v)}(y||y===0)&&e.lift(f,y)})}),!0},rWe=t=>e=>t(e),iWe=()=>({state:t,dispatch:e})=>lae(t,e),aWe=(t,e)=>({editor:n,tr:r})=>{const{state:a}=n,s=a.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 Dn(r.doc.resolve(Math.max(o-1,0)))),!0},sWe=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,r=n.$anchor.node();if(r.content.size>0)return!1;const a=t.selection.$anchor;for(let s=a.depth;s>0;s-=1)if(a.node(s).type===r.type){if(e){const l=a.before(s),c=a.after(s);t.delete(l,c).scrollIntoView()}return!0}return!1};function ca(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 oWe=t=>({tr:e,state:n,dispatch:r})=>{const a=ca(t,n.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===a){if(r){const c=s.before(o),u=s.after(o);e.delete(c,u).scrollIntoView()}return!0}return!1},lWe=t=>({tr:e,dispatch:n})=>{const{from:r,to:a}=t;return n&&e.delete(r,a),!0},cWe=()=>({state:t,dispatch:e})=>BI(t,e),uWe=()=>({commands:t})=>t.keyboardShortcut("Enter"),dWe=()=>({state:t,dispatch:e})=>K7e(t,e);function n5(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function fC(t,e,n={strict:!0}){const r=Object.keys(e);return r.length?r.every(a=>n.strict?e[a]===t[a]:n5(e[a])?e[a].test(t[a]):e[a]===t[a]):!0}function Yae(t,e,n={}){return t.find(r=>r.type===e&&fC(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function IK(t,e,n={}){return!!Yae(t,e,n)}function r5(t,e,n){var r;if(!t||!e)return;let a=t.parent.childAfter(t.parentOffset);if((!a.node||!a.node.marks.some(d=>d.type===e))&&(a=t.parent.childBefore(t.parentOffset)),!a.node||!a.node.marks.some(d=>d.type===e)||(n=n||((r=a.node.marks[0])==null?void 0:r.attrs),!Yae([...a.node.marks],e,n)))return;let o=a.index,l=t.start()+a.offset,c=o+1,u=l+a.node.nodeSize;for(;o>0&&IK([...t.parent.child(o-1).marks],e,n);)o-=1,l-=t.parent.child(o).nodeSize;for(;c({tr:n,state:r,dispatch:a})=>{const s=sm(t,r.schema),{doc:o,selection:l}=n,{$from:c,from:u,to:d}=l;if(a){const m=r5(c,s,e);if(m&&m.from<=u&&m.to>=d){const p=Dn.create(o,m.from,m.to);n.setSelection(p)}}return!0},hWe=t=>e=>{const n=typeof t=="function"?t(e):t;for(let r=0;r({editor:n,view:r,tr:a,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(gC()||zK())&&r.dom.focus(),pWe()&&!gC()&&!zK()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),e?.scrollIntoView&&n.commands.scrollIntoView())})};try{if(r.hasFocus()&&t===null||t===!1)return!0}catch{return!1}if(s&&t===null&&!Xae(n.state.selection))return o(),!0;const l=Qae(a.doc,t)||n.state.selection,c=n.state.selection.eq(l);return s&&(c||a.setSelection(l),c&&a.storedMarks&&a.setStoredMarks(a.storedMarks),o()),!0},gWe=(t,e)=>n=>t.every((r,a)=>e(r,{...n,index:a})),bWe=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),Zae=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&&Zae(r)}return t};function I1(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 Zae(n)}function sw(t,e,n){if(t instanceof kc||t instanceof Bt)return t;n={slice:!0,parseOptions:{},...n};const r=typeof t=="object"&&t!==null,a=typeof t=="string";if(r)try{if(Array.isArray(t)&&t.length>0)return Bt.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),sw("",e,n)}if(a){if(n.errorOnInvalidContent){let o=!1,l="";const c=new Fie({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?r0.fromSchema(c).parseSlice(I1(t),n.parseOptions):r0.fromSchema(c).parse(I1(t),n.parseOptions),n.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=r0.fromSchema(e);return n.slice?s.parseSlice(I1(t),n.parseOptions).content:s.parse(I1(t),n.parseOptions)}return sw("",e,n)}function xWe(t,e,n){const r=t.steps.length-1;if(r{o===0&&(o=d)}),t.setSelection(Kn.near(t.doc.resolve(o),n))}var yWe=t=>!("type"in t),vWe=(t,e,n)=>({tr:r,dispatch:a,editor:s})=>{var o;if(a){n={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let l;const c=b=>{s.emit("contentError",{editor:s,error:b,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{sw(e,s.schema,{parseOptions:u,errorOnInvalidContent:!0})}catch(b){c(b)}try{l=sw(e,s.schema,{parseOptions:u,errorOnInvalidContent:(o=n.errorOnInvalidContent)!=null?o:s.options.enableContentCheck})}catch(b){return c(b),!1}let{from:d,to:m}=typeof t=="number"?{from:t,to:t}:{from:t.from,to:t.to},p=!0,f=!0;if((yWe(l)?l:[l]).forEach(b=>{b.check(),p=p?b.isText&&b.marks.length===0:!1,f=f?b.isBlock:!1}),d===m&&f){const{parent:b}=r.doc.resolve(d);b.isTextblock&&!b.type.spec.code&&!b.childCount&&(d-=1,m+=1)}let v;if(p){if(Array.isArray(e))v=e.map(b=>b.text||"").join("");else if(e instanceof Bt){let b="";e.forEach(g=>{g.text&&(b+=g.text)}),v=b}else typeof e=="object"&&e&&e.text?v=e.text:v=e;r.insertText(v,d,m)}else{v=l;const b=r.doc.resolve(d),g=b.node(),_=b.parentOffset===0,N=g.isText||g.isTextblock,C=g.content.size>0;_&&N&&C&&(d=Math.max(0,d-1)),r.replaceWith(d,m,v)}n.updateSelection&&xWe(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:d,text:v}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:d,text:v})}return!0},wWe=()=>({state:t,dispatch:e})=>V7e(t,e),SWe=()=>({state:t,dispatch:e})=>G7e(t,e),_We=()=>({state:t,dispatch:e})=>tae(t,e),NWe=()=>({state:t,dispatch:e})=>aae(t,e),kWe=()=>({state:t,dispatch:e,tr:n})=>{try{const r=vA(t.doc,t.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},CWe=()=>({state:t,dispatch:e,tr:n})=>{try{const r=vA(t.doc,t.selection.$from.pos,1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},TWe=()=>({state:t,dispatch:e})=>$7e(t,e),AWe=()=>({state:t,dispatch:e})=>q7e(t,e);function Jae(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function PWe(t){const e=t.split(/-(?!$)/);let n=e[e.length-1];n==="Space"&&(n=" ");let r,a,s,o;for(let l=0;l({editor:e,view:n,tr:r,dispatch:a})=>{const s=PWe(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&&a&&r.maybeStep(d)}),!0};function Kh(t,e,n={}){const{from:r,to:a,empty:s}=t.selection,o=e?ca(e,t.schema):null,l=[];t.doc.nodesBetween(r,a,(m,p)=>{if(m.isText)return;const f=Math.max(r,p),y=Math.min(a,p+m.nodeSize);l.push({node:m,from:f,to:y})});const c=a-r,u=l.filter(m=>o?o.name===m.node.type.name:!0).filter(m=>fC(m.node.attrs,n,{strict:!1}));return s?!!u.length:u.reduce((m,p)=>m+p.to-p.from,0)>=c}var EWe=(t,e={})=>({state:n,dispatch:r})=>{const a=ca(t,n.schema);return Kh(n,a,e)?W7e(n,r):!1},jWe=()=>({state:t,dispatch:e})=>cae(t,e),DWe=t=>({state:e,dispatch:n})=>{const r=ca(t,e.schema);return aGe(r)(e,n)},RWe=()=>({state:t,dispatch:e})=>oae(t,e);function AA(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function UK(t,e){const n=typeof e=="string"?[e]:e;return Object.keys(t).reduce((r,a)=>(n.includes(a)||(r[a]=t[a]),r),{})}var FWe=(t,e)=>({tr:n,state:r,dispatch:a})=>{let s=null,o=null;const l=AA(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=ca(t,r.schema)),l==="mark"&&(o=sm(t,r.schema));let c=!1;return n.selection.ranges.forEach(u=>{r.doc.nodesBetween(u.$from.pos,u.$to.pos,(d,m)=>{s&&s===d.type&&(c=!0,a&&n.setNodeMarkup(m,void 0,UK(d.attrs,e))),o&&d.marks.length&&d.marks.forEach(p=>{o===p.type&&(c=!0,a&&n.addMark(m,m+d.nodeSize,o.create(UK(p.attrs,e))))})})}),c},LWe=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),OWe=()=>({tr:t,dispatch:e})=>{if(e){const n=new nl(t.doc);t.setSelection(n)}return!0},IWe=()=>({state:t,dispatch:e})=>rae(t,e),zWe=()=>({state:t,dispatch:e})=>sae(t,e),UWe=()=>({state:t,dispatch:e})=>Q7e(t,e),BWe=()=>({state:t,dispatch:e})=>eGe(t,e),HWe=()=>({state:t,dispatch:e})=>J7e(t,e);function nL(t,e,n={},r={}){return sw(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var $We=(t,{errorOnInvalidContent:e,emitUpdate:n=!0,parseOptions:r={}}={})=>({editor:a,tr:s,dispatch:o,commands:l})=>{const{doc:c}=s;if(r.preserveWhitespace!=="full"){const u=nL(t,a.schema,r,{errorOnInvalidContent:e??a.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??a.options.enableContentCheck})};function ese(t,e){const n=sm(e,t.schema),{from:r,to:a,empty:s}=t.selection,o=[];s?(t.storedMarks&&o.push(...t.storedMarks),o.push(...t.selection.$head.marks())):t.doc.nodesBetween(r,a,c=>{o.push(...c.marks)});const l=o.find(c=>c.type.name===n.name);return l?{...l.attrs}:{}}function tse(t,e){const n=new Qie(t);return e.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function qWe(t){for(let e=0;e{n(a)&&r.push({node:a,pos:s})}),r}function GWe(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 PA(t){return e=>GWe(e.$from,t)}function pn(t,e,n){return t.config[e]===void 0&&t.parent?pn(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?pn(t.parent,e,n):null}):t.config[e]}function i5(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},r=pn(e,"addExtensions",n);return r?[e,...i5(r())]:e}).flat(10)}function a5(t,e){const n=og.fromSchema(e).serializeFragment(t),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}function nse(t){return typeof t=="function"}function jr(t,e=void 0,...n){return nse(t)?e?t.bind(e)(...n):t(...n):t}function WWe(t={}){return Object.keys(t).length===0&&t.constructor===Object}function Lx(t){const e=t.filter(a=>a.type==="extension"),n=t.filter(a=>a.type==="node"),r=t.filter(a=>a.type==="mark");return{baseExtensions:e,nodeExtensions:n,markExtensions:r}}function rse(t){const e=[],{nodeExtensions:n,markExtensions:r}=Lx(t),a=[...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:a},c=pn(o,"addGlobalAttributes",l);if(!c)return;c().forEach(d=>{d.types.forEach(m=>{Object.entries(d.attributes).forEach(([p,f])=>{e.push({type:m,name:p,attribute:{...s,...f}})})})})}),a.forEach(o=>{const l={name:o.name,options:o.options,storage:o.storage},c=pn(o,"addAttributes",l);if(!c)return;const u=c();Object.entries(u).forEach(([d,m])=>{const p={...s,...m};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 Oi(...t){return t.filter(e=>!!e).reduce((e,n)=>{const r={...e};return Object.entries(n).forEach(([a,s])=>{if(!r[a]){r[a]=s;return}if(a==="class"){const l=s?String(s).split(" "):[],c=r[a]?r[a].split(" "):[],u=l.filter(d=>!c.includes(d));r[a]=[...c,...u].join(" ")}else if(a==="style"){const l=s?s.split(";").map(d=>d.trim()).filter(Boolean):[],c=r[a]?r[a].split(";").map(d=>d.trim()).filter(Boolean):[],u=new Map;c.forEach(d=>{const[m,p]=d.split(":").map(f=>f.trim());u.set(m,p)}),l.forEach(d=>{const[m,p]=d.split(":").map(f=>f.trim());u.set(m,p)}),r[a]=Array.from(u.entries()).map(([d,m])=>`${d}: ${m}`).join("; ")}else r[a]=s}),r},{})}function ow(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)=>Oi(n,r),{})}function KWe(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function BK(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 a=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(n):KWe(n.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...a}}}}function HK(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&WWe(n)?!1:n!=null))}function $K(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 YWe(t,e){var n;const r=rse(t),{nodeExtensions:a,markExtensions:s}=Lx(t),o=(n=a.find(u=>pn(u,"topNode")))==null?void 0:n.name,l=Object.fromEntries(a.map(u=>{const d=r.filter(g=>g.type===u.name),m={name:u.name,options:u.options,storage:u.storage,editor:e},p=t.reduce((g,_)=>{const N=pn(_,"extendNodeSchema",m);return{...g,...N?N(u):{}}},{}),f=HK({...p,content:jr(pn(u,"content",m)),marks:jr(pn(u,"marks",m)),group:jr(pn(u,"group",m)),inline:jr(pn(u,"inline",m)),atom:jr(pn(u,"atom",m)),selectable:jr(pn(u,"selectable",m)),draggable:jr(pn(u,"draggable",m)),code:jr(pn(u,"code",m)),whitespace:jr(pn(u,"whitespace",m)),linebreakReplacement:jr(pn(u,"linebreakReplacement",m)),defining:jr(pn(u,"defining",m)),isolating:jr(pn(u,"isolating",m)),attrs:Object.fromEntries(d.map($K))}),y=jr(pn(u,"parseHTML",m));y&&(f.parseDOM=y.map(g=>BK(g,d)));const v=pn(u,"renderHTML",m);v&&(f.toDOM=g=>v({node:g,HTMLAttributes:ow(g,d)}));const b=pn(u,"renderText",m);return b&&(f.toText=b),[u.name,f]})),c=Object.fromEntries(s.map(u=>{const d=r.filter(b=>b.type===u.name),m={name:u.name,options:u.options,storage:u.storage,editor:e},p=t.reduce((b,g)=>{const _=pn(g,"extendMarkSchema",m);return{...b,..._?_(u):{}}},{}),f=HK({...p,inclusive:jr(pn(u,"inclusive",m)),excludes:jr(pn(u,"excludes",m)),group:jr(pn(u,"group",m)),spanning:jr(pn(u,"spanning",m)),code:jr(pn(u,"code",m)),attrs:Object.fromEntries(d.map($K))}),y=jr(pn(u,"parseHTML",m));y&&(f.parseDOM=y.map(b=>BK(b,d)));const v=pn(u,"renderHTML",m);return v&&(f.toDOM=b=>v({mark:b,HTMLAttributes:ow(b,d)})),[u.name,f]}));return new Fie({topNode:o,nodes:l,marks:c})}function XWe(t){const e=t.filter((n,r)=>t.indexOf(n)!==r);return Array.from(new Set(e))}function bC(t){return t.sort((n,r)=>{const a=pn(n,"priority")||100,s=pn(r,"priority")||100;return a>s?-1:ar.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function ase(t,e,n){const{from:r,to:a}=e,{blockSeparator:s=` +`))),0,0),t.someProp("transformPasted",p=>{l=p(l,t,!0)}),l;let m=t.someProp("clipboardTextParser",p=>p(e,a,r,t));if(m)l=m;else{let p=a.marks(),{schema:f}=t.state,y=og.fromSchema(f);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(v=>{let b=o.appendChild(document.createElement("p"));v&&b.appendChild(y.serializeNode(f.text(v,p)))})}}else t.someProp("transformPastedHTML",m=>{n=m(n,t)}),o=e9e(n),Zw&&t9e(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 m=+d[3];m>0;m--){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")||r0.fromSchema(t.state.schema)).parseSlice(o,{preserveWhitespace:!!(c||d),context:a,ruleFromNode(p){return p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!QGe.test(p.parentNode.nodeName)?{ignore:!0}:null}})),d)l=n9e(kK(l,+d[1],+d[2]),d[4]);else if(l=Zt.maxOpen(ZGe(l.content,a),!0),l.openStart||l.openEnd){let m=0,p=0;for(let f=l.content.firstChild;m{l=m(l,t,c)}),l}const QGe=/^(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 ZGe(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let a=e.node(n).contentMatchAt(e.index(n)),s,o=[];if(t.forEach(l=>{if(!o)return;let c=a.findWrapping(l.type),u;if(!c)return o=null;if(u=o.length&&s.length&&jae(c,s,l,o[o.length-1],0))o[o.length-1]=u;else{o.length&&(o[o.length-1]=Dae(o[o.length-1],s.length));let d=Eae(l,c);o.push(d),a=a.matchType(d.type),s=c}}),o)return Bt.from(o)}return t}function Eae(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,Bt.from(t));return t}function jae(t,e,n,r,a){if(a1&&(s=0),a=n&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=a).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(Bt.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,o.copy(l))}function kK(t,e,n){return en})),SD.createHTML(t)):t}function e9e(t){let e=/^(\s*]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=Fae().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(t),a;if((a=r&&Rae[r[1].toLowerCase()])&&(t=a.map(s=>"<"+s+">").join("")+t+a.map(s=>"").reverse().join("")),n.innerHTML=JGe(t),a)for(let s=0;s=0;l-=2){let c=n.nodes[r[l]];if(!c||c.hasRequiredAttrs())break;a=Bt.from(c.create(r[l+1],a)),s++,o++}return new Zt(a,s,o)}const Js={},eo={},r9e={touchstart:!0,touchmove:!0};class i9e{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.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function a9e(t){for(let e in Js){let n=Js[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{o9e(t,r)&&!X4(t,r)&&(t.editable||!(r.type in eo))&&n(t,r)},r9e[e]?{passive:!0}:void 0)}Ss&&t.dom.addEventListener("input",()=>null),tL(t)}function wh(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function s9e(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 tL(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>X4(t,r))})}function X4(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function o9e(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 l9e(t,e){!X4(t,e)&&Js[e.type]&&(t.editable||!(e.type in eo))&&Js[e.type](t,e)}eo.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!Oae(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Pd&&ss&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),Fx&&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",a=>a(t,Xp(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||XGe(t,n)?n.preventDefault():wh(t,"key")};eo.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};eo.keypress=(t,e)=>{let n=e;if(Oae(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||El&&n.metaKey)return;if(t.someProp("handleKeyPress",a=>a(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof Dn)||!r.$from.sameParent(r.$to)){let a=String.fromCharCode(n.charCode),s=()=>t.state.tr.insertText(a).scrollIntoView();!/[\r\n]/.test(a)&&!t.someProp("handleTextInput",o=>o(t,r.$from.pos,r.$to.pos,a,s))&&t.dispatch(s()),n.preventDefault()}};function kA(t){return{left:t.clientX,top:t.clientY}}function c9e(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,a){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),a,!0):l(t,n,s.node(o),s.before(o),a,!1)))return!0;return!1}function sx(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 u9e(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&yn.isSelectable(r)?(sx(t,new yn(n)),!0):!1}function d9e(t,e){if(e==-1)return!1;let n=t.state.selection,r,a;n instanceof yn&&(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(yn.isSelectable(l)){r&&n.$from.depth>0&&o>=n.$from.depth&&s.before(n.$from.depth+1)==n.$from.pos?a=s.before(n.$from.depth):a=s.before(o);break}}return a!=null?(sx(t,yn.create(t.state.doc,a)),!0):!1}function m9e(t,e,n,r,a){return Q4(t,"handleClickOn",e,n,r)||t.someProp("handleClick",s=>s(t,e,r))||(a?d9e(t,n):u9e(t,n))}function h9e(t,e,n,r){return Q4(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",a=>a(t,e,r))}function p9e(t,e,n,r){return Q4(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",a=>a(t,e,r))||f9e(t,n,r)}function f9e(t,e,n){if(n.button!=0)return!1;let r=t.state.doc;if(e==-1)return r.inlineContent?(sx(t,Dn.create(r,0,r.content.size)),!0):!1;let a=r.resolve(e);for(let s=a.depth+1;s>0;s--){let o=s>a.depth?a.nodeAfter:a.node(s),l=a.before(s);if(o.inlineContent)sx(t,Dn.create(r,l+1,l+1+o.content.size));else if(yn.isSelectable(o))sx(t,yn.create(r,l));else continue;return!0}}function Z4(t){return dC(t)}const Lae=El?"metaKey":"ctrlKey";Js.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=Z4(t),a=Date.now(),s="singleClick";a-t.input.lastClick.time<500&&c9e(n,t.input.lastClick)&&!n[Lae]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?s="doubleClick":t.input.lastClick.type=="doubleClick"&&(s="tripleClick")),t.input.lastClick={time:a,x:n.clientX,y:n.clientY,type:s,button:n.button};let o=t.posAtCoords(kA(n));o&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new g9e(t,o,n,!!r)):(s=="doubleClick"?h9e:p9e)(t,o.pos,o.inside,n)?n.preventDefault():wh(t,"pointer"))};class g9e{constructor(e,n,r,a){this.view=e,this.pos=n,this.event=r,this.flushed=a,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!r[Lae],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=a?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 yn&&u.from<=o&&u.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Hl&&!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)),wh(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(()=>Id(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(kA(e))),this.updateAllowDefault(e),this.allowDefault||!n?wh(this.view,"pointer"):m9e(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Ss&&this.mightDrag&&!this.mightDrag.node.isAtom||ss&&!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)?(sx(this.view,Kn.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):wh(this.view,"pointer")}move(e){this.updateAllowDefault(e),wh(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)}}Js.touchstart=t=>{t.input.lastTouch=Date.now(),Z4(t),wh(t,"pointer")};Js.touchmove=t=>{t.input.lastTouch=Date.now(),wh(t,"pointer")};Js.contextmenu=t=>Z4(t);function Oae(t,e){return t.composing?!0:Ss&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const b9e=Pd?5e3:-1;eo.compositionstart=eo.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof Dn&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||ss&&pae&&x9e(t)))t.markCursor=t.state.storedMarks||n.marks(),dC(t,!0),t.markCursor=null;else if(dC(t,!e.selection.empty),Hl&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let a=r.focusNode,s=r.focusOffset;a&&a.nodeType==1&&s!=0;){let o=s<0?a.lastChild:a.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=t.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else a=o,s=-1}}t.input.composing=!0}Iae(t,b9e)};function x9e(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||e.nodeType!=1||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}eo.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.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,Iae(t,20))};function Iae(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>dC(t),e))}function zae(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=v9e());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function y9e(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=dGe(e.focusNode,e.focusOffset),r=mGe(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let a=r.pmViewDesc,s=t.domObserver.lastChangedTextNode;if(n==s||r==s)return s;if(!a||!a.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 v9e(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function dC(t,e=!1){if(!(Pd&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),zae(t),e||t.docView&&t.docView.dirty){let n=W4(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 w9e(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(),a=document.createRange();a.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(a),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}const rw=No&&Lh<15||Fx&&gGe<604;Js.copy=eo.cut=(t,e)=>{let n=e,r=t.state.selection,a=n.type=="cut";if(r.empty)return;let s=rw?null:n.clipboardData,o=r.content(),{dom:l,text:c}=Y4(t,o);s?(n.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",c)):w9e(t,l),a&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function S9e(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function _9e(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 a=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?iw(t,r.value,null,a,e):iw(t,r.textContent,r.innerHTML,a,e)},50)}function iw(t,e,n,r,a){let s=Mae(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",c=>c(t,a,s||Zt.empty)))return!0;if(!s)return!1;let o=S9e(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 Uae(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," "):""}eo.paste=(t,e)=>{let n=e;if(t.composing&&!Pd)return;let r=rw?null:n.clipboardData,a=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&iw(t,Uae(r),r.getData("text/html"),a,n)?n.preventDefault():_9e(t,n)};class Bae{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}}const N9e=El?"altKey":"ctrlKey";function Hae(t,e){let n=t.someProp("dragCopies",r=>!r(e));return n??!e[N9e]}Js.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let a=t.state.selection,s=a.empty?null:t.posAtCoords(kA(n)),o;if(!(s&&s.pos>=a.from&&s.pos<=(a instanceof yn?a.to-1:a.to))){if(r&&r.mightDrag)o=yn.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let m=t.docView.nearestDesc(n.target,!0);m&&m.node.type.spec.draggable&&m!=t.docView&&(o=yn.create(t.state.doc,m.posBefore))}}let l=(o||t.state.selection).content(),{dom:c,text:u,slice:d}=Y4(t,l);(!n.dataTransfer.files.length||!ss||hae>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(rw?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",rw||n.dataTransfer.setData("text/plain",u),t.dragging=new Bae(d,Hae(t,n),o)};Js.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};eo.dragover=eo.dragenter=(t,e)=>e.preventDefault();eo.drop=(t,e)=>{try{k9e(t,e,t.dragging)}finally{t.dragging=null}};function k9e(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(kA(e));if(!r)return;let a=t.state.doc.resolve(r.pos),s=n&&n.slice;s?t.someProp("transformPasted",f=>{s=f(s,t,!1)}):s=Mae(t,Uae(e.dataTransfer),rw?null:e.dataTransfer.getData("text/html"),!1,a);let o=!!(n&&Hae(t,e));if(t.someProp("handleDrop",f=>f(t,e,s||Zt.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Gie(t.state.doc,a.pos,s):a.pos;l==null&&(l=a.pos);let c=t.state.tr;if(o){let{node:f}=n;f?f.replace(c):c.deleteSelection()}let u=c.mapping.map(l),d=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,m=c.doc;if(d?c.replaceRangeWith(u,u,s.content.firstChild):c.replaceRange(u,u,s),c.doc.eq(m))return;let p=c.doc.resolve(u);if(d&&yn.isSelectable(s.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(s.content.firstChild))c.setSelection(new yn(p));else{let f=c.mapping.map(l);c.mapping.maps[c.mapping.maps.length-1].forEach((y,v,b,g)=>f=g),c.setSelection(K4(t,p,c.doc.resolve(f)))}t.focus(),t.dispatch(c.setMeta("uiEvent","drop"))}Js.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())&&Id(t)},20))};Js.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)};Js.beforeinput=(t,e)=>{if(ss&&Pd&&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,Xp(8,"Backspace")))))return;let{$cursor:a}=t.state.selection;a&&a.pos>0&&t.dispatch(t.state.tr.delete(a.pos-1,a.pos).scrollIntoView())},50)}};for(let t in eo)Js[t]=eo[t];function aw(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 mC{constructor(e,n){this.toDOM=e,this.spec=n||Sf,this.side=this.spec.side||0}map(e,n,r,a){let{pos:s,deleted:o}=e.mapResult(n.from+a,this.side<0?-1:1);return o?null:new qs(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof mC&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&aw(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Ih{constructor(e,n){this.attrs=e,this.spec=n||Sf}map(e,n,r,a){let s=e.map(n.from+a,this.spec.inclusiveStart?-1:1)-r,o=e.map(n.to+a,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new qs(s,o,this)}valid(e,n){return n.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+a,l.to+a))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,n-l,r,a+l,s)}}map(e,n,r){return this==bs||e.maps.length==0?this:this.mapInner(e,n,0,0,r||Sf)}mapInner(e,n,r,a,s){let o;for(let l=0;l{let u=c+r,d;if(d=qae(n,l,u)){for(a||(a=this.children.slice());sl&&m.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 Ih){let u=Math.max(s,c.from)-s,d=Math.min(o,c.to)-s;ua.map(e,n,Sf));return oh.from(r)}forChild(e,n){if(n.isLeaf)return xi.empty;let r=[];for(let a=0;an instanceof xi)?e:e.reduce((n,r)=>n.concat(r instanceof xi?r:r.members),[]))}}forEachSet(e){for(let n=0;n{let b=v-y-(f-p);for(let g=0;g_+d-m)continue;let N=l[g]+d-m;f>=N?l[g+1]=p<=N?-2:-1:p>=d&&b&&(l[g]+=b,l[g+1]+=b)}m+=b}),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),f=p-a,{index:y,offset:v}=r.content.findIndex(m),b=r.maybeChild(y);if(b&&v==m&&v+b.nodeSize==f){let g=l[u+2].mapInner(n,b,d+1,t[u]+s+1,o);g!=bs?(l[u]=m,l[u+1]=f,l[u+2]=g):(l[u+1]=-2,c=!0)}else c=!0}if(c){let u=T9e(l,t,e,n,a,s,o),d=hC(u,r,0,o);e=d.local;for(let m=0;mn&&o.to{let u=qae(t,l,c+n);if(u){s=!0;let d=hC(u,l,n+c+1,r);d!=bs&&a.push(c,c+l.nodeSize,d)}});let o=$ae(s?Vae(t):t,-n).sort(_f);for(let l=0;l0;)e++;t.splice(e,0,n)}function _D(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=bs&&e.push(r)}),t.cursorWrapper&&e.push(xi.create(t.state.doc,[t.cursorWrapper.deco])),oh.from(e)}const A9e={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},P9e=No&&Lh<=11;class M9e{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 E9e{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new M9e,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let a=0;aa.type=="childList"&&a.removedNodes.length||a.type=="characterData"&&a.oldValue.length>a.target.nodeValue.length)?this.flushSoon():Ss&&e.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),P9e&&(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,A9e)),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(yK(this.view)){if(this.suppressingSelectionUpdates)return Id(this.view);if(No&&Lh<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Xf(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=Rx(s))n.add(s);for(let s=e.anchorNode;s;s=Rx(s))if(n.has(s)){r=s;break}let a=r&&this.view.docView.nearestDesc(r);if(a&&a.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(),a=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&yK(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,c=[];if(e.editable)for(let d=0;dd.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let d of c)if(d.nodeName=="BR"&&d.parentNode){let m=d.nextSibling;m&&m.nodeType==1&&m.contentEditable=="false"&&d.parentNode.removeChild(d)}}else if(Hl&&c.length){let d=c.filter(m=>m.nodeName=="BR");if(d.length==2){let[m,p]=d;m.parentNode&&m.parentNode.parentNode==p.parentNode?p.remove():m.remove()}else{let{focusNode:m}=this.currentSelection;for(let p of d){let f=p.parentNode;f&&f.nodeName=="LI"&&(!m||R9e(e,m)!=f)&&p.remove()}}}let u=null;s<0&&a&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||a)&&(s>-1&&(e.docView.markDirty(s,o),j9e(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,F9e(e,c)),this.handleDOMChange(s,o,l,c),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Id(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;da;b--){let g=r.childNodes[b-1],_=g.pmViewDesc;if(g.nodeName=="BR"&&!_){s=b;break}if(!_||_.size)break}let m=t.state.doc,p=t.someProp("domParser")||r0.fromSchema(t.state.schema),f=m.resolve(o),y=null,v=p.parse(r,{topNode:f.parent,topMatch:f.parent.contentMatchAt(f.index()),topOpen:!0,from:a,to:s,preserveWhitespace:f.parent.type.whitespace=="pre"?"full":!0,findPositions:u,ruleFromNode:O9e,context:f});if(u&&u[0].pos!=null){let b=u[0].pos,g=u[1]&&u[1].pos;g==null&&(g=b),y={anchor:b+o,head:g+o}}return{doc:v,sel:y,from:o,to:l}}function O9e(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Ss&&/^(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||Ss&&/^(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 I9e=/^(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 z9e(t,e,n,r,a){let s=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let T=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,D=W4(t,T);if(D&&!t.state.selection.eq(D)){if(ss&&Pd&&t.input.lastKeyCode===13&&Date.now()-100R(t,Xp(13,"Enter"))))return;let A=t.state.tr.setSelection(D);T=="pointer"?A.setMeta("pointer",!0):T=="key"&&A.scrollIntoView(),s&&A.setMeta("composition",s),t.dispatch(A)}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=L9e(t,e,n),d=t.state.doc,m=d.slice(u.from,u.to),p,f;t.input.lastKeyCode===8&&Date.now()-100Date.now()-225||Pd)&&a.some(T=>T.nodeType==1&&!I9e.test(T.nodeName))&&(!y||y.endA>=y.endB)&&t.someProp("handleKeyDown",T=>T(t,Xp(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!y)if(r&&c instanceof Dn&&!c.empty&&c.$head.sameParent(c.$anchor)&&!t.composing&&!(u.sel&&u.sel.anchor!=u.sel.head))y={start:c.from,endA:c.to,endB:c.to};else{if(u.sel){let T=EK(t,t.state.doc,u.sel);if(T&&!T.eq(t.state.selection)){let D=t.state.tr.setSelection(T);s&&D.setMeta("composition",s),t.dispatch(D)}}return}t.state.selection.fromt.state.selection.from&&y.start<=t.state.selection.from+2&&t.state.selection.from>=u.from?y.start=t.state.selection.from:y.endA=t.state.selection.to-2&&t.state.selection.to<=u.to&&(y.endB+=t.state.selection.to-y.endA,y.endA=t.state.selection.to)),No&&Lh<=11&&y.endB==y.start+1&&y.endA==y.start&&y.start>u.from&&u.doc.textBetween(y.start-u.from-1,y.start-u.from+1)=="  "&&(y.start--,y.endA--,y.endB--);let v=u.doc.resolveNoCache(y.start-u.from),b=u.doc.resolveNoCache(y.endB-u.from),g=d.resolve(y.start),_=v.sameParent(b)&&v.parent.inlineContent&&g.end()>=y.endA;if((Fx&&t.input.lastIOSEnter>Date.now()-225&&(!_||a.some(T=>T.nodeName=="DIV"||T.nodeName=="P"))||!_&&v.posT(t,Xp(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>y.start&&B9e(d,y.start,y.endA,v,b)&&t.someProp("handleKeyDown",T=>T(t,Xp(8,"Backspace")))){Pd&&ss&&t.domObserver.suppressSelectionUpdates();return}ss&&y.endB==y.start&&(t.input.lastChromeDelete=Date.now()),Pd&&!_&&v.start()!=b.start()&&b.parentOffset==0&&v.depth==b.depth&&u.sel&&u.sel.anchor==u.sel.head&&u.sel.head==y.endA&&(y.endB-=2,b=u.doc.resolveNoCache(y.endB-u.from),setTimeout(()=>{t.someProp("handleKeyDown",function(T){return T(t,Xp(13,"Enter"))})},20));let N=y.start,C=y.endA,k=T=>{let D=T||t.state.tr.replace(N,C,u.doc.slice(y.start-u.from,y.endB-u.from));if(u.sel){let A=EK(t,D.doc,u.sel);A&&!(ss&&t.composing&&A.empty&&(y.start!=y.endB||t.input.lastChromeDeleteId(t),20));let T=k(t.state.tr.delete(N,C)),D=d.resolve(y.start).marksAcross(d.resolve(y.endA));D&&T.ensureMarks(D),t.dispatch(T)}else if(y.endA==y.endB&&(P=U9e(v.parent.content.cut(v.parentOffset,b.parentOffset),g.parent.content.cut(g.parentOffset,y.endA-g.start())))){let T=k(t.state.tr);P.type=="add"?T.addMark(N,C,P.mark):T.removeMark(N,C,P.mark),t.dispatch(T)}else if(v.parent.child(v.index()).isText&&v.index()==b.index()-(b.textOffset?0:1)){let T=v.parent.textBetween(v.parentOffset,b.parentOffset),D=()=>k(t.state.tr.insertText(T,N,C));t.someProp("handleTextInput",A=>A(t,N,C,T,D))||t.dispatch(D())}else t.dispatch(k());else t.dispatch(k())}function EK(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:K4(t,e.resolve(n.anchor),e.resolve(n.head))}function U9e(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,a=n,s=r,o,l,c;for(let d=0;dd.mark(l.addToSet(d.marks));else if(a.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||ND(o,!0,!1)0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,a++,e=!1;if(n){let s=t.node(r).maybeChild(t.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,a++}return a}function H9e(t,e,n,r,a){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(a=="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 Gae{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 i9e,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(OK),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=FK(this),RK(this),this.nodeViews=LK(this),this.docView=hK(this.state.doc,DK(this),_D(this),this.dom,this),this.domObserver=new E9e(this,(r,a,s,o)=>z9e(this,r,a,s,o)),this.domObserver.start(),a9e(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&&tL(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(OK),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 a=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(zae(this),o=!0),this.state=e;let l=a.plugins!=e.plugins||this._props.plugins!=n.plugins;if(l||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let f=LK(this);q9e(f,this.nodeViews)&&(this.nodeViews=f,s=!0)}(l||n.handleDOMEvents!=this._props.handleDOMEvents)&&tL(this),this.editable=FK(this),RK(this);let c=_D(this),u=DK(this),d=a.plugins!=e.plugins&&!a.doc.eq(e.doc)?"reset":e.scrollToSelection>a.scrollToSelection?"to selection":"preserve",m=s||!this.docView.matchesNode(e.doc,u,c);(m||!e.selection.eq(a.selection))&&(o=!0);let p=d=="preserve"&&o&&this.dom.style.overflowAnchor==null&&yGe(this);if(o){this.domObserver.stop();let f=m&&(No||ss)&&!this.composing&&!a.selection.empty&&!e.selection.empty&&$9e(a.selection,e.selection);if(m){let y=ss?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=y9e(this)),(s||!this.docView.update(e.doc,u,c,this))&&(this.docView.updateOuterDeco(u),this.docView.destroy(),this.docView=hK(e.doc,u,c,this.dom,this)),y&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}f||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&$Ge(this))?Id(this,f):(Tae(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(a),!((r=this.dragging)===null||r===void 0)&&r.node&&!a.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,a),d=="reset"?this.dom.scrollTop=0:d=="to selection"?this.scrollToSelection():p&&vGe(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 yn){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&oK(this,n.getBoundingClientRect(),e)}else oK(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&&(a=s)}this.dragging=new Bae(e.slice,e.move,a<0?void 0:yn.create(this.state.doc,a))}someProp(e,n){let r=this._props&&this._props[e],a;if(r!=null&&(a=n?n(r):r))return a;for(let o=0;on.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return CGe(this,e)}coordsAtPos(e,n=1){return yae(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 a=this.docView.posFromDOM(e,n,r);if(a==null)throw new RangeError("DOM position not inside the editor");return a}endOfTextblock(e,n){return EGe(this,n||this.state,e)}pasteHTML(e,n){return iw(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return iw(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return Y4(this,e)}destroy(){this.docView&&(s9e(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],_D(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,cGe())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return l9e(this,e)}domSelectionRange(){let e=this.domSelection();return e?Ss&&this.root.nodeType===11&&pGe(this.dom.ownerDocument)==this.dom&&D9e(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}Gae.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function DK(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"),[qs.node(0,t.state.doc.content.size,e)]}function RK(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:qs.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function FK(t){return!t.someProp("editable",e=>e(t.state)===!1)}function $9e(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 LK(t){let e=Object.create(null);function n(r){for(let a in r)Object.prototype.hasOwnProperty.call(e,a)||(e[a]=r[a])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function q9e(t,e){let n=0,r=0;for(let a in t){if(t[a]!=e[a])return!0;n++}for(let a in e)r++;return n!=r}function OK(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 Wh={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:"'"},pC={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},V9e=typeof navigator<"u"&&/Mac/.test(navigator.platform),G9e=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var is=0;is<10;is++)Wh[48+is]=Wh[96+is]=String(is);for(var is=1;is<=24;is++)Wh[is+111]="F"+is;for(var is=65;is<=90;is++)Wh[is]=String.fromCharCode(is+32),pC[is]=String.fromCharCode(is);for(var kD in Wh)pC.hasOwnProperty(kD)||(pC[kD]=Wh[kD]);function W9e(t){var e=V9e&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||G9e&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?pC:Wh)[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 K9e=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),Y9e=typeof navigator<"u"&&/Win/.test(navigator.platform);function X9e(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let r,a,s,o;for(let l=0;l{for(var n in e)J9e(t,n,{get:e[n],enumerable:!0})};function CA(t){const{state:e,transaction:n}=t;let{selection:r}=n,{doc:a}=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 a},get tr(){return r=n.selection,a=n.doc,s=n.storedMarks,n}}}var TA=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:a}=n,s=this.buildProps(a);return Object.fromEntries(Object.entries(t).map(([o,l])=>[o,(...u)=>{const d=l(...u)(s);return!a.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(a),d}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,e=!0){const{rawCommands:n,editor:r,state:a}=this,{view:s}=r,o=[],l=!!t,c=t||a.tr,u=()=>(!l&&e&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&s.dispatch(c),o.every(m=>m===!0)),d={...Object.fromEntries(Object.entries(n).map(([m,p])=>[m,(...y)=>{const v=this.buildProps(c,e),b=p(...y)(v);return o.push(b),d}])),run:u};return d}createCan(t){const{rawCommands:e,state:n}=this,r=!1,a=t||n.tr,s=this.buildProps(a,r);return{...Object.fromEntries(Object.entries(e).map(([l,c])=>[l,(...u)=>c(...u)({...s,dispatch:void 0})])),chain:()=>this.createChain(a,r)}}buildProps(t,e=!0){const{rawCommands:n,editor:r,state:a}=this,{view:s}=r,o={tr:t,editor:r,view:s,state:CA({state:a,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}},Kae={};t5(Kae,{blur:()=>eWe,clearContent:()=>tWe,clearNodes:()=>nWe,command:()=>rWe,createParagraphNear:()=>iWe,cut:()=>aWe,deleteCurrentNode:()=>sWe,deleteNode:()=>oWe,deleteRange:()=>lWe,deleteSelection:()=>cWe,enter:()=>uWe,exitCode:()=>dWe,extendMarkRange:()=>mWe,first:()=>hWe,focus:()=>fWe,forEach:()=>gWe,insertContent:()=>bWe,insertContentAt:()=>vWe,joinBackward:()=>_We,joinDown:()=>SWe,joinForward:()=>NWe,joinItemBackward:()=>kWe,joinItemForward:()=>CWe,joinTextblockBackward:()=>TWe,joinTextblockForward:()=>AWe,joinUp:()=>wWe,keyboardShortcut:()=>MWe,lift:()=>EWe,liftEmptyBlock:()=>jWe,liftListItem:()=>DWe,newlineInCode:()=>RWe,resetAttributes:()=>FWe,scrollIntoView:()=>LWe,selectAll:()=>OWe,selectNodeBackward:()=>IWe,selectNodeForward:()=>zWe,selectParentNode:()=>UWe,selectTextblockEnd:()=>BWe,selectTextblockStart:()=>HWe,setContent:()=>$We,setMark:()=>cKe,setMeta:()=>uKe,setNode:()=>dKe,setNodeSelection:()=>mKe,setTextDirection:()=>hKe,setTextSelection:()=>pKe,sinkListItem:()=>fKe,splitBlock:()=>gKe,splitListItem:()=>bKe,toggleList:()=>xKe,toggleMark:()=>yKe,toggleNode:()=>vKe,toggleWrap:()=>wKe,undoInputRule:()=>SKe,unsetAllMarks:()=>_Ke,unsetMark:()=>NKe,unsetTextDirection:()=>kKe,updateAttributes:()=>CKe,wrapIn:()=>TKe,wrapInList:()=>AKe});var eWe=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window?.getSelection())==null||n.removeAllRanges())}),!0),tWe=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),nWe=()=>({state:t,tr:e,dispatch:n})=>{const{selection:r}=e,{ranges:a}=r;return n&&a.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,m=u.resolve(d.map(c)),p=u.resolve(d.map(c+l.nodeSize)),f=m.blockRange(p);if(!f)return;const y=cy(f);if(l.type.isTextblock){const{defaultType:v}=m.parent.contentMatchAt(m.index());e.setNodeMarkup(f.start,v)}(y||y===0)&&e.lift(f,y)})}),!0},rWe=t=>e=>t(e),iWe=()=>({state:t,dispatch:e})=>lae(t,e),aWe=(t,e)=>({editor:n,tr:r})=>{const{state:a}=n,s=a.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 Dn(r.doc.resolve(Math.max(o-1,0)))),!0},sWe=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,r=n.$anchor.node();if(r.content.size>0)return!1;const a=t.selection.$anchor;for(let s=a.depth;s>0;s-=1)if(a.node(s).type===r.type){if(e){const l=a.before(s),c=a.after(s);t.delete(l,c).scrollIntoView()}return!0}return!1};function ca(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 oWe=t=>({tr:e,state:n,dispatch:r})=>{const a=ca(t,n.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===a){if(r){const c=s.before(o),u=s.after(o);e.delete(c,u).scrollIntoView()}return!0}return!1},lWe=t=>({tr:e,dispatch:n})=>{const{from:r,to:a}=t;return n&&e.delete(r,a),!0},cWe=()=>({state:t,dispatch:e})=>B4(t,e),uWe=()=>({commands:t})=>t.keyboardShortcut("Enter"),dWe=()=>({state:t,dispatch:e})=>K7e(t,e);function n5(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function fC(t,e,n={strict:!0}){const r=Object.keys(e);return r.length?r.every(a=>n.strict?e[a]===t[a]:n5(e[a])?e[a].test(t[a]):e[a]===t[a]):!0}function Yae(t,e,n={}){return t.find(r=>r.type===e&&fC(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function IK(t,e,n={}){return!!Yae(t,e,n)}function r5(t,e,n){var r;if(!t||!e)return;let a=t.parent.childAfter(t.parentOffset);if((!a.node||!a.node.marks.some(d=>d.type===e))&&(a=t.parent.childBefore(t.parentOffset)),!a.node||!a.node.marks.some(d=>d.type===e)||(n=n||((r=a.node.marks[0])==null?void 0:r.attrs),!Yae([...a.node.marks],e,n)))return;let o=a.index,l=t.start()+a.offset,c=o+1,u=l+a.node.nodeSize;for(;o>0&&IK([...t.parent.child(o-1).marks],e,n);)o-=1,l-=t.parent.child(o).nodeSize;for(;c({tr:n,state:r,dispatch:a})=>{const s=sm(t,r.schema),{doc:o,selection:l}=n,{$from:c,from:u,to:d}=l;if(a){const m=r5(c,s,e);if(m&&m.from<=u&&m.to>=d){const p=Dn.create(o,m.from,m.to);n.setSelection(p)}}return!0},hWe=t=>e=>{const n=typeof t=="function"?t(e):t;for(let r=0;r({editor:n,view:r,tr:a,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(gC()||zK())&&r.dom.focus(),pWe()&&!gC()&&!zK()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),e?.scrollIntoView&&n.commands.scrollIntoView())})};try{if(r.hasFocus()&&t===null||t===!1)return!0}catch{return!1}if(s&&t===null&&!Xae(n.state.selection))return o(),!0;const l=Qae(a.doc,t)||n.state.selection,c=n.state.selection.eq(l);return s&&(c||a.setSelection(l),c&&a.storedMarks&&a.setStoredMarks(a.storedMarks),o()),!0},gWe=(t,e)=>n=>t.every((r,a)=>e(r,{...n,index:a})),bWe=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),Zae=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&&Zae(r)}return t};function I1(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 Zae(n)}function sw(t,e,n){if(t instanceof kc||t instanceof Bt)return t;n={slice:!0,parseOptions:{},...n};const r=typeof t=="object"&&t!==null,a=typeof t=="string";if(r)try{if(Array.isArray(t)&&t.length>0)return Bt.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),sw("",e,n)}if(a){if(n.errorOnInvalidContent){let o=!1,l="";const c=new Fie({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?r0.fromSchema(c).parseSlice(I1(t),n.parseOptions):r0.fromSchema(c).parse(I1(t),n.parseOptions),n.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=r0.fromSchema(e);return n.slice?s.parseSlice(I1(t),n.parseOptions).content:s.parse(I1(t),n.parseOptions)}return sw("",e,n)}function xWe(t,e,n){const r=t.steps.length-1;if(r{o===0&&(o=d)}),t.setSelection(Kn.near(t.doc.resolve(o),n))}var yWe=t=>!("type"in t),vWe=(t,e,n)=>({tr:r,dispatch:a,editor:s})=>{var o;if(a){n={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let l;const c=b=>{s.emit("contentError",{editor:s,error:b,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{sw(e,s.schema,{parseOptions:u,errorOnInvalidContent:!0})}catch(b){c(b)}try{l=sw(e,s.schema,{parseOptions:u,errorOnInvalidContent:(o=n.errorOnInvalidContent)!=null?o:s.options.enableContentCheck})}catch(b){return c(b),!1}let{from:d,to:m}=typeof t=="number"?{from:t,to:t}:{from:t.from,to:t.to},p=!0,f=!0;if((yWe(l)?l:[l]).forEach(b=>{b.check(),p=p?b.isText&&b.marks.length===0:!1,f=f?b.isBlock:!1}),d===m&&f){const{parent:b}=r.doc.resolve(d);b.isTextblock&&!b.type.spec.code&&!b.childCount&&(d-=1,m+=1)}let v;if(p){if(Array.isArray(e))v=e.map(b=>b.text||"").join("");else if(e instanceof Bt){let b="";e.forEach(g=>{g.text&&(b+=g.text)}),v=b}else typeof e=="object"&&e&&e.text?v=e.text:v=e;r.insertText(v,d,m)}else{v=l;const b=r.doc.resolve(d),g=b.node(),_=b.parentOffset===0,N=g.isText||g.isTextblock,C=g.content.size>0;_&&N&&C&&(d=Math.max(0,d-1)),r.replaceWith(d,m,v)}n.updateSelection&&xWe(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:d,text:v}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:d,text:v})}return!0},wWe=()=>({state:t,dispatch:e})=>V7e(t,e),SWe=()=>({state:t,dispatch:e})=>G7e(t,e),_We=()=>({state:t,dispatch:e})=>tae(t,e),NWe=()=>({state:t,dispatch:e})=>aae(t,e),kWe=()=>({state:t,dispatch:e,tr:n})=>{try{const r=vA(t.doc,t.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},CWe=()=>({state:t,dispatch:e,tr:n})=>{try{const r=vA(t.doc,t.selection.$from.pos,1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},TWe=()=>({state:t,dispatch:e})=>$7e(t,e),AWe=()=>({state:t,dispatch:e})=>q7e(t,e);function Jae(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function PWe(t){const e=t.split(/-(?!$)/);let n=e[e.length-1];n==="Space"&&(n=" ");let r,a,s,o;for(let l=0;l({editor:e,view:n,tr:r,dispatch:a})=>{const s=PWe(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&&a&&r.maybeStep(d)}),!0};function Kh(t,e,n={}){const{from:r,to:a,empty:s}=t.selection,o=e?ca(e,t.schema):null,l=[];t.doc.nodesBetween(r,a,(m,p)=>{if(m.isText)return;const f=Math.max(r,p),y=Math.min(a,p+m.nodeSize);l.push({node:m,from:f,to:y})});const c=a-r,u=l.filter(m=>o?o.name===m.node.type.name:!0).filter(m=>fC(m.node.attrs,n,{strict:!1}));return s?!!u.length:u.reduce((m,p)=>m+p.to-p.from,0)>=c}var EWe=(t,e={})=>({state:n,dispatch:r})=>{const a=ca(t,n.schema);return Kh(n,a,e)?W7e(n,r):!1},jWe=()=>({state:t,dispatch:e})=>cae(t,e),DWe=t=>({state:e,dispatch:n})=>{const r=ca(t,e.schema);return aGe(r)(e,n)},RWe=()=>({state:t,dispatch:e})=>oae(t,e);function AA(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function UK(t,e){const n=typeof e=="string"?[e]:e;return Object.keys(t).reduce((r,a)=>(n.includes(a)||(r[a]=t[a]),r),{})}var FWe=(t,e)=>({tr:n,state:r,dispatch:a})=>{let s=null,o=null;const l=AA(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=ca(t,r.schema)),l==="mark"&&(o=sm(t,r.schema));let c=!1;return n.selection.ranges.forEach(u=>{r.doc.nodesBetween(u.$from.pos,u.$to.pos,(d,m)=>{s&&s===d.type&&(c=!0,a&&n.setNodeMarkup(m,void 0,UK(d.attrs,e))),o&&d.marks.length&&d.marks.forEach(p=>{o===p.type&&(c=!0,a&&n.addMark(m,m+d.nodeSize,o.create(UK(p.attrs,e))))})})}),c},LWe=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),OWe=()=>({tr:t,dispatch:e})=>{if(e){const n=new nl(t.doc);t.setSelection(n)}return!0},IWe=()=>({state:t,dispatch:e})=>rae(t,e),zWe=()=>({state:t,dispatch:e})=>sae(t,e),UWe=()=>({state:t,dispatch:e})=>Q7e(t,e),BWe=()=>({state:t,dispatch:e})=>eGe(t,e),HWe=()=>({state:t,dispatch:e})=>J7e(t,e);function nL(t,e,n={},r={}){return sw(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var $We=(t,{errorOnInvalidContent:e,emitUpdate:n=!0,parseOptions:r={}}={})=>({editor:a,tr:s,dispatch:o,commands:l})=>{const{doc:c}=s;if(r.preserveWhitespace!=="full"){const u=nL(t,a.schema,r,{errorOnInvalidContent:e??a.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??a.options.enableContentCheck})};function ese(t,e){const n=sm(e,t.schema),{from:r,to:a,empty:s}=t.selection,o=[];s?(t.storedMarks&&o.push(...t.storedMarks),o.push(...t.selection.$head.marks())):t.doc.nodesBetween(r,a,c=>{o.push(...c.marks)});const l=o.find(c=>c.type.name===n.name);return l?{...l.attrs}:{}}function tse(t,e){const n=new Qie(t);return e.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function qWe(t){for(let e=0;e{n(a)&&r.push({node:a,pos:s})}),r}function GWe(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 PA(t){return e=>GWe(e.$from,t)}function pn(t,e,n){return t.config[e]===void 0&&t.parent?pn(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?pn(t.parent,e,n):null}):t.config[e]}function i5(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},r=pn(e,"addExtensions",n);return r?[e,...i5(r())]:e}).flat(10)}function a5(t,e){const n=og.fromSchema(e).serializeFragment(t),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}function nse(t){return typeof t=="function"}function jr(t,e=void 0,...n){return nse(t)?e?t.bind(e)(...n):t(...n):t}function WWe(t={}){return Object.keys(t).length===0&&t.constructor===Object}function Lx(t){const e=t.filter(a=>a.type==="extension"),n=t.filter(a=>a.type==="node"),r=t.filter(a=>a.type==="mark");return{baseExtensions:e,nodeExtensions:n,markExtensions:r}}function rse(t){const e=[],{nodeExtensions:n,markExtensions:r}=Lx(t),a=[...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:a},c=pn(o,"addGlobalAttributes",l);if(!c)return;c().forEach(d=>{d.types.forEach(m=>{Object.entries(d.attributes).forEach(([p,f])=>{e.push({type:m,name:p,attribute:{...s,...f}})})})})}),a.forEach(o=>{const l={name:o.name,options:o.options,storage:o.storage},c=pn(o,"addAttributes",l);if(!c)return;const u=c();Object.entries(u).forEach(([d,m])=>{const p={...s,...m};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 Oi(...t){return t.filter(e=>!!e).reduce((e,n)=>{const r={...e};return Object.entries(n).forEach(([a,s])=>{if(!r[a]){r[a]=s;return}if(a==="class"){const l=s?String(s).split(" "):[],c=r[a]?r[a].split(" "):[],u=l.filter(d=>!c.includes(d));r[a]=[...c,...u].join(" ")}else if(a==="style"){const l=s?s.split(";").map(d=>d.trim()).filter(Boolean):[],c=r[a]?r[a].split(";").map(d=>d.trim()).filter(Boolean):[],u=new Map;c.forEach(d=>{const[m,p]=d.split(":").map(f=>f.trim());u.set(m,p)}),l.forEach(d=>{const[m,p]=d.split(":").map(f=>f.trim());u.set(m,p)}),r[a]=Array.from(u.entries()).map(([d,m])=>`${d}: ${m}`).join("; ")}else r[a]=s}),r},{})}function ow(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)=>Oi(n,r),{})}function KWe(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function BK(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 a=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(n):KWe(n.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...a}}}}function HK(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&WWe(n)?!1:n!=null))}function $K(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 YWe(t,e){var n;const r=rse(t),{nodeExtensions:a,markExtensions:s}=Lx(t),o=(n=a.find(u=>pn(u,"topNode")))==null?void 0:n.name,l=Object.fromEntries(a.map(u=>{const d=r.filter(g=>g.type===u.name),m={name:u.name,options:u.options,storage:u.storage,editor:e},p=t.reduce((g,_)=>{const N=pn(_,"extendNodeSchema",m);return{...g,...N?N(u):{}}},{}),f=HK({...p,content:jr(pn(u,"content",m)),marks:jr(pn(u,"marks",m)),group:jr(pn(u,"group",m)),inline:jr(pn(u,"inline",m)),atom:jr(pn(u,"atom",m)),selectable:jr(pn(u,"selectable",m)),draggable:jr(pn(u,"draggable",m)),code:jr(pn(u,"code",m)),whitespace:jr(pn(u,"whitespace",m)),linebreakReplacement:jr(pn(u,"linebreakReplacement",m)),defining:jr(pn(u,"defining",m)),isolating:jr(pn(u,"isolating",m)),attrs:Object.fromEntries(d.map($K))}),y=jr(pn(u,"parseHTML",m));y&&(f.parseDOM=y.map(g=>BK(g,d)));const v=pn(u,"renderHTML",m);v&&(f.toDOM=g=>v({node:g,HTMLAttributes:ow(g,d)}));const b=pn(u,"renderText",m);return b&&(f.toText=b),[u.name,f]})),c=Object.fromEntries(s.map(u=>{const d=r.filter(b=>b.type===u.name),m={name:u.name,options:u.options,storage:u.storage,editor:e},p=t.reduce((b,g)=>{const _=pn(g,"extendMarkSchema",m);return{...b,..._?_(u):{}}},{}),f=HK({...p,inclusive:jr(pn(u,"inclusive",m)),excludes:jr(pn(u,"excludes",m)),group:jr(pn(u,"group",m)),spanning:jr(pn(u,"spanning",m)),code:jr(pn(u,"code",m)),attrs:Object.fromEntries(d.map($K))}),y=jr(pn(u,"parseHTML",m));y&&(f.parseDOM=y.map(b=>BK(b,d)));const v=pn(u,"renderHTML",m);return v&&(f.toDOM=b=>v({mark:b,HTMLAttributes:ow(b,d)})),[u.name,f]}));return new Fie({topNode:o,nodes:l,marks:c})}function XWe(t){const e=t.filter((n,r)=>t.indexOf(n)!==r);return Array.from(new Set(e))}function bC(t){return t.sort((n,r)=>{const a=pn(n,"priority")||100,s=pn(r,"priority")||100;return a>s?-1:ar.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function ase(t,e,n){const{from:r,to:a}=e,{blockSeparator:s=` `,textSerializers:o={}}=n||{};let l="";return t.nodesBetween(r,a,(c,u,d,m)=>{var p;c.isBlock&&u>r&&(l+=s);const f=o?.[c.type.name];if(f)return d&&(l+=f({node:c,pos:u,parent:d,index:m,range:e})),!1;c.isText&&(l+=(p=c?.text)==null?void 0:p.slice(Math.max(r,u)-u,a-u))}),l}function QWe(t,e){const n={from:0,to:t.content.size};return ase(t,n,e)}function sse(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function ZWe(t,e){const n=ca(e,t.schema),{from:r,to:a}=t.selection,s=[];t.doc.nodesBetween(r,a,l=>{s.push(l)});const o=s.reverse().find(l=>l.type.name===n.name);return o?{...o.attrs}:{}}function ose(t,e){const n=AA(typeof e=="string"?e:e.name,t.schema);return n==="node"?ZWe(t,e):n==="mark"?ese(t,e):{}}function JWe(t,e=JSON.stringify){const n={};return t.filter(r=>{const a=e(r);return Object.prototype.hasOwnProperty.call(n,a)?!1:n[a]=!0})}function eKe(t){const e=JWe(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 lse(t){const{mapping:e,steps:n}=t,r=[];return e.maps.forEach((a,s)=>{const o=[];if(a.ranges.length)a.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),m=e.invert().map(u,-1),p=e.invert().map(d);r.push({oldRange:{from:m,to:p},newRange:{from:u,to:d}})})}),eKe(r)}function s5(t,e,n){const r=[];return t===e?n.resolve(t).marks().forEach(a=>{const s=n.resolve(t),o=r5(s,a.type);o&&r.push({mark:a,...o})}):n.nodesBetween(t,e,(a,s)=>{!a||a?.nodeSize===void 0||r.push(...a.marks.map(o=>({from:s,to:s+a.nodeSize,mark:o})))}),r}var tKe=(t,e,n,r=20)=>{const a=t.doc.resolve(n);let s=r,o=null;for(;s>0&&o===null;){const l=a.node(s);l?.type.name===e?o=l:s-=1}return[o,s]};function z1(t,e){return e.nodes[t]||e.marks[t]||null}function NN(t,e,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const a=t.find(s=>s.type===e&&s.name===r);return a?a.attribute.keepOnSplit:!1}))}var nKe=(t,e=500)=>{let n="";const r=t.parentOffset;return t.parent.nodesBetween(Math.max(0,r-e),r,(a,s,o,l)=>{var c,u;const d=((u=(c=a.type.spec).toText)==null?void 0:u.call(c,{node:a,pos:s,parent:o,index:l}))||a.textContent||"%leaf%";n+=a.isAtom&&!a.isText?d:d.slice(0,Math.max(0,r-s))}),n};function rL(t,e,n={}){const{empty:r,ranges:a}=t.selection,s=e?sm(e,t.schema):null;if(r)return!!(t.storedMarks||t.selection.$from.marks()).filter(m=>s?s.name===m.type.name:!0).find(m=>fC(m.attrs,n,{strict:!1}));let o=0;const l=[];if(a.forEach(({$from:m,$to:p})=>{const f=m.pos,y=p.pos;t.doc.nodesBetween(f,y,(v,b)=>{if(!v.isText&&!v.marks.length)return;const g=Math.max(f,b),_=Math.min(y,b+v.nodeSize),N=_-g;o+=N,l.push(...v.marks.map(C=>({mark:C,from:g,to:_})))})}),o===0)return!1;const c=l.filter(m=>s?s.name===m.mark.type.name:!0).filter(m=>fC(m.mark.attrs,n,{strict:!1})).reduce((m,p)=>m+p.to-p.from,0),u=l.filter(m=>s?m.mark.type!==s&&m.mark.type.excludes(s):!0).reduce((m,p)=>m+p.to-p.from,0);return(c>0?c+u:c)>=o}function rKe(t,e,n={}){if(!e)return Kh(t,null,n)||rL(t,null,n);const r=AA(e,t.schema);return r==="node"?Kh(t,e,n):r==="mark"?rL(t,e,n):!1}var iKe=(t,e)=>{const{$from:n,$to:r,$anchor:a}=t.selection;if(e){const s=PA(l=>l.type.name===e)(t.selection);if(!s)return!1;const o=t.doc.resolve(s.pos+1);return a.pos+1===o.end()}return!(r.parentOffset{const{$from:e,$to:n}=t.selection;return!(e.parentOffset>0||e.pos!==n.pos)};function qK(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function VK(t,e){const{nodeExtensions:n}=Lx(e),r=n.find(o=>o.name===t);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},s=jr(pn(r,"group",a));return typeof s!="string"?!1:s.split(" ").includes("list")}function MA(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 a=!0;return t.content.forEach(s=>{a!==!1&&(MA(s,{ignoreWhitespace:n,checkChildren:e})||(a=!1))}),a}return!1}function cse(t){return t instanceof yn}var use=class dse{constructor(e){this.position=e}static fromJSON(e){return new dse(e.position)}toJSON(){return{position:this.position}}};function sKe(t,e){const n=e.mapping.mapResult(t.position);return{position:new use(n.pos),mapResult:n}}function oKe(t){return new use(t)}function lKe(t,e,n){var r;const{selection:a}=e;let s=null;if(Xae(a)&&(s=a.$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}=a;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,m,p)=>{if(u)return!1;if(d.isInline){const f=!p||p.type.allowsMarkType(n),y=!!n.isInSet(d.marks)||!d.marks.some(v=>v.type.excludes(n));u=f&&y}return!u}),u})}var cKe=(t,e={})=>({tr:n,state:r,dispatch:a})=>{const{selection:s}=n,{empty:o,ranges:l}=s,c=sm(t,r.schema);if(a)if(o){const u=ese(r,c);n.addStoredMark(c.create({...u,...e}))}else l.forEach(u=>{const d=u.$from.pos,m=u.$to.pos;r.doc.nodesBetween(d,m,(p,f)=>{const y=Math.max(f,d),v=Math.min(f+p.nodeSize,m);p.marks.find(g=>g.type===c)?p.marks.forEach(g=>{c===g.type&&n.addMark(y,v,c.create({...g.attrs,...e}))}):n.addMark(y,v,c.create(e))})});return lKe(r,n,c)},uKe=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),dKe=(t,e={})=>({state:n,dispatch:r,chain:a})=>{const s=ca(t,n.schema);let o;return n.selection.$anchor.sameParent(n.selection.$head)&&(o=n.selection.$anchor.parent.attrs),s.isTextblock?a().command(({commands:l})=>iK(s,{...o,...e})(n)?!0:l.clearNodes()).command(({state:l})=>iK(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},mKe=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,a=uf(t,0,r.content.size),s=yn.create(r,a);e.setSelection(s)}return!0},hKe=(t,e)=>({tr:n,state:r,dispatch:a})=>{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),a&&n.doc.nodesBetween(o,l,(c,u)=>{c.isText||n.setNodeMarkup(u,void 0,{...c.attrs,dir:t})}),!0},pKe=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,{from:a,to:s}=typeof t=="number"?{from:t,to:t}:t,o=Dn.atStart(r).from,l=Dn.atEnd(r).to,c=uf(a,o,l),u=uf(s,o,l),d=Dn.create(r,c,u);e.setSelection(d)}return!0},fKe=t=>({state:e,dispatch:n})=>{const r=ca(t,e.schema);return lGe(r)(e,n)};function GK(t,e){const n=t.storedMarks||t.selection.$to.parentOffset&&t.selection.$from.marks();if(n){const r=n.filter(a=>e?.includes(a.type.name));t.tr.ensureMarks(r)}}var gKe=({keepMarks:t=!0}={})=>({tr:e,state:n,dispatch:r,editor:a})=>{const{selection:s,doc:o}=e,{$from:l,$to:c}=s,u=a.extensionManager.attributes,d=NN(u,l.node().type.name,l.node().attrs);if(s instanceof yn&&s.node.isBlock)return!l.parentOffset||!Od(o,l.pos)?!1:(r&&(t&&GK(n,a.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const m=c.parentOffset===c.parent.content.size,p=l.depth===0?void 0:qWe(l.node(-1).contentMatchAt(l.indexAfter(-1)));let f=m&&p?[{type:p,attrs:d}]:void 0,y=Od(e.doc,e.mapping.map(l.pos),1,f);if(!f&&!y&&Od(e.doc,e.mapping.map(l.pos),1,p?[{type:p}]:void 0)&&(y=!0,f=p?[{type:p,attrs:d}]:void 0),r){if(y&&(s instanceof Dn&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,f),p&&!m&&!l.parentOffset&&l.parent.type!==p)){const v=e.mapping.map(l.before()),b=e.doc.resolve(v);l.node(-1).canReplaceWith(b.index(),b.index()+1,p)&&e.setNodeMarkup(e.mapping.map(l.before()),p)}t&&GK(n,a.extensionManager.splittableMarks),e.scrollIntoView()}return y},bKe=(t,e={})=>({tr:n,state:r,dispatch:a,editor:s})=>{var o;const l=ca(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 m=c.node(-1);if(m.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(a){let g=Bt.empty;const _=c.index(-1)?1:c.index(-2)?2:3;for(let D=c.depth-_;D>=c.depth-3;D-=1)g=Bt.from(c.node(D).copy(g));const N=c.indexAfter(-1){if(T>-1)return!1;D.isTextblock&&D.content.size===0&&(T=A+1)}),T>-1&&n.setSelection(Dn.near(n.doc.resolve(T))),n.scrollIntoView()}return!0}const f=u.pos===c.end()?m.contentMatchAt(0).defaultType:null,y={...NN(p,m.type.name,m.attrs),...e},v={...NN(p,c.node().type.name,c.node().attrs),...e};n.delete(c.pos,u.pos);const b=f?[{type:l,attrs:y},{type:f,attrs:v}]:[{type:l,attrs:y}];if(!Od(n.doc,c.pos,2))return!1;if(a){const{selection:g,storedMarks:_}=r,{splittableMarks:N}=s.extensionManager,C=_||g.$to.parentOffset&&g.$from.marks();if(n.split(c.pos,2,b).scrollIntoView(),!C||!a)return!0;const k=C.filter(P=>N.includes(P.type.name));n.ensureMarks(k)}return!0},TD=(t,e)=>{const n=PA(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 a=t.doc.nodeAt(r);return n.node.type===a?.type&&tp(t.doc,n.pos)&&t.join(n.pos),!0},AD=(t,e)=>{const n=PA(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 a=t.doc.nodeAt(r);return n.node.type===a?.type&&tp(t.doc,r)&&t.join(r),!0},xKe=(t,e,n,r={})=>({editor:a,tr:s,state:o,dispatch:l,chain:c,commands:u,can:d})=>{const{extensions:m,splittableMarks:p}=a.extensionManager,f=ca(t,o.schema),y=ca(e,o.schema),{selection:v,storedMarks:b}=o,{$from:g,$to:_}=v,N=g.blockRange(_),C=b||v.$to.parentOffset&&v.$from.marks();if(!N)return!1;const k=PA(P=>VK(P.type.name,m))(v);if(N.depth>=1&&k&&N.depth-k.depth<=1){if(k.node.type===f)return u.liftListItem(y);if(VK(k.node.type.name,m)&&f.validContent(k.node.content)&&l)return c().command(()=>(s.setNodeMarkup(k.pos,f),!0)).command(()=>TD(s,f)).command(()=>AD(s,f)).run()}return!n||!C||!l?c().command(()=>d().wrapInList(f,r)?!0:u.clearNodes()).wrapInList(f,r).command(()=>TD(s,f)).command(()=>AD(s,f)).run():c().command(()=>{const P=d().wrapInList(f,r),T=C.filter(D=>p.includes(D.type.name));return s.ensureMarks(T),P?!0:u.clearNodes()}).wrapInList(f,r).command(()=>TD(s,f)).command(()=>AD(s,f)).run()},yKe=(t,e={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:s=!1}=n,o=sm(t,r.schema);return rL(r,o,e)?a.unsetMark(o,{extendEmptyMarkRange:s}):a.setMark(o,e)},vKe=(t,e,n={})=>({state:r,commands:a})=>{const s=ca(t,r.schema),o=ca(e,r.schema),l=Kh(r,s,n);let c;return r.selection.$anchor.sameParent(r.selection.$head)&&(c=r.selection.$anchor.parent.attrs),l?a.setNode(o,c):a.setNode(s,{...c,...n})},wKe=(t,e={})=>({state:n,commands:r})=>{const a=ca(t,n.schema);return Kh(n,a,e)?r.lift(a):r.wrapIn(a,e)},SKe=()=>({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},_Ke=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,{empty:r,ranges:a}=n;return r||e&&a.forEach(s=>{t.removeMark(s.$from.pos,s.$to.pos)}),!0},NKe=(t,e={})=>({tr:n,state:r,dispatch:a})=>{var s;const{extendEmptyMarkRange:o=!1}=e,{selection:l}=n,c=sm(t,r.schema),{$from:u,empty:d,ranges:m}=l;if(!a)return!0;if(d&&o){let{from:p,to:f}=l;const y=(s=u.marks().find(b=>b.type===c))==null?void 0:s.attrs,v=r5(u,c,y);v&&(p=v.from,f=v.to),n.removeMark(p,f,c)}else m.forEach(p=>{n.removeMark(p.$from.pos,p.$to.pos,c)});return n.removeStoredMark(c),!0},kKe=t=>({tr:e,state:n,dispatch:r})=>{const{selection:a}=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=a.from,o=a.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},CKe=(t,e={})=>({tr:n,state:r,dispatch:a})=>{let s=null,o=null;const l=AA(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=ca(t,r.schema)),l==="mark"&&(o=sm(t,r.schema));let c=!1;return n.selection.ranges.forEach(u=>{const d=u.$from.pos,m=u.$to.pos;let p,f,y,v;n.selection.empty?r.doc.nodesBetween(d,m,(b,g)=>{s&&s===b.type&&(c=!0,y=Math.max(g,d),v=Math.min(g+b.nodeSize,m),p=g,f=b)}):r.doc.nodesBetween(d,m,(b,g)=>{g=d&&g<=m&&(s&&s===b.type&&(c=!0,a&&n.setNodeMarkup(g,void 0,{...b.attrs,...e})),o&&b.marks.length&&b.marks.forEach(_=>{if(o===_.type&&(c=!0,a)){const N=Math.max(g,d),C=Math.min(g+b.nodeSize,m);n.addMark(N,C,o.create({..._.attrs,...e}))}}))}),f&&(p!==void 0&&a&&n.setNodeMarkup(p,void 0,{...f.attrs,...e}),o&&f.marks.length&&f.marks.forEach(b=>{o===b.type&&a&&n.addMark(y,v,o.create({...b.attrs,...e}))}))}),c},TKe=(t,e={})=>({state:n,dispatch:r})=>{const a=ca(t,n.schema);return tGe(a,e)(n,r)},AKe=(t,e={})=>({state:n,dispatch:r})=>{const a=ca(t,n.schema);return nGe(a,e)(n,r)},PKe=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={}}},EA=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},MKe=(t,e)=>{if(n5(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 U1(t){var e;const{editor:n,from:r,to:a,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 m=nKe(u)+s;return o.forEach(p=>{if(d)return;const f=MKe(m,p.find);if(!f)return;const y=c.state.tr,v=CA({state:c.state,transaction:y}),b={from:r-(f[0].length-s.length),to:a},{commands:g,chain:_,can:N}=new TA({editor:n,state:v});p.handler({state:v,range:b,match:f,commands:g,chain:_,can:N})===null||!y.steps.length||(p.undoable&&y.setMeta(l,{transform:y,from:r,to:a,text:s}),c.dispatch(y),d=!0)}),d}function EKe(t){const{editor:e,rules:n}=t,r=new _i({state:{init(){return null},apply(a,s,o){const l=a.getMeta(r);if(l)return l;const c=a.getMeta("applyInputRules");return c&&setTimeout(()=>{let{text:d}=c;typeof d=="string"?d=d:d=a5(Bt.from(d),o.schema);const{from:m}=c,p=m+d.length;U1({editor:e,from:m,to:p,text:d,rules:n,plugin:r})}),a.selectionSet||a.docChanged?null:s}},props:{handleTextInput(a,s,o,l){return U1({editor:e,from:s,to:o,text:l,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:s}=a.state.selection;s&&U1({editor:e,from:s.pos,to:s.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(a,s){if(s.key!=="Enter")return!1;const{$cursor:o}=a.state.selection;return o?U1({editor:e,from:o.pos,to:o.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function jKe(t){return Object.prototype.toString.call(t).slice(8,-1)}function B1(t){return jKe(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function mse(t,e){const n={...t};return B1(t)&&B1(e)&&Object.keys(e).forEach(r=>{B1(e[r])&&B1(t[r])?n[r]=mse(t[r],e[r]):n[r]=e[r]}),n}var o5=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{...jr(pn(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...jr(pn(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>mse(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}},rp=class hse extends o5{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new hse(n)}static handleExit({editor:e,mark:n}){const{tr:r}=e.state,a=e.state.selection.$from;if(a.pos===a.end()){const o=a.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(" ",a.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 DKe(t){return typeof t=="number"}var RKe=class{constructor(t){this.find=t.find,this.handler=t.handler}},FKe=(t,e,n)=>{if(n5(e))return[...t.matchAll(e)];const r=e(t,n);return r?r.map(a=>{const s=[a.text];return s.index=a.index,s.input=t,s.data=a.data,a.replaceWith&&(a.text.includes(a.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),s.push(a.replaceWith)),s}):[]};function LKe(t){const{editor:e,state:n,from:r,to:a,rule:s,pasteEvent:o,dropEvent:l}=t,{commands:c,chain:u,can:d}=new TA({editor:e,state:n}),m=[];return n.doc.nodesBetween(r,a,(f,y)=>{var v,b,g,_,N;if((b=(v=f.type)==null?void 0:v.spec)!=null&&b.code||!(f.isText||f.isTextblock||f.isInline))return;const C=(N=(_=(g=f.content)==null?void 0:g.size)!=null?_:f.nodeSize)!=null?N:0,k=Math.max(r,y),P=Math.min(a,y+C);if(k>=P)return;const T=f.isText?f.text||"":f.textBetween(k-y,P-y,void 0,"");FKe(T,s.find,o).forEach(A=>{if(A.index===void 0)return;const R=k+A.index+1,G=R+A[0].length,z={from:n.tr.mapping.map(R),to:n.tr.mapping.map(G)},Z=s.handler({state:n,range:z,match:A,commands:c,chain:u,can:d,pasteEvent:o,dropEvent:l});m.push(Z)})}),m.every(f=>f!==null)}var H1=null,OKe=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function IKe(t){const{editor:e,rules:n}=t;let r=null,a=!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:m,to:p,rule:f,pasteEvt:y})=>{const v=d.tr,b=CA({state:d,transaction:v});if(!(!LKe({editor:e,state:b,from:Math.max(m-1,0),to:p.b-1,rule:f,pasteEvent:y,dropEvent:l})||!v.steps.length)){try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}return o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,v}};return n.map(d=>new _i({view(m){const p=y=>{var v;r=(v=m.dom.parentElement)!=null&&v.contains(y.target)?m.dom.parentElement:null,r&&(H1=e)},f=()=>{H1&&(H1=null)};return window.addEventListener("dragstart",p),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",p),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(m,p)=>{if(s=r===m.dom.parentElement,l=p,!s){const f=H1;f?.isEditable&&setTimeout(()=>{const y=f.state.selection;y&&f.commands.deleteRange({from:y.from,to:y.to})},10)}return!1},paste:(m,p)=>{var f;const y=(f=p.clipboardData)==null?void 0:f.getData("text/html");return o=p,a=!!y?.includes("data-pm-slice"),!1}}},appendTransaction:(m,p,f)=>{const y=m[0],v=y.getMeta("uiEvent")==="paste"&&!a,b=y.getMeta("uiEvent")==="drop"&&!s,g=y.getMeta("applyPasteRules"),_=!!g;if(!v&&!b&&!_)return;if(_){let{text:k}=g;typeof k=="string"?k=k:k=a5(Bt.from(k),f.schema);const{from:P}=g,T=P+k.length,D=OKe(k);return c({rule:d,state:f,from:P,to:{b:T},pasteEvt:D})}const N=p.doc.content.findDiffStart(f.doc.content),C=p.doc.content.findDiffEnd(f.doc.content);if(!(!DKe(N)||!C||N===C.b))return c({rule:d,state:f,from:N,to:C,pasteEvt:o})}}))}var jA=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=ise(t),this.schema=YWe(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:z1(e.name,this.schema)},r=pn(e,"addCommands",n);return r?{...t,...r()}:t},{})}get plugins(){const{editor:t}=this;return bC([...this.extensions].reverse()).flatMap(r=>{const a={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:z1(r.name,this.schema)},s=[],o=pn(r,"addKeyboardShortcuts",a);let l={};if(r.type==="mark"&&pn(r,"exitable",a)&&(l.ArrowRight=()=>rp.handleExit({editor:t,mark:r})),o){const p=Object.fromEntries(Object.entries(o()).map(([f,y])=>[f,()=>y({editor:t})]));l={...l,...p}}const c=Z9e(l);s.push(c);const u=pn(r,"addInputRules",a);if(qK(r,t.options.enableInputRules)&&u){const p=u();if(p&&p.length){const f=EKe({editor:t,rules:p}),y=Array.isArray(f)?f:[f];s.push(...y)}}const d=pn(r,"addPasteRules",a);if(qK(r,t.options.enablePasteRules)&&d){const p=d();if(p&&p.length){const f=IKe({editor:t,rules:p});s.push(...f)}}const m=pn(r,"addProseMirrorPlugins",a);if(m){const p=m();s.push(...p)}return s})}get attributes(){return rse(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=Lx(this.extensions);return Object.fromEntries(e.filter(n=>!!pn(n,"addNodeView")).map(n=>{const r=this.attributes.filter(c=>c.type===n.name),a={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:ca(n.name,this.schema)},s=pn(n,"addNodeView",a);if(!s)return[];const o=s();if(!o)return[];const l=(c,u,d,m,p)=>{const f=ow(c,r);return o({node:c,view:u,getPos:d,decorations:m,innerDecorations:p,editor:t,extension:n,HTMLAttributes:f})};return[n.name,l]}))}dispatchTransaction(t){const{editor:e}=this;return bC([...this.extensions].reverse()).reduceRight((r,a)=>{const s={name:a.name,options:a.options,storage:this.editor.extensionStorage[a.name],editor:e,type:z1(a.name,this.schema)},o=pn(a,"dispatchTransaction",s);return o?l=>{o.call(s,{transaction:l,next:r})}:r},t)}get markViews(){const{editor:t}=this,{markExtensions:e}=Lx(this.extensions);return Object.fromEntries(e.filter(n=>!!pn(n,"addMarkView")).map(n=>{const r=this.attributes.filter(l=>l.type===n.name),a={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:sm(n.name,this.schema)},s=pn(n,"addMarkView",a);if(!s)return[];const o=(l,c,u)=>{const d=ow(l,r);return s()({mark:l,view:c,inline:u,editor:t,extension:n,HTMLAttributes:d,updateAttributes:m=>{JKe(l,t,m)}})};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:z1(e.name,this.schema)};e.type==="mark"&&((n=jr(pn(e,"keepOnSplit",r)))==null||n)&&this.splittableMarks.push(e.name);const a=pn(e,"onBeforeCreate",r),s=pn(e,"onCreate",r),o=pn(e,"onUpdate",r),l=pn(e,"onSelectionUpdate",r),c=pn(e,"onTransaction",r),u=pn(e,"onFocus",r),d=pn(e,"onBlur",r),m=pn(e,"onDestroy",r);a&&this.editor.on("beforeCreate",a),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),m&&this.editor.on("destroy",m)})}};jA.resolve=ise;jA.sort=bC;jA.flatten=i5;var zKe={};t5(zKe,{ClipboardTextSerializer:()=>fse,Commands:()=>gse,Delete:()=>bse,Drop:()=>xse,Editable:()=>yse,FocusEvents:()=>wse,Keymap:()=>Sse,Paste:()=>_se,Tabindex:()=>Nse,TextDirection:()=>kse,focusEventsPluginKey:()=>vse});var Vr=class pse extends o5{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new pse(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},fse=Vr.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new _i({key:new Na("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:t}=this,{state:e,schema:n}=t,{doc:r,selection:a}=e,{ranges:s}=a,o=Math.min(...s.map(d=>d.$from.pos)),l=Math.max(...s.map(d=>d.$to.pos)),c=sse(n);return ase(r,{from:o,to:l},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),gse=Vr.create({name:"commands",addCommands(){return{...Kae}}}),bse=Vr.create({name:"delete",onUpdate({transaction:t,appendedTransactions:e}){var n,r,a;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=tse(t.before,[t,...e]);lse(d).forEach(f=>{d.mapping.mapResult(f.oldRange.from).deletedAfter&&d.mapping.mapResult(f.oldRange.to).deletedBefore&&d.before.nodesBetween(f.oldRange.from,f.oldRange.to,(y,v)=>{const b=v+y.nodeSize-2,g=f.oldRange.from<=v&&b<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:y,from:v,to:b,newFrom:d.mapping.map(v),newTo:d.mapping.map(b),deletedRange:f.oldRange,newRange:f.newRange,partial:!g,editor:this.editor,transaction:t,combinedTransform:d})})});const p=d.mapping;d.steps.forEach((f,y)=>{var v,b;if(f instanceof _c){const g=p.slice(y).map(f.from,-1),_=p.slice(y).map(f.to),N=p.invert().map(g,-1),C=p.invert().map(_),k=(v=d.doc.nodeAt(g-1))==null?void 0:v.marks.some(T=>T.eq(f.mark)),P=(b=d.doc.nodeAt(_))==null?void 0:b.marks.some(T=>T.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:N,to:C},newRange:{from:g,to:_},partial:!!(P||k),editor:this.editor,transaction:t,combinedTransform:d})}})};(a=(r=(n=this.editor.options.coreExtensionOptions)==null?void 0:n.delete)==null?void 0:r.async)==null||a?setTimeout(s,0):s()}}),xse=Vr.create({name:"drop",addProseMirrorPlugins(){return[new _i({key:new Na("tiptapDrop"),props:{handleDrop:(t,e,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:r})}}})]}}),yse=Vr.create({name:"editable",addProseMirrorPlugins(){return[new _i({key:new Na("editable"),props:{editable:()=>this.editor.options.editable}})]}}),vse=new Na("focusEvents"),wse=Vr.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new _i({key:vse,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}}}})]}}),Sse=Vr.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:m}=c,{pos:p,parent:f}=m,y=m.parent.isTextblock&&p>0?l.doc.resolve(p-1):m,v=y.parent.type.spec.isolating,b=m.pos-m.parentOffset,g=v&&y.parent.childCount===1?b===m.pos:Kn.atStart(u).from===p;return!d||!f.type.isTextblock||f.textContent.length||!g||g&&m.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()},a={...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 gC()||Jae()?s:a},addProseMirrorPlugins(){return[new _i({key:new Na("clearDocument"),appendTransaction:(t,e,n)=>{if(t.some(v=>v.getMeta("composition")))return;const r=t.some(v=>v.docChanged)&&!e.doc.eq(n.doc),a=t.some(v=>v.getMeta("preventClearDocument"));if(!r||a)return;const{empty:s,from:o,to:l}=e.selection,c=Kn.atStart(e.doc).from,u=Kn.atEnd(e.doc).to;if(s||!(o===c&&l===u)||!MA(n.doc))return;const p=n.tr,f=CA({state:n,transaction:p}),{commands:y}=new TA({editor:this.editor,state:f});if(y.clearNodes(),!!p.steps.length)return p}})]}}),_se=Vr.create({name:"paste",addProseMirrorPlugins(){return[new _i({key:new Na("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),Nse=Vr.create({name:"tabindex",addProseMirrorPlugins(){return[new _i({key:new Na("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),kse=Vr.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=Lx(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 _i({key:new Na("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),UKe=class Hv{constructor(e,n,r=!1,a=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=n,this.currentNode=a}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 Hv(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 Hv(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 Hv(e,this.editor)}get children(){const e=[];return this.node.content.forEach((n,r)=>{const a=n.isBlock&&!n.isTextblock,s=n.isAtom&&!n.isText,o=n.isInline,l=this.pos+r+(s?0:1);if(l<0||l>this.resolvedPos.doc.nodeSize-2)return;const c=this.resolvedPos.doc.resolve(l);if(!a&&!o&&c.depth<=this.depth)return;const u=new Hv(c,this.editor,a,a||o?n:null);a&&(u.actualDepth=this.depth+1),e.push(u)}),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,a=this.parent;for(;a&&!r;){if(a.node.type.name===e)if(Object.keys(n).length>0){const s=a.node.attrs,o=Object.keys(n);for(let l=0;l{r&&a.length>0||(o.node.type.name===e&&s.every(c=>n[c]===o.node.attrs[c])&&a.push(o),!(r&&a.length>0)&&(a=a.concat(o.querySelectorAll(e,n,r))))}),a}setAttribute(e){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(n)}},BKe=`.ProseMirror { @@ -8623,7 +8623,7 @@ img.ProseMirror-separator { display: block; }`;function HKe(t,e,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const a=document.createElement("style");return e&&a.setAttribute("nonce",e),a.setAttribute("data-tiptap-style",""),a.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(a),a}var $Ke=class extends PKe{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,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:sKe,createMappablePosition:oKe},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:a,moved:s})=>this.options.onDrop(r,a,s)),this.on("paste",({event:r,slice:a})=>this.options.onPaste(r,a)),this.on("delete",this.options.onDelete);const e=this.createDoc(),n=Qae(e,this.options.autofocus);this.editorState=Vb.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=HKe(BKe,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=nse(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(a=>{const s=typeof a=="string"?`${a}$`:a.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?[yse,fse.configure({blockSeparator:(e=(t=this.options.coreExtensionOptions)==null?void 0:t.clipboardTextSerializer)==null?void 0:e.blockSeparator}),gse,wse,Sse,Nse,xse,_se,bse,kse.configure({direction:this.options.textDirection})].filter(a=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[a.name]!==!1:!0):[],...this.options.extensions].filter(a=>["extension","node","mark"].includes(a?.type));this.extensionManager=new jA(r,this)}createCommandManager(){this.commandManager=new TA({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let t;try{t=nL(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=nL(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return t}createView(t){const{editorProps:e,enableExtensionDispatchTransaction:n}=this.options,r=e.dispatchTransaction||this.dispatchTransaction.bind(this),a=n?this.extensionManager.dispatchTransaction(r):r;this.editorView=new Gae(t,{...e,attributes:{role:"textbox",...e?.attributes},dispatchTransaction:a,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const s=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(s),this.prependClass(),this.injectCSS();const o=this.view.dom;o.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),a=n.includes(t),s=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:t,nextState:e}),!a)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 ose(this.state,t)}isActive(t,e){const n=typeof t=="string"?t:null,r=typeof t=="string"?e:t;return rKe(this.state,n,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return a5(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:e=` -`,textSerializers:n={}}=t||{};return QWe(this.state.doc,{blockSeparator:e,textSerializers:{...sse(this.schema),...n}})}get isEmpty(){return MA(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 UKe(e,this)}get $doc(){return this.$pos(0)}};function Ox(t){return new EA({find:t.find,handler:({state:e,range:n,match:r})=>{const a=jr(t.getAttributes,void 0,r);if(a===!1||a===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(s5(n.from,n.to,e.doc).filter(f=>f.mark.type.excluded.find(v=>v===t.type&&v!==f.mark.type)).filter(f=>f.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(a||{})),s.removeStoredMark(t.type)}},undoable:t.undoable})}function Cse(t){return new EA({find:t.find,handler:({state:e,range:n,match:r})=>{const a=jr(t.getAttributes,void 0,r)||{},{tr:s}=e,o=n.from;let l=n.to;const c=t.type.create(a);if(r[1]){const u=r[0].lastIndexOf(r[1]);let d=o+u;d>l?d=l:l=d+r[1].length;const m=r[0][r[0].length-1];s.insertText(m,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(a)).delete(s.mapping.map(o),s.mapping.map(l))}s.scrollIntoView()},undoable:t.undoable})}function iL(t){return new EA({find:t.find,handler:({state:e,range:n,match:r})=>{const a=e.doc.resolve(n.from),s=jr(t.getAttributes,void 0,r)||{};if(!a.node(-1).canReplaceWith(a.index(-1),a.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 Ix(t){return new EA({find:t.find,handler:({state:e,range:n,match:r,chain:a})=>{const s=jr(t.getAttributes,void 0,r)||{},o=e.tr.delete(n.from,n.to),c=o.doc.resolve(n.from).blockRange(),u=c&&zI(c,t.type,s);if(!u)return null;if(o.wrap(c,u),t.keepMarks&&t.editor){const{selection:m,storedMarks:p}=e,{splittableMarks:f}=t.editor.extensionManager,y=p||m.$to.parentOffset&&m.$from.marks();if(y){const v=y.filter(b=>f.includes(b.type.name));o.ensureMarks(v)}}if(t.keepAttributes){const m=t.type.name==="bulletList"||t.type.name==="orderedList"?"listItem":"taskList";a().updateAttributes(m,s).run()}const d=o.doc.resolve(n.from-1).nodeBefore;d&&d.type===t.type&&tp(o.doc,n.from-1)&&(!t.joinPredicate||t.joinPredicate(r,d))&&o.join(n.from-1)},undoable:t.undoable})}var qKe=t=>"touches"in t,VKe=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.lastEditableState=void 0,this.handleMap=new Map,this.handleMouseMove=l=>{if(!this.isResizing||!this.activeHandle)return;const c=l.clientX-this.startX,u=l.clientY-this.startY;this.handleResize(c,u)},this.handleTouchMove=l=>{if(!this.isResizing||!this.activeHandle)return;const c=l.touches[0];if(!c)return;const u=c.clientX-this.startX,d=c.clientY-this.startY;this.handleResize(u,d)},this.handleMouseUp=()=>{if(!this.isResizing)return;const l=this.element.offsetWidth,c=this.element.offsetHeight;this.onCommit(l,c),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=l=>{l.key==="Shift"&&(this.isShiftKeyPressed=!0)},this.handleKeyUp=l=>{l.key==="Shift"&&(this.isShiftKeyPressed=!1)};var e,n,r,a,s,o;this.node=t.node,this.editor=t.editor,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),(a=t.options)!=null&&a.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||""}),(o=t.options)!=null&&o.createCustomHandle&&(this.createCustomHandle=t.options.createCustomHandle),this.wrapper=this.createWrapper(),this.container=this.createContainer(),this.applyInitialSize(),this.attachHandles(),this.editor.on("update",this.handleEditorUpdate.bind(this))}get dom(){return this.container}get contentDOM(){var t;return(t=this.contentElement)!=null?t:null}handleEditorUpdate(){const t=this.editor.isEditable;t!==this.lastEditableState&&(this.lastEditableState=t,t?t&&this.handleMap.size===0&&this.attachHandles():this.removeHandles())}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.editor.off("update",this.handleEditorUpdate.bind(this)),this.container.remove()}createContainer(){const t=document.createElement("div");return t.dataset.resizeContainer="",t.dataset.node=this.node.type.name,t.style.display="flex",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"),a=e.includes("left"),s=e.includes("right");n&&(t.style.top="0"),r&&(t.style.bottom="0"),a&&(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=>{let e;this.createCustomHandle?e=this.createCustomHandle(t):e=this.createHandle(t),e instanceof HTMLElement||(console.warn(`[ResizableNodeView] createCustomHandle("${t}") did not return an HTMLElement. Falling back to default handle.`),e=this.createHandle(t)),this.createCustomHandle||this.positionHandle(e,t),e.addEventListener("mousedown",n=>this.handleResizeStart(n,t)),e.addEventListener("touchstart",n=>this.handleResizeStart(n,t)),this.handleMap.set(t,e),this.wrapper.appendChild(e)})}removeHandles(){this.handleMap.forEach(t=>t.remove()),this.handleMap.clear()}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,qKe(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:a}=this.calculateNewDimensions(this.activeHandle,t,e),s=this.applyConstraints(r,a,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,a=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?a=this.startHeight+n:c&&(a=this.startHeight-n),(t==="right"||t==="left")&&(r=this.startWidth+(s?e:-e)),(t==="top"||t==="bottom")&&(a=this.startHeight+(l?n:-n)),this.preserveAspectRatio||this.isShiftKeyPressed?this.applyAspectRatio(r,a,t):{width:r,height:a}}applyConstraints(t,e,n){var r,a,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)),(a=this.maxSize)!=null&&a.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",a=n==="top"||n==="bottom";return r?{width:t,height:t/this.aspectRatio}:a?{width:e*this.aspectRatio,height:e}:{width:t,height:t/this.aspectRatio}}};function GKe(t,e){const{selection:n}=t,{$from:r}=n;if(n instanceof yn){const s=r.index();return r.parent.canReplaceWith(s,s+1,e)}let a=r.depth;for(;a>=0;){const s=r.index(a);if(r.node(a).contentMatchAt(s).matchType(e))return!0;a-=1}return!1}var WKe={};t5(WKe,{createAtomBlockMarkdownSpec:()=>KKe,createBlockMarkdownSpec:()=>YKe,createInlineMarkdownSpec:()=>ZKe,parseAttributes:()=>l5,parseIndentedBlocks:()=>aL,renderNestedMarkdownContent:()=>u5,serializeAttributes:()=>c5});function l5(t){if(!t?.trim())return{};const e={},n=[],r=t.replace(/["']([^"']*)["']/g,u=>(n.push(u),`__QUOTED_${n.length-1}__`)),a=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(a){const u=a.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 m;const p=parseInt(((m=d.match(/__QUOTED_(\d+)__/))==null?void 0:m[1])||"0",10),f=n[p];f&&(e[u]=f.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 c5(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 KKe(t){const{nodeName:e,name:n,parseAttributes:r=l5,serializeAttributes:a=c5,defaultAttributes:s={},requiredAttributes:o=[],allowedAttributes:l}=t,c=n||e,u=d=>{if(!l)return d;const m={};return l.forEach(p=>{p in d&&(m[p]=d[p])}),m};return{parseMarkdown:(d,m)=>{const p={...s,...d.attributes};return m.createNode(e,p,[])},markdownTokenizer:{name:e,level:"block",start(d){var m;const p=new RegExp(`^:::${c}(?:\\s|$)`,"m"),f=(m=d.match(p))==null?void 0:m.index;return f!==void 0?f:-1},tokenize(d,m,p){const f=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),y=d.match(f);if(!y)return;const v=y[1]||"",b=r(v);if(!o.find(_=>!(_ in b)))return{type:e,raw:y[0],attributes:b}}},renderMarkdown:d=>{const m=u(d.attrs||{}),p=a(m),f=p?` {${p}}`:"";return`:::${c}${f} :::`}}}function YKe(t){const{nodeName:e,name:n,getContent:r,parseAttributes:a=l5,serializeAttributes:s=c5,defaultAttributes:o={},content:l="block",allowedAttributes:c}=t,u=n||e,d=m=>{if(!c)return m;const p={};return c.forEach(f=>{f in m&&(p[f]=m[f])}),p};return{parseMarkdown:(m,p)=>{let f;if(r){const v=r(m);f=typeof v=="string"?[{type:"text",text:v}]:v}else l==="block"?f=p.parseChildren(m.tokens||[]):f=p.parseInline(m.tokens||[]);const y={...o,...m.attributes};return p.createNode(e,y,f)},markdownTokenizer:{name:e,level:"block",start(m){var p;const f=new RegExp(`^:::${u}`,"m"),y=(p=m.match(f))==null?void 0:p.index;return y!==void 0?y:-1},tokenize(m,p,f){var y;const v=new RegExp(`^:::${u}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),b=m.match(v);if(!b)return;const[g,_=""]=b,N=a(_);let C=1;const k=g.length;let P="";const T=/^:::([\w-]*)(\s.*)?/gm,D=m.slice(k);for(T.lastIndex=0;;){const A=T.exec(D);if(A===null)break;const R=A.index,G=A[1];if(!((y=A[2])!=null&&y.endsWith(":::"))){if(G)C+=1;else if(C-=1,C===0){const z=D.slice(0,R);P=z.trim();const Z=m.slice(0,k+R+A[0].length);let I=[];if(P)if(l==="block")for(I=f.blockTokens(z),I.forEach(J=>{J.text&&(!J.tokens||J.tokens.length===0)&&(J.tokens=f.inlineTokens(J.text))});I.length>0;){const J=I[I.length-1];if(J.type==="paragraph"&&(!J.text||J.text.trim()===""))I.pop();else break}else I=f.inlineTokens(P);return{type:e,raw:Z,attributes:N,content:P,tokens:I}}}}}},renderMarkdown:(m,p)=>{const f=d(m.attrs||{}),y=s(f),v=y?` {${y}}`:"",b=p.renderChildren(m.content||[],` +`,textSerializers:n={}}=t||{};return QWe(this.state.doc,{blockSeparator:e,textSerializers:{...sse(this.schema),...n}})}get isEmpty(){return MA(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 UKe(e,this)}get $doc(){return this.$pos(0)}};function Ox(t){return new EA({find:t.find,handler:({state:e,range:n,match:r})=>{const a=jr(t.getAttributes,void 0,r);if(a===!1||a===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(s5(n.from,n.to,e.doc).filter(f=>f.mark.type.excluded.find(v=>v===t.type&&v!==f.mark.type)).filter(f=>f.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(a||{})),s.removeStoredMark(t.type)}},undoable:t.undoable})}function Cse(t){return new EA({find:t.find,handler:({state:e,range:n,match:r})=>{const a=jr(t.getAttributes,void 0,r)||{},{tr:s}=e,o=n.from;let l=n.to;const c=t.type.create(a);if(r[1]){const u=r[0].lastIndexOf(r[1]);let d=o+u;d>l?d=l:l=d+r[1].length;const m=r[0][r[0].length-1];s.insertText(m,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(a)).delete(s.mapping.map(o),s.mapping.map(l))}s.scrollIntoView()},undoable:t.undoable})}function iL(t){return new EA({find:t.find,handler:({state:e,range:n,match:r})=>{const a=e.doc.resolve(n.from),s=jr(t.getAttributes,void 0,r)||{};if(!a.node(-1).canReplaceWith(a.index(-1),a.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 Ix(t){return new EA({find:t.find,handler:({state:e,range:n,match:r,chain:a})=>{const s=jr(t.getAttributes,void 0,r)||{},o=e.tr.delete(n.from,n.to),c=o.doc.resolve(n.from).blockRange(),u=c&&z4(c,t.type,s);if(!u)return null;if(o.wrap(c,u),t.keepMarks&&t.editor){const{selection:m,storedMarks:p}=e,{splittableMarks:f}=t.editor.extensionManager,y=p||m.$to.parentOffset&&m.$from.marks();if(y){const v=y.filter(b=>f.includes(b.type.name));o.ensureMarks(v)}}if(t.keepAttributes){const m=t.type.name==="bulletList"||t.type.name==="orderedList"?"listItem":"taskList";a().updateAttributes(m,s).run()}const d=o.doc.resolve(n.from-1).nodeBefore;d&&d.type===t.type&&tp(o.doc,n.from-1)&&(!t.joinPredicate||t.joinPredicate(r,d))&&o.join(n.from-1)},undoable:t.undoable})}var qKe=t=>"touches"in t,VKe=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.lastEditableState=void 0,this.handleMap=new Map,this.handleMouseMove=l=>{if(!this.isResizing||!this.activeHandle)return;const c=l.clientX-this.startX,u=l.clientY-this.startY;this.handleResize(c,u)},this.handleTouchMove=l=>{if(!this.isResizing||!this.activeHandle)return;const c=l.touches[0];if(!c)return;const u=c.clientX-this.startX,d=c.clientY-this.startY;this.handleResize(u,d)},this.handleMouseUp=()=>{if(!this.isResizing)return;const l=this.element.offsetWidth,c=this.element.offsetHeight;this.onCommit(l,c),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=l=>{l.key==="Shift"&&(this.isShiftKeyPressed=!0)},this.handleKeyUp=l=>{l.key==="Shift"&&(this.isShiftKeyPressed=!1)};var e,n,r,a,s,o;this.node=t.node,this.editor=t.editor,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),(a=t.options)!=null&&a.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||""}),(o=t.options)!=null&&o.createCustomHandle&&(this.createCustomHandle=t.options.createCustomHandle),this.wrapper=this.createWrapper(),this.container=this.createContainer(),this.applyInitialSize(),this.attachHandles(),this.editor.on("update",this.handleEditorUpdate.bind(this))}get dom(){return this.container}get contentDOM(){var t;return(t=this.contentElement)!=null?t:null}handleEditorUpdate(){const t=this.editor.isEditable;t!==this.lastEditableState&&(this.lastEditableState=t,t?t&&this.handleMap.size===0&&this.attachHandles():this.removeHandles())}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.editor.off("update",this.handleEditorUpdate.bind(this)),this.container.remove()}createContainer(){const t=document.createElement("div");return t.dataset.resizeContainer="",t.dataset.node=this.node.type.name,t.style.display="flex",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"),a=e.includes("left"),s=e.includes("right");n&&(t.style.top="0"),r&&(t.style.bottom="0"),a&&(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=>{let e;this.createCustomHandle?e=this.createCustomHandle(t):e=this.createHandle(t),e instanceof HTMLElement||(console.warn(`[ResizableNodeView] createCustomHandle("${t}") did not return an HTMLElement. Falling back to default handle.`),e=this.createHandle(t)),this.createCustomHandle||this.positionHandle(e,t),e.addEventListener("mousedown",n=>this.handleResizeStart(n,t)),e.addEventListener("touchstart",n=>this.handleResizeStart(n,t)),this.handleMap.set(t,e),this.wrapper.appendChild(e)})}removeHandles(){this.handleMap.forEach(t=>t.remove()),this.handleMap.clear()}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,qKe(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:a}=this.calculateNewDimensions(this.activeHandle,t,e),s=this.applyConstraints(r,a,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,a=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?a=this.startHeight+n:c&&(a=this.startHeight-n),(t==="right"||t==="left")&&(r=this.startWidth+(s?e:-e)),(t==="top"||t==="bottom")&&(a=this.startHeight+(l?n:-n)),this.preserveAspectRatio||this.isShiftKeyPressed?this.applyAspectRatio(r,a,t):{width:r,height:a}}applyConstraints(t,e,n){var r,a,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)),(a=this.maxSize)!=null&&a.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",a=n==="top"||n==="bottom";return r?{width:t,height:t/this.aspectRatio}:a?{width:e*this.aspectRatio,height:e}:{width:t,height:t/this.aspectRatio}}};function GKe(t,e){const{selection:n}=t,{$from:r}=n;if(n instanceof yn){const s=r.index();return r.parent.canReplaceWith(s,s+1,e)}let a=r.depth;for(;a>=0;){const s=r.index(a);if(r.node(a).contentMatchAt(s).matchType(e))return!0;a-=1}return!1}var WKe={};t5(WKe,{createAtomBlockMarkdownSpec:()=>KKe,createBlockMarkdownSpec:()=>YKe,createInlineMarkdownSpec:()=>ZKe,parseAttributes:()=>l5,parseIndentedBlocks:()=>aL,renderNestedMarkdownContent:()=>u5,serializeAttributes:()=>c5});function l5(t){if(!t?.trim())return{};const e={},n=[],r=t.replace(/["']([^"']*)["']/g,u=>(n.push(u),`__QUOTED_${n.length-1}__`)),a=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(a){const u=a.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 m;const p=parseInt(((m=d.match(/__QUOTED_(\d+)__/))==null?void 0:m[1])||"0",10),f=n[p];f&&(e[u]=f.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 c5(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 KKe(t){const{nodeName:e,name:n,parseAttributes:r=l5,serializeAttributes:a=c5,defaultAttributes:s={},requiredAttributes:o=[],allowedAttributes:l}=t,c=n||e,u=d=>{if(!l)return d;const m={};return l.forEach(p=>{p in d&&(m[p]=d[p])}),m};return{parseMarkdown:(d,m)=>{const p={...s,...d.attributes};return m.createNode(e,p,[])},markdownTokenizer:{name:e,level:"block",start(d){var m;const p=new RegExp(`^:::${c}(?:\\s|$)`,"m"),f=(m=d.match(p))==null?void 0:m.index;return f!==void 0?f:-1},tokenize(d,m,p){const f=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),y=d.match(f);if(!y)return;const v=y[1]||"",b=r(v);if(!o.find(_=>!(_ in b)))return{type:e,raw:y[0],attributes:b}}},renderMarkdown:d=>{const m=u(d.attrs||{}),p=a(m),f=p?` {${p}}`:"";return`:::${c}${f} :::`}}}function YKe(t){const{nodeName:e,name:n,getContent:r,parseAttributes:a=l5,serializeAttributes:s=c5,defaultAttributes:o={},content:l="block",allowedAttributes:c}=t,u=n||e,d=m=>{if(!c)return m;const p={};return c.forEach(f=>{f in m&&(p[f]=m[f])}),p};return{parseMarkdown:(m,p)=>{let f;if(r){const v=r(m);f=typeof v=="string"?[{type:"text",text:v}]:v}else l==="block"?f=p.parseChildren(m.tokens||[]):f=p.parseInline(m.tokens||[]);const y={...o,...m.attributes};return p.createNode(e,y,f)},markdownTokenizer:{name:e,level:"block",start(m){var p;const f=new RegExp(`^:::${u}`,"m"),y=(p=m.match(f))==null?void 0:p.index;return y!==void 0?y:-1},tokenize(m,p,f){var y;const v=new RegExp(`^:::${u}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),b=m.match(v);if(!b)return;const[g,_=""]=b,N=a(_);let C=1;const k=g.length;let P="";const T=/^:::([\w-]*)(\s.*)?/gm,D=m.slice(k);for(T.lastIndex=0;;){const A=T.exec(D);if(A===null)break;const R=A.index,G=A[1];if(!((y=A[2])!=null&&y.endsWith(":::"))){if(G)C+=1;else if(C-=1,C===0){const z=D.slice(0,R);P=z.trim();const Z=m.slice(0,k+R+A[0].length);let I=[];if(P)if(l==="block")for(I=f.blockTokens(z),I.forEach(J=>{J.text&&(!J.tokens||J.tokens.length===0)&&(J.tokens=f.inlineTokens(J.text))});I.length>0;){const J=I[I.length-1];if(J.type==="paragraph"&&(!J.text||J.text.trim()===""))I.pop();else break}else I=f.inlineTokens(P);return{type:e,raw:Z,attributes:N,content:P,tokens:I}}}}}},renderMarkdown:(m,p)=>{const f=d(m.attrs||{}),y=s(f),v=y?` {${y}}`:"",b=p.renderChildren(m.content||[],` `);return`:::${u}${v} @@ -8688,7 +8688,7 @@ ${f.slice(u+2)}`,m+=1;else break}e.push({indent:u,number:parseInt(l,10),content: [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer`}),i.jsx("span",{className:"text-xs text-bambu-gray w-12",children:Ym(f)})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:N,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip back 5s",children:i.jsx(Kge,{className:"w-5 h-5 text-bambu-gray"})}),i.jsx("button",{onClick:g,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?i.jsx(lT,{className:"w-5 h-5 text-white"}):i.jsx(Co,{className:"w-5 h-5 text-white"})}),i.jsx("button",{onClick:C,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip forward 5s",children:i.jsx(YL,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:"Speed:"}),i.jsx("div",{className:"flex gap-1",children:QQe.map(P=>i.jsxs("button",{onClick:()=>d(P),className:`px-2 py-1 text-xs rounded transition-colors ${u===P?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary/80"}`,children:[P,"x"]},P))})]})]})]})]})]}),v&&r&&i.jsx(XQe,{archiveId:r,timelapseSrc:t,onClose:()=>b(!1),onSave:s})]})}function ZQe({archiveIds:t,onClose:e}){w.useEffect(()=>{const s=o=>{o.key==="Escape"&&e()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e]);const{data:n,isLoading:r,error:a}=et({queryKey:["archive-comparison",t],queryFn:()=>ge.compareArchives(t)});return i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:e,children:i.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:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white",children:["Compare Archives (",t.length,")"]}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white p-1",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"flex-1 overflow-auto p-4 bg-bambu-dark-secondary",children:r?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a?i.jsxs("div",{className:"text-center py-12 text-red-400",children:[i.jsx(jn,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),i.jsx("p",{children:"Failed to load comparison"}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:a instanceof Error?a.message:"Unknown error"})]}):n?i.jsx(JQe,{comparison:n}):null}),i.jsx("div",{className:"p-4 border-t border-bambu-dark-tertiary",children:i.jsx(ze,{variant:"secondary",onClick:e,className:"w-full",children:"Close"})})]})})}function JQe({comparison:t}){return i.jsxs("div",{className:"space-y-6",children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.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=>i.jsxs("th",{className:"text-left text-sm font-medium pb-2 px-2 min-w-[120px]",children:[i.jsx("div",{className:"text-white truncate max-w-[150px]",title:e.print_name,children:e.print_name}),i.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))]})}),i.jsx("tbody",{className:"divide-y divide-bambu-gray/20",children:t.comparison.map(e=>i.jsxs("tr",{className:e.has_difference?"bg-yellow-500/5":"",children:[i.jsx("td",{className:"py-2 pr-4 text-sm",children:i.jsxs("div",{className:"flex items-center gap-2",children:[e.has_difference&&i.jsx(jn,{className:"w-3 h-3 text-yellow-400 flex-shrink-0"}),i.jsx("span",{className:e.has_difference?"text-yellow-400":"text-bambu-gray",children:e.label})]})}),e.values.map((n,r)=>i.jsxs("td",{className:"py-2 px-2 text-sm text-white",children:[n??i.jsx("span",{className:"text-bambu-gray/50",children:"-"}),e.unit&&n!==null&&i.jsx("span",{className:"text-bambu-gray ml-1",children:e.unit})]},r))]},e.field))})]})}),t.differences.length>0&&i.jsxs("div",{className:"p-4 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[i.jsxs("h4",{className:"text-sm font-medium text-yellow-400 mb-2 flex items-center gap-2",children:[i.jsx(jn,{className:"w-4 h-4"}),t.differences.length," Difference",t.differences.length>1?"s":""," Found"]}),i.jsxs("ul",{className:"text-sm text-white/80 space-y-1",children:[t.differences.slice(0,5).map(e=>i.jsxs("li",{children:[i.jsx("span",{className:"text-yellow-400",children:e.label}),": ",e.values.join(" vs ")," ",e.unit||""]},e.field)),t.differences.length>5&&i.jsxs("li",{className:"text-bambu-gray",children:["...and ",t.differences.length-5," more"]})]})]}),t.success_correlation.has_both_outcomes?i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("h4",{className:"text-sm font-medium text-white mb-3 flex items-center gap-2",children:[i.jsx(Zr,{className:"w-4 h-4 text-bambu-green"}),"Success/Failure Analysis"]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm mb-3",children:[i.jsxs("span",{className:"text-bambu-green",children:[t.success_correlation.successful_count," successful"]}),i.jsxs("span",{className:"text-red-400",children:[t.success_correlation.failed_count," failed"]})]}),t.success_correlation.insights&&t.success_correlation.insights.length>0?i.jsx("div",{className:"space-y-2",children:t.success_correlation.insights.map(e=>i.jsxs("div",{className:"text-sm p-2 bg-bambu-dark-secondary rounded",children:[i.jsxs("span",{className:"text-white font-medium",children:[e.label,":"]})," ",i.jsx("span",{className:"text-white/80",children:e.insight})]},e.field))}):i.jsx("p",{className:"text-sm text-bambu-gray",children:"No clear correlations found between settings and outcomes."})]}):i.jsx("div",{className:"p-4 bg-bambu-dark rounded-lg text-sm text-bambu-gray",children:i.jsx("p",{children:t.success_correlation.message||"Need both successful and failed prints for correlation analysis."})})]})}function eZe(t){const e=new Date(t),r=new Date().getTime()-e.getTime(),a=Math.floor(r/6e4);if(a<1)return"Just now";if(a<60)return`${a}m ago`;const s=Math.floor(a/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}function tZe({upload:t,projects:e,onArchive:n,onDiscard:r,isArchiving:a,isDiscarding:s}){const[o,l]=w.useState(!1),[c,u]=w.useState(t.tags||""),[d,m]=w.useState(t.notes||""),[p,f]=w.useState(t.project_id),[y,v]=w.useState(!1);return i.jsx(Pt,{children:i.jsxs(Et,{className:"py-3",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(mf,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:t.filename}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[i.jsx("span",{children:xo(t.file_size)}),i.jsx("span",{children:"·"}),i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Zn,{className:"w-3 h-3"}),eZe(t.uploaded_at)]}),t.source_ip&&i.jsxs(i.Fragment,{children:[i.jsx("span",{children:"·"}),i.jsxs("span",{children:["from ",t.source_ip]})]})]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>l(!o),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:o?i.jsx(Vl,{className:"w-5 h-5"}):i.jsx(In,{className:"w-5 h-5"})}),i.jsx(ze,{variant:"primary",size:"sm",onClick:()=>n(t.id,{tags:c,notes:d,project_id:p||void 0}),disabled:a,children:a?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsxs(i.Fragment,{children:[i.jsx(Vs,{className:"w-4 h-4"}),"Archive"]})}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>v(!0),disabled:s,children:s?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(nn,{className:"w-4 h-4 text-red-400"})})]})]}),y&&i.jsx(Nn,{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),v(!1)},onCancel:()=>v(!1)}),o&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary space-y-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Tags"}),i.jsx("input",{type:"text",value:c,onChange:b=>u(b.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes"}),i.jsx("textarea",{value:d,onChange:b=>m(b.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Project"}),i.jsxs("select",{value:p||"",onChange:b=>f(b.target.value?Number(b.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:[i.jsx("option",{value:"",children:"No project"}),e.map(b=>i.jsx("option",{value:b.id,children:b.name},b.id))]})]})]})]})})}function nZe(){const t=sn(),{showToast:e}=bn(),[n,r]=w.useState(!1),[a,s]=w.useState(!1),[o,l]=w.useState(new Set),[c,u]=w.useState(new Set),{data:d,isLoading:m}=et({queryKey:["pending-uploads"],queryFn:Eb.list,refetchInterval:1e4}),{data:p}=et({queryKey:["projects"],queryFn:()=>ge.getProjects()}),f=gt({mutationFn:({id:g,data:_})=>Eb.archive(g,_),onMutate:({id:g})=>{l(_=>new Set(_).add(g))},onSettled:(g,_,{id:N})=>{l(C=>{const k=new Set(C);return k.delete(N),k})},onSuccess:g=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived: ${g.print_name}`)},onError:g=>{e(g.message||"Failed to archive","error")}}),y=gt({mutationFn:g=>Eb.discard(g),onMutate:g=>{u(_=>new Set(_).add(g))},onSettled:(g,_,N)=>{u(C=>{const k=new Set(C);return k.delete(N),k})},onSuccess:()=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e("Upload discarded")},onError:g=>{e(g.message||"Failed to discard","error")}}),v=gt({mutationFn:Eb.archiveAll,onSuccess:g=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived ${g.archived} files${g.failed>0?`, ${g.failed} failed`:""}`)},onError:g=>{e(g.message||"Failed to archive all","error")}}),b=gt({mutationFn:Eb.discardAll,onSuccess:g=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e(`Discarded ${g.discarded} files`)},onError:g=>{e(g.message||"Failed to discard all","error")}});return m?i.jsx(Pt,{children:i.jsx(Et,{className:"py-8 flex justify-center",children:i.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})})}):!d||d.length===0?null:i.jsxs("div",{className:"mb-6",children:[i.jsxs(Pt,{className:"border-l-4 border-l-yellow-500",children:[i.jsx(Bn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(yi,{className:"w-5 h-5 text-yellow-500"}),i.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Pending Uploads (",d.length,")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ze,{variant:"primary",size:"sm",onClick:()=>r(!0),disabled:v.isPending,children:v.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsxs(i.Fragment,{children:[i.jsx(Vs,{className:"w-4 h-4"}),"Archive All"]})}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>s(!0),disabled:b.isPending,children:b.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsxs(i.Fragment,{children:[i.jsx(nn,{className:"w-4 h-4"}),"Discard All"]})})]})]})}),i.jsxs(Et,{children:[i.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."}),i.jsx("div",{className:"space-y-3",children:d.map(g=>i.jsx(tZe,{upload:g,projects:p||[],onArchive:(_,N)=>f.mutate({id:_,data:N}),onDiscard:_=>y.mutate(_),isArchiving:o.has(g.id),isDiscarding:c.has(g.id)},g.id))})]})]}),n&&i.jsx(Nn,{title:"Archive All Uploads",message:`Are you sure you want to archive all ${d.length} pending uploads?`,confirmText:"Archive All",onConfirm:()=>{v.mutate(),r(!1)},onCancel:()=>r(!1)}),a&&i.jsx(Nn,{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:()=>{b.mutate(),s(!1)},onCancel:()=>s(!1)})]})}function rZe({onClose:t}){const e=sn(),{showToast:n}=bn(),[r,a]=w.useState(""),[s,o]=w.useState(null),[l,c]=w.useState(""),[u,d]=w.useState(null),[m,p]=w.useState("count");w.useEffect(()=>{const A=R=>{R.key==="Escape"&&(s?o(null):u?d(null):t())};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[t,s,u]);const{data:f,isLoading:y}=et({queryKey:["tags"],queryFn:ge.getTags}),v=gt({mutationFn:({oldName:A,newName:R})=>ge.renameTag(A,R),onSuccess:(A,{oldName:R,newName:G})=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Renamed "${R}" to "${G}" in ${A.affected} archive${A.affected!==1?"s":""}`),o(null)},onError:A=>{n(A.message||"Failed to rename tag","error")}}),b=gt({mutationFn:A=>ge.deleteTag(A),onSuccess:(A,R)=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Deleted "${R}" from ${A.affected} archive${A.affected!==1?"s":""}`),d(null)},onError:A=>{n(A.message||"Failed to delete tag","error")}}),g=A=>{o(A.name),c(A.name),d(null)},_=()=>{o(null),c("")},N=()=>{if(!s||!l.trim())return;const A=l.trim();if(A===s){_();return}v.mutate({oldName:s,newName:A})},C=A=>{A.key==="Enter"?(A.preventDefault(),N()):A.key==="Escape"&&(A.preventDefault(),_())},k=A=>{d(A),o(null)},P=()=>{u&&b.mutate(u)},T=f?.filter(A=>A.name.toLowerCase().includes(r.toLowerCase())).sort((A,R)=>m==="count"&&R.count-A.count||A.name.localeCompare(R.name)),D=f?.reduce((A,R)=>A+R.count,0)||0;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-lg max-h-[80vh] flex flex-col",children:i.jsxs(Et,{className:"p-0 flex flex-col min-h-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Hd,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:"Manage Tags"})]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.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:A=>a(A.target.value)})]}),i.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:m,onChange:A=>p(A.target.value),children:[i.jsx("option",{value:"count",children:"Sort by Count"}),i.jsx("option",{value:"name",children:"Sort by Name"})]})]}),f&&i.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[f.length," tag",f.length!==1?"s":""," across ",D," usage",D!==1?"s":""]})]}),i.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 p-4",children:y?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):T?.length?i.jsx("div",{className:"space-y-2",children:T.map(A=>i.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===A.name?i.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[i.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:R=>c(R.target.value),onKeyDown:C,autoFocus:!0}),i.jsx(ze,{size:"sm",variant:"primary",onClick:N,disabled:!l.trim()||v.isPending,className:"p-1.5",children:v.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(Zr,{className:"w-4 h-4"})}),i.jsx(ze,{size:"sm",variant:"ghost",onClick:_,className:"p-1.5",children:i.jsx(Ht,{className:"w-4 h-4"})})]}):u===A.name?i.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[i.jsx(jn,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),i.jsxs("span",{className:"text-sm text-bambu-gray-light flex-1",children:['Delete "',A.name,'" from ',A.count," archive",A.count!==1?"s":"","?"]}),i.jsx(ze,{size:"sm",variant:"danger",onClick:P,disabled:b.isPending,className:"p-1.5",children:b.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(nn,{className:"w-4 h-4"})}),i.jsx(ze,{size:"sm",variant:"ghost",onClick:()=>d(null),className:"p-1.5",children:i.jsx(Ht,{className:"w-4 h-4"})})]}):i.jsxs(i.Fragment,{children:[i.jsx(Hd,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"text-white flex-1 truncate",children:A.name}),i.jsx("span",{className:"px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-xs",children:A.count}),i.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[i.jsx("button",{onClick:()=>g(A),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors",title:"Rename tag",children:i.jsx(Yi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>k(A.name),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors",title:"Delete tag",children:i.jsx(nn,{className:"w-4 h-4"})})]})]})},A.name))}):i.jsx("div",{className:"text-center py-8 text-bambu-gray",children:r?"No tags match your search":"No tags found"})}),i.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:i.jsx(ze,{variant:"secondary",onClick:t,className:"flex-1",children:"Close"})})]})})})}function ch(t){const e=t.filename;if(e){const n=e.toLowerCase();if(n.endsWith(".gcode")||n.includes(".gcode."))return!0}return!!(t.total_layers||t.print_time_seconds)}function doe(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()}async function uh(t,e,n,r){try{if(n==="source"){const{token:a}=await ge.createSourceSlicerToken(t),s=ge.getSourceSlicerDownloadUrl(t,a,e);of(`${window.location.origin}${s}`,r)}else{const{token:a}=await ge.createArchiveSlicerToken(t),s=ge.getArchiveSlicerDownloadUrl(t,a,e);of(`${window.location.origin}${s}`,r)}}catch{const a=n==="source"?ge.getSource3mfForSlicer(t,e):ge.getArchiveForSlicer(t,e);of(`${window.location.origin}${a}`,r)}}function iZe({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:a,projects:s,isHighlighted:o,timeFormat:l="system",preferredSlicer:c="bambu_studio",currency:u,t:d,onNavigateToArchive:m}){o&&console.log("ArchiveCard isHighlighted=true for archive:",t.id);const p=sn(),{showToast:f}=bn(),{hasPermission:y,canModify:v}=Ar(),b=uie(),[g,_]=w.useState(!1),[N,C]=w.useState(!1),[k,P]=w.useState(!1),[T,D]=w.useState(!1),[A,R]=w.useState(!1),[G,z]=w.useState(!1),[Z,I]=w.useState([]),[J,ae]=w.useState(!1),[Y,ue]=w.useState(!1),[de,he]=w.useState(!1),[V,ne]=w.useState(!1),[se,pe]=w.useState(!1),[Te,q]=w.useState(!1),[X,j]=w.useState(!1),[E,U]=w.useState(null),[K,H]=w.useState(null),[re,O]=w.useState(!1),$=w.useRef(null),ee=w.useRef(null),W=w.useRef(null),{data:ie}=et({queryKey:["archive-plates",t.id],queryFn:()=>ge.getArchivePlates(t.id),enabled:re,staleTime:300*1e3}),ce=t.duplicate_sequence??0,be=t.original_archive_id??null,xe=ie?.plates??[],oe=ie?.is_multi_plate??!1,L=K??0,F=gt({mutationFn:()=>ge.deleteArchiveTimelapse(t.id),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.timelapseRemoved"))},onError:ye=>{f(ye.message||d("archives.toast.failedRemoveTimelapse"),"error")}}),te=gt({mutationFn:ye=>ge.uploadArchiveTimelapse(t.id,ye),onSuccess:ye=>{p.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.timelapseUploaded",{filename:ye.filename}))},onError:ye=>{f(ye.message||d("archives.toast.failedUploadTimelapse"),"error")}}),ve=gt({mutationFn:ye=>ge.uploadSource3mf(t.id,ye),onSuccess:ye=>{p.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.source3mfAttached",{filename:ye.filename}))},onError:ye=>{f(ye.message||d("archives.toast.failedUploadSource3mf"),"error")}}),fe=gt({mutationFn:()=>ge.deleteSource3mf(t.id),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.source3mfRemoved"))},onError:ye=>{f(ye.message||d("archives.toast.failedRemoveSource3mf"),"error")}}),me=gt({mutationFn:ye=>ge.uploadF3d(t.id,ye),onSuccess:ye=>{p.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.f3dAttached",{filename:ye.filename}))},onError:ye=>{f(ye.message||d("archives.toast.failedUploadF3d"),"error")}}),je=gt({mutationFn:()=>ge.deleteF3d(t.id),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.f3dRemoved"))},onError:ye=>{f(ye.message||d("archives.toast.failedRemoveF3d"),"error")}}),we=gt({mutationFn:()=>ge.scanArchiveTimelapse(t.id),onSuccess:ye=>{ye.status==="attached"?(p.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.timelapseAttached",{filename:ye.filename}))):ye.status==="exists"?f(d("archives.toast.timelapseAlreadyAttached")):ye.status==="not_found"&&ye.available_files&&ye.available_files.length>0?(I(ye.available_files),z(!0)):f(ye.message||d("archives.toast.noMatchingTimelapse"),"warning")},onError:ye=>{f(ye.message||d("archives.toast.failedScanTimelapse"),"error")}}),Fe=gt({mutationFn:ye=>ge.selectArchiveTimelapse(t.id,ye),onSuccess:ye=>{p.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.timelapseAttached",{filename:ye.filename})),z(!1),I([])},onError:ye=>{f(ye.message||d("archives.toast.failedAttachTimelapse"),"error")}}),He=gt({mutationFn:()=>ge.deleteArchive(t.id),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.archiveDeleted"))},onError:()=>{f(d("archives.toast.failedDeleteArchive"),"error")}}),Oe=gt({mutationFn:()=>ge.toggleFavorite(t.id),onSuccess:ye=>{p.invalidateQueries({queryKey:["archives"]}),f(ye.is_favorite?d("archives.toast.addedToFavorites"):d("archives.toast.removedFromFavorites"))}}),{data:_e}=et({queryKey:["archive-folders",t.id],queryFn:()=>ge.getLibraryFoldersByArchive(t.id)}),Ae=gt({mutationFn:ye=>ge.updateArchive(t.id,{project_id:ye}),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),p.invalidateQueries({queryKey:["projects"]}),f(d("archives.toast.projectUpdated"))},onError:()=>{f(d("archives.toast.failedUpdateProject"),"error")}}),Be=ye=>{ye.preventDefault(),U({x:ye.clientX,y:ye.clientY})},Xe=[...ch(t)?[{label:d("archives.menu.print"),icon:i.jsx(_r,{className:"w-4 h-4"}),onClick:()=>C(!0),disabled:!t.file_path||!v("archives","reprint",t.created_by_id),title:t.file_path?v("archives","reprint",t.created_by_id)?void 0:d("archives.permission.noReprint"):d("archives.card.noFileForReprint")},{label:d("archives.menu.schedule"),icon:i.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>ne(!0),disabled:!t.file_path||!y("queue:create"),title:t.file_path?y("queue:create")?void 0:d("archives.permission.noAddToQueue"):d("archives.card.noFileForReprint")},{label:d("archives.menu.openInBambuStudio"),icon:i.jsx(ni,{className:"w-4 h-4"}),onClick:()=>{const ye=t.print_name||t.filename||"model";uh(t.id,ye,"file",c)},disabled:!t.file_path,title:t.file_path?void 0:d("archives.card.noFileForReprint")}]:[{label:d("archives.menu.slice"),icon:i.jsx(ni,{className:"w-4 h-4"}),onClick:()=>{const ye=t.print_name||t.filename||"model";uh(t.id,ye,"file",c)}}],{label:t.external_url?d("archives.menu.externalLink"):d("archives.menu.viewOnMakerWorld"),icon:i.jsx(Ch,{className:"w-4 h-4"}),onClick:()=>{const ye=t.external_url||t.makerworld_url;ye&&window.open(ye,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:d("archives.menu.preview3d"),icon:i.jsx(ia,{className:"w-4 h-4"}),onClick:()=>_(!0)},{label:d("archives.menu.viewTimelapse"),icon:i.jsx(kh,{className:"w-4 h-4"}),onClick:()=>R(!0),disabled:!t.timelapse_path},{label:d("archives.menu.scanForTimelapse"),icon:i.jsx(BN,{className:"w-4 h-4"}),onClick:()=>we.mutate(),disabled:!t.printer_id||!!t.timelapse_path||we.isPending||!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},{label:d("archives.menu.uploadTimelapse"),icon:i.jsx(yi,{className:"w-4 h-4"}),onClick:()=>W.current?.click(),disabled:!!t.timelapse_path||!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},...t.timelapse_path?[{label:d("archives.menu.removeTimelapse"),icon:i.jsx(nn,{className:"w-4 h-4"}),onClick:()=>j(!0),danger:!0,disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:t.source_3mf_path?d("archives.menu.downloadSource3mf"):d("archives.menu.uploadSource3mf"),icon:i.jsx(ON,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?ge.downloadSource3mf(t.id).catch(ye=>{console.error("Source 3MF download failed:",ye)}):$.current?.click()},disabled:!t.source_3mf_path&&!v("archives","update",t.created_by_id),title:!t.source_3mf_path&&!v("archives","update",t.created_by_id)?d("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:d("archives.menu.replaceSource3mf"),icon:i.jsx(yi,{className:"w-4 h-4"}),onClick:()=>$.current?.click(),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},{label:d("archives.menu.removeSource3mf"),icon:i.jsx(nn,{className:"w-4 h-4"}),onClick:()=>pe(!0),danger:!0,disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")}]:[],{label:t.f3d_path?d("archives.menu.replaceF3d"):d("archives.menu.uploadF3d"),icon:i.jsx(ia,{className:"w-4 h-4"}),onClick:()=>ee.current?.click(),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:d("archives.menu.downloadF3d"),icon:i.jsx(fi,{className:"w-4 h-4"}),onClick:()=>{ge.downloadF3d(t.id).catch(ye=>{console.error("F3D download failed:",ye)})}},{label:d("archives.menu.removeF3d"),icon:i.jsx(nn,{className:"w-4 h-4"}),onClick:()=>q(!0),danger:!0,disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:d("archives.menu.download"),icon:i.jsx(fi,{className:"w-4 h-4"}),onClick:()=>{ge.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ye=>{console.error("Archive download failed:",ye)})},disabled:!y("archives:read"),title:y("archives:read")?void 0:d("archives.permission.noDownload")},{label:d("archives.menu.copyDownloadLink"),icon:i.jsx(ko,{className:"w-4 h-4"}),onClick:()=>{const ye=`${window.location.origin}${ge.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(ye).then(()=>{f(d("archives.toast.linkCopied"))}).catch(()=>{f(d("archives.toast.failedCopyLink"),"error")})},disabled:!y("archives:read"),title:y("archives:read")?void 0:d("archives.permission.noCopyLink")},{label:d("archives.menu.qrCode"),icon:i.jsx(eQ,{className:"w-4 h-4"}),onClick:()=>ae(!0)},{label:t.photos?.length?d("archives.menu.viewPhotosCount",{count:t.photos.length}):d("archives.menu.viewPhotos"),icon:i.jsx(dx,{className:"w-4 h-4"}),onClick:()=>ue(!0),disabled:!t.photos?.length},{label:d("archives.menu.projectPage"),icon:i.jsx(Bs,{className:"w-4 h-4"}),onClick:()=>he(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?d("archives.menu.removeFromFavorites"):d("archives.menu.addToFavorites"),icon:i.jsx(Mf,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>Oe.mutate(),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},{label:d("archives.menu.edit"),icon:i.jsx(Yi,{className:"w-4 h-4"}),onClick:()=>D(!0),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},...t.project_id&&t.project_name?[{label:d("archives.menu.goToProject",{name:t.project_name}),icon:i.jsx(vs,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:d("archives.menu.addToProject"),icon:i.jsx(vs,{className:"w-4 h-4"}),onClick:()=>{},disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives"),submenu:(()=>{const ye=[];if(t.project_id&&ye.push({label:d("archives.menu.removeFromProject"),icon:i.jsx(Ht,{className:"w-4 h-4"}),onClick:()=>Ae.mutate(null),disabled:!v("archives","update",t.created_by_id)}),!s)ye.push({label:d("archives.menu.loading"),icon:i.jsx(ft,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const We=s.filter(Pe=>Pe.status==="active");We.length===0?ye.push({label:d("archives.menu.noProjectsAvailable"),icon:i.jsx(vs,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):We.forEach(Pe=>{ye.push({label:Pe.name,icon:i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:Pe.color||"#888"}}),onClick:()=>Ae.mutate(Pe.id),disabled:t.project_id===Pe.id||!v("archives","update",t.created_by_id)})})}return ye})()},{label:d(n?"archives.menu.deselect":"archives.menu.select"),icon:n?i.jsx(Ks,{className:"w-4 h-4"}):i.jsx(rl,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:d("archives.menu.delete"),icon:i.jsx(nn,{className:"w-4 h-4"}),onClick:()=>P(!0),danger:!0,disabled:!v("archives","delete",t.created_by_id),title:v("archives","delete",t.created_by_id)?void 0:d("archives.permission.noDelete")}];return i.jsxs(Pt,{"data-archive-id":t.id,className:`relative flex flex-col group ${n?"ring-2 ring-bambu-green":""} ${a?"cursor-pointer":""}`,style:o?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,onContextMenu:Be,onClick:a?()=>r(t.id):void 0,children:[a&&i.jsx("button",{className:"absolute top-2 left-2 z-10 p-1 rounded bg-black/50 hover:bg-black/70 transition-colors",onClick:ye=>{ye.stopPropagation(),r(t.id)},children:n?i.jsx(Ks,{className:"w-5 h-5 text-bambu-green"}):i.jsx(rl,{className:"w-5 h-5 text-white"})}),i.jsxs("div",{className:"aspect-video bg-bambu-dark relative flex-shrink-0 overflow-hidden rounded-t-xl",onMouseEnter:()=>O(!0),onMouseLeave:()=>O(!1),children:[t.thumbnail_path?i.jsx("img",{src:K!==null&&xe.length>0?ge.getArchivePlateThumbnail(t.id,xe[L]?.index??0):ge.getArchiveThumbnail(t.id),alt:t.print_name||t.filename,className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(Ud,{className:"w-12 h-12 text-bambu-dark-tertiary"})}),oe&&xe.length>1&&i.jsxs(i.Fragment,{children:[i.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:ye=>{ye.stopPropagation(),H(We=>{const Pe=We??0;return Pe>0?Pe-1:xe.length-1})},title:d("archives.card.previousPlate"),children:i.jsx(Cc,{className:"w-4 h-4 text-white"})}),i.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:ye=>{ye.stopPropagation(),H(We=>{const Pe=We??0;return Pei.jsx("button",{className:`w-2 h-2 rounded-full transition-colors ${We===L?"bg-bambu-green":"bg-white/50 hover:bg-white/80"}`,onClick:Pe=>{Pe.stopPropagation(),H(We)},title:ye.name||d("archives.card.plateNumber",{index:ye.index})},ye.index))})]}),i.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"} ${a?"left-10":""}`,onClick:ye=>{ye.stopPropagation();const We=ye.currentTarget.getBoundingClientRect();U({x:We.left,y:We.bottom+4})},title:d("archives.card.moreOptions"),children:i.jsx(Nh,{className:"w-5 h-5 text-white"})}),i.jsx("button",{className:`absolute top-2 right-2 p-1 rounded transition-colors ${v("archives","update",t.created_by_id)?"bg-black/50 hover:bg-black/70":"bg-black/30 cursor-not-allowed"}`,onClick:ye=>{ye.stopPropagation(),v("archives","update",t.created_by_id)&&Oe.mutate()},disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?t.is_favorite?d("archives.card.removeFromFavorites"):d("archives.card.addToFavorites"):d("archives.permission.noUpdateArchives"),children:i.jsx(Mf,{className:`w-5 h-5 ${t.is_favorite?"text-yellow-400 fill-yellow-400":"text-white"} ${v("archives","update",t.created_by_id)?"":"opacity-50"}`})}),(t.status==="failed"||t.status==="aborted")&&i.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"?d("archives.card.cancelled"):d("archives.card.failed")}),t.duplicate_count>0&&ce>0&&be&&i.jsxs("button",{onClick:ye=>{ye.stopPropagation(),m?.(be)},className:"absolute top-2 right-12 px-2 py-1 rounded text-xs bg-purple-500/80 hover:bg-purple-600/90 text-white flex items-center gap-1 transition-colors cursor-pointer",title:d("archives.viewOriginalPrint",{id:be}),children:[i.jsx(ko,{className:"w-3 h-3"}),"#",ce]}),t.duplicate_count>0&&ce===0&&i.jsxs("span",{className:"absolute top-2 right-12 px-2 py-1 rounded text-xs bg-purple-500/80 text-white flex items-center gap-1",title:`${t.duplicate_count} reprint${t.duplicate_count===1?"":"s"}`,children:[i.jsx(XX,{className:"w-3 h-3"}),"+",t.duplicate_count]}),t.source_3mf_path&&i.jsx("button",{className:"absolute bottom-2 left-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:ye=>{ye.stopPropagation();const We=(t.print_name||t.filename||"source").replace(/\.gcode\.3mf$/i,"")+"_source";uh(t.id,We,"source",c)},title:d("archives.card.openSource3mf"),children:i.jsx(ON,{className:"w-4 h-4 text-orange-400"})}),t.f3d_path&&i.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:ye=>{ye.stopPropagation(),ge.downloadF3d(t.id).catch(We=>{console.error("F3D download failed:",We)})},title:d("archives.card.downloadF3d"),children:i.jsx(ia,{className:"w-4 h-4 text-cyan-400"})}),i.jsx("button",{className:"absolute bottom-2 right-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:ye=>{ye.stopPropagation(),_(!0)},title:d("archives.card.preview3d"),children:i.jsx(Gi,{className:"w-4 h-4 text-white"})}),t.timelapse_path&&i.jsx("button",{className:"absolute bottom-2 right-12 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:ye=>{ye.stopPropagation(),R(!0)},title:d("archives.card.viewTimelapse"),children:i.jsx(kh,{className:"w-4 h-4 text-bambu-green"})}),t.photos&&t.photos.length>0&&i.jsxs("button",{className:`absolute bottom-2 ${t.timelapse_path?"right-[5.5rem]":"right-12"} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`,onClick:ye=>{ye.stopPropagation(),ue(!0)},title:t.photos.length===1?d("archives.card.viewPhoto"):d("archives.card.viewPhotos",{count:t.photos.length}),children:[i.jsx(dx,{className:"w-4 h-4 text-blue-400"}),t.photos.length>1&&i.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})]}),_e&&_e.length>0&&i.jsx(fo,{to:`/files?folder=${_e[0].id}`,className:"absolute bottom-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:ye=>ye.stopPropagation(),title:d("archives.card.openFolder",{name:_e[0].name}),style:{left:t.source_3mf_path?t.f3d_path?"5.5rem":"3rem":t.f3d_path?"3rem":"0.5rem"},children:i.jsx(Ac,{className:"w-4 h-4 text-yellow-400"})})]}),i.jsxs(Et,{className:"p-4 flex-1 flex flex-col",children:[i.jsxs("p",{className:"text-[10px] text-bambu-gray/70 mb-1",children:["#",t.id]}),i.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[i.jsx("h3",{className:"min-w-0 font-medium text-white truncate",children:t.print_name||t.filename}),i.jsx(ze,{variant:"ghost",size:"sm",className:"p-1 sm:p-1.5 shrink-0",onClick:()=>D(!0),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?d("archives.card.edit"):d("archives.card.noPermissionEdit"),children:i.jsx(Yi,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-wrap",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:e}),i.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium ${ch(t)?"bg-bambu-green/20 text-bambu-green":"bg-orange-500/20 text-orange-400"}`,title:ch(t)?d("archives.card.slicedFile"):d("archives.card.sourceFile"),children:ch(t)?d("archives.card.gcode"):d("archives.card.source")}),t.content_hash&&i.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded font-mono bg-bambu-dark-tertiary/50 text-bambu-gray-light opacity-0 transition-opacity duration-150 group-hover:opacity-100",title:`SHA256: ${t.content_hash}`,children:t.content_hash.slice(0,8).toUpperCase()}),t.project_name&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full truncate max-w-[120px]",style:{backgroundColor:`${s?.find(ye=>ye.id===t.project_id)?.color||"#6b7280"}20`,color:s?.find(ye=>ye.id===t.project_id)?.color||"#6b7280"},title:d("archives.card.project",{name:t.project_name}),children:t.project_name})]}),i.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)&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.time_accuracy?`Estimated: ${Us(t.print_time_seconds||0)} Actual: ${Us(t.actual_time_seconds||0)} -Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${Us(t.actual_time_seconds)}`:`Estimated: ${Us(t.print_time_seconds||0)}`,children:[i.jsx(Zn,{className:"w-3 h-3"}),Us(t.actual_time_seconds||t.print_time_seconds||0),t.time_accuracy&&i.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&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(Wi,{className:"w-3 h-3"}),t.filament_used_grams.toFixed(1),"g"]}),(t.cost!=null||t.energy_cost!=null)&&i.jsxs("div",{className:"flex items-center gap-3 text-bambu-gray",children:[t.cost!=null&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx(bpe,{className:"w-3 h-3"}),u,t.cost.toFixed(2)]}),t.energy_cost!=null&&i.jsxs("div",{className:"flex items-center gap-1.5",title:`${d("stats.energyUsed")}: ${t.energy_kwh?.toFixed(3)||"N/A"} kWh`,children:[i.jsx(Pc,{className:"w-3 h-3"}),u,t.energy_cost.toFixed(2)]})]}),(t.layer_height||t.total_layers)&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(Gi,{className:"w-3 h-3"}),t.total_layers&&i.jsx("span",{children:t.total_layers===1?d("archives.card.layer",{count:t.total_layers}):d("archives.card.layers",{count:t.total_layers})}),t.total_layers&&t.layer_height&&i.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.layer_height&&i.jsxs("span",{children:[t.layer_height,"mm"]})]}),t.object_count!=null&&t.object_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.object_count===1?d("archives.card.object",{count:t.object_count}):d("archives.card.objects",{count:t.object_count}),children:[i.jsx(ia,{className:"w-3 h-3"}),t.object_count===1?d("archives.card.object",{count:t.object_count}):d("archives.card.objects",{count:t.object_count})]}),t.sliced_for_model&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:d("archives.card.slicedFor",{model:t.sliced_for_model}),children:[i.jsx(_r,{className:"w-3 h-3"}),t.sliced_for_model]}),t.filament_type&&i.jsxs("div",{className:"flex items-center gap-1.5 col-span-2",children:[i.jsx("span",{className:"text-bambu-gray text-xs",children:t.filament_type}),t.filament_color&&i.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((ye,We)=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:ye},title:ye},We))})]})]}),(t.tags||t.notes)&&i.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[t.notes&&i.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:i.jsx(rQ,{className:"w-3 h-3"})}),t.tags?.split(",").map((ye,We)=>i.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-dark-tertiary text-bambu-gray-light rounded text-xs",children:ye.trim()},We))]}),i.jsx("div",{className:"flex-1"}),i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray border-t border-bambu-dark-tertiary pt-3",children:[i.jsx("span",{children:Df(t.created_at,l)}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.created_by_username&&i.jsxs("span",{className:"flex items-center gap-1",title:d("archives.card.uploadedBy",{name:t.created_by_username}),children:[i.jsx($d,{className:"w-3 h-3"}),t.created_by_username]}),i.jsx("span",{children:xo(t.file_size)})]})]}),i.jsxs("div",{className:"flex gap-1 mt-3",children:[ch(t)?i.jsxs(i.Fragment,{children:[i.jsxs(ze,{variant:"primary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>C(!0),disabled:!t.file_path||!v("archives","reprint",t.created_by_id),title:t.file_path?v("archives","reprint",t.created_by_id)?void 0:d("archives.card.noPermissionReprint"):d("archives.card.noFileForReprint"),children:[i.jsx(_r,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"hidden sm:inline truncate",children:d("archives.card.reprint")})]}),i.jsxs(ze,{variant:"secondary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>ne(!0),disabled:!t.file_path||!y("queue:create"),title:t.file_path?y("queue:create")?d("archives.card.schedulePrint"):d("archives.permission.noAddToQueue"):d("archives.card.noFileForReprint"),children:[i.jsx(Xr,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"hidden sm:inline truncate",children:d("archives.card.schedule")})]}),i.jsx(ze,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const ye=t.print_name||t.filename||"model";uh(t.id,ye,"file",c)},title:d("archives.card.openInBambuStudio"),children:i.jsx(ni,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}):i.jsxs(ze,{variant:"primary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>{const ye=t.print_name||t.filename||"model";uh(t.id,ye,"file",c)},title:d("archives.card.openInBambuStudioToSlice"),children:[i.jsx(ni,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"hidden sm:inline truncate",children:d("archives.card.slice")})]}),i.jsx(ze,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const ye=t.external_url||t.makerworld_url;ye&&window.open(ye,"_blank")},disabled:!t.external_url&&!t.makerworld_url,title:t.external_url?d("archives.card.externalLink"):t.makerworld_url?d("archives.card.makerWorld",{designer:t.designer||d("archives.card.viewProject")}):d("archives.card.noExternalLink"),children:i.jsx(Ch,{className:`w-3 h-3 sm:w-4 sm:h-4 ${!t.external_url&&!t.makerworld_url?"opacity-20":""}`})}),i.jsx(ze,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{ge.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ye=>{console.error("Archive download failed:",ye)})},title:d("archives.card.download"),children:i.jsx(fi,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),i.jsx(ze,{variant:"ghost",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>P(!0),disabled:!v("archives","delete",t.created_by_id),title:v("archives","delete",t.created_by_id)?d("archives.card.delete"):d("archives.card.noPermissionDelete"),children:i.jsx(nn,{className:"w-3 h-3 sm:w-4 sm:h-4 text-red-400"})})]})]}),T&&i.jsx(die,{archive:t,onClose:()=>D(!1)}),g&&i.jsx(LI,{archiveId:t.id,title:t.print_name||t.filename,fileType:doe(t.filename),onClose:()=>_(!1)}),N&&i.jsx(xu,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>C(!1)}),k&&i.jsx(Nn,{title:d("archives.modal.deleteArchive"),message:d("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{He.mutate(),P(!1)},onCancel:()=>P(!1)}),se&&i.jsx(Nn,{title:d("archives.modal.removeSource3mf"),message:d("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{fe.mutate(),pe(!1)},onCancel:()=>pe(!1)}),Te&&i.jsx(Nn,{title:d("archives.modal.removeF3d"),message:d("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{je.mutate(),q(!1)},onCancel:()=>q(!1)}),X&&i.jsx(Nn,{title:d("archives.modal.removeTimelapse"),message:d("archives.modal.removeTimelapseConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{F.mutate(),j(!1)},onCancel:()=>j(!1)}),E&&i.jsx(mie,{x:E.x,y:E.y,items:Xe,onClose:()=>U(null)}),A&&t.timelapse_path&&i.jsx(uoe,{src:ge.getArchiveTimelapse(t.id),title:d("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>R(!1),onEdit:()=>{p.invalidateQueries({queryKey:["archives"]}),R(!1)}}),G&&Z.length>0&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:d("archives.modal.selectTimelapse")}),i.jsx("p",{className:"text-sm text-gray-400 mt-1",children:d("archives.modal.selectTimelapseDesc")})]}),i.jsx("button",{onClick:()=>{z(!1),I([])},className:"text-gray-400 hover:text-white p-1",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:Z.map(ye=>i.jsxs("button",{onClick:()=>Fe.mutate(ye.name),disabled:Fe.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:[i.jsx(kh,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-white font-medium truncate",children:ye.name}),i.jsxs("p",{className:"text-sm text-gray-400",children:[xo(ye.size),ye.mtime&&` • ${Df(ye.mtime,l)}`]})]})]},ye.name))}),i.jsx("div",{className:"p-4 border-t border-gray-700",children:i.jsx(ze,{variant:"secondary",onClick:()=>{z(!1),I([])},className:"w-full",children:"Cancel"})})]})}),J&&i.jsx(hie,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>ae(!1)}),Y&&t.photos&&t.photos.length>0&&i.jsx(pie,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>ue(!1),onDelete:async ye=>{try{await ge.deleteArchivePhoto(t.id,ye),p.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.photoDeleted"))}catch{f(d("archives.toast.failedDeletePhoto"),"error")}}}),de&&i.jsx(coe,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>he(!1)}),V&&i.jsx(xu,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>ne(!1)}),i.jsx("input",{ref:$,type:"file",accept:".3mf",className:"hidden",onChange:ye=>{const We=ye.target.files?.[0];We&&ve.mutate(We),ye.target.value=""}}),i.jsx("input",{ref:ee,type:"file",accept:".f3d",className:"hidden",onChange:ye=>{const We=ye.target.files?.[0];We&&me.mutate(We),ye.target.value=""}}),i.jsx("input",{ref:W,type:"file",accept:".mp4,.avi,.mkv",className:"hidden",onChange:ye=>{const We=ye.target.files?.[0];We&&te.mutate(We),ye.target.value=""}})]})}function aZe({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:a,projects:s,isHighlighted:o,preferredSlicer:l="bambu_studio",t:c,onNavigateToArchive:u}){const d=sn(),{showToast:m}=bn(),{hasPermission:p,canModify:f}=Ar(),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,N]=w.useState(!1),[C,k]=w.useState(!1),[P,T]=w.useState(!1),[D,A]=w.useState(!1),[R,G]=w.useState(!1),[z,Z]=w.useState([]),[I,J]=w.useState(!1),[ae,Y]=w.useState(!1),[ue,de]=w.useState(!1),[he,V]=w.useState(!1),[ne,se]=w.useState(!1),[pe,Te]=w.useState(!1),[q,X]=w.useState(null),j=w.useRef(null),E=w.useRef(null),U=w.useRef(null),K=t.duplicate_sequence??0,H=t.original_archive_id??null,re=gt({mutationFn:()=>ge.deleteArchiveTimelapse(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseRemoved"))},onError:me=>{m(me.message||c("archives.toast.failedRemoveTimelapse"),"error")}}),O=gt({mutationFn:me=>ge.uploadArchiveTimelapse(t.id,me),onSuccess:me=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseUploaded",{filename:me.filename}))},onError:me=>{m(me.message||c("archives.toast.failedUploadTimelapse"),"error")}}),$=gt({mutationFn:me=>ge.uploadSource3mf(t.id,me),onSuccess:me=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.source3mfAttached",{filename:me.filename}))},onError:me=>{m(me.message||c("archives.toast.failedUploadSource3mf"),"error")}}),ee=gt({mutationFn:()=>ge.deleteSource3mf(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.source3mfRemoved"))},onError:me=>{m(me.message||c("archives.toast.failedRemoveSource3mf"),"error")}}),W=gt({mutationFn:me=>ge.uploadF3d(t.id,me),onSuccess:me=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.f3dAttached",{filename:me.filename}))},onError:me=>{m(me.message||c("archives.toast.failedUploadF3d"),"error")}}),ie=gt({mutationFn:()=>ge.deleteF3d(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.f3dRemoved"))},onError:me=>{m(me.message||c("archives.toast.failedRemoveF3d"),"error")}}),ce=gt({mutationFn:()=>ge.scanArchiveTimelapse(t.id),onSuccess:me=>{me.status==="attached"?(d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseAttached",{filename:me.filename}))):me.status==="exists"?m(c("archives.toast.timelapseAlreadyAttached")):me.status==="not_found"&&me.available_files&&me.available_files.length>0?(Z(me.available_files),G(!0)):m(me.message||c("archives.toast.noMatchingTimelapse"),"warning")},onError:me=>{m(me.message||c("archives.toast.failedScanTimelapse"),"error")}}),be=gt({mutationFn:me=>ge.selectArchiveTimelapse(t.id,me),onSuccess:me=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseAttached",{filename:me.filename})),G(!1),Z([])},onError:me=>{m(me.message||c("archives.toast.failedAttachTimelapse"),"error")}}),xe=gt({mutationFn:()=>ge.deleteArchive(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.archiveDeleted"))},onError:()=>{m(c("archives.toast.failedDeleteArchive"),"error")}}),oe=gt({mutationFn:()=>ge.toggleFavorite(t.id),onSuccess:me=>{d.invalidateQueries({queryKey:["archives"]}),m(me.is_favorite?c("archives.toast.addedToFavorites"):c("archives.toast.removedFromFavorites"))}}),{data:L}=et({queryKey:["archive-folders",t.id],queryFn:()=>ge.getLibraryFoldersByArchive(t.id)}),F=gt({mutationFn:me=>ge.updateArchive(t.id,{project_id:me}),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),d.invalidateQueries({queryKey:["projects"]}),m(c("archives.toast.projectUpdated"))},onError:()=>{m(c("archives.toast.failedUpdateProject"),"error")}}),te=me=>{me.preventDefault(),X({x:me.clientX,y:me.clientY})},fe=[...ch(t)?[{label:c("archives.menu.print"),icon:i.jsx(_r,{className:"w-4 h-4"}),onClick:()=>N(!0),disabled:!t.file_path||!f("archives","reprint",t.created_by_id),title:t.file_path?f("archives","reprint",t.created_by_id)?void 0:c("archives.permission.noReprint"):c("archives.card.noFileForReprint")},{label:c("archives.menu.schedule"),icon:i.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>k(!0),disabled:!t.file_path||!p("queue:create"),title:t.file_path?p("queue:create")?void 0:c("archives.permission.noAddToQueue"):c("archives.card.noFileForReprint")},{label:c("archives.menu.openInBambuStudio"),icon:i.jsx(ni,{className:"w-4 h-4"}),onClick:()=>{const me=t.print_name||t.filename||"model";uh(t.id,me,"file",l)},disabled:!t.file_path,title:t.file_path?void 0:c("archives.card.noFileForReprint")}]:[{label:c("archives.menu.slice"),icon:i.jsx(ni,{className:"w-4 h-4"}),onClick:()=>{const me=t.print_name||t.filename||"model";uh(t.id,me,"file",l)}}],{label:t.external_url?c("archives.menu.externalLink"):c("archives.menu.viewOnMakerWorld"),icon:i.jsx(Ch,{className:"w-4 h-4"}),onClick:()=>{const me=t.external_url||t.makerworld_url;me&&window.open(me,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.preview3d"),icon:i.jsx(ia,{className:"w-4 h-4"}),onClick:()=>T(!0)},{label:c("archives.menu.viewTimelapse"),icon:i.jsx(kh,{className:"w-4 h-4"}),onClick:()=>A(!0),disabled:!t.timelapse_path},{label:c("archives.menu.scanForTimelapse"),icon:i.jsx(BN,{className:"w-4 h-4"}),onClick:()=>ce.mutate(),disabled:!t.printer_id||!!t.timelapse_path||ce.isPending||!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.uploadTimelapse"),icon:i.jsx(yi,{className:"w-4 h-4"}),onClick:()=>U.current?.click(),disabled:!!t.timelapse_path||!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.timelapse_path?[{label:c("archives.menu.removeTimelapse"),icon:i.jsx(nn,{className:"w-4 h-4"}),onClick:()=>Te(!0),danger:!0,disabled:!f("archives","update",t.created_by_id),title:f("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:i.jsx(ON,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?ge.downloadSource3mf(t.id).catch(me=>{console.error("Source 3MF download failed:",me)}):j.current?.click()},disabled:!t.source_3mf_path&&!f("archives","update",t.created_by_id),title:!t.source_3mf_path&&!f("archives","update",t.created_by_id)?c("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:c("archives.menu.replaceSource3mf"),icon:i.jsx(yi,{className:"w-4 h-4"}),onClick:()=>j.current?.click(),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.removeSource3mf"),icon:i.jsx(nn,{className:"w-4 h-4"}),onClick:()=>V(!0),danger:!0,disabled:!f("archives","update",t.created_by_id),title:f("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:i.jsx(ia,{className:"w-4 h-4"}),onClick:()=>E.current?.click(),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:c("archives.menu.downloadF3d"),icon:i.jsx(fi,{className:"w-4 h-4"}),onClick:()=>{ge.downloadF3d(t.id).catch(me=>{console.error("F3D download failed:",me)})}},{label:c("archives.menu.removeF3d"),icon:i.jsx(nn,{className:"w-4 h-4"}),onClick:()=>se(!0),danger:!0,disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.download"),icon:i.jsx(fi,{className:"w-4 h-4"}),onClick:()=>{ge.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(me=>{console.error("Archive download failed:",me)})},disabled:!p("archives:read"),title:p("archives:read")?void 0:c("archives.permission.noDownload")},{label:c("archives.menu.copyDownloadLink"),icon:i.jsx(ko,{className:"w-4 h-4"}),onClick:()=>{const me=`${window.location.origin}${ge.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(me).then(()=>{m(c("archives.toast.linkCopied"))}).catch(()=>{m(c("archives.toast.failedCopyLink"),"error")})},disabled:!p("archives:read"),title:p("archives:read")?void 0:c("archives.permission.noCopyLink")},{label:c("archives.menu.qrCode"),icon:i.jsx(eQ,{className:"w-4 h-4"}),onClick:()=>J(!0)},{label:t.photos?.length?c("archives.menu.viewPhotosCount",{count:t.photos.length}):c("archives.menu.viewPhotos"),icon:i.jsx(dx,{className:"w-4 h-4"}),onClick:()=>Y(!0),disabled:!t.photos?.length},{label:c("archives.menu.projectPage"),icon:i.jsx(Bs,{className:"w-4 h-4"}),onClick:()=>de(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?c("archives.menu.removeFromFavorites"):c("archives.menu.addToFavorites"),icon:i.jsx(Mf,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>oe.mutate(),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.edit"),icon:i.jsx(Yi,{className:"w-4 h-4"}),onClick:()=>v(!0),disabled:!f("archives","update",t.created_by_id),title:f("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:i.jsx(vs,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:c("archives.menu.addToProject"),icon:i.jsx(vs,{className:"w-4 h-4"}),onClick:()=>{},submenu:(()=>{const me=[];if(t.project_id&&me.push({label:c("archives.menu.removeFromProject"),icon:i.jsx(Ht,{className:"w-4 h-4"}),onClick:()=>F.mutate(null)}),!s)me.push({label:c("archives.menu.loading"),icon:i.jsx(ft,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const je=s.filter(we=>we.status==="active");je.length===0?me.push({label:c("archives.menu.noProjectsAvailable"),icon:i.jsx(vs,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):je.forEach(we=>{me.push({label:we.name,icon:i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:we.color||"#888"}}),onClick:()=>F.mutate(we.id),disabled:t.project_id===we.id})})}return me})()},{label:c(n?"archives.menu.deselect":"archives.menu.select"),icon:n?i.jsx(Ks,{className:"w-4 h-4"}):i.jsx(rl,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.delete"),icon:i.jsx(nn,{className:"w-4 h-4"}),onClick:()=>g(!0),danger:!0,disabled:!f("archives","delete",t.created_by_id),title:f("archives","delete",t.created_by_id)?void 0:c("archives.permission.noDelete")}];return i.jsxs(i.Fragment,{children:[i.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:te,children:[i.jsxs("div",{className:"col-span-1 flex items-center gap-2",children:[a&&i.jsx("button",{onClick:()=>r(t.id),children:n?i.jsx(Ks,{className:"w-4 h-4 text-bambu-green"}):i.jsx(rl,{className:"w-4 h-4 text-bambu-gray"})}),t.thumbnail_path?i.jsx("img",{src:ge.getArchiveThumbnail(t.id),alt:"",className:"w-10 h-10 object-cover rounded"}):i.jsx("div",{className:"w-10 h-10 bg-bambu-dark rounded flex items-center justify-center",children:i.jsx(Ud,{className:"w-5 h-5 text-bambu-dark-tertiary"})})]}),i.jsxs("div",{className:"col-span-4",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("p",{className:"text-white text-sm truncate",children:t.print_name||t.filename}),(t.status==="failed"||t.status==="aborted")&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] leading-tight bg-status-error/80 text-white flex-shrink-0",children:t.status==="aborted"?c("archives.card.cancelled"):c("archives.card.failed")}),t.duplicate_count>0&&K>0&&H&&i.jsxs("button",{onClick:me=>{me.stopPropagation(),u?.(H)},className:"px-1.5 py-0.5 rounded text-[10px] leading-tight bg-purple-500/80 hover:bg-purple-600/90 text-white flex-shrink-0 transition-colors flex items-center gap-1",title:c("archives.viewOriginalPrint",{id:H}),children:[i.jsx(ko,{className:"w-3 h-3"}),"#",K]}),t.duplicate_count>0&&K===0&&i.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] leading-tight bg-purple-500/80 text-white flex-shrink-0 flex items-center gap-1",title:`${t.duplicate_count} reprint${t.duplicate_count===1?"":"s"}`,children:[i.jsx(XX,{className:"w-3 h-3"}),"+",t.duplicate_count]}),t.timelapse_path&&i.jsx("span",{title:c("archives.list.hasTimelapse"),children:i.jsx(kh,{className:"w-3.5 h-3.5 text-bambu-green flex-shrink-0"})}),L&&L.length>0&&i.jsx(fo,{to:`/files?folder=${L[0].id}`,className:"flex-shrink-0",title:c("archives.card.openFolder",{name:L[0].name}),onClick:me=>me.stopPropagation(),children:i.jsx(Ac,{className:"w-3.5 h-3.5 text-yellow-400"})})]}),(t.filament_type||t.sliced_for_model)&&i.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[t.sliced_for_model&&i.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",title:c("archives.card.slicedFor",{model:t.sliced_for_model}),children:[i.jsx(_r,{className:"w-2.5 h-2.5"}),t.sliced_for_model]}),t.sliced_for_model&&t.filament_type&&i.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.filament_type&&i.jsx("span",{className:"text-xs text-bambu-gray",children:t.filament_type}),t.filament_color&&i.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((me,je)=>i.jsx("div",{className:"w-2.5 h-2.5 rounded-full border border-black/20",style:{backgroundColor:me},title:me},je))})]})]}),i.jsx("div",{className:"col-span-2 text-sm text-bambu-gray truncate",children:e}),i.jsxs("div",{className:"col-span-2 text-sm text-bambu-gray",children:[i.jsx("div",{children:jf(t.created_at)}),t.created_by_username&&i.jsxs("div",{className:"flex items-center gap-1 text-xs opacity-75",title:c("archives.card.uploadedBy",{name:t.created_by_username}),children:[i.jsx($d,{className:"w-3 h-3"}),t.created_by_username]})]}),i.jsx("div",{className:"col-span-1 text-sm text-bambu-gray",children:xo(t.file_size)}),i.jsxs("div",{className:"col-span-2 flex justify-end gap-1",children:[ch(t)&&i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>N(!0),disabled:!f("archives","reprint",t.created_by_id),title:f("archives","reprint",t.created_by_id)?c("archives.card.reprint"):c("archives.card.noPermissionReprint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:i.jsx(Co,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{const me=t.print_name||t.filename||"model";uh(t.id,me,"file",l)},title:c("archives.card.openInBambuStudio"),children:i.jsx(ni,{className:"w-4 h-4"})}),(t.external_url||t.makerworld_url)&&i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>window.open(t.external_url||t.makerworld_url,"_blank"),title:t.external_url?c("archives.card.externalLink"):"MakerWorld",children:i.jsx(Ch,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{ge.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(me=>{console.error("Archive download failed:",me)})},title:c("archives.card.download"),children:i.jsx(fi,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>v(!0),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?c("archives.card.edit"):c("archives.card.noPermissionEdit"),children:i.jsx(Yi,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>g(!0),disabled:!f("archives","delete",t.created_by_id),title:f("archives","delete",t.created_by_id)?c("archives.card.delete"):c("archives.card.noPermissionDelete"),children:i.jsx(nn,{className:"w-4 h-4 text-red-400"})}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:me=>{const je=me.currentTarget.getBoundingClientRect();X({x:je.left,y:je.bottom+4})},title:c("archives.card.moreOptions"),children:i.jsx(Nh,{className:"w-4 h-4"})})]})]}),y&&i.jsx(die,{archive:t,onClose:()=>v(!1)}),P&&i.jsx(LI,{archiveId:t.id,title:t.print_name||t.filename,fileType:doe(t.filename),onClose:()=>T(!1)}),_&&i.jsx(xu,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>N(!1)}),b&&i.jsx(Nn,{title:c("archives.modal.deleteArchive"),message:c("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{xe.mutate(),g(!1)},onCancel:()=>g(!1)}),he&&i.jsx(Nn,{title:c("archives.modal.removeSource3mf"),message:c("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{ee.mutate(),V(!1)},onCancel:()=>V(!1)}),ne&&i.jsx(Nn,{title:c("archives.modal.removeF3d"),message:c("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{ie.mutate(),se(!1)},onCancel:()=>se(!1)}),pe&&i.jsx(Nn,{title:c("archives.modal.removeTimelapse"),message:c("archives.modal.removeTimelapseConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{re.mutate(),Te(!1)},onCancel:()=>Te(!1)}),q&&i.jsx(mie,{x:q.x,y:q.y,items:fe,onClose:()=>X(null)}),D&&t.timelapse_path&&i.jsx(uoe,{src:ge.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:()=>A(!1),onEdit:()=>{d.invalidateQueries({queryKey:["archives"]}),A(!1)}}),R&&z.length>0&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:c("archives.modal.selectTimelapse")}),i.jsx("p",{className:"text-sm text-gray-400 mt-1",children:c("archives.modal.selectTimelapseDesc")})]}),i.jsx("button",{onClick:()=>{G(!1),Z([])},className:"text-gray-400 hover:text-white p-1",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:z.map(me=>i.jsxs("button",{onClick:()=>be.mutate(me.name),disabled:be.isPending,className:"w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors mb-1",children:[i.jsx("div",{className:"font-medium text-white",children:me.name}),i.jsxs("div",{className:"text-sm text-gray-400 flex gap-3",children:[i.jsx("span",{children:xo(me.size)}),me.mtime&&i.jsx("span",{children:jf(me.mtime)})]})]},me.name))})]})}),I&&i.jsx(hie,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>J(!1)}),ae&&t.photos&&i.jsx(pie,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>Y(!1),onDelete:async me=>{try{await ge.deleteArchivePhoto(t.id,me),d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.photoDeleted"))}catch{m(c("archives.toast.failedDeletePhoto"),"error")}}}),ue&&i.jsx(coe,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>de(!1)}),C&&i.jsx(xu,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>k(!1)}),i.jsx("input",{ref:j,type:"file",accept:".3mf",className:"hidden",onChange:me=>{const je=me.target.files?.[0];je&&$.mutate(je),me.target.value=""}}),i.jsx("input",{ref:E,type:"file",accept:".f3d",className:"hidden",onChange:me=>{const je=me.target.files?.[0];je&&W.mutate(je),me.target.value=""}}),i.jsx("input",{ref:U,type:"file",accept:".mp4,.avi,.mkv",className:"hidden",onChange:me=>{const je=me.target.files?.[0];je&&O.mutate(je),me.target.value=""}})]})}const sZe=[{id:"all",label:"All Archives",icon:i.jsx(Ac,{className:"w-4 h-4"})},{id:"recent",label:"Last 24 Hours",icon:i.jsx(Zn,{className:"w-4 h-4"})},{id:"this-week",label:"This Week",icon:i.jsx(Xr,{className:"w-4 h-4"})},{id:"this-month",label:"This Month",icon:i.jsx(Xr,{className:"w-4 h-4"})},{id:"favorites",label:"Favorites",icon:i.jsx(Mf,{className:"w-4 h-4"})},{id:"failed",label:"Failed Prints",icon:i.jsx(Li,{className:"w-4 h-4"})},{id:"duplicates",label:"Duplicates",icon:i.jsx(ko,{className:"w-4 h-4"})}];function oZe(){const{t}=Dt(),e=sn(),{showToast:n}=bn(),{hasPermission:r,hasAnyPermission:a}=Ar(),s=w.useRef(null),[o,l]=w.useState(""),[c,u]=w.useState(()=>{const le=localStorage.getItem("archiveFilterPrinter");return le?Number(le):null}),[d,m]=w.useState(()=>localStorage.getItem("archiveFilterMaterial")),[p,f]=w.useState(()=>{const le=localStorage.getItem("archiveFilterColors");return le?new Set(JSON.parse(le)):new Set}),[y,v]=w.useState(()=>localStorage.getItem("archiveColorFilterMode")||"or"),[b,g]=w.useState(()=>localStorage.getItem("archiveFilterFavorites")==="true"),[_,N]=w.useState(()=>localStorage.getItem("archiveHideFailed")==="true"),[C,k]=w.useState(()=>localStorage.getItem("archiveHideDuplicates")==="true"),[P,T]=w.useState(()=>localStorage.getItem("archiveFilterTag")),[D,A]=w.useState(()=>localStorage.getItem("archiveFilterFileType")||"all"),[R,G]=w.useState(!1),[z,Z]=w.useState([]),[I,J]=w.useState(!1),[ae,Y]=w.useState(new Set),[ue,de]=w.useState(!1),[he,V]=w.useState(!1),[ne,se]=w.useState(!1),[pe,Te]=w.useState(!1),[q,X]=w.useState(()=>localStorage.getItem("archiveViewMode")||"grid"),[j,E]=w.useState(()=>localStorage.getItem("archiveSortBy")||"date-desc"),[U,K]=w.useState(()=>localStorage.getItem("archiveCollection")||"all"),[H,re]=w.useState(!1),[O,$]=w.useState(!1),[ee,W]=w.useState(!1),[ie,ce]=w.useState(!1),[be,xe]=w.useState(null),[oe,L]=w.useState(null),[F,te]=w.useState(()=>localStorage.getItem("logFilterUser")||null),[ve,fe]=w.useState(()=>localStorage.getItem("logFilterStatus")),[me,je]=w.useState(()=>localStorage.getItem("logFilterDateFrom")||""),[we,Fe]=w.useState(()=>localStorage.getItem("logFilterDateTo")||""),[He,Oe]=w.useState(()=>{const le=localStorage.getItem("logOffset");return le?Number(le):0}),[_e,Ae]=w.useState(!1),[Be,Me]=w.useState(()=>{const le=localStorage.getItem("logPageSize");return le?Number(le):25}),Xe=w.useCallback(le=>{L(le),xe(le)},[]);w.useEffect(()=>{if(be){const le=setTimeout(()=>{const Ye=document.querySelector(`[data-archive-id="${be}"]`);Ye?Ye.scrollIntoView({behavior:"smooth",block:"center"}):oe===be&&n(t("archives.originalPrintNotVisible"),"warning"),oe===be&&L(null)},100),Le=setTimeout(()=>xe(null),5e3);return()=>{clearTimeout(le),clearTimeout(Le)}}},[be,oe,n,t]);const{data:ye,isLoading:We}=et({queryKey:["archives",c],queryFn:()=>ge.getArchives(c||void 0)}),{data:Pe}=et({queryKey:["printers"],queryFn:ge.getPrinters}),{data:Ke}=et({queryKey:["projects"],queryFn:()=>ge.getProjects()}),{data:Ve}=et({queryKey:["settings"],queryFn:ge.getSettings}),{data:ke}=et({queryKey:["users"],queryFn:ge.getUsers,enabled:q==="log"}),{data:Ce,isLoading:$e}=et({queryKey:["print-log",c,F,ve,me,we,o,He,Be],queryFn:()=>ge.getPrintLog({search:o||void 0,printerId:c||void 0,username:F||void 0,status:ve||void 0,dateFrom:me||void 0,dateTo:we||void 0,limit:Be,offset:He}),enabled:q==="log"}),nt=Ve?.time_format||"system",xt=Ve?.preferred_slicer||"bambu_studio",vt=Wo(Ve?.currency||"USD"),mt=gt({mutationFn:async le=>(await Promise.all(le.map(Le=>ge.deleteArchive(Le))),le.length),onSuccess:le=>{e.invalidateQueries({queryKey:["archives"]}),Y(new Set),n(`${le} archive${le!==1?"s":""} deleted`)},onError:()=>{n(t("archives.toast.failedDeleteArchives"),"error")}}),qe=gt({mutationFn:()=>ge.clearPrintLog(),onSuccess:le=>{e.invalidateQueries({queryKey:["print-log"]}),Oe(0),n(t("archives.log.cleared",{count:le.deleted}))},onError:()=>{n(t("archives.log.clearFailed"),"error")}});w.useEffect(()=>{c!==null?localStorage.setItem("archiveFilterPrinter",c.toString()):localStorage.removeItem("archiveFilterPrinter")},[c]),w.useEffect(()=>{d?localStorage.setItem("archiveFilterMaterial",d):localStorage.removeItem("archiveFilterMaterial")},[d]),w.useEffect(()=>{localStorage.setItem("archiveFilterColors",JSON.stringify([...p]))},[p]),w.useEffect(()=>{localStorage.setItem("archiveColorFilterMode",y)},[y]),w.useEffect(()=>{localStorage.setItem("archiveFilterFavorites",b.toString())},[b]),w.useEffect(()=>{localStorage.setItem("archiveHideFailed",_.toString())},[_]),w.useEffect(()=>{localStorage.setItem("archiveHideDuplicates",C.toString())},[C]),w.useEffect(()=>{P?localStorage.setItem("archiveFilterTag",P):localStorage.removeItem("archiveFilterTag")},[P]),w.useEffect(()=>{localStorage.setItem("archiveFilterFileType",D)},[D]),w.useEffect(()=>{localStorage.setItem("archiveViewMode",q)},[q]),w.useEffect(()=>{localStorage.setItem("archiveSortBy",j)},[j]),w.useEffect(()=>{localStorage.setItem("archiveCollection",U)},[U]),w.useEffect(()=>{F?localStorage.setItem("logFilterUser",F):localStorage.removeItem("logFilterUser")},[F]),w.useEffect(()=>{ve?localStorage.setItem("logFilterStatus",ve):localStorage.removeItem("logFilterStatus")},[ve]),w.useEffect(()=>{me?localStorage.setItem("logFilterDateFrom",me):localStorage.removeItem("logFilterDateFrom")},[me]),w.useEffect(()=>{we?localStorage.setItem("logFilterDateTo",we):localStorage.removeItem("logFilterDateTo")},[we]),w.useEffect(()=>{localStorage.setItem("logOffset",He.toString())},[He]),w.useEffect(()=>{localStorage.setItem("logPageSize",Be.toString())},[Be]);const Nt=new Map(Pe?.map(le=>[le.id,le.name])||[]),_t=[...new Set(ye?.flatMap(le=>le.filament_type?.split(", ")||[]).filter(Boolean)||[])].sort(),rt=[...new Set(ye?.flatMap(le=>le.filament_color?.split(",")||[]).filter(Boolean)||[])],Rt=[...new Set(ye?.flatMap(le=>le.tags?.split(",").map(Le=>Le.trim())||[]).filter(Boolean)||[])].sort(),qt=ye?.filter(le=>{const Le=new Date,Ye=Qn(le.created_at)||new Date(0);let Ge=!0;switch(U){case"recent":Ge=Le.getTime()-Ye.getTime()<1440*60*1e3;break;case"this-week":Ge=Le.getTime()-Ye.getTime()<10080*60*1e3;break;case"this-month":Ge=Ye.getMonth()===Le.getMonth()&&Ye.getFullYear()===Le.getFullYear();break;case"favorites":Ge=le.is_favorite===!0;break;case"failed":Ge=le.status==="failed"||le.status==="aborted";break;case"duplicates":Ge=le.duplicate_count>0;break}const Ie=(le.print_name||le.filename).toLowerCase().includes(o.toLowerCase()),pt=!d||le.filament_type?.split(", ").includes(d),dt=le.filament_color?.split(",")||[],Je=p.size===0||(y==="or"?dt.some(wn=>p.has(wn)):[...p].every(wn=>dt.includes(wn))),Tt=U==="favorites"||!b||le.is_favorite,zt=U==="failed"||!_||le.status!=="failed"&&le.status!=="aborted",Ut=U==="duplicates"||!C||le.duplicate_count===0||le.duplicate_sequence===0,It=le.tags?.split(",").map(wn=>wn.trim())||[],cn=!P||It.includes(P),Xt=ch(le);return Ge&&Ie&&pt&&Je&&Tt&&zt&&Ut&&cn&&(D==="all"||D==="gcode"&&Xt||D==="source"&&!Xt)}).sort((le,Le)=>{switch(j){case"date-desc":return(Qn(Le.created_at)?.getTime()||0)-(Qn(le.created_at)?.getTime()||0);case"date-asc":return(Qn(le.created_at)?.getTime()||0)-(Qn(Le.created_at)?.getTime()||0);case"name-asc":return(le.print_name||le.filename).localeCompare(Le.print_name||Le.filename);case"name-desc":return(Le.print_name||Le.filename).localeCompare(le.print_name||le.filename);case"size-desc":return Le.file_size-le.file_size;case"size-asc":return le.file_size-Le.file_size;default:return 0}}),Kt=ue||ae.size>0,Qt=le=>{Y(Le=>{const Ye=new Set(Le);return Ye.has(le)?Ye.delete(le):Ye.add(le),Ye})},mn=()=>{qt&&Y(new Set(qt.map(le=>le.id)))},hn=()=>{Y(new Set),de(!1)},Hn=le=>{f(Le=>{const Ye=new Set(Le);return Ye.has(le)?Ye.delete(le):Ye.add(le),Ye})},Qe=()=>{f(new Set)},De=()=>{l(""),u(null),m(null),g(!1),N(!1),k(!1),T(null),A("all")},ot=o||c||d||b||_||C||P||D!=="all",st=w.useCallback(le=>{le.preventDefault(),le.dataTransfer.types.includes("Files")&&J(!0)},[]),Ze=w.useCallback(le=>{le.preventDefault(),le.currentTarget===le.target&&J(!1)},[]),Ee=w.useCallback(le=>{le.preventDefault(),J(!1);const Le=Array.from(le.dataTransfer.files).filter(Ye=>Ye.name.endsWith(".3mf"));Le.length>0?(Z(Le),G(!0)):le.dataTransfer.files.length>0&&n(t("archives.page.only3mfSupported"),"warning")},[n,t]),ct=w.useCallback(le=>{const Le=le.target;if(Le.tagName==="INPUT"||Le.tagName==="TEXTAREA"||Le.isContentEditable){le.key==="Escape"&&Le.blur();return}switch(le.key){case"/":le.preventDefault(),s.current?.focus();break;case"u":case"U":!le.metaKey&&!le.ctrlKey&&(le.preventDefault(),G(!0));break;case"Escape":Kt&&hn();break}},[Kt]);return w.useEffect(()=>(document.addEventListener("keydown",ct),()=>document.removeEventListener("keydown",ct)),[ct]),i.jsxs("div",{className:"p-4 md:p-8 relative",onDragOver:st,onDragLeave:Ze,onDrop:Ee,children:[I&&i.jsx("div",{className:"fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none",children:i.jsxs("div",{className:"border-4 border-dashed border-bambu-green rounded-xl p-12 text-center",children:[i.jsx(yi,{className:"w-16 h-16 mx-auto mb-4 text-bambu-green"}),i.jsx("p",{className:"text-2xl font-semibold text-white mb-2",children:"Drop .3mf files here"}),i.jsx("p",{className:"text-bambu-gray",children:t("archives.releaseToUpload")})]})}),Kt&&i.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:[i.jsxs(ze,{variant:"secondary",size:"sm",onClick:hn,children:[i.jsx(Ht,{className:"w-4 h-4"}),"Close"]}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsxs("span",{className:"text-white font-medium",children:[ae.size," selected"]}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:mn,children:"Select All"}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>se(!0),disabled:!a("archives:update_own","archives:update_all"),title:a("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[i.jsx(Hd,{className:"w-4 h-4"}),"Tags"]}),i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>Te(!0),disabled:!a("archives:update_own","archives:update_all"),title:a("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[i.jsx(vs,{className:"w-4 h-4"}),"Project"]}),i.jsxs(ze,{variant:"secondary",size:"sm",disabled:!a("archives:update_own","archives:update_all"),title:a("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),onClick:()=>{const le=Array.from(ae);Promise.all(le.map(Le=>ge.toggleFavorite(Le))).then(()=>{e.invalidateQueries({queryKey:["archives"]}),n(`Toggled favorites for ${le.length} archive${le.length!==1?"s":""}`)}).catch(()=>{n(t("archives.toast.failedUpdateFavorites"),"error")})},children:[i.jsx(Mf,{className:"w-4 h-4"}),"Favorite"]}),i.jsxs(ze,{size:"sm",className:"bg-red-500 hover:bg-red-600",onClick:()=>V(!0),disabled:!a("archives:delete_own","archives:delete_all"),title:a("archives:delete_own","archives:delete_all")?void 0:t("archives.permission.noDelete"),children:[i.jsx(nn,{className:"w-4 h-4"}),"Delete"]})]}),i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:"Archives"}),i.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:U,onChange:le=>K(le.target.value),children:sZe.map(le=>i.jsx("option",{value:le.id,children:le.label},le.id))})]}),i.jsxs("p",{className:"text-bambu-gray",children:[qt?.length||0," of ",ye?.length||0," prints"]})]}),i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[i.jsxs("div",{className:"relative",children:[i.jsxs(ze,{variant:"secondary",onClick:()=>re(!H),disabled:O,children:[O?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(IN,{className:"w-4 h-4"}),"Export"]}),H&&i.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:[i.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()=>{re(!1),$(!0);try{const{blob:le,filename:Le}=await ge.exportArchives({format:"csv",printerId:c||void 0,status:U==="failed"?"failed":void 0,search:o||void 0}),Ye=URL.createObjectURL(le),Ge=document.createElement("a");Ge.href=Ye,Ge.download=Le,Ge.click(),URL.revokeObjectURL(Ye),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{$(!1)}},children:[i.jsx(Bs,{className:"w-4 h-4"}),"Export as CSV"]}),i.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()=>{re(!1),$(!0);try{const{blob:le,filename:Le}=await ge.exportArchives({format:"xlsx",printerId:c||void 0,status:U==="failed"?"failed":void 0,search:o||void 0}),Ye=URL.createObjectURL(le),Ge=document.createElement("a");Ge.href=Ye,Ge.download=Le,Ge.click(),URL.revokeObjectURL(Ye),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{$(!1)}},children:[i.jsx(IN,{className:"w-4 h-4"}),"Export as Excel"]})]})]}),ae.size>=2&&ae.size<=5&&i.jsxs(ze,{variant:"secondary",onClick:()=>W(!0),children:[i.jsx(Gb,{className:"w-4 h-4"}),"Compare (",ae.size,")"]}),!Kt&&i.jsxs(ze,{variant:"secondary",onClick:()=>de(!0),children:[i.jsx(Ks,{className:"w-4 h-4"}),"Select"]}),i.jsxs(ze,{onClick:()=>G(!0),disabled:!r("archives:create"),title:r("archives:create")?void 0:t("archives.permission.noCreate"),children:[i.jsx(yi,{className:"w-4 h-4"}),"Upload 3MF"]})]})]}),i.jsxs("div",{className:"flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden flex-shrink-0 w-fit mb-4",children:[i.jsx("button",{className:`p-2 ${q==="grid"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>X("grid"),title:t("archives.gridView"),children:i.jsx(ww,{className:"w-4 h-4"})}),i.jsx("button",{className:`p-2 ${q==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>X("list"),title:t("archives.listView"),children:i.jsx(sT,{className:"w-4 h-4"})}),i.jsx("button",{className:`p-2 ${q==="calendar"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>X("calendar"),title:t("archives.calendarView"),children:i.jsx(Ohe,{className:"w-4 h-4"})}),i.jsx("button",{className:`p-2 ${q==="log"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>X("log"),title:t("archives.logView"),children:i.jsx(spe,{className:"w-4 h-4"})})]}),q!=="log"&&i.jsx(Pt,{className:"mb-6",children:i.jsxs(Et,{className:"py-4",children:[i.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:gap-4 md:items-center md:flex-wrap",children:[i.jsxs("div",{className:"w-full md:flex-1 relative md:min-w-[200px]",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.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:le=>l(le.target.value)})]}),i.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:[i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(aT,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.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:le=>u(le.target.value?Number(le.target.value):null),children:[i.jsx("option",{value:"",children:"All Printers"}),Pe?.map(le=>i.jsx("option",{value:le.id,children:le.name},le.id))]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(Wi,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.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:le=>m(le.target.value||null),children:[i.jsx("option",{value:"",children:"All Materials"}),_t.map(le=>i.jsx("option",{value:le,children:le},le))]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(ON,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.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:le=>A(le.target.value),children:[i.jsx("option",{value:"all",children:"All Files"}),i.jsx("option",{value:"gcode",children:"Sliced (GCODE)"}),i.jsx("option",{value:"source",children:"Source Only"})]})]}),i.jsxs("button",{onClick:()=>g(!b),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${b?"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(b?"archives.showAll":"archives.showFavoritesOnly"),children:[i.jsx(Mf,{className:`w-4 h-4 ${b?"fill-yellow-400":""}`}),i.jsx("span",{className:"text-sm hidden md:inline",children:"Favorites"})]}),i.jsxs("button",{onClick:()=>N(!_),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${_?"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(_?"archives.showFailedPrints":"archives.hideFailedPrints"),children:[i.jsx(Li,{className:"w-4 h-4 "}),i.jsx("span",{className:"text-sm hidden md:inline",children:"Hide Failed"})]}),i.jsxs("button",{onClick:()=>k(!C),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${C?"bg-purple-500/20 border-purple-500 text-purple-400":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t("archives.hideDuplicates"),children:[i.jsx(ko,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm hidden md:inline",children:t("archives.hideDuplicates")})]}),Rt.length>0&&i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(Hd,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.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:P||"",onChange:le=>T(le.target.value||null),children:[i.jsx("option",{value:"",children:"All Tags"}),Rt.map(le=>i.jsx("option",{value:le,children:le},le))]}),i.jsx("button",{onClick:()=>ce(!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:i.jsx(dT,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(qL,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.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:j,onChange:le=>E(le.target.value),children:[i.jsx("option",{value:"date-desc",children:t("archives.sortNewest")}),i.jsx("option",{value:"date-asc",children:t("archives.sortOldest")}),i.jsxs("option",{value:"name-asc",children:[t("archives.sortName")," A-Z"]}),i.jsxs("option",{value:"name-desc",children:[t("archives.sortName")," Z-A"]}),i.jsx("option",{value:"size-desc",children:t("archives.sortLargest")}),i.jsx("option",{value:"size-asc",children:t("archives.sortSmallest")})]})]})]}),ot&&i.jsxs(ze,{variant:"ghost",size:"sm",onClick:De,className:"text-bambu-gray hover:text-white",children:[i.jsx(Ht,{className:"w-4 h-4"}),"Reset"]})]}),rt.length>0&&i.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Colors:"}),p.size>1&&i.jsx("button",{onClick:()=>v(le=>le==="or"?"and":"or"),className:`px-2 py-0.5 text-xs rounded transition-colors ${y==="and"?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:y==="or"?"Match ANY selected color":"Match ALL selected colors",children:y.toUpperCase()}),i.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:rt.map(le=>i.jsx("button",{onClick:()=>Hn(le),className:`w-6 h-6 rounded-full border-2 transition-all ${p.has(le)?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:le},title:le},le))}),p.size>0&&i.jsxs("button",{onClick:Qe,className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1",children:[i.jsx(Ht,{className:"w-3 h-3"}),"Clear"]})]})]})}),i.jsx(nZe,{}),We?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.loadingArchives")}):qt?.length===0?i.jsx(Pt,{children:i.jsxs(Et,{className:"text-center py-12",children:[i.jsx("p",{className:"text-bambu-gray",children:t(o?"archives.noArchivesSearch":"archives.noArchivesYet")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:"Archives are created automatically when prints complete"})]})}):q==="calendar"?i.jsx(Pt,{className:"p-6",children:i.jsx(CVe,{archives:qt||[],onArchiveClick:le=>{l(""),X("grid"),xe(le.id)},highlightedArchiveId:be})}):q==="grid"?i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:qt?.map(le=>i.jsx(iZe,{archive:le,printerName:le.printer_id?Nt.get(le.printer_id)||"Unknown":le.sliced_for_model?`Sliced for ${le.sliced_for_model}`:"No Printer",isSelected:ae.has(le.id),onSelect:Qt,selectionMode:Kt,projects:Ke,isHighlighted:le.id===be,timeFormat:nt,preferredSlicer:xt,currency:vt,t,onNavigateToArchive:Xe},le.id))}):q==="list"?i.jsx(Pt,{children:i.jsxs("div",{className:"divide-y divide-bambu-dark-tertiary",children:[i.jsxs("div",{className:"grid grid-cols-12 gap-4 px-4 py-3 text-xs text-bambu-gray font-medium",children:[i.jsx("div",{className:"col-span-1"}),i.jsx("div",{className:"col-span-4",children:"Name"}),i.jsx("div",{className:"col-span-2",children:"Printer"}),i.jsx("div",{className:"col-span-2",children:"Date"}),i.jsx("div",{className:"col-span-1",children:"Size"}),i.jsx("div",{className:"col-span-2 text-right",children:"Actions"})]}),qt?.map(le=>i.jsx(aZe,{archive:le,printerName:le.printer_id?Nt.get(le.printer_id)||"Unknown":le.sliced_for_model?`Sliced for ${le.sliced_for_model}`:"No Printer",isSelected:ae.has(le.id),onSelect:Qt,selectionMode:Kt,projects:Ke,isHighlighted:le.id===be,preferredSlicer:xt,t,onNavigateToArchive:Xe},le.id))]})}):q==="log"?i.jsxs("div",{className:"space-y-4",children:[i.jsx(Pt,{children:i.jsx(Et,{className:"py-3",children:i.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:items-center md:flex-wrap",children:[i.jsxs("div",{className:"flex-1 relative md:min-w-[200px]",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:t("archives.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:o,onChange:le=>{l(le.target.value),Oe(0)}})]}),i.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 text-sm",value:c||"",onChange:le=>{u(le.target.value?Number(le.target.value):null),Oe(0)},children:[i.jsx("option",{value:"",children:t("archives.log.allPrinters")}),Pe?.map(le=>i.jsx("option",{value:le.id,children:le.name},le.id))]}),i.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 text-sm",value:F||"",onChange:le=>{te(le.target.value||null),Oe(0)},children:[i.jsx("option",{value:"",children:t("archives.log.allUsers")}),ke?.map(le=>i.jsx("option",{value:le.username,children:le.username},le.id))]}),i.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 text-sm",value:ve||"",onChange:le=>{fe(le.target.value||null),Oe(0)},children:[i.jsx("option",{value:"",children:t("archives.log.allStatuses")}),i.jsx("option",{value:"completed",children:t("archives.status.completed")}),i.jsx("option",{value:"failed",children:t("archives.status.failed")}),i.jsx("option",{value:"stopped",children:t("archives.status.stopped")}),i.jsx("option",{value:"cancelled",children:t("archives.log.cancelled")}),i.jsx("option",{value:"skipped",children:t("archives.log.skipped")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("label",{className:"text-sm text-bambu-gray",children:t("archives.log.dateFrom")}),i.jsx("input",{type:"date",className:"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:me,onChange:le=>{je(le.target.value),Oe(0)}})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("label",{className:"text-sm text-bambu-gray",children:t("archives.log.dateTo")}),i.jsx("input",{type:"date",className:"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:we,onChange:le=>{Fe(le.target.value),Oe(0)}})]}),i.jsx("div",{className:"ml-auto",children:i.jsxs(ze,{variant:"danger",size:"sm",onClick:()=>Ae(!0),disabled:!r("archives:delete_all")||qe.isPending,children:[i.jsx(nn,{className:"w-4 h-4"}),t("archives.log.clearLog")]})})]})})}),i.jsx(Pt,{children:$e?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):Ce?.items.length?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary text-bambu-gray text-left",children:[i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.date")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.printName")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.printer")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.user")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.status")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.duration")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.filament")})]})}),i.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:Ce.items.map(le=>i.jsxs("tr",{className:"hover:bg-bambu-dark-secondary/50",children:[i.jsx("td",{className:"px-4 py-3 text-white whitespace-nowrap",children:Df(le.started_at||le.created_at,nt)}),i.jsx("td",{className:"px-4 py-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[le.thumbnail_path&&i.jsx("img",{src:ge.getPrintLogThumbnail(le.id),alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0",onError:Le=>{Le.target.style.display="none"}}),i.jsx("span",{className:"text-white truncate max-w-[200px]",children:le.print_name||"—"})]})}),i.jsx("td",{className:"px-4 py-3 text-bambu-gray-light",children:le.printer_name||"—"}),i.jsx("td",{className:"px-4 py-3 text-bambu-gray-light",children:le.created_by_username||"—"}),i.jsx("td",{className:"px-4 py-3",children:i.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${le.status==="completed"?"bg-green-500/20 text-green-400":le.status==="failed"?"bg-red-500/20 text-red-400":le.status==="stopped"?"bg-yellow-500/20 text-yellow-400":le.status==="cancelled"?"bg-orange-500/20 text-orange-400":le.status==="skipped"?"bg-blue-500/20 text-blue-400":"bg-gray-500/20 text-gray-400"}`,children:le.status})}),i.jsx("td",{className:"px-4 py-3 text-bambu-gray-light whitespace-nowrap",children:le.duration_seconds?Us(le.duration_seconds):"—"}),i.jsx("td",{className:"px-4 py-3",children:i.jsxs("div",{className:"flex items-center gap-1.5",children:[le.filament_color&&i.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:le.filament_color.startsWith("#")?le.filament_color:void 0}}),i.jsx("span",{className:"text-bambu-gray-light text-xs",children:le.filament_type||"—"})]})})]},le.id))})]})}),i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-bambu-dark-tertiary flex-wrap gap-2",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:t("archives.log.showing",{count:Math.min(He+Be,Ce.total),total:Ce.total})}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:t("archives.log.rowsPerPage")}),i.jsxs("select",{className:"px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-xs focus:border-bambu-green focus:outline-none",value:Be,onChange:le=>{Me(Number(le.target.value)),Oe(0)},children:[i.jsx("option",{value:10,children:"10"}),i.jsx("option",{value:25,children:"25"}),i.jsx("option",{value:50,children:"50"}),i.jsx("option",{value:100,children:"100"})]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("archives.log.page")," ",Math.floor(He/Be)+1," / ",Math.max(1,Math.ceil(Ce.total/Be))]}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>Oe(Math.max(0,He-Be)),disabled:He===0,children:i.jsx(Cc,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>Oe(He+Be),disabled:He+Be>=Ce.total,children:i.jsx(fa,{className:"w-4 h-4"})})]})]})]}):i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.log.noEntries")})})]}):null,R&&i.jsx(bVe,{onClose:()=>{G(!1),Z([])},initialFiles:z}),he&&i.jsx(Nn,{title:t("archives.modal.deleteArchives"),message:t("archives.modal.deleteArchivesConfirm",{count:ae.size}),confirmText:t("archives.modal.deleteCount",{count:ae.size}),variant:"danger",onConfirm:()=>{mt.mutate(Array.from(ae)),V(!1)},onCancel:()=>V(!1)}),ne&&i.jsx(vVe,{selectedIds:Array.from(ae),existingTags:Rt,onClose:()=>se(!1)}),pe&&i.jsx(wVe,{selectedIds:Array.from(ae),onClose:()=>Te(!1)}),ee&&ae.size>=2&&ae.size<=5&&i.jsx(ZQe,{archiveIds:Array.from(ae),onClose:()=>{W(!1),Y(new Set),de(!1)}}),ie&&i.jsx(rZe,{onClose:()=>ce(!1)}),_e&&i.jsx(Nn,{title:t("archives.log.clearLogTitle"),message:t("archives.log.clearLogConfirm"),confirmText:t("archives.log.clearLogButton"),variant:"danger",onConfirm:()=>{qe.mutate(),Ae(!1)},onCancel:()=>Ae(!1)})]})}function lZe(){for(var t=arguments.length,e=new Array(t),n=0;nr=>{e.forEach(a=>a(r))},e)}const RA=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function uy(t){const e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function _5(t){return"nodeType"in t}function Mo(t){var e,n;return t?uy(t)?t:_5(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function N5(t){const{Document:e}=Mo(t);return t instanceof e}function tS(t){return uy(t)?!1:t instanceof Mo(t).HTMLElement}function moe(t){return t instanceof Mo(t).SVGElement}function dy(t){return t?uy(t)?t.document:_5(t)?N5(t)?t:tS(t)||moe(t)?t.ownerDocument:document:document:document}const Cu=RA?w.useLayoutEffect:w.useEffect;function k5(t){const e=w.useRef(t);return Cu(()=>{e.current=t}),w.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a{t.current=setInterval(r,a)},[]),n=w.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function uw(t,e){e===void 0&&(e=[t]);const n=w.useRef(t);return Cu(()=>{n.current!==t&&(n.current=t)},e),n}function nS(t,e){const n=w.useRef();return w.useMemo(()=>{const r=t(n.current);return n.current=r,r},[...e])}function KC(t){const e=k5(t),n=w.useRef(null),r=w.useCallback(a=>{a!==n.current&&e?.(a,n.current),n.current=a},[]);return[n,r]}function xL(t){const e=w.useRef();return w.useEffect(()=>{e.current=t},[t]),e.current}let zD={};function rS(t,e){return w.useMemo(()=>{if(e)return e;const n=zD[t]==null?0:zD[t]+1;return zD[t]=n,t+"-"+n},[t,e])}function hoe(t){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a{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 ox=hoe(1),dw=hoe(-1);function uZe(t){return"clientX"in t&&"clientY"in t}function C5(t){if(!t)return!1;const{KeyboardEvent:e}=Mo(t.target);return e&&t instanceof e}function dZe(t){if(!t)return!1;const{TouchEvent:e}=Mo(t.target);return e&&t instanceof e}function yL(t){if(dZe(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 uZe(t)?{x:t.clientX,y:t.clientY}:null}const zx=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[zx.Translate.toString(t),zx.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:r}=t;return e+" "+n+"ms "+r}}}),fY="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function mZe(t){return t.matches(fY)?t:t.querySelector(fY)}const hZe={display:"none"};function pZe(t){let{id:e,value:n}=t;return Kr.createElement("div",{id:e,style:hZe},n)}function fZe(t){let{id:e,announcement:n,ariaLiveType:r="assertive"}=t;const a={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 Kr.createElement("div",{id:e,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function gZe(){const[t,e]=w.useState("");return{announce:w.useCallback(r=>{r!=null&&e(r)},[]),announcement:t}}const poe=w.createContext(null);function bZe(t){const e=w.useContext(poe);w.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(t)},[t,e])}function xZe(){const[t]=w.useState(()=>new Set),e=w.useCallback(r=>(t.add(r),()=>t.delete(r)),[t]);return[w.useCallback(r=>{let{type:a,event:s}=r;t.forEach(o=>{var l;return(l=o[a])==null?void 0:l.call(o,s)})},[t]),e]}const yZe={draggable:` +Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${Us(t.actual_time_seconds)}`:`Estimated: ${Us(t.print_time_seconds||0)}`,children:[i.jsx(Zn,{className:"w-3 h-3"}),Us(t.actual_time_seconds||t.print_time_seconds||0),t.time_accuracy&&i.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&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(Wi,{className:"w-3 h-3"}),t.filament_used_grams.toFixed(1),"g"]}),(t.cost!=null||t.energy_cost!=null)&&i.jsxs("div",{className:"flex items-center gap-3 text-bambu-gray",children:[t.cost!=null&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx(bpe,{className:"w-3 h-3"}),u,t.cost.toFixed(2)]}),t.energy_cost!=null&&i.jsxs("div",{className:"flex items-center gap-1.5",title:`${d("stats.energyUsed")}: ${t.energy_kwh?.toFixed(3)||"N/A"} kWh`,children:[i.jsx(Pc,{className:"w-3 h-3"}),u,t.energy_cost.toFixed(2)]})]}),(t.layer_height||t.total_layers)&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(Gi,{className:"w-3 h-3"}),t.total_layers&&i.jsx("span",{children:t.total_layers===1?d("archives.card.layer",{count:t.total_layers}):d("archives.card.layers",{count:t.total_layers})}),t.total_layers&&t.layer_height&&i.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.layer_height&&i.jsxs("span",{children:[t.layer_height,"mm"]})]}),t.object_count!=null&&t.object_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.object_count===1?d("archives.card.object",{count:t.object_count}):d("archives.card.objects",{count:t.object_count}),children:[i.jsx(ia,{className:"w-3 h-3"}),t.object_count===1?d("archives.card.object",{count:t.object_count}):d("archives.card.objects",{count:t.object_count})]}),t.sliced_for_model&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:d("archives.card.slicedFor",{model:t.sliced_for_model}),children:[i.jsx(_r,{className:"w-3 h-3"}),t.sliced_for_model]}),t.filament_type&&i.jsxs("div",{className:"flex items-center gap-1.5 col-span-2",children:[i.jsx("span",{className:"text-bambu-gray text-xs",children:t.filament_type}),t.filament_color&&i.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((ye,We)=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:ye},title:ye},We))})]})]}),(t.tags||t.notes)&&i.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[t.notes&&i.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:i.jsx(rQ,{className:"w-3 h-3"})}),t.tags?.split(",").map((ye,We)=>i.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-dark-tertiary text-bambu-gray-light rounded text-xs",children:ye.trim()},We))]}),i.jsx("div",{className:"flex-1"}),i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray border-t border-bambu-dark-tertiary pt-3",children:[i.jsx("span",{children:Df(t.created_at,l)}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.created_by_username&&i.jsxs("span",{className:"flex items-center gap-1",title:d("archives.card.uploadedBy",{name:t.created_by_username}),children:[i.jsx($d,{className:"w-3 h-3"}),t.created_by_username]}),i.jsx("span",{children:xo(t.file_size)})]})]}),i.jsxs("div",{className:"flex gap-1 mt-3",children:[ch(t)?i.jsxs(i.Fragment,{children:[i.jsxs(ze,{variant:"primary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>C(!0),disabled:!t.file_path||!v("archives","reprint",t.created_by_id),title:t.file_path?v("archives","reprint",t.created_by_id)?void 0:d("archives.card.noPermissionReprint"):d("archives.card.noFileForReprint"),children:[i.jsx(_r,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"hidden sm:inline truncate",children:d("archives.card.reprint")})]}),i.jsxs(ze,{variant:"secondary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>ne(!0),disabled:!t.file_path||!y("queue:create"),title:t.file_path?y("queue:create")?d("archives.card.schedulePrint"):d("archives.permission.noAddToQueue"):d("archives.card.noFileForReprint"),children:[i.jsx(Xr,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"hidden sm:inline truncate",children:d("archives.card.schedule")})]}),i.jsx(ze,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const ye=t.print_name||t.filename||"model";uh(t.id,ye,"file",c)},title:d("archives.card.openInBambuStudio"),children:i.jsx(ni,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}):i.jsxs(ze,{variant:"primary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>{const ye=t.print_name||t.filename||"model";uh(t.id,ye,"file",c)},title:d("archives.card.openInBambuStudioToSlice"),children:[i.jsx(ni,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"hidden sm:inline truncate",children:d("archives.card.slice")})]}),i.jsx(ze,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const ye=t.external_url||t.makerworld_url;ye&&window.open(ye,"_blank")},disabled:!t.external_url&&!t.makerworld_url,title:t.external_url?d("archives.card.externalLink"):t.makerworld_url?d("archives.card.makerWorld",{designer:t.designer||d("archives.card.viewProject")}):d("archives.card.noExternalLink"),children:i.jsx(Ch,{className:`w-3 h-3 sm:w-4 sm:h-4 ${!t.external_url&&!t.makerworld_url?"opacity-20":""}`})}),i.jsx(ze,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{ge.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ye=>{console.error("Archive download failed:",ye)})},title:d("archives.card.download"),children:i.jsx(fi,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),i.jsx(ze,{variant:"ghost",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>P(!0),disabled:!v("archives","delete",t.created_by_id),title:v("archives","delete",t.created_by_id)?d("archives.card.delete"):d("archives.card.noPermissionDelete"),children:i.jsx(nn,{className:"w-3 h-3 sm:w-4 sm:h-4 text-red-400"})})]})]}),T&&i.jsx(die,{archive:t,onClose:()=>D(!1)}),g&&i.jsx(L4,{archiveId:t.id,title:t.print_name||t.filename,fileType:doe(t.filename),onClose:()=>_(!1)}),N&&i.jsx(xu,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>C(!1)}),k&&i.jsx(Nn,{title:d("archives.modal.deleteArchive"),message:d("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{He.mutate(),P(!1)},onCancel:()=>P(!1)}),se&&i.jsx(Nn,{title:d("archives.modal.removeSource3mf"),message:d("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{fe.mutate(),pe(!1)},onCancel:()=>pe(!1)}),Te&&i.jsx(Nn,{title:d("archives.modal.removeF3d"),message:d("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{je.mutate(),q(!1)},onCancel:()=>q(!1)}),X&&i.jsx(Nn,{title:d("archives.modal.removeTimelapse"),message:d("archives.modal.removeTimelapseConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{F.mutate(),j(!1)},onCancel:()=>j(!1)}),E&&i.jsx(mie,{x:E.x,y:E.y,items:Xe,onClose:()=>U(null)}),A&&t.timelapse_path&&i.jsx(uoe,{src:ge.getArchiveTimelapse(t.id),title:d("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>R(!1),onEdit:()=>{p.invalidateQueries({queryKey:["archives"]}),R(!1)}}),G&&Z.length>0&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:d("archives.modal.selectTimelapse")}),i.jsx("p",{className:"text-sm text-gray-400 mt-1",children:d("archives.modal.selectTimelapseDesc")})]}),i.jsx("button",{onClick:()=>{z(!1),I([])},className:"text-gray-400 hover:text-white p-1",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:Z.map(ye=>i.jsxs("button",{onClick:()=>Fe.mutate(ye.name),disabled:Fe.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:[i.jsx(kh,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-white font-medium truncate",children:ye.name}),i.jsxs("p",{className:"text-sm text-gray-400",children:[xo(ye.size),ye.mtime&&` • ${Df(ye.mtime,l)}`]})]})]},ye.name))}),i.jsx("div",{className:"p-4 border-t border-gray-700",children:i.jsx(ze,{variant:"secondary",onClick:()=>{z(!1),I([])},className:"w-full",children:"Cancel"})})]})}),J&&i.jsx(hie,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>ae(!1)}),Y&&t.photos&&t.photos.length>0&&i.jsx(pie,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>ue(!1),onDelete:async ye=>{try{await ge.deleteArchivePhoto(t.id,ye),p.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.photoDeleted"))}catch{f(d("archives.toast.failedDeletePhoto"),"error")}}}),de&&i.jsx(coe,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>he(!1)}),V&&i.jsx(xu,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>ne(!1)}),i.jsx("input",{ref:$,type:"file",accept:".3mf",className:"hidden",onChange:ye=>{const We=ye.target.files?.[0];We&&ve.mutate(We),ye.target.value=""}}),i.jsx("input",{ref:ee,type:"file",accept:".f3d",className:"hidden",onChange:ye=>{const We=ye.target.files?.[0];We&&me.mutate(We),ye.target.value=""}}),i.jsx("input",{ref:W,type:"file",accept:".mp4,.avi,.mkv",className:"hidden",onChange:ye=>{const We=ye.target.files?.[0];We&&te.mutate(We),ye.target.value=""}})]})}function aZe({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:a,projects:s,isHighlighted:o,preferredSlicer:l="bambu_studio",t:c,onNavigateToArchive:u}){const d=sn(),{showToast:m}=bn(),{hasPermission:p,canModify:f}=Ar(),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,N]=w.useState(!1),[C,k]=w.useState(!1),[P,T]=w.useState(!1),[D,A]=w.useState(!1),[R,G]=w.useState(!1),[z,Z]=w.useState([]),[I,J]=w.useState(!1),[ae,Y]=w.useState(!1),[ue,de]=w.useState(!1),[he,V]=w.useState(!1),[ne,se]=w.useState(!1),[pe,Te]=w.useState(!1),[q,X]=w.useState(null),j=w.useRef(null),E=w.useRef(null),U=w.useRef(null),K=t.duplicate_sequence??0,H=t.original_archive_id??null,re=gt({mutationFn:()=>ge.deleteArchiveTimelapse(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseRemoved"))},onError:me=>{m(me.message||c("archives.toast.failedRemoveTimelapse"),"error")}}),O=gt({mutationFn:me=>ge.uploadArchiveTimelapse(t.id,me),onSuccess:me=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseUploaded",{filename:me.filename}))},onError:me=>{m(me.message||c("archives.toast.failedUploadTimelapse"),"error")}}),$=gt({mutationFn:me=>ge.uploadSource3mf(t.id,me),onSuccess:me=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.source3mfAttached",{filename:me.filename}))},onError:me=>{m(me.message||c("archives.toast.failedUploadSource3mf"),"error")}}),ee=gt({mutationFn:()=>ge.deleteSource3mf(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.source3mfRemoved"))},onError:me=>{m(me.message||c("archives.toast.failedRemoveSource3mf"),"error")}}),W=gt({mutationFn:me=>ge.uploadF3d(t.id,me),onSuccess:me=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.f3dAttached",{filename:me.filename}))},onError:me=>{m(me.message||c("archives.toast.failedUploadF3d"),"error")}}),ie=gt({mutationFn:()=>ge.deleteF3d(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.f3dRemoved"))},onError:me=>{m(me.message||c("archives.toast.failedRemoveF3d"),"error")}}),ce=gt({mutationFn:()=>ge.scanArchiveTimelapse(t.id),onSuccess:me=>{me.status==="attached"?(d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseAttached",{filename:me.filename}))):me.status==="exists"?m(c("archives.toast.timelapseAlreadyAttached")):me.status==="not_found"&&me.available_files&&me.available_files.length>0?(Z(me.available_files),G(!0)):m(me.message||c("archives.toast.noMatchingTimelapse"),"warning")},onError:me=>{m(me.message||c("archives.toast.failedScanTimelapse"),"error")}}),be=gt({mutationFn:me=>ge.selectArchiveTimelapse(t.id,me),onSuccess:me=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseAttached",{filename:me.filename})),G(!1),Z([])},onError:me=>{m(me.message||c("archives.toast.failedAttachTimelapse"),"error")}}),xe=gt({mutationFn:()=>ge.deleteArchive(t.id),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.archiveDeleted"))},onError:()=>{m(c("archives.toast.failedDeleteArchive"),"error")}}),oe=gt({mutationFn:()=>ge.toggleFavorite(t.id),onSuccess:me=>{d.invalidateQueries({queryKey:["archives"]}),m(me.is_favorite?c("archives.toast.addedToFavorites"):c("archives.toast.removedFromFavorites"))}}),{data:L}=et({queryKey:["archive-folders",t.id],queryFn:()=>ge.getLibraryFoldersByArchive(t.id)}),F=gt({mutationFn:me=>ge.updateArchive(t.id,{project_id:me}),onSuccess:()=>{d.invalidateQueries({queryKey:["archives"]}),d.invalidateQueries({queryKey:["projects"]}),m(c("archives.toast.projectUpdated"))},onError:()=>{m(c("archives.toast.failedUpdateProject"),"error")}}),te=me=>{me.preventDefault(),X({x:me.clientX,y:me.clientY})},fe=[...ch(t)?[{label:c("archives.menu.print"),icon:i.jsx(_r,{className:"w-4 h-4"}),onClick:()=>N(!0),disabled:!t.file_path||!f("archives","reprint",t.created_by_id),title:t.file_path?f("archives","reprint",t.created_by_id)?void 0:c("archives.permission.noReprint"):c("archives.card.noFileForReprint")},{label:c("archives.menu.schedule"),icon:i.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>k(!0),disabled:!t.file_path||!p("queue:create"),title:t.file_path?p("queue:create")?void 0:c("archives.permission.noAddToQueue"):c("archives.card.noFileForReprint")},{label:c("archives.menu.openInBambuStudio"),icon:i.jsx(ni,{className:"w-4 h-4"}),onClick:()=>{const me=t.print_name||t.filename||"model";uh(t.id,me,"file",l)},disabled:!t.file_path,title:t.file_path?void 0:c("archives.card.noFileForReprint")}]:[{label:c("archives.menu.slice"),icon:i.jsx(ni,{className:"w-4 h-4"}),onClick:()=>{const me=t.print_name||t.filename||"model";uh(t.id,me,"file",l)}}],{label:t.external_url?c("archives.menu.externalLink"):c("archives.menu.viewOnMakerWorld"),icon:i.jsx(Ch,{className:"w-4 h-4"}),onClick:()=>{const me=t.external_url||t.makerworld_url;me&&window.open(me,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.preview3d"),icon:i.jsx(ia,{className:"w-4 h-4"}),onClick:()=>T(!0)},{label:c("archives.menu.viewTimelapse"),icon:i.jsx(kh,{className:"w-4 h-4"}),onClick:()=>A(!0),disabled:!t.timelapse_path},{label:c("archives.menu.scanForTimelapse"),icon:i.jsx(BN,{className:"w-4 h-4"}),onClick:()=>ce.mutate(),disabled:!t.printer_id||!!t.timelapse_path||ce.isPending||!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.uploadTimelapse"),icon:i.jsx(yi,{className:"w-4 h-4"}),onClick:()=>U.current?.click(),disabled:!!t.timelapse_path||!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.timelapse_path?[{label:c("archives.menu.removeTimelapse"),icon:i.jsx(nn,{className:"w-4 h-4"}),onClick:()=>Te(!0),danger:!0,disabled:!f("archives","update",t.created_by_id),title:f("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:i.jsx(ON,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?ge.downloadSource3mf(t.id).catch(me=>{console.error("Source 3MF download failed:",me)}):j.current?.click()},disabled:!t.source_3mf_path&&!f("archives","update",t.created_by_id),title:!t.source_3mf_path&&!f("archives","update",t.created_by_id)?c("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:c("archives.menu.replaceSource3mf"),icon:i.jsx(yi,{className:"w-4 h-4"}),onClick:()=>j.current?.click(),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.removeSource3mf"),icon:i.jsx(nn,{className:"w-4 h-4"}),onClick:()=>V(!0),danger:!0,disabled:!f("archives","update",t.created_by_id),title:f("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:i.jsx(ia,{className:"w-4 h-4"}),onClick:()=>E.current?.click(),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:c("archives.menu.downloadF3d"),icon:i.jsx(fi,{className:"w-4 h-4"}),onClick:()=>{ge.downloadF3d(t.id).catch(me=>{console.error("F3D download failed:",me)})}},{label:c("archives.menu.removeF3d"),icon:i.jsx(nn,{className:"w-4 h-4"}),onClick:()=>se(!0),danger:!0,disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.download"),icon:i.jsx(fi,{className:"w-4 h-4"}),onClick:()=>{ge.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(me=>{console.error("Archive download failed:",me)})},disabled:!p("archives:read"),title:p("archives:read")?void 0:c("archives.permission.noDownload")},{label:c("archives.menu.copyDownloadLink"),icon:i.jsx(ko,{className:"w-4 h-4"}),onClick:()=>{const me=`${window.location.origin}${ge.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(me).then(()=>{m(c("archives.toast.linkCopied"))}).catch(()=>{m(c("archives.toast.failedCopyLink"),"error")})},disabled:!p("archives:read"),title:p("archives:read")?void 0:c("archives.permission.noCopyLink")},{label:c("archives.menu.qrCode"),icon:i.jsx(eQ,{className:"w-4 h-4"}),onClick:()=>J(!0)},{label:t.photos?.length?c("archives.menu.viewPhotosCount",{count:t.photos.length}):c("archives.menu.viewPhotos"),icon:i.jsx(dx,{className:"w-4 h-4"}),onClick:()=>Y(!0),disabled:!t.photos?.length},{label:c("archives.menu.projectPage"),icon:i.jsx(Bs,{className:"w-4 h-4"}),onClick:()=>de(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?c("archives.menu.removeFromFavorites"):c("archives.menu.addToFavorites"),icon:i.jsx(Mf,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>oe.mutate(),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.edit"),icon:i.jsx(Yi,{className:"w-4 h-4"}),onClick:()=>v(!0),disabled:!f("archives","update",t.created_by_id),title:f("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:i.jsx(vs,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:c("archives.menu.addToProject"),icon:i.jsx(vs,{className:"w-4 h-4"}),onClick:()=>{},submenu:(()=>{const me=[];if(t.project_id&&me.push({label:c("archives.menu.removeFromProject"),icon:i.jsx(Ht,{className:"w-4 h-4"}),onClick:()=>F.mutate(null)}),!s)me.push({label:c("archives.menu.loading"),icon:i.jsx(ft,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const je=s.filter(we=>we.status==="active");je.length===0?me.push({label:c("archives.menu.noProjectsAvailable"),icon:i.jsx(vs,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):je.forEach(we=>{me.push({label:we.name,icon:i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:we.color||"#888"}}),onClick:()=>F.mutate(we.id),disabled:t.project_id===we.id})})}return me})()},{label:c(n?"archives.menu.deselect":"archives.menu.select"),icon:n?i.jsx(Ks,{className:"w-4 h-4"}):i.jsx(rl,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.delete"),icon:i.jsx(nn,{className:"w-4 h-4"}),onClick:()=>g(!0),danger:!0,disabled:!f("archives","delete",t.created_by_id),title:f("archives","delete",t.created_by_id)?void 0:c("archives.permission.noDelete")}];return i.jsxs(i.Fragment,{children:[i.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:te,children:[i.jsxs("div",{className:"col-span-1 flex items-center gap-2",children:[a&&i.jsx("button",{onClick:()=>r(t.id),children:n?i.jsx(Ks,{className:"w-4 h-4 text-bambu-green"}):i.jsx(rl,{className:"w-4 h-4 text-bambu-gray"})}),t.thumbnail_path?i.jsx("img",{src:ge.getArchiveThumbnail(t.id),alt:"",className:"w-10 h-10 object-cover rounded"}):i.jsx("div",{className:"w-10 h-10 bg-bambu-dark rounded flex items-center justify-center",children:i.jsx(Ud,{className:"w-5 h-5 text-bambu-dark-tertiary"})})]}),i.jsxs("div",{className:"col-span-4",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("p",{className:"text-white text-sm truncate",children:t.print_name||t.filename}),(t.status==="failed"||t.status==="aborted")&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] leading-tight bg-status-error/80 text-white flex-shrink-0",children:t.status==="aborted"?c("archives.card.cancelled"):c("archives.card.failed")}),t.duplicate_count>0&&K>0&&H&&i.jsxs("button",{onClick:me=>{me.stopPropagation(),u?.(H)},className:"px-1.5 py-0.5 rounded text-[10px] leading-tight bg-purple-500/80 hover:bg-purple-600/90 text-white flex-shrink-0 transition-colors flex items-center gap-1",title:c("archives.viewOriginalPrint",{id:H}),children:[i.jsx(ko,{className:"w-3 h-3"}),"#",K]}),t.duplicate_count>0&&K===0&&i.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] leading-tight bg-purple-500/80 text-white flex-shrink-0 flex items-center gap-1",title:`${t.duplicate_count} reprint${t.duplicate_count===1?"":"s"}`,children:[i.jsx(XX,{className:"w-3 h-3"}),"+",t.duplicate_count]}),t.timelapse_path&&i.jsx("span",{title:c("archives.list.hasTimelapse"),children:i.jsx(kh,{className:"w-3.5 h-3.5 text-bambu-green flex-shrink-0"})}),L&&L.length>0&&i.jsx(fo,{to:`/files?folder=${L[0].id}`,className:"flex-shrink-0",title:c("archives.card.openFolder",{name:L[0].name}),onClick:me=>me.stopPropagation(),children:i.jsx(Ac,{className:"w-3.5 h-3.5 text-yellow-400"})})]}),(t.filament_type||t.sliced_for_model)&&i.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[t.sliced_for_model&&i.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",title:c("archives.card.slicedFor",{model:t.sliced_for_model}),children:[i.jsx(_r,{className:"w-2.5 h-2.5"}),t.sliced_for_model]}),t.sliced_for_model&&t.filament_type&&i.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.filament_type&&i.jsx("span",{className:"text-xs text-bambu-gray",children:t.filament_type}),t.filament_color&&i.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((me,je)=>i.jsx("div",{className:"w-2.5 h-2.5 rounded-full border border-black/20",style:{backgroundColor:me},title:me},je))})]})]}),i.jsx("div",{className:"col-span-2 text-sm text-bambu-gray truncate",children:e}),i.jsxs("div",{className:"col-span-2 text-sm text-bambu-gray",children:[i.jsx("div",{children:jf(t.created_at)}),t.created_by_username&&i.jsxs("div",{className:"flex items-center gap-1 text-xs opacity-75",title:c("archives.card.uploadedBy",{name:t.created_by_username}),children:[i.jsx($d,{className:"w-3 h-3"}),t.created_by_username]})]}),i.jsx("div",{className:"col-span-1 text-sm text-bambu-gray",children:xo(t.file_size)}),i.jsxs("div",{className:"col-span-2 flex justify-end gap-1",children:[ch(t)&&i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>N(!0),disabled:!f("archives","reprint",t.created_by_id),title:f("archives","reprint",t.created_by_id)?c("archives.card.reprint"):c("archives.card.noPermissionReprint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:i.jsx(Co,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{const me=t.print_name||t.filename||"model";uh(t.id,me,"file",l)},title:c("archives.card.openInBambuStudio"),children:i.jsx(ni,{className:"w-4 h-4"})}),(t.external_url||t.makerworld_url)&&i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>window.open(t.external_url||t.makerworld_url,"_blank"),title:t.external_url?c("archives.card.externalLink"):"MakerWorld",children:i.jsx(Ch,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{ge.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(me=>{console.error("Archive download failed:",me)})},title:c("archives.card.download"),children:i.jsx(fi,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>v(!0),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?c("archives.card.edit"):c("archives.card.noPermissionEdit"),children:i.jsx(Yi,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>g(!0),disabled:!f("archives","delete",t.created_by_id),title:f("archives","delete",t.created_by_id)?c("archives.card.delete"):c("archives.card.noPermissionDelete"),children:i.jsx(nn,{className:"w-4 h-4 text-red-400"})}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:me=>{const je=me.currentTarget.getBoundingClientRect();X({x:je.left,y:je.bottom+4})},title:c("archives.card.moreOptions"),children:i.jsx(Nh,{className:"w-4 h-4"})})]})]}),y&&i.jsx(die,{archive:t,onClose:()=>v(!1)}),P&&i.jsx(L4,{archiveId:t.id,title:t.print_name||t.filename,fileType:doe(t.filename),onClose:()=>T(!1)}),_&&i.jsx(xu,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>N(!1)}),b&&i.jsx(Nn,{title:c("archives.modal.deleteArchive"),message:c("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{xe.mutate(),g(!1)},onCancel:()=>g(!1)}),he&&i.jsx(Nn,{title:c("archives.modal.removeSource3mf"),message:c("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{ee.mutate(),V(!1)},onCancel:()=>V(!1)}),ne&&i.jsx(Nn,{title:c("archives.modal.removeF3d"),message:c("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{ie.mutate(),se(!1)},onCancel:()=>se(!1)}),pe&&i.jsx(Nn,{title:c("archives.modal.removeTimelapse"),message:c("archives.modal.removeTimelapseConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{re.mutate(),Te(!1)},onCancel:()=>Te(!1)}),q&&i.jsx(mie,{x:q.x,y:q.y,items:fe,onClose:()=>X(null)}),D&&t.timelapse_path&&i.jsx(uoe,{src:ge.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:()=>A(!1),onEdit:()=>{d.invalidateQueries({queryKey:["archives"]}),A(!1)}}),R&&z.length>0&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:c("archives.modal.selectTimelapse")}),i.jsx("p",{className:"text-sm text-gray-400 mt-1",children:c("archives.modal.selectTimelapseDesc")})]}),i.jsx("button",{onClick:()=>{G(!1),Z([])},className:"text-gray-400 hover:text-white p-1",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:z.map(me=>i.jsxs("button",{onClick:()=>be.mutate(me.name),disabled:be.isPending,className:"w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors mb-1",children:[i.jsx("div",{className:"font-medium text-white",children:me.name}),i.jsxs("div",{className:"text-sm text-gray-400 flex gap-3",children:[i.jsx("span",{children:xo(me.size)}),me.mtime&&i.jsx("span",{children:jf(me.mtime)})]})]},me.name))})]})}),I&&i.jsx(hie,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>J(!1)}),ae&&t.photos&&i.jsx(pie,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>Y(!1),onDelete:async me=>{try{await ge.deleteArchivePhoto(t.id,me),d.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.photoDeleted"))}catch{m(c("archives.toast.failedDeletePhoto"),"error")}}}),ue&&i.jsx(coe,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>de(!1)}),C&&i.jsx(xu,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>k(!1)}),i.jsx("input",{ref:j,type:"file",accept:".3mf",className:"hidden",onChange:me=>{const je=me.target.files?.[0];je&&$.mutate(je),me.target.value=""}}),i.jsx("input",{ref:E,type:"file",accept:".f3d",className:"hidden",onChange:me=>{const je=me.target.files?.[0];je&&W.mutate(je),me.target.value=""}}),i.jsx("input",{ref:U,type:"file",accept:".mp4,.avi,.mkv",className:"hidden",onChange:me=>{const je=me.target.files?.[0];je&&O.mutate(je),me.target.value=""}})]})}const sZe=[{id:"all",label:"All Archives",icon:i.jsx(Ac,{className:"w-4 h-4"})},{id:"recent",label:"Last 24 Hours",icon:i.jsx(Zn,{className:"w-4 h-4"})},{id:"this-week",label:"This Week",icon:i.jsx(Xr,{className:"w-4 h-4"})},{id:"this-month",label:"This Month",icon:i.jsx(Xr,{className:"w-4 h-4"})},{id:"favorites",label:"Favorites",icon:i.jsx(Mf,{className:"w-4 h-4"})},{id:"failed",label:"Failed Prints",icon:i.jsx(Li,{className:"w-4 h-4"})},{id:"duplicates",label:"Duplicates",icon:i.jsx(ko,{className:"w-4 h-4"})}];function oZe(){const{t}=Dt(),e=sn(),{showToast:n}=bn(),{hasPermission:r,hasAnyPermission:a}=Ar(),s=w.useRef(null),[o,l]=w.useState(""),[c,u]=w.useState(()=>{const le=localStorage.getItem("archiveFilterPrinter");return le?Number(le):null}),[d,m]=w.useState(()=>localStorage.getItem("archiveFilterMaterial")),[p,f]=w.useState(()=>{const le=localStorage.getItem("archiveFilterColors");return le?new Set(JSON.parse(le)):new Set}),[y,v]=w.useState(()=>localStorage.getItem("archiveColorFilterMode")||"or"),[b,g]=w.useState(()=>localStorage.getItem("archiveFilterFavorites")==="true"),[_,N]=w.useState(()=>localStorage.getItem("archiveHideFailed")==="true"),[C,k]=w.useState(()=>localStorage.getItem("archiveHideDuplicates")==="true"),[P,T]=w.useState(()=>localStorage.getItem("archiveFilterTag")),[D,A]=w.useState(()=>localStorage.getItem("archiveFilterFileType")||"all"),[R,G]=w.useState(!1),[z,Z]=w.useState([]),[I,J]=w.useState(!1),[ae,Y]=w.useState(new Set),[ue,de]=w.useState(!1),[he,V]=w.useState(!1),[ne,se]=w.useState(!1),[pe,Te]=w.useState(!1),[q,X]=w.useState(()=>localStorage.getItem("archiveViewMode")||"grid"),[j,E]=w.useState(()=>localStorage.getItem("archiveSortBy")||"date-desc"),[U,K]=w.useState(()=>localStorage.getItem("archiveCollection")||"all"),[H,re]=w.useState(!1),[O,$]=w.useState(!1),[ee,W]=w.useState(!1),[ie,ce]=w.useState(!1),[be,xe]=w.useState(null),[oe,L]=w.useState(null),[F,te]=w.useState(()=>localStorage.getItem("logFilterUser")||null),[ve,fe]=w.useState(()=>localStorage.getItem("logFilterStatus")),[me,je]=w.useState(()=>localStorage.getItem("logFilterDateFrom")||""),[we,Fe]=w.useState(()=>localStorage.getItem("logFilterDateTo")||""),[He,Oe]=w.useState(()=>{const le=localStorage.getItem("logOffset");return le?Number(le):0}),[_e,Ae]=w.useState(!1),[Be,Me]=w.useState(()=>{const le=localStorage.getItem("logPageSize");return le?Number(le):25}),Xe=w.useCallback(le=>{L(le),xe(le)},[]);w.useEffect(()=>{if(be){const le=setTimeout(()=>{const Ye=document.querySelector(`[data-archive-id="${be}"]`);Ye?Ye.scrollIntoView({behavior:"smooth",block:"center"}):oe===be&&n(t("archives.originalPrintNotVisible"),"warning"),oe===be&&L(null)},100),Le=setTimeout(()=>xe(null),5e3);return()=>{clearTimeout(le),clearTimeout(Le)}}},[be,oe,n,t]);const{data:ye,isLoading:We}=et({queryKey:["archives",c],queryFn:()=>ge.getArchives(c||void 0)}),{data:Pe}=et({queryKey:["printers"],queryFn:ge.getPrinters}),{data:Ke}=et({queryKey:["projects"],queryFn:()=>ge.getProjects()}),{data:Ve}=et({queryKey:["settings"],queryFn:ge.getSettings}),{data:ke}=et({queryKey:["users"],queryFn:ge.getUsers,enabled:q==="log"}),{data:Ce,isLoading:$e}=et({queryKey:["print-log",c,F,ve,me,we,o,He,Be],queryFn:()=>ge.getPrintLog({search:o||void 0,printerId:c||void 0,username:F||void 0,status:ve||void 0,dateFrom:me||void 0,dateTo:we||void 0,limit:Be,offset:He}),enabled:q==="log"}),nt=Ve?.time_format||"system",xt=Ve?.preferred_slicer||"bambu_studio",vt=Wo(Ve?.currency||"USD"),mt=gt({mutationFn:async le=>(await Promise.all(le.map(Le=>ge.deleteArchive(Le))),le.length),onSuccess:le=>{e.invalidateQueries({queryKey:["archives"]}),Y(new Set),n(`${le} archive${le!==1?"s":""} deleted`)},onError:()=>{n(t("archives.toast.failedDeleteArchives"),"error")}}),qe=gt({mutationFn:()=>ge.clearPrintLog(),onSuccess:le=>{e.invalidateQueries({queryKey:["print-log"]}),Oe(0),n(t("archives.log.cleared",{count:le.deleted}))},onError:()=>{n(t("archives.log.clearFailed"),"error")}});w.useEffect(()=>{c!==null?localStorage.setItem("archiveFilterPrinter",c.toString()):localStorage.removeItem("archiveFilterPrinter")},[c]),w.useEffect(()=>{d?localStorage.setItem("archiveFilterMaterial",d):localStorage.removeItem("archiveFilterMaterial")},[d]),w.useEffect(()=>{localStorage.setItem("archiveFilterColors",JSON.stringify([...p]))},[p]),w.useEffect(()=>{localStorage.setItem("archiveColorFilterMode",y)},[y]),w.useEffect(()=>{localStorage.setItem("archiveFilterFavorites",b.toString())},[b]),w.useEffect(()=>{localStorage.setItem("archiveHideFailed",_.toString())},[_]),w.useEffect(()=>{localStorage.setItem("archiveHideDuplicates",C.toString())},[C]),w.useEffect(()=>{P?localStorage.setItem("archiveFilterTag",P):localStorage.removeItem("archiveFilterTag")},[P]),w.useEffect(()=>{localStorage.setItem("archiveFilterFileType",D)},[D]),w.useEffect(()=>{localStorage.setItem("archiveViewMode",q)},[q]),w.useEffect(()=>{localStorage.setItem("archiveSortBy",j)},[j]),w.useEffect(()=>{localStorage.setItem("archiveCollection",U)},[U]),w.useEffect(()=>{F?localStorage.setItem("logFilterUser",F):localStorage.removeItem("logFilterUser")},[F]),w.useEffect(()=>{ve?localStorage.setItem("logFilterStatus",ve):localStorage.removeItem("logFilterStatus")},[ve]),w.useEffect(()=>{me?localStorage.setItem("logFilterDateFrom",me):localStorage.removeItem("logFilterDateFrom")},[me]),w.useEffect(()=>{we?localStorage.setItem("logFilterDateTo",we):localStorage.removeItem("logFilterDateTo")},[we]),w.useEffect(()=>{localStorage.setItem("logOffset",He.toString())},[He]),w.useEffect(()=>{localStorage.setItem("logPageSize",Be.toString())},[Be]);const Nt=new Map(Pe?.map(le=>[le.id,le.name])||[]),_t=[...new Set(ye?.flatMap(le=>le.filament_type?.split(", ")||[]).filter(Boolean)||[])].sort(),rt=[...new Set(ye?.flatMap(le=>le.filament_color?.split(",")||[]).filter(Boolean)||[])],Rt=[...new Set(ye?.flatMap(le=>le.tags?.split(",").map(Le=>Le.trim())||[]).filter(Boolean)||[])].sort(),qt=ye?.filter(le=>{const Le=new Date,Ye=Qn(le.created_at)||new Date(0);let Ge=!0;switch(U){case"recent":Ge=Le.getTime()-Ye.getTime()<1440*60*1e3;break;case"this-week":Ge=Le.getTime()-Ye.getTime()<10080*60*1e3;break;case"this-month":Ge=Ye.getMonth()===Le.getMonth()&&Ye.getFullYear()===Le.getFullYear();break;case"favorites":Ge=le.is_favorite===!0;break;case"failed":Ge=le.status==="failed"||le.status==="aborted";break;case"duplicates":Ge=le.duplicate_count>0;break}const Ie=(le.print_name||le.filename).toLowerCase().includes(o.toLowerCase()),pt=!d||le.filament_type?.split(", ").includes(d),dt=le.filament_color?.split(",")||[],Je=p.size===0||(y==="or"?dt.some(wn=>p.has(wn)):[...p].every(wn=>dt.includes(wn))),Tt=U==="favorites"||!b||le.is_favorite,zt=U==="failed"||!_||le.status!=="failed"&&le.status!=="aborted",Ut=U==="duplicates"||!C||le.duplicate_count===0||le.duplicate_sequence===0,It=le.tags?.split(",").map(wn=>wn.trim())||[],cn=!P||It.includes(P),Xt=ch(le);return Ge&&Ie&&pt&&Je&&Tt&&zt&&Ut&&cn&&(D==="all"||D==="gcode"&&Xt||D==="source"&&!Xt)}).sort((le,Le)=>{switch(j){case"date-desc":return(Qn(Le.created_at)?.getTime()||0)-(Qn(le.created_at)?.getTime()||0);case"date-asc":return(Qn(le.created_at)?.getTime()||0)-(Qn(Le.created_at)?.getTime()||0);case"name-asc":return(le.print_name||le.filename).localeCompare(Le.print_name||Le.filename);case"name-desc":return(Le.print_name||Le.filename).localeCompare(le.print_name||le.filename);case"size-desc":return Le.file_size-le.file_size;case"size-asc":return le.file_size-Le.file_size;default:return 0}}),Kt=ue||ae.size>0,Qt=le=>{Y(Le=>{const Ye=new Set(Le);return Ye.has(le)?Ye.delete(le):Ye.add(le),Ye})},mn=()=>{qt&&Y(new Set(qt.map(le=>le.id)))},hn=()=>{Y(new Set),de(!1)},Hn=le=>{f(Le=>{const Ye=new Set(Le);return Ye.has(le)?Ye.delete(le):Ye.add(le),Ye})},Qe=()=>{f(new Set)},De=()=>{l(""),u(null),m(null),g(!1),N(!1),k(!1),T(null),A("all")},ot=o||c||d||b||_||C||P||D!=="all",st=w.useCallback(le=>{le.preventDefault(),le.dataTransfer.types.includes("Files")&&J(!0)},[]),Ze=w.useCallback(le=>{le.preventDefault(),le.currentTarget===le.target&&J(!1)},[]),Ee=w.useCallback(le=>{le.preventDefault(),J(!1);const Le=Array.from(le.dataTransfer.files).filter(Ye=>Ye.name.endsWith(".3mf"));Le.length>0?(Z(Le),G(!0)):le.dataTransfer.files.length>0&&n(t("archives.page.only3mfSupported"),"warning")},[n,t]),ct=w.useCallback(le=>{const Le=le.target;if(Le.tagName==="INPUT"||Le.tagName==="TEXTAREA"||Le.isContentEditable){le.key==="Escape"&&Le.blur();return}switch(le.key){case"/":le.preventDefault(),s.current?.focus();break;case"u":case"U":!le.metaKey&&!le.ctrlKey&&(le.preventDefault(),G(!0));break;case"Escape":Kt&&hn();break}},[Kt]);return w.useEffect(()=>(document.addEventListener("keydown",ct),()=>document.removeEventListener("keydown",ct)),[ct]),i.jsxs("div",{className:"p-4 md:p-8 relative",onDragOver:st,onDragLeave:Ze,onDrop:Ee,children:[I&&i.jsx("div",{className:"fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none",children:i.jsxs("div",{className:"border-4 border-dashed border-bambu-green rounded-xl p-12 text-center",children:[i.jsx(yi,{className:"w-16 h-16 mx-auto mb-4 text-bambu-green"}),i.jsx("p",{className:"text-2xl font-semibold text-white mb-2",children:"Drop .3mf files here"}),i.jsx("p",{className:"text-bambu-gray",children:t("archives.releaseToUpload")})]})}),Kt&&i.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:[i.jsxs(ze,{variant:"secondary",size:"sm",onClick:hn,children:[i.jsx(Ht,{className:"w-4 h-4"}),"Close"]}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsxs("span",{className:"text-white font-medium",children:[ae.size," selected"]}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:mn,children:"Select All"}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>se(!0),disabled:!a("archives:update_own","archives:update_all"),title:a("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[i.jsx(Hd,{className:"w-4 h-4"}),"Tags"]}),i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>Te(!0),disabled:!a("archives:update_own","archives:update_all"),title:a("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[i.jsx(vs,{className:"w-4 h-4"}),"Project"]}),i.jsxs(ze,{variant:"secondary",size:"sm",disabled:!a("archives:update_own","archives:update_all"),title:a("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),onClick:()=>{const le=Array.from(ae);Promise.all(le.map(Le=>ge.toggleFavorite(Le))).then(()=>{e.invalidateQueries({queryKey:["archives"]}),n(`Toggled favorites for ${le.length} archive${le.length!==1?"s":""}`)}).catch(()=>{n(t("archives.toast.failedUpdateFavorites"),"error")})},children:[i.jsx(Mf,{className:"w-4 h-4"}),"Favorite"]}),i.jsxs(ze,{size:"sm",className:"bg-red-500 hover:bg-red-600",onClick:()=>V(!0),disabled:!a("archives:delete_own","archives:delete_all"),title:a("archives:delete_own","archives:delete_all")?void 0:t("archives.permission.noDelete"),children:[i.jsx(nn,{className:"w-4 h-4"}),"Delete"]})]}),i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:"Archives"}),i.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:U,onChange:le=>K(le.target.value),children:sZe.map(le=>i.jsx("option",{value:le.id,children:le.label},le.id))})]}),i.jsxs("p",{className:"text-bambu-gray",children:[qt?.length||0," of ",ye?.length||0," prints"]})]}),i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[i.jsxs("div",{className:"relative",children:[i.jsxs(ze,{variant:"secondary",onClick:()=>re(!H),disabled:O,children:[O?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(IN,{className:"w-4 h-4"}),"Export"]}),H&&i.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:[i.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()=>{re(!1),$(!0);try{const{blob:le,filename:Le}=await ge.exportArchives({format:"csv",printerId:c||void 0,status:U==="failed"?"failed":void 0,search:o||void 0}),Ye=URL.createObjectURL(le),Ge=document.createElement("a");Ge.href=Ye,Ge.download=Le,Ge.click(),URL.revokeObjectURL(Ye),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{$(!1)}},children:[i.jsx(Bs,{className:"w-4 h-4"}),"Export as CSV"]}),i.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()=>{re(!1),$(!0);try{const{blob:le,filename:Le}=await ge.exportArchives({format:"xlsx",printerId:c||void 0,status:U==="failed"?"failed":void 0,search:o||void 0}),Ye=URL.createObjectURL(le),Ge=document.createElement("a");Ge.href=Ye,Ge.download=Le,Ge.click(),URL.revokeObjectURL(Ye),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{$(!1)}},children:[i.jsx(IN,{className:"w-4 h-4"}),"Export as Excel"]})]})]}),ae.size>=2&&ae.size<=5&&i.jsxs(ze,{variant:"secondary",onClick:()=>W(!0),children:[i.jsx(Gb,{className:"w-4 h-4"}),"Compare (",ae.size,")"]}),!Kt&&i.jsxs(ze,{variant:"secondary",onClick:()=>de(!0),children:[i.jsx(Ks,{className:"w-4 h-4"}),"Select"]}),i.jsxs(ze,{onClick:()=>G(!0),disabled:!r("archives:create"),title:r("archives:create")?void 0:t("archives.permission.noCreate"),children:[i.jsx(yi,{className:"w-4 h-4"}),"Upload 3MF"]})]})]}),i.jsxs("div",{className:"flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden flex-shrink-0 w-fit mb-4",children:[i.jsx("button",{className:`p-2 ${q==="grid"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>X("grid"),title:t("archives.gridView"),children:i.jsx(ww,{className:"w-4 h-4"})}),i.jsx("button",{className:`p-2 ${q==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>X("list"),title:t("archives.listView"),children:i.jsx(sT,{className:"w-4 h-4"})}),i.jsx("button",{className:`p-2 ${q==="calendar"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>X("calendar"),title:t("archives.calendarView"),children:i.jsx(Ohe,{className:"w-4 h-4"})}),i.jsx("button",{className:`p-2 ${q==="log"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>X("log"),title:t("archives.logView"),children:i.jsx(spe,{className:"w-4 h-4"})})]}),q!=="log"&&i.jsx(Pt,{className:"mb-6",children:i.jsxs(Et,{className:"py-4",children:[i.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:gap-4 md:items-center md:flex-wrap",children:[i.jsxs("div",{className:"w-full md:flex-1 relative md:min-w-[200px]",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.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:le=>l(le.target.value)})]}),i.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:[i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(aT,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.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:le=>u(le.target.value?Number(le.target.value):null),children:[i.jsx("option",{value:"",children:"All Printers"}),Pe?.map(le=>i.jsx("option",{value:le.id,children:le.name},le.id))]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(Wi,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.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:le=>m(le.target.value||null),children:[i.jsx("option",{value:"",children:"All Materials"}),_t.map(le=>i.jsx("option",{value:le,children:le},le))]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(ON,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.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:le=>A(le.target.value),children:[i.jsx("option",{value:"all",children:"All Files"}),i.jsx("option",{value:"gcode",children:"Sliced (GCODE)"}),i.jsx("option",{value:"source",children:"Source Only"})]})]}),i.jsxs("button",{onClick:()=>g(!b),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${b?"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(b?"archives.showAll":"archives.showFavoritesOnly"),children:[i.jsx(Mf,{className:`w-4 h-4 ${b?"fill-yellow-400":""}`}),i.jsx("span",{className:"text-sm hidden md:inline",children:"Favorites"})]}),i.jsxs("button",{onClick:()=>N(!_),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${_?"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(_?"archives.showFailedPrints":"archives.hideFailedPrints"),children:[i.jsx(Li,{className:"w-4 h-4 "}),i.jsx("span",{className:"text-sm hidden md:inline",children:"Hide Failed"})]}),i.jsxs("button",{onClick:()=>k(!C),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${C?"bg-purple-500/20 border-purple-500 text-purple-400":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t("archives.hideDuplicates"),children:[i.jsx(ko,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm hidden md:inline",children:t("archives.hideDuplicates")})]}),Rt.length>0&&i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(Hd,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.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:P||"",onChange:le=>T(le.target.value||null),children:[i.jsx("option",{value:"",children:"All Tags"}),Rt.map(le=>i.jsx("option",{value:le,children:le},le))]}),i.jsx("button",{onClick:()=>ce(!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:i.jsx(dT,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(qL,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.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:j,onChange:le=>E(le.target.value),children:[i.jsx("option",{value:"date-desc",children:t("archives.sortNewest")}),i.jsx("option",{value:"date-asc",children:t("archives.sortOldest")}),i.jsxs("option",{value:"name-asc",children:[t("archives.sortName")," A-Z"]}),i.jsxs("option",{value:"name-desc",children:[t("archives.sortName")," Z-A"]}),i.jsx("option",{value:"size-desc",children:t("archives.sortLargest")}),i.jsx("option",{value:"size-asc",children:t("archives.sortSmallest")})]})]})]}),ot&&i.jsxs(ze,{variant:"ghost",size:"sm",onClick:De,className:"text-bambu-gray hover:text-white",children:[i.jsx(Ht,{className:"w-4 h-4"}),"Reset"]})]}),rt.length>0&&i.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Colors:"}),p.size>1&&i.jsx("button",{onClick:()=>v(le=>le==="or"?"and":"or"),className:`px-2 py-0.5 text-xs rounded transition-colors ${y==="and"?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:y==="or"?"Match ANY selected color":"Match ALL selected colors",children:y.toUpperCase()}),i.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:rt.map(le=>i.jsx("button",{onClick:()=>Hn(le),className:`w-6 h-6 rounded-full border-2 transition-all ${p.has(le)?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:le},title:le},le))}),p.size>0&&i.jsxs("button",{onClick:Qe,className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1",children:[i.jsx(Ht,{className:"w-3 h-3"}),"Clear"]})]})]})}),i.jsx(nZe,{}),We?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.loadingArchives")}):qt?.length===0?i.jsx(Pt,{children:i.jsxs(Et,{className:"text-center py-12",children:[i.jsx("p",{className:"text-bambu-gray",children:t(o?"archives.noArchivesSearch":"archives.noArchivesYet")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:"Archives are created automatically when prints complete"})]})}):q==="calendar"?i.jsx(Pt,{className:"p-6",children:i.jsx(CVe,{archives:qt||[],onArchiveClick:le=>{l(""),X("grid"),xe(le.id)},highlightedArchiveId:be})}):q==="grid"?i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:qt?.map(le=>i.jsx(iZe,{archive:le,printerName:le.printer_id?Nt.get(le.printer_id)||"Unknown":le.sliced_for_model?`Sliced for ${le.sliced_for_model}`:"No Printer",isSelected:ae.has(le.id),onSelect:Qt,selectionMode:Kt,projects:Ke,isHighlighted:le.id===be,timeFormat:nt,preferredSlicer:xt,currency:vt,t,onNavigateToArchive:Xe},le.id))}):q==="list"?i.jsx(Pt,{children:i.jsxs("div",{className:"divide-y divide-bambu-dark-tertiary",children:[i.jsxs("div",{className:"grid grid-cols-12 gap-4 px-4 py-3 text-xs text-bambu-gray font-medium",children:[i.jsx("div",{className:"col-span-1"}),i.jsx("div",{className:"col-span-4",children:"Name"}),i.jsx("div",{className:"col-span-2",children:"Printer"}),i.jsx("div",{className:"col-span-2",children:"Date"}),i.jsx("div",{className:"col-span-1",children:"Size"}),i.jsx("div",{className:"col-span-2 text-right",children:"Actions"})]}),qt?.map(le=>i.jsx(aZe,{archive:le,printerName:le.printer_id?Nt.get(le.printer_id)||"Unknown":le.sliced_for_model?`Sliced for ${le.sliced_for_model}`:"No Printer",isSelected:ae.has(le.id),onSelect:Qt,selectionMode:Kt,projects:Ke,isHighlighted:le.id===be,preferredSlicer:xt,t,onNavigateToArchive:Xe},le.id))]})}):q==="log"?i.jsxs("div",{className:"space-y-4",children:[i.jsx(Pt,{children:i.jsx(Et,{className:"py-3",children:i.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:items-center md:flex-wrap",children:[i.jsxs("div",{className:"flex-1 relative md:min-w-[200px]",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:t("archives.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:o,onChange:le=>{l(le.target.value),Oe(0)}})]}),i.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 text-sm",value:c||"",onChange:le=>{u(le.target.value?Number(le.target.value):null),Oe(0)},children:[i.jsx("option",{value:"",children:t("archives.log.allPrinters")}),Pe?.map(le=>i.jsx("option",{value:le.id,children:le.name},le.id))]}),i.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 text-sm",value:F||"",onChange:le=>{te(le.target.value||null),Oe(0)},children:[i.jsx("option",{value:"",children:t("archives.log.allUsers")}),ke?.map(le=>i.jsx("option",{value:le.username,children:le.username},le.id))]}),i.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 text-sm",value:ve||"",onChange:le=>{fe(le.target.value||null),Oe(0)},children:[i.jsx("option",{value:"",children:t("archives.log.allStatuses")}),i.jsx("option",{value:"completed",children:t("archives.status.completed")}),i.jsx("option",{value:"failed",children:t("archives.status.failed")}),i.jsx("option",{value:"stopped",children:t("archives.status.stopped")}),i.jsx("option",{value:"cancelled",children:t("archives.log.cancelled")}),i.jsx("option",{value:"skipped",children:t("archives.log.skipped")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("label",{className:"text-sm text-bambu-gray",children:t("archives.log.dateFrom")}),i.jsx("input",{type:"date",className:"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:me,onChange:le=>{je(le.target.value),Oe(0)}})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("label",{className:"text-sm text-bambu-gray",children:t("archives.log.dateTo")}),i.jsx("input",{type:"date",className:"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:we,onChange:le=>{Fe(le.target.value),Oe(0)}})]}),i.jsx("div",{className:"ml-auto",children:i.jsxs(ze,{variant:"danger",size:"sm",onClick:()=>Ae(!0),disabled:!r("archives:delete_all")||qe.isPending,children:[i.jsx(nn,{className:"w-4 h-4"}),t("archives.log.clearLog")]})})]})})}),i.jsx(Pt,{children:$e?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):Ce?.items.length?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary text-bambu-gray text-left",children:[i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.date")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.printName")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.printer")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.user")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.status")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.duration")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.filament")})]})}),i.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:Ce.items.map(le=>i.jsxs("tr",{className:"hover:bg-bambu-dark-secondary/50",children:[i.jsx("td",{className:"px-4 py-3 text-white whitespace-nowrap",children:Df(le.started_at||le.created_at,nt)}),i.jsx("td",{className:"px-4 py-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[le.thumbnail_path&&i.jsx("img",{src:ge.getPrintLogThumbnail(le.id),alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0",onError:Le=>{Le.target.style.display="none"}}),i.jsx("span",{className:"text-white truncate max-w-[200px]",children:le.print_name||"—"})]})}),i.jsx("td",{className:"px-4 py-3 text-bambu-gray-light",children:le.printer_name||"—"}),i.jsx("td",{className:"px-4 py-3 text-bambu-gray-light",children:le.created_by_username||"—"}),i.jsx("td",{className:"px-4 py-3",children:i.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${le.status==="completed"?"bg-green-500/20 text-green-400":le.status==="failed"?"bg-red-500/20 text-red-400":le.status==="stopped"?"bg-yellow-500/20 text-yellow-400":le.status==="cancelled"?"bg-orange-500/20 text-orange-400":le.status==="skipped"?"bg-blue-500/20 text-blue-400":"bg-gray-500/20 text-gray-400"}`,children:le.status})}),i.jsx("td",{className:"px-4 py-3 text-bambu-gray-light whitespace-nowrap",children:le.duration_seconds?Us(le.duration_seconds):"—"}),i.jsx("td",{className:"px-4 py-3",children:i.jsxs("div",{className:"flex items-center gap-1.5",children:[le.filament_color&&i.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:le.filament_color.startsWith("#")?le.filament_color:void 0}}),i.jsx("span",{className:"text-bambu-gray-light text-xs",children:le.filament_type||"—"})]})})]},le.id))})]})}),i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-bambu-dark-tertiary flex-wrap gap-2",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:t("archives.log.showing",{count:Math.min(He+Be,Ce.total),total:Ce.total})}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:t("archives.log.rowsPerPage")}),i.jsxs("select",{className:"px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-xs focus:border-bambu-green focus:outline-none",value:Be,onChange:le=>{Me(Number(le.target.value)),Oe(0)},children:[i.jsx("option",{value:10,children:"10"}),i.jsx("option",{value:25,children:"25"}),i.jsx("option",{value:50,children:"50"}),i.jsx("option",{value:100,children:"100"})]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("archives.log.page")," ",Math.floor(He/Be)+1," / ",Math.max(1,Math.ceil(Ce.total/Be))]}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>Oe(Math.max(0,He-Be)),disabled:He===0,children:i.jsx(Cc,{className:"w-4 h-4"})}),i.jsx(ze,{variant:"secondary",size:"sm",onClick:()=>Oe(He+Be),disabled:He+Be>=Ce.total,children:i.jsx(fa,{className:"w-4 h-4"})})]})]})]}):i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.log.noEntries")})})]}):null,R&&i.jsx(bVe,{onClose:()=>{G(!1),Z([])},initialFiles:z}),he&&i.jsx(Nn,{title:t("archives.modal.deleteArchives"),message:t("archives.modal.deleteArchivesConfirm",{count:ae.size}),confirmText:t("archives.modal.deleteCount",{count:ae.size}),variant:"danger",onConfirm:()=>{mt.mutate(Array.from(ae)),V(!1)},onCancel:()=>V(!1)}),ne&&i.jsx(vVe,{selectedIds:Array.from(ae),existingTags:Rt,onClose:()=>se(!1)}),pe&&i.jsx(wVe,{selectedIds:Array.from(ae),onClose:()=>Te(!1)}),ee&&ae.size>=2&&ae.size<=5&&i.jsx(ZQe,{archiveIds:Array.from(ae),onClose:()=>{W(!1),Y(new Set),de(!1)}}),ie&&i.jsx(rZe,{onClose:()=>ce(!1)}),_e&&i.jsx(Nn,{title:t("archives.log.clearLogTitle"),message:t("archives.log.clearLogConfirm"),confirmText:t("archives.log.clearLogButton"),variant:"danger",onConfirm:()=>{qe.mutate(),Ae(!1)},onCancel:()=>Ae(!1)})]})}function lZe(){for(var t=arguments.length,e=new Array(t),n=0;nr=>{e.forEach(a=>a(r))},e)}const RA=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function uy(t){const e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function _5(t){return"nodeType"in t}function Mo(t){var e,n;return t?uy(t)?t:_5(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function N5(t){const{Document:e}=Mo(t);return t instanceof e}function tS(t){return uy(t)?!1:t instanceof Mo(t).HTMLElement}function moe(t){return t instanceof Mo(t).SVGElement}function dy(t){return t?uy(t)?t.document:_5(t)?N5(t)?t:tS(t)||moe(t)?t.ownerDocument:document:document:document}const Cu=RA?w.useLayoutEffect:w.useEffect;function k5(t){const e=w.useRef(t);return Cu(()=>{e.current=t}),w.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a{t.current=setInterval(r,a)},[]),n=w.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function uw(t,e){e===void 0&&(e=[t]);const n=w.useRef(t);return Cu(()=>{n.current!==t&&(n.current=t)},e),n}function nS(t,e){const n=w.useRef();return w.useMemo(()=>{const r=t(n.current);return n.current=r,r},[...e])}function KC(t){const e=k5(t),n=w.useRef(null),r=w.useCallback(a=>{a!==n.current&&e?.(a,n.current),n.current=a},[]);return[n,r]}function xL(t){const e=w.useRef();return w.useEffect(()=>{e.current=t},[t]),e.current}let zD={};function rS(t,e){return w.useMemo(()=>{if(e)return e;const n=zD[t]==null?0:zD[t]+1;return zD[t]=n,t+"-"+n},[t,e])}function hoe(t){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a{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 ox=hoe(1),dw=hoe(-1);function uZe(t){return"clientX"in t&&"clientY"in t}function C5(t){if(!t)return!1;const{KeyboardEvent:e}=Mo(t.target);return e&&t instanceof e}function dZe(t){if(!t)return!1;const{TouchEvent:e}=Mo(t.target);return e&&t instanceof e}function yL(t){if(dZe(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 uZe(t)?{x:t.clientX,y:t.clientY}:null}const zx=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[zx.Translate.toString(t),zx.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:r}=t;return e+" "+n+"ms "+r}}}),fY="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function mZe(t){return t.matches(fY)?t:t.querySelector(fY)}const hZe={display:"none"};function pZe(t){let{id:e,value:n}=t;return Kr.createElement("div",{id:e,style:hZe},n)}function fZe(t){let{id:e,announcement:n,ariaLiveType:r="assertive"}=t;const a={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 Kr.createElement("div",{id:e,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function gZe(){const[t,e]=w.useState("");return{announce:w.useCallback(r=>{r!=null&&e(r)},[]),announcement:t}}const poe=w.createContext(null);function bZe(t){const e=w.useContext(poe);w.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(t)},[t,e])}function xZe(){const[t]=w.useState(()=>new Set),e=w.useCallback(r=>(t.add(r),()=>t.delete(r)),[t]);return[w.useCallback(r=>{let{type:a,event:s}=r;t.forEach(o=>{var l;return(l=o[a])==null?void 0:l.call(o,s)})},[t]),e]}const yZe={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. @@ -8712,11 +8712,11 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${Us(t. `+n+"]";if(typeof t=="object"){const r=Object.entries(t);return r.length===0?"{}":`{ `+r.map(([s,o])=>n+" "+JSON.stringify(s)+": "+NL(o,e+1)).join(`, `)+` -`+n+"}"}return String(t)}function Qet({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:a,hasPermission:s,t:o}){const{showToast:l}=bn(),c=sn(),[u,d]=w.useState(!1),{data:m,isLoading:p}=et({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ge.getCloudSettingDetail(t.setting_id)}),f=gt({mutationFn:()=>ge.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),y=hw(t.setting_id),v=M5(t.name,m?.setting?.inherits);return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:i.jsxs(Et,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),y&&i.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")})]}),i.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[i.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&i.jsxs(i.Fragment,{children:[i.jsx("span",{children:"•"}),i.jsx("span",{children:v.printer})]})]})]}),i.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?i.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:NL(m)}):i.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),u?i.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[i.jsx(jn,{className:"w-5 h-5"}),i.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:()=>d(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),i.jsxs(ze,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(nn,{className:"w-4 h-4"}),o("common.delete")]})]})]}):i.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),i.jsxs(ze,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[i.jsx(ko,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),y&&i.jsxs(i.Fragment,{children:[i.jsxs(ze,{variant:"secondary",onClick:a,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[i.jsx(Yi,{className:"w-4 h-4"}),o("common.edit")]}),i.jsx(ze,{variant:"danger",onClick:()=>d(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:i.jsx(nn,{className:"w-4 h-4"})})]})]})})]})})})}function qoe(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Voe(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Zet({onClose:t,onApply:e,t:n}){const{showToast:r}=bn(),[a,s]=w.useState(qoe),[o,l]=w.useState("all"),[c,u]=w.useState(null),[d,m]=w.useState(""),[p,f]=w.useState(""),[y,v]=w.useState("{}"),[b,g]=w.useState(null),[_,N]=w.useState(null),C=o==="all"?a:a.filter(Z=>Z.type===o),k=Z=>{s(Z),Voe(Z)},P=Z=>{const I=a.filter(J=>J.id!==Z);k(I),N(null),r(n("profiles.templates.toast.deleted"))},T=Z=>{u(Z.id),m(Z.name),f(Z.description),v(JSON.stringify(Z.settings,null,2)),g(null)},D=()=>{if(!(!c||!d.trim()))try{const Z=JSON.parse(y),I=a.map(J=>J.id===c?{...J,name:d.trim(),description:p.trim(),settings:Z}:J);k(I),u(null),r(n("profiles.templates.toast.updated"))}catch(Z){g(Z.message)}},A=()=>{u(null),m(""),f(""),v("{}"),g(null)},R=Z=>{const I=a.map(J=>J.id===Z?{...J,showInModal:!J.showInModal}:J);k(I)},G={filament:{label:n("profiles.presets.types.filament"),icon:rT,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:Bd,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:_r,color:"text-purple-400"}},z=_?a.find(Z=>Z.id===_):null;return w.useEffect(()=>{const Z=I=>{I.key==="Escape"&&(_?N(null):c?A():t())};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[_,c,t]),i.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[z&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:i.jsx(Pt,{className:"w-full max-w-md",children:i.jsxs(Et,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:i.jsx(jn,{className:"w-6 h-6 text-red-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),i.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:z.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),i.jsxs(ze,{onClick:()=>P(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[i.jsx(nn,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),i.jsx(Pt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:i.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(hx,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(Z=>i.jsx("button",{onClick:()=>l(Z),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===Z?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:Z==="all"?n("common.all"):G[Z].label},Z))]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:C.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(hx,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:n("profiles.templates.noTemplates")}),i.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):i.jsx("div",{className:"space-y-2",children:C.map(Z=>{const I=G[Z.type],J=I.icon;return c===Z.id?i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[i.jsx("input",{type:"text",value:d,onChange:ae=>m(ae.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}),i.jsx("input",{type:"text",value:p,onChange:ae=>f(ae.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"})]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),i.jsx("textarea",{value:y,onChange:ae=>{v(ae.target.value),g(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${b?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),b&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(ze,{size:"sm",onClick:D,disabled:!d.trim(),children:[i.jsx(as,{className:"w-4 h-4"}),"Save"]}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:A,children:"Cancel"})]})]},Z.id):i.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:[i.jsx(J,{className:`w-5 h-5 ${I.color} flex-shrink-0`}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:Z.name}),i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Z.description})]}),i.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(Z.settings).length})}),i.jsx("button",{onClick:()=>R(Z.id),className:`p-1 transition-colors ${Z.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:Z.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:Z.showInModal?i.jsx(Tc,{className:"w-4 h-4"}):i.jsx(xw,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>e(Z),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")}),i.jsx("button",{onClick:()=>T(Z),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:i.jsx(Yi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>N(Z.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:i.jsx(nn,{className:"w-4 h-4"})})]},Z.id)})})})]})})]})}function Goe({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:a,t:s}){const[o,l]=w.useState("changes"),[c,u]=w.useState(""),d=w.useMemo(()=>{const y=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const b of y){if(b==="inherits"||b==="version")continue;const g=e[b],_=n[b],N=b in e,C=b in n;let k;!N&&C?k="added":N&&!C?k="removed":JSON.stringify(g)!==JSON.stringify(_)?k="changed":k="same",v.push({key:b,left:g,right:_,status:k})}return v.sort((b,g)=>{const _={changed:0,added:1,removed:2,same:3};return _[b.status]!==_[g.status]?_[b.status]-_[g.status]:b.key.localeCompare(g.key)})},[e,n]),m=w.useMemo(()=>{let y=[...d];if(o==="changes"&&(y=y.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();y=y.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return y},[d,o,c]),p=w.useMemo(()=>({added:d.filter(y=>y.status==="added").length,removed:d.filter(y=>y.status==="removed").length,changed:d.filter(y=>y.status==="changed").length,same:d.filter(y=>y.status==="same").length}),[d]),f=y=>{if(y===void 0)return"—";if(y===null)return"null";if(Array.isArray(y))return y.length===0?"[]":y.length===1?String(y[0]):y.join(", ");if(typeof y=="object")return JSON.stringify(y);const v=String(y);if(v.includes("\\n")||v.length>100){const b=v.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const y=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:i.jsxs(Et,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Gb,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),i.jsx("p",{className:"text-white font-medium truncate",children:r})]}),i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),i.jsx("p",{className:"text-white font-medium truncate",children:a})]})]}),i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[i.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[i.jsx(ir,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(zN,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[i.jsx(v3,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[i.jsx(XM,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:c,onChange:y=>u(y.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&&i.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[i.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")}),i.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")})]})]})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(XM,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:i.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[i.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),i.jsx("th",{className:"text-left p-3 w-1/3",children:r}),i.jsx("th",{className:"text-left p-3 w-1/3",children:a})]})}),i.jsx("tbody",{children:m.map(y=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[y.status],b={added:i.jsx(ir,{className:"w-3.5 h-3.5 text-green-400"}),removed:i.jsx(zN,{className:"w-3.5 h-3.5 text-red-400"}),changed:i.jsx(v3,{className:"w-3.5 h-3.5 text-amber-400"}),same:i.jsx(XM,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[y.status];return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[i.jsx("td",{className:"p-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[b,i.jsx("span",{className:"text-sm text-white font-mono",children:y.key})]})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${y.status==="removed"?"text-red-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.left)})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${y.status==="added"?"text-green-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.right)})})]},y.key)})})]})})]})})})}function Jet({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:a}=bn(),s=sn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[u,d]=w.useState(e?.type||"filament"),[m,p]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,y]=w.useState(e?.base_id||""),[v,b]=w.useState(""),[g,_]=w.useState(e?.setting||{inherits:""}),[N,C]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[k,P]=w.useState(null),[T,D]=w.useState(""),[A,R]=w.useState(!1),[G,z]=w.useState(""),[Z,I]=w.useState(!1),[J,ae]=w.useState(qoe),[Y,ue]=w.useState(!1),[de,he]=w.useState(""),[V,ne]=w.useState(""),[se,pe]=w.useState(!0),[Te,q]=w.useState(null),[X,j]=w.useState(!1),E=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),U=w.useMemo(()=>E.filter(Ae=>hw(Ae.setting_id)),[E]),{data:K}=et({queryKey:["cloudFields",u],queryFn:()=>ge.getCloudFields(u==="print"?"process":u),staleTime:1e3*60*60}),{data:H}=et({queryKey:["allPresetDetails",u,U.map(Ae=>Ae.setting_id).join(",")],queryFn:async()=>{const Ae={};for(let Me=0;Me{try{const Pe=await ge.getCloudSettingDetail(We.setting_id);return{id:We.setting_id,detail:Pe}}catch{return null}}))).forEach(We=>{We&&(Ae[We.id]=We.detail)})}return Ae},enabled:U.length>0,staleTime:1e3*60*10}),{data:re,isLoading:O}=et({queryKey:["cloudSettingDetail",f],queryFn:()=>ge.getCloudSettingDetail(f),enabled:!!f});w.useEffect(()=>{l!=="json"&&C(JSON.stringify(g,null,2))},[g,l]);const $=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(Be=>!hw(Be.setting_id)).sort((Be,Me)=>Be.name.localeCompare(Me.name)),[n,u]);w.useEffect(()=>{if(!f)return;const Ae=$.find(Be=>Be.setting_id===f);Ae&&(b(Ae.name),o||(_({inherits:Ae.name}),C(JSON.stringify({inherits:Ae.name},null,2))))},[f,$,o]);const ee=w.useMemo(()=>{const Ae=K?.fields||[],Be=new Set(Ae.map(We=>We.key)),Me=new Set,Xe=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);H&&Object.values(H).forEach(We=>{We?.setting&&Object.keys(We.setting).forEach(Pe=>{!Be.has(Pe)&&!Xe.has(Pe)&&Me.add(Pe)})}),Object.keys(g).forEach(We=>{!Be.has(We)&&!Xe.has(We)&&Me.add(We)});const ye=Array.from(Me).sort().map(We=>({key:We,label:We.replace(/_/g," ").replace(/\b\w/g,Pe=>Pe.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Ae,...ye]},[K,H,g,r]),W=ee.filter(Ae=>Ae.label.toLowerCase().includes(T.toLowerCase())||Ae.key.toLowerCase().includes(T.toLowerCase())),ie=()=>{if(G.trim()){const Ae=G.trim().toLowerCase().replace(/\s+/g,"_");ce(Ae,""),z(""),I(!1),a(r("profiles.presets.toast.fieldAdded",{key:Ae}))}},ce=(Ae,Be)=>{_(Me=>{const Xe={...Me};return Be===""||Be===void 0?delete Xe[Ae]:Xe[Ae]=Be,Xe})},be=Ae=>{_(Be=>({...Be,...Ae.settings})),q(Ae.name),a(r("profiles.templates.toast.applied"))},xe=()=>{if(!de.trim())return;const Ae={...g};if(delete Ae.inherits,Object.keys(Ae).length===0){a(r("profiles.presets.noOverridesToSave"),"error");return}const Be={id:Date.now().toString(),name:de.trim(),description:V.trim()||r("profiles.presets.customTemplate"),type:u,settings:Ae,showInModal:se},Me=[...J,Be];ae(Me),Voe(Me),ue(!1),he(""),ne(""),pe(!0),a(r("profiles.templates.toast.created"))},oe=w.useMemo(()=>J.filter(Ae=>Ae.type===u&&Ae.showInModal),[u,J]),L=Ae=>{C(Ae);try{const Be=JSON.parse(Ae);_(Be),P(null)}catch(Be){P(Be.message)}},F=Ae=>{Ae.preventDefault(),R(!1);const Be=Ae.dataTransfer.files[0];if(Be&&Be.name.endsWith(".json")){const Me=new FileReader;Me.onload=Xe=>{try{const ye=Xe.target?.result,We=JSON.parse(ye),Pe=We.setting||We;_(Ke=>({...Ke,...Pe})),C(JSON.stringify({...g,...Pe},null,2)),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJsonFile"),"error")}},Me.readAsText(Be)}},te=gt({mutationFn:()=>{const Ae={...g},Be=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";Ae[Be]=`"${m}"`;const Me={type:u,name:m,base_id:f,setting:Ae};return ge.createCloudSetting(Me)},onSuccess:async()=>{a(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Ae=>a(Ae.message,"error")}),ve=gt({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return ge.updateCloudSetting(e.setting_id,{name:m,setting:g})},onSuccess:async()=>{a(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Ae=>a(Ae.message,"error")}),fe=o?ve:te,me=re?.setting?.inherits,je=me?$.find(Ae=>Ae.name===me):void 0,{data:we}=et({queryKey:["cloudSettingDetail",je?.setting_id],queryFn:()=>ge.getCloudSettingDetail(je.setting_id),enabled:!!je?.setting_id}),Fe=w.useMemo(()=>{const Ae=we?.setting||{},Be=re?.setting||{},Me=f&&H?.[f]?.setting?H[f].setting:{};return{...Ae,...Be,...Me}},[f,re,we,H]),He=Ae=>{if(Ae==null)return"";if(Array.isArray(Ae)){const Be=[...new Set(Ae.map(Me=>String(Me)))];return Be.length===1?Be[0]:Ae.join(", ")}return String(Ae)},Oe=Ae=>{const Be=g[Ae.key],Me=Fe[Ae.key],Xe=He(Me),ye=O?r("common.loading"):Xe||"",We="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(Ae.type==="boolean"){const Pe=Be==="1"||Be===void 0&&Me==="1";return i.jsx("button",{type:"button",onClick:()=>ce(Ae.key,Be==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Pe?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Pe?"translate-x-3.5":"translate-x-0.5"}`})})}return Ae.type==="select"?i.jsxs("select",{value:Be||"",onChange:Pe=>ce(Ae.key,Pe.target.value),className:We,children:[i.jsx("option",{value:"",children:ye}),Ae.options?.map(Pe=>i.jsx("option",{value:Pe.value,children:Pe.label},Pe.value))]}):i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:Ae.type==="number"?"number":"text",value:Be!==void 0?String(Be):"",onChange:Pe=>ce(Ae.key,Pe.target.value),step:Ae.step,min:Ae.min,max:Ae.max,placeholder:ye,className:We}),Ae.unit&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Ae.unit})]})},_e=w.useMemo(()=>re?.setting?re.setting:{},[re]);return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Ae=>{Ae.preventDefault(),R(!0)},onDragLeave:()=>R(!1),onDrop:F,children:[X&&f&&i.jsx(Goe,{onClose:()=>j(!1),leftPreset:_e,rightPreset:g,leftLabel:r("profiles.presets.baseLabel",{name:v||f}),rightLabel:r("profiles.presets.currentLabel",{name:m||r("profiles.presets.newPreset")}),t:r}),i.jsx(Pt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:i.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[f&&i.jsxs("button",{onClick:()=>j(!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:[i.jsx(Gb,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),i.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]})]}),A&&i.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:i.jsxs("div",{className:"text-center",children:[i.jsx(yi,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),i.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),i.jsxs("select",{value:u,onChange:Ae=>{d(Ae.target.value),y("")},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:[i.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),i.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),i.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),i.jsxs("select",{value:f,onChange:Ae=>y(Ae.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:[i.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),$.map(Ae=>i.jsx("option",{value:Ae.setting_id,children:Ae.name},Ae.setting_id))]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),i.jsx("input",{type:"text",value:m,onChange:Ae=>p(Ae.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("profiles.presets.myCustomPreset")})]})]}),v&&i.jsx("div",{className:"text-xs text-bambu-gray",children:i.jsxs("p",{className:"flex items-center gap-1",children:[i.jsx(Zr,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",i.jsx("span",{className:"text-white",children:v}),O&&i.jsx(ft,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[i.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:[i.jsx(X8,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),i.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:[i.jsx(sT,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),i.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:[i.jsx(WX,{className:"w-4 h-4"}),"JSON",k&&i.jsx(Li,{className:"w-3 h-3 text-red-400"})]}),i.jsx("div",{className:"flex-1 max-[640px]:hidden"}),i.jsxs("button",{onClick:()=>{const Ae={name:m,type:u,base_id:f,setting:g},Be=new Blob([JSON.stringify(Ae,null,2)],{type:"application/json"}),Me=URL.createObjectURL(Be),Xe=document.createElement("a");Xe.href=Me,Xe.download=`${m||"preset"}.json`,document.body.appendChild(Xe),Xe.click(),document.body.removeChild(Xe),URL.revokeObjectURL(Me),a(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:[i.jsx(fi,{className:"w-4 h-4"}),r("common.download")]}),i.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:[i.jsx(yi,{className:"w-4 h-4"}),r("common.upload")]}),i.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Ae=>{const Be=Ae.target.files?.[0];if(Be){const Me=new FileReader;Me.onload=Xe=>{try{const ye=JSON.parse(Xe.target?.result),We=ye.setting||ye;_(Pe=>({...Pe,...We})),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJson"),"error")}},Me.readAsText(Be)}}})]}),i.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(hx,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(g).filter(Ae=>Ae!=="inherits").length>0&&i.jsxs("button",{onClick:()=>ue(!Y),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[i.jsx(as,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),Y&&i.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[i.jsx("input",{type:"text",value:de,onChange:Ae=>he(Ae.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}),i.jsx("input",{type:"text",value:V,onChange:Ae=>ne(Ae.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"})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(ze,{size:"sm",onClick:xe,disabled:!de.trim(),children:[i.jsx(as,{className:"w-3 h-3"}),r("common.save")]}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:()=>ue(!1),children:r("common.cancel")})]}),i.jsxs("button",{onClick:()=>pe(!se),className:`flex items-center gap-1.5 text-xs transition-colors ${se?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[se?i.jsx(Tc,{className:"w-3.5 h-3.5"}):i.jsx(xw,{className:"w-3.5 h-3.5"}),r(se?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Te&&i.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:[i.jsx(Zr,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",i.jsx("span",{className:"font-medium",children:Te})]}),i.jsx("button",{onClick:()=>q(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[oe.map(Ae=>i.jsxs("button",{onClick:()=>be(Ae),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:Ae.name}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Ae.description})]},Ae.id)),oe.length===0&&i.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),i.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),i.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:ee.slice(0,10).map(Ae=>i.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[i.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Ae.label}),i.jsx("div",{className:"w-48 max-[640px]:w-full",children:Oe(Ae)})]},Ae.key))})]}),Object.keys(g).length>1&&i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(g).filter(([Ae])=>Ae!=="inherits").map(([Ae,Be])=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Ae,": ",String(Be).slice(0,20),i.jsx("button",{onClick:()=>ce(Ae,void 0),className:"hover:text-white",children:i.jsx(Ht,{className:"w-3 h-3"})})]},Ae))})]})]}),l==="fields"&&i.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:H?r("profiles.templates.fieldsCount",{count:ee.length}):r("common.loading")})]}),i.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:T,onChange:Ae=>D(Ae.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"})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[W.filter(Ae=>!(Ae.key in g)).map(Ae=>{const Be=Fe[Ae.key],Me=He(Be);return i.jsxs("div",{onClick:()=>{_(Xe=>({...Xe,[Ae.key]:Me||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white truncate",children:Ae.label}),i.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Ae.key})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Me&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Me,children:[Me.slice(0,20),Me.length>20?"...":""]}),i.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:i.jsx(ir,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Ae.key)}),W.filter(Ae=>!(Ae.key in g)).length===0&&i.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(T?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:Z?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:G,onChange:Ae=>z(Ae.target.value),onKeyDown:Ae=>Ae.key==="Enter"&&ie(),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}),i.jsx(ze,{size:"sm",onClick:ie,disabled:!G.trim(),children:i.jsx(ir,{className:"w-4 h-4"})}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:()=>{I(!1),z("")},children:i.jsx(Ht,{className:"w-4 h-4"})})]}):i.jsxs("button",{onClick:()=>I(!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:[i.jsx(ir,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(g).filter(Ae=>Ae!=="inherits").length})})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(g).filter(([Ae])=>Ae!=="inherits").map(([Ae,Be])=>{const Me=ee.find(Xe=>Xe.key===Ae);return i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium text-white",children:Me?.label||Ae}),i.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Ae})]}),i.jsx("button",{onClick:()=>ce(Ae,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),Me?Oe(Me):i.jsx("input",{type:"text",value:String(Be),onChange:Xe=>ce(Ae,Xe.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"})]},Ae)}),Object.keys(g).filter(Ae=>Ae!=="inherits").length===0&&i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(X8,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),i.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),i.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(g).filter(Ae=>Ae!=="inherits").length>0&&i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:i.jsxs("button",{onClick:()=>{ue(!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:[i.jsx(as,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&i.jsxs("div",{className:"space-y-2",children:[k&&i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(Li,{className:"w-4 h-4"}),k]}),i.jsx("textarea",{value:N,onChange:Ae=>L(Ae.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 ${k?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsxs(ze,{onClick:()=>fe.mutate(),disabled:fe.isPending||!m.trim()||!o&&!f||!!k,className:"flex-1",children:[fe.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):o?i.jsx(as,{className:"w-4 h-4"}):i.jsx(ir,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function ett({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:a,hasPermission:s,t:o}){const[l,c]=w.useState(""),[u,d]=w.useState("all"),[m,p]=w.useState("all"),[f,y]=w.useState("all"),[v,b]=w.useState("all"),[g,_]=w.useState("all"),[N,C]=w.useState("all"),[k,P]=w.useState(null),[T,D]=w.useState(!1),[A,R]=w.useState(!1),[G,z]=w.useState(null),[Z,I]=w.useState(null),[J,ae]=w.useState(null),[Y,ue]=w.useState(!1),[de,he]=w.useState([null,null]),[V,ne]=w.useState(!1),[se,pe]=w.useState(null),Te=sn(),q=w.useMemo(()=>[...t.filament.map(ie=>({...ie,type:"filament"})),...t.printer.map(ie=>({...ie,type:"printer"})),...t.process.map(ie=>({...ie,type:"process"}))].map(ie=>({...ie,meta:M5(ie.name)})),[t]),X=w.useMemo(()=>{const W=new Set,ie=new Set,ce=new Set;return q.forEach(be=>{be.meta.nozzle&&W.add(be.meta.nozzle),be.meta.filamentType&&ie.add(be.meta.filamentType),be.meta.layerHeight&&ce.add(be.meta.layerHeight)}),{printers:a.map(be=>({id:be.id.toString(),name:be.name})),nozzles:Array.from(W).sort((be,xe)=>parseFloat(be)-parseFloat(xe)),filaments:Array.from(ie).sort(),layerHeights:Array.from(ce).sort((be,xe)=>parseFloat(be)-parseFloat(xe))}},[q,a]),j=w.useMemo(()=>f==="all"?null:a.find(ie=>ie.id.toString()===f)?.model||null,[f,a]),E=w.useMemo(()=>q.filter(W=>u==="all"||W.type===u).filter(W=>{if(m==="all")return!0;const ie=hw(W.setting_id);return m==="custom"?ie:!ie}).filter(W=>{if(f==="all"||!j)return!0;const ie=W.meta.printer?.toLowerCase()||"",ce=j.toLowerCase();return ie.includes(ce)||ce.includes(ie)}).filter(W=>v==="all"||W.meta.nozzle===v).filter(W=>g==="all"||W.meta.filamentType===g).filter(W=>N==="all"||W.meta.layerHeight===N).filter(W=>l===""||W.name.toLowerCase().includes(l.toLowerCase())).sort((W,ie)=>W.name.localeCompare(ie.name)),[q,u,m,f,j,v,g,N,l]),U=W=>{if(Y){const ie=de[0]?.setting_id===W.setting_id,ce=de[1]?.setting_id===W.setting_id;if(ie)he([de[1],null]);else if(ce)he([de[0],null]);else if(!de[0])he([W,null]);else if(de[1]){if(de[0].type!==W.type)return;he([de[0],W])}else{if(de[0].type!==W.type)return;he([de[0],W])}}else P(W)},K=W=>{if(de[0]?.setting_id===W.setting_id)return 0;if(de[1]?.setting_id===W.setting_id)return 1},H=async W=>{try{const ie=await ge.getCloudSettingDetail(W.setting_id),ce=W.type==="process"?"print":W.type;z({type:ce,name:W.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{}}),P(null)}catch(ie){console.error("Failed to fetch preset details for duplication:",ie)}},re=async W=>{try{Te.removeQueries({queryKey:["cloudSettingDetail",W.setting_id]});const ie=await ge.getCloudSettingDetail(W.setting_id),ce=W.type==="process"?"print":W.type;I({type:ce,name:W.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{},setting_id:W.setting_id}),P(null)}catch(ie){console.error("Failed to fetch preset details for editing:",ie)}},O=()=>{d("all"),p("all"),y("all"),b("all"),_("all"),C("all"),c("")},$=u!=="all"||m!=="all"||f!=="all"||v!=="all"||g!=="all"||N!=="all"||l!=="",ee=t.filament.length+t.printer.length+t.process.length;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-4 mb-6",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:l,onChange:W=>c(W.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"})]}),i.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[i.jsxs(ze,{variant:Y?"primary":"secondary",onClick:()=>{Y?(ue(!1),he([null,null])):ue(!0)},children:[i.jsx(Gb,{className:"w-4 h-4"}),o(Y?"common.cancel":"profiles.presets.compare")]}),i.jsxs(ze,{variant:"secondary",onClick:()=>R(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[i.jsx(hx,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),i.jsxs(ze,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[i.jsx(Sr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),i.jsxs(ze,{onClick:()=>D(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[i.jsx(ir,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(aT,{className:"w-4 h-4 text-bambu-gray"}),i.jsx(Tb,{label:o("profiles.cloudView.filters.type"),value:u,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:ee},{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:W=>d(W)}),i.jsx(Tb,{label:o("profiles.cloudView.filters.owner"),value:m,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:W=>p(W)}),X.printers.length>0&&i.jsx(Tb,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...X.printers.map(W=>({value:W.id,label:W.name}))],onChange:y}),X.nozzles.length>0&&i.jsx(Tb,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...X.nozzles.map(W=>({value:W,label:W}))],onChange:b}),X.filaments.length>0&&(u==="all"||u==="filament")&&i.jsx(Tb,{label:o("profiles.cloudView.filters.filament"),value:g,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...X.filaments.map(W=>({value:W,label:W}))],onChange:_}),X.layerHeights.length>0&&(u==="all"||u==="process")&&i.jsx(Tb,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...X.layerHeights.map(W=>({value:W,label:W}))],onChange:C}),$&&i.jsx("button",{onClick:O,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),Y&&i.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(Gb,{className:"w-5 h-5 text-blue-400"}),i.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),i.jsx("span",{className:"text-bambu-gray",children:de[0]?o("profiles.cloudView.selectAnotherPreset",{type:de[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${de[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[0]?de[0].name:o("profiles.cloudView.selectFirst")}),i.jsx(v3,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${de[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[1]?de[1].name:o("profiles.cloudView.selectSecond")})]}),de[0]&&de[1]&&i.jsxs(ze,{size:"sm",onClick:async()=>{try{const[W,ie]=await Promise.all([ge.getCloudSettingDetail(de[0].setting_id),ge.getCloudSettingDetail(de[1].setting_id)]);pe([W.setting||{},ie.setting||{}]),ne(!0)}catch{}},children:[i.jsx(Gb,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),i.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(Zn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",C0(e.toISOString(),"system",o)]}),i.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:E.length,total:ee})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),i.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),E.length===0?i.jsxs("div",{className:"text-center py-16",children:[i.jsx(Gi,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),i.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),$&&i.jsx("button",{onClick:O,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(rT,{className:"w-4 h-4 text-amber-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(W=>W.type==="filament").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(W=>W.type==="filament").map(W=>i.jsx(YD,{setting:W,onClick:()=>U(W),onDuplicate:()=>H(W),compareMode:Y,isCompareSelected:K(W)!==void 0,compareIndex:K(W),compareDisabled:Y&&!!de[0]&&de[0].type!==W.type,t:o},W.setting_id)),E.filter(W=>W.type==="filament").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(Bd,{className:"w-4 h-4 text-blue-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(W=>W.type==="process").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(W=>W.type==="process").map(W=>i.jsx(YD,{setting:W,onClick:()=>U(W),onDuplicate:()=>H(W),compareMode:Y,isCompareSelected:K(W)!==void 0,compareIndex:K(W),compareDisabled:Y&&!!de[0]&&de[0].type!==W.type,t:o},W.setting_id)),E.filter(W=>W.type==="process").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(_r,{className:"w-4 h-4 text-purple-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(W=>W.type==="printer").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(W=>W.type==="printer").map(W=>i.jsx(YD,{setting:W,onClick:()=>U(W),onDuplicate:()=>H(W),compareMode:Y,isCompareSelected:K(W)!==void 0,compareIndex:K(W),compareDisabled:Y&&!!de[0]&&de[0].type!==W.type,t:o},W.setting_id)),E.filter(W=>W.type==="printer").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),k&&i.jsx(Qet,{setting:k,onClose:()=>P(null),onDeleted:()=>P(null),onDuplicate:()=>H(k),onEdit:()=>re(k),hasPermission:s,t:o}),(T||G||Z||J)&&i.jsx(Jet,{onClose:()=>{D(!1),z(null),I(null),ae(null)},initialData:Z||G||(J?{type:J.type,name:"",base_id:"",setting:J.setting}:void 0),allPresets:t,t:o}),A&&i.jsx(Zet,{onClose:()=>R(!1),onApply:W=>{ae({type:W.type,setting:W.settings}),R(!1)},t:o}),V&&se&&de[0]&&de[1]&&i.jsx(Goe,{onClose:()=>{ne(!1),pe(null)},leftPreset:se[0],rightPreset:se[1],leftLabel:de[0].name,rightLabel:de[1].name,t:o})]})}function ttt(){const{t}=Dt(),e=sn(),{showToast:n}=bn(),{hasPermission:r}=Ar(),[a,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:u}=et({queryKey:["cloudStatus"],queryFn:ge.getCloudStatus}),{data:d=[]}=et({queryKey:["printers"],queryFn:ge.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:y}=et({queryKey:["cloudSettings"],queryFn:()=>ge.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{y&&l(new Date(y))},[y]);const v=gt({mutationFn:ge.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return u?i.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"p-6 lg:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),i.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[i.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 ${a==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(qx,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),i.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 ${a==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(Vx,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),i.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 ${a==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(yw,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),a==="cloud"&&i.jsxs(i.Fragment,{children:[c?.is_authenticated&&i.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",i.jsx("span",{className:"text-white",children:c.email})]})]}),i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[i.jsx(N3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?i.jsx(ett,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:d,hasPermission:r,t}):i.jsxs("div",{className:"text-center py-16",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),i.jsx(ze,{onClick:()=>f(),children:t("profiles.retry")})]}):i.jsx(Yet,{onSuccess:b,t})]}),a==="local"&&i.jsx(Ket,{}),a==="kprofiles"&&i.jsx(qet,{}),i.jsx(Xet,{})]})}const Vv={Droplet:rT,Flame:qp,Ruler:Mge,Sparkles:hx,Square:rl,Cable:VL,Wrench:Ef,Calendar:Xr,Timer:Sd,Cog:ype,Fan:KX,Zap:Pc,Wind:oQ,Thermometer:mT,Layers:Gi,Box:ia,Target:iQ,RefreshCw:Sr,Settings:dT,Filter:aT,CircleDot:epe};function g0(t){return t&&Vv[t]||Ef}function Ab(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 a=Math.round(t);return n?n("maintenance.days",{count:a}):`${a} days`}if(t<180){const a=Math.round(t/7);return a===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:a}):`${a} 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 a=r/7;return a<12?`${a<2?a.toFixed(1):Math.round(a)}w`:`${Math.round(a/4)}mo`}}function XD(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 ntt(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),a=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,m=n.includes("P2S");switch(t){case"Lubricate Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||a?"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":m?"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":a?"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":m?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||a?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return r||a?"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 rtt({item:t,onPerform:e,onToggle:n,hasPermission:r,t:a}){const s=g0(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const f=t.days_since_maintenance??0;return Math.max(0,Math.min(100,f/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),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",m=()=>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 a("common.disabled");if(o==="days"){const f=t.days_until_due??0;return t.is_due?a("maintenance.overdueBy",{duration:Ab(Math.abs(f),"days",a)}):t.is_warning?a("maintenance.dueIn",{duration:Ab(f,"days",a)}):a("maintenance.timeLeft",{duration:Ab(f,"days",a)})}else return t.is_due?a("maintenance.overdueBy",{duration:Ab(Math.abs(t.hours_until_due),"hours",a)}):t.is_warning?a("maintenance.dueIn",{duration:Ab(t.hours_until_due,"hours",a)}):a("maintenance.timeLeft",{duration:Ab(t.hours_until_due,"hours",a)})};return i.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:i.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[i.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[i.jsx(s,{className:`w-5 h-5 ${u()}`}),t.enabled&&(t.is_due||t.is_warning)&&i.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`})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&i.jsx("span",{title:a("maintenance.timeBasedInterval"),children:i.jsx(Xr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||ntt(t.maintenance_type_name,t.printer_model);return f?i.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:a("maintenance.viewDocumentation"),onClick:y=>y.stopPropagation(),children:i.jsx(ni,{className:"w-3.5 h-3.5"})}):null})()]}),i.jsx("div",{className:"mt-2 mb-1.5",children:i.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${d()}`,style:{width:`${c}%`}})})}),i.jsxs("div",{className:`text-xs flex items-center gap-1 ${u()}`,children:[t.is_due&&i.jsx(jn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&i.jsx(Zn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&i.jsx(Zr,{className:"w-3 h-3"}),p()]})]}),i.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[i.jsx("span",{title:r("maintenance:update")?void 0:a("maintenance.noPermissionUpdate"),children:i.jsx(zn,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!r("maintenance:update")})}),i.jsxs(ze,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:a("maintenance.noPermissionPerform"),className:"!px-3",children:[i.jsx(To,{className:"w-3.5 h-3.5"}),a("common.reset")]})]})]})})}function itt({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:a,t:s}){const[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,m]=w.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((v,b)=>v.is_due&&!b.is_due?-1:!v.is_due&&b.is_due?1:v.is_warning&&!b.is_warning?-1:!v.is_warning&&b.is_warning?1:v.maintenance_type_id-b.maintenance_type_id),f=p.find(v=>v.enabled&&(v.is_due||v.is_warning)),y=()=>{const v=parseFloat(d);!isNaN(v)&&v>=0&&(r(t.printer_id,v),u(!1))};return i.jsxs(Pt,{className:"overflow-hidden",children:[i.jsxs("div",{className:"p-5",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&i.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:[i.jsx(jn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&i.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:[i.jsx(Zn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&i.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:[i.jsx(Zr,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),i.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?i.jsx(Vl,{className:"w-4 h-4"}):i.jsx(In,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),i.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:i.jsx(Sd,{className:"w-4 h-4 text-bambu-gray"})}),c?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",value:d,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&y(),v.key==="Escape"&&u(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),i.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),i.jsx(ze,{size:"sm",onClick:y,children:s("common.save")}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:()=>u(!1),children:s("common.cancel")})]}):i.jsxs("button",{onClick:()=>{a("maintenance:update")&&(m(Math.round(t.total_print_hours).toString()),u(!0))},className:`group ${a("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:a("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[i.jsxs("div",{className:`text-sm font-medium text-white ${a("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),i.jsx(Pf,{className:`w-3 h-3 text-bambu-gray ${a("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),i.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),i.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=g0(f.maintenance_type_icon);return i.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),i.jsxs("div",{children:[i.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),i.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&i.jsx(Et,{className:"pt-0 border-t border-bambu-dark-tertiary",children:i.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>i.jsx(rtt,{item:v,onPerform:e,onToggle:n,hasPermission:a,t:s},v.id))})})]})}function att({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:a,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:u,hasPermission:d,t:m}){const[p,f]=w.useState(null),[y,v]=w.useState(""),[b,g]=w.useState("hours"),[_,N]=w.useState(!1),[C,k]=w.useState(""),[P,T]=w.useState("100"),[D,A]=w.useState("hours"),[R,G]=w.useState("Wrench"),[z,Z]=w.useState(""),[I,J]=w.useState(new Set),[ae,Y]=w.useState(null),[ue,de]=w.useState(null),he=w.useMemo(()=>t?t.map(L=>({id:L.printer_id,name:L.printer_name})):[],[t]),V=L=>t?t.filter(F=>F.maintenance_items.some(te=>te.maintenance_type_id===L)).map(F=>({printerId:F.printer_id,printerName:F.printer_name,itemId:F.maintenance_items.find(te=>te.maintenance_type_id===L)?.id})):[],ne=L=>{if(!t)return[];const F=new Set(V(L).map(te=>te.printerId));return he.filter(te=>!F.has(te.id))},[se,pe]=w.useState(null),[Te,q]=w.useState(""),[X,j]=w.useState(""),[E,U]=w.useState("hours"),[K,H]=w.useState("Wrench"),[re,O]=w.useState(""),$=L=>{pe(L),q(L.name),j(L.default_interval_hours.toString()),U(L.interval_type||"hours"),H(L.icon||"Wrench"),O(L.wiki_url||"")},ee=()=>{se&&Te.trim()&&parseFloat(X)>0&&(a(se.id,{name:Te.trim(),default_interval_hours:parseFloat(X),interval_type:E,icon:K,wiki_url:re.trim()||null}),pe(null))},W=(L,F,te)=>{const ve=parseFloat(y);if(!isNaN(ve)&&ve>0){const fe=Math.abs(ve-F)<.01?null:ve;n(L,{custom_interval_hours:fe,custom_interval_type:b!==te?b:null})}f(null)},ie=L=>{L.preventDefault(),C.trim()&&parseFloat(P)>0&&I.size>0&&(r({name:C.trim(),default_interval_hours:parseFloat(P),interval_type:D,icon:R,wiki_url:z.trim()||null},Array.from(I)),k(""),T("100"),A("hours"),Z(""),J(new Set),N(!1))},ce=L=>{J(F=>{const te=new Set(F);return te.has(L)?te.delete(L):te.add(L),te})},be=t?.map(L=>({printerId:L.printer_id,printerName:L.printer_name,items:L.maintenance_items.sort((F,te)=>F.maintenance_type_id-te.maintenance_type_id)})).sort((L,F)=>L.printerName.localeCompare(F.printerName))||[],xe=e.filter(L=>L.is_system),oe=e.filter(L=>!L.is_system);return i.jsxs("div",{className:"space-y-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:o,disabled:!d("maintenance:delete")||l,title:d("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),i.jsxs(ze,{onClick:()=>N(!_),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[i.jsx(ir,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),_&&i.jsx(Pt,{className:"mb-6",children:i.jsx(Et,{className:"py-4",children:i.jsxs("form",{onSubmit:ie,children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"lg:col-span-2",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),i.jsx("input",{type:"text",value:C,onChange:L=>k(L.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:m("maintenance.exampleName"),autoFocus:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),i.jsxs("select",{value:D,onChange:L=>{A(L.target.value),L.target.value==="days"?T("30"):T("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:[i.jsx("option",{value:"hours",children:m("maintenance.printHours")}),i.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:D==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),i.jsx("input",{type:"number",value:P,onChange:L=>T(L.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"})]})]}),i.jsx("div",{className:"mt-4 flex items-end justify-between",children:i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),i.jsx("div",{className:"flex gap-1",children:Object.keys(Vv).map(L=>{const F=Vv[L];return i.jsx("button",{type:"button",onClick:()=>G(L),className:`p-2 rounded-lg transition-colors ${R===L?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:i.jsx(F,{className:"w-4 h-4"})},L)})})]})}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),i.jsx("input",{type:"url",value:z,onChange:L=>Z(L.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/..."})]}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:he.map(L=>i.jsx("button",{type:"button",onClick:()=>ce(L.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${I.has(L.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:L.name},L.id))}),I.size===0&&i.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),i.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:()=>{N(!1),J(new Set)},children:m("common.cancel")}),i.jsx(ze,{type:"submit",disabled:!C.trim()||I.size===0,children:m("maintenance.addType")})]})]})})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[xe.map(L=>{const F=g0(L.icon),te=L.interval_type||"hours";return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:i.jsx(F,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[te==="days"?i.jsx(Xr,{className:"w-3 h-3"}):i.jsx(Sd,{className:"w-3 h-3"}),XD(L.default_interval_hours,te,m)]})]}),i.jsx("button",{onClick:()=>{d("maintenance:delete")&&de(L)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(nn,{className:"w-4 h-4"})})]})},L.id)}),oe.map(L=>{const F=g0(L.icon),te=L.interval_type||"hours";if(se?.id===L.id)return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx("input",{type:"text",value:Te,onChange:we=>q(we.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:m("common.name"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("select",{value:E,onChange:we=>U(we.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:[i.jsx("option",{value:"hours",children:m("maintenance.printHours")}),i.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:X,onChange:we=>j(we.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"})]}),i.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(Vv).map(we=>{const Fe=Vv[we];return i.jsx("button",{type:"button",onClick:()=>H(we),className:`p-1.5 rounded transition-colors ${K===we?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:i.jsx(Fe,{className:"w-3.5 h-3.5"})},we)})}),i.jsx("input",{type:"url",value:re,onChange:we=>O(we.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:m("maintenance.documentationLink")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{size:"sm",onClick:ee,disabled:!Te.trim(),children:m("common.save")}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:()=>pe(null),children:m("common.cancel")})]})]})},L.id);const fe=V(L.id),me=ne(L.id),je=ae===L.id;return i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:i.jsx(F,{className:"w-5 h-5 text-bambu-green"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:m("maintenance.custom")})]}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[te==="days"?i.jsx(Xr,{className:"w-3 h-3"}):i.jsx(Sd,{className:"w-3 h-3"}),XD(L.default_interval_hours,te,m)]})]}),i.jsxs("button",{onClick:()=>Y(je?null:L.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${fe.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:m("maintenance.printersAssignedClick",{count:fe.length}),children:[i.jsx(_r,{className:"w-3 h-3"}),i.jsx("span",{className:"text-xs font-medium",children:fe.length}),i.jsx(In,{className:`w-3 h-3 transition-transform ${je?"rotate-180":""}`})]}),i.jsx("button",{onClick:()=>$(L),disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:m("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${d("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Pf,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:L.name}))&&s(L.id)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(nn,{className:"w-4 h-4"})})]}),je&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),fe.length===0?i.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):i.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:fe.map(we=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[we.printerName,i.jsx("button",{onClick:()=>we.itemId&&u(we.itemId),disabled:!d("maintenance:delete"),title:d("maintenance:delete")?m("maintenance.removeFromPrinter"):m("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${d("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},we.printerId))}),me.length>0&&i.jsxs("div",{className:"flex flex-wrap gap-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),me.map(we=>i.jsxs("button",{onClick:()=>c(we.id,L.id),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:m("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${d("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",we.name]},we.id))]})]})]},L.id)})]})]}),be.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"mb-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),i.jsx("div",{className:"space-y-4",children:be.map(L=>i.jsx(Pt,{children:i.jsxs(Et,{className:"py-4",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:L.printerName}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:L.items.map(F=>{const te=g0(F.maintenance_type_icon),ve=e.find(Fe=>Fe.id===F.maintenance_type_id),fe=ve?.default_interval_hours||F.interval_hours,me=ve?.interval_type||"hours",je=F.interval_type||"hours",we=p===F.id;return i.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[i.jsx(te,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:F.maintenance_type_name}),we?i.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?i.jsx(Xr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):i.jsx(Sd,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),i.jsxs("select",{value:b,onChange:Fe=>g(Fe.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[i.jsx("option",{value:"hours",children:m("maintenance.printHours")}),i.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:y,onChange:Fe=>v(Fe.target.value),onKeyDown:Fe=>{Fe.key==="Enter"&&W(F.id,fe,me),Fe.key==="Escape"&&f(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),i.jsx(ze,{size:"sm",onClick:()=>W(F.id,fe,me),children:"OK"})]}):i.jsxs("button",{onClick:()=>{d("maintenance:update")&&(f(F.id),v(F.interval_hours.toString()),g(je))},disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:m("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${d("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[je==="days"?i.jsx(Xr,{className:"w-3 h-3"}):i.jsx(Sd,{className:"w-3 h-3"}),XD(F.interval_hours,je,m),i.jsx(Pf,{className:"w-3 h-3 text-bambu-gray"})]})]},F.id)})})]})},L.printerId))})]}),be.length===0&&i.jsx(Pt,{children:i.jsxs(Et,{className:"text-center py-12",children:[i.jsx(Zn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),ue&&i.jsx(Nn,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:ue.name}),confirmText:m("common.delete"),cancelText:m("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(ue.id),de(null)},onCancel:()=>de(null)})]})}function stt(){const{t}=Dt(),e=sn(),{showToast:n}=bn(),{hasPermission:r}=Ar(),[a,s]=w.useState("status"),{data:o,isLoading:l}=et({queryKey:["maintenanceOverview"],queryFn:ge.getMaintenanceOverview}),{data:c}=et({queryKey:["maintenanceTypes"],queryFn:ge.getMaintenanceTypes}),u=gt({mutationFn:({id:P,notes:T})=>ge.performMaintenance(P,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:P=>{n(P.message,"error")}}),d=gt({mutationFn:({id:P,data:T})=>ge.updateMaintenanceItem(P,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:P=>{n(P.message,"error")}}),m=gt({mutationFn:({id:P,data:T})=>ge.updateMaintenanceType(P,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:P=>{n(P.message,"error")}}),p=gt({mutationFn:ge.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:P=>{n(P.message,"error")}}),f=gt({mutationFn:ge.restoreDefaultMaintenanceTypes,onSuccess:P=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:P.restored}))},onError:P=>{n(P.message,"error")}}),y=gt({mutationFn:({printerId:P,hours:T})=>ge.setPrinterHours(P,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:P=>{n(P.message,"error")}}),v=gt({mutationFn:({printerId:P,typeId:T})=>ge.assignMaintenanceType(P,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:P=>{n(P.message,"error")}}),b=gt({mutationFn:ge.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:P=>{n(P.message,"error")}}),g=P=>{u.mutate({id:P})},_=(P,T)=>{d.mutate({id:P,data:{enabled:T}})},N=(P,T)=>{y.mutate({printerId:P,hours:T})};if(l)return i.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})});const C=o?.reduce((P,T)=>P+T.due_count,0)||0,k=o?.reduce((P,T)=>P+T.warning_count,0)||0;return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),i.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:a==="status"?i.jsxs(i.Fragment,{children:[C>0&&i.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:C})}),C>0&&k>0&&" · ",k>0&&i.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:k})}),C===0&&k===0&&i.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),i.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),i.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),a==="status"?i.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((P,T)=>{const D=P.due_count*10+P.warning_count,A=T.due_count*10+T.warning_count;return D!==A?A-D:P.printer_name.localeCompare(T.printer_name)}).map(P=>i.jsx(itt,{overview:P,onPerform:g,onToggle:_,onSetHours:N,hasPermission:r,t},P.printer_id)):i.jsx(Pt,{children:i.jsxs(Et,{className:"text-center py-16",children:[i.jsx(Ef,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),i.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):i.jsx(att,{overview:o,types:c||[],onUpdateInterval:(P,T)=>d.mutate({id:P,data:T}),onAddType:async(P,T)=>{const D=await ge.createMaintenanceType(P);for(const A of T)await ge.assignMaintenanceType(A,D.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(P,T)=>m.mutate({id:P,data:T}),onDeleteType:P=>p.mutate(P),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(P,T)=>v.mutate({printerId:P,typeId:T}),onRemoveItem:P=>b.mutate(P),hasPermission:r,t})]})}const RY=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Woe({project:t,onClose:e,onSave:n,isLoading:r,currencySymbol:a,t:s}){const[o,l]=w.useState(t?.name||""),[c,u]=w.useState(t?.description||""),[d,m]=w.useState(t?.color||RY[0]),[p,f]=w.useState(t?.target_count?.toString()||""),[y,v]=w.useState(t?.target_parts_count?.toString()||""),[b,g]=w.useState(t?.status||"active"),[_,N]=w.useState(t?.tags||""),[C,k]=w.useState(t?.due_date?.split("T")[0]||""),[P,T]=w.useState(t?.priority||"normal"),[D,A]=w.useState(t?.budget?.toString()||""),R=G=>{G.preventDefault(),n({name:o.trim(),description:c.trim()||void 0,color:d,target_count:p?parseInt(p,10):void 0,target_parts_count:y?parseInt(y,10):void 0,tags:_.trim()||void 0,due_date:C||void 0,priority:P,budget:D.trim()?parseFloat(D):null,...t&&{status:b}})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),i.jsxs("form",{onSubmit:R,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),i.jsx("input",{type:"text",value:o,onChange:G=>l(G.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:s("projects.namePlaceholder"),required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),i.jsx("textarea",{value:c,onChange:G=>u(G.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:s("projects.descriptionPlaceholder"),rows:2})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),i.jsx("div",{className:"flex gap-2 flex-wrap",children:RY.map(G=>i.jsx("button",{type:"button",onClick:()=>m(G),className:`w-8 h-8 rounded-full transition-transform ${d===G?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:G}},G))})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),i.jsx("input",{type:"number",value:p,onChange:G=>f(G.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:s("projects.targetPlatesPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),i.jsx("input",{type:"number",value:y,onChange:G=>v(G.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:s("projects.targetPartsPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),i.jsx("input",{type:"text",value:_,onChange:G=>N(G.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:s("projects.tagsPlaceholder")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),i.jsx("input",{type:"date",value:C,onChange:G=>k(G.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),i.jsxs("select",{value:P,onChange:G=>T(G.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:[i.jsx("option",{value:"low",children:s("projects.priorityLow")}),i.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),i.jsx("option",{value:"high",children:s("projects.priorityHigh")}),i.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),i.jsxs("div",{className:"relative",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:a}),i.jsx("input",{type:"number",step:"0.01",min:"0",value:D,onChange:G=>A(G.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded pl-8 pr-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"0.00"})]})]}),t&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),i.jsxs("select",{value:b,onChange:G=>g(G.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:[i.jsx("option",{value:"active",children:s("projects.statusActive")}),i.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),i.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(ze,{type:"submit",disabled:!o.trim()||r,children:r?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function ott({project:t,onClick:e,onEdit:n,onDelete:r,hasPermission:a,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,m]=w.useState(!1),f=c?{icon:vc,color:"text-bambu-green",bg:"bg-bambu-green/10"}:u?{icon:Vs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Zn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:vs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return i.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:[i.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`}}),i.jsxs("div",{className:"p-5 pl-6",children:[i.jsxs("div",{className:"flex items-start justify-between mb-4",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:i.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?i.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?i.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?i.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&&i.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&&i.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&&i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const y=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(Boolean),v=[...new Set(y)],b=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),g=[...new Set(b)];return v.length===0&&g.length===0?null:i.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>i.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),g.length>0&&i.jsxs("div",{className:"flex items-center gap-0.5",children:[g.slice(0,5).map(_=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),g.length>5&&i.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",g.length-5]})]})]})})()]})]}),i.jsxs("div",{className:"relative",onClick:y=>y.stopPropagation(),children:[i.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:()=>m(!d),children:i.jsx(Nh,{className:"w-4 h-4"})}),d&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),i.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:[i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:update")&&(n(),m(!1))},disabled:!a("projects:update"),title:a("projects:update")?void 0:s("projects.noEditPermission"),children:[i.jsx(Pf,{className:"w-4 h-4"}),s("common.edit")]}),i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:delete")&&(r(),m(!1))},disabled:!a("projects:delete"),title:a("projects:delete")?void 0:s("projects.noDeletePermission"),children:[i.jsx(nn,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),i.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?i.jsxs("div",{className:"space-y-3",children:[t.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),i.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.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&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),i.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.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&&i.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?i.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(Vs,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[i.jsx(jn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[i.jsx(Zn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):i.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&i.jsxs("div",{className:"mb-4",children:[i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(y=>i.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:y.print_name||"Unknown",children:[y.thumbnail_path?i.jsx("img",{src:ge.getArchiveThumbnail(y.id),alt:y.print_name||"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:i.jsx(Wi,{className:"w-6 h-6"})}),y.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:i.jsx(jn,{className:"w-4 h-4 text-white"})})]},y.id))}),t.archive_count>4&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),i.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[i.jsx(Gi,{className:"w-3.5 h-3.5 text-blue-400"}),i.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[i.jsx(Wi,{className:"w-3.5 h-3.5 text-bambu-green"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[i.jsx(jn,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[i.jsx(_3,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.queue_count})]})]}),i.jsx(fa,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function ltt(){const{t}=Dt(),e=ol(),n=sn(),{showToast:r}=bn(),{hasPermission:a}=Ar(),[s,o]=w.useState(!1),[l,c]=w.useState(),[u,d]=w.useState("active"),[m,p]=w.useState(null),{data:f}=et({queryKey:["settings"],queryFn:ge.getSettings}),y=Wo(f?.currency||"USD"),{data:v,isLoading:b}=et({queryKey:["projects",u==="all"?void 0:u],queryFn:()=>ge.getProjects(u==="all"?void 0:u)}),g=gt({mutationFn:J=>ge.createProject(J),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:J=>{r(J.message,"error")}}),_=gt({mutationFn:({id:J,data:ae})=>ge.updateProject(J,ae),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:J=>{r(J.message,"error")}}),N=gt({mutationFn:J=>ge.deleteProject(J),onSuccess:()=>{p(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:J=>{p(null),r(J.message,"error")}}),C=gt({mutationFn:J=>ge.importProject(J),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:J=>{r(J.message,"error")}}),k=w.useRef(null),P=async()=>{try{const J=await ge.getProjects(),ae=await Promise.all(J.map(async he=>await ge.exportProjectJson(he.id))),Y=new Blob([JSON.stringify(ae,null,2)],{type:"application/json"}),ue=URL.createObjectURL(Y),de=document.createElement("a");de.href=ue,de.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,de.click(),URL.revokeObjectURL(ue),r(t("projects.toast.exported"),"success")}catch(J){r(J.message,"error")}},T=()=>{k.current?.click()},D=async J=>{const ae=J.target.files?.[0];if(ae){try{if(ae.name.toLowerCase().endsWith(".zip"))await ge.importProjectFile(ae),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const ue=await ae.text(),de=JSON.parse(ue),he=Array.isArray(de)?de:[de];for(const V of he)await C.mutateAsync(V);he.length>1&&r(t("projects.toast.multipleImported",{count:he.length}),"success")}}catch(Y){r(`${t("projects.toast.importFailed")}: ${Y.message}`,"error")}J.target.value=""}},A=J=>{l?_.mutate({id:l.id,data:J}):g.mutate(J)},R=J=>{c(J),o(!0)},G=J=>{e(`/projects/${J.id}`)},z=J=>{p(J)},Z=()=>{m!==null&&N.mutate(m)},I=v?.reduce((J,ae)=>(J[ae.status]=(J[ae.status]||0)+1,J.all=(J.all||0)+1,J),{})||{};return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsx("input",{ref:k,type:"file",accept:".json,.zip",onChange:D,className:"hidden"}),i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(vs,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(ze,{variant:"secondary",onClick:T,disabled:!a("projects:create"),title:a("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[i.jsx(yi,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),i.jsxs(ze,{variant:"secondary",onClick:P,disabled:!a("projects:read"),title:a("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[i.jsx(fi,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),i.jsxs(ze,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(ir,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),i.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Zn},{key:"completed",label:t("projects.statusCompleted"),icon:vc},{key:"archived",label:t("projects.statusArchived"),icon:Vs},{key:"all",label:t("common.all"),icon:vs}].map(({key:J,label:ae,icon:Y})=>i.jsxs("button",{onClick:()=>d(J),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===J?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Y,{className:"w-4 h-4"}),i.jsx("span",{children:ae}),I[J]>0&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===J?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:I[J]})]},J))}),b?i.jsx("div",{className:"flex items-center justify-center py-20",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(vs,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:u==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:u})}),i.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"&&i.jsxs(ze,{onClick:()=>o(!0),disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(ir,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(J=>i.jsx(ott,{project:J,onClick:()=>G(J),onEdit:()=>R(J),onDelete:()=>z(J.id),hasPermission:a,t},J.id))}),m!==null&&i.jsx(Nn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:Z,onCancel:()=>p(null)}),s&&i.jsx(Woe,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:A,isLoading:g.isPending||_.isPending,currencySymbol:y,t})]})}function ctt(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function utt({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,a={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return i.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:a[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function FY({icon:t,label:e,value:n,subValue:r,hint:a,color:s="text-bambu-gray"}){return i.jsx(Pt,{children:i.jsx(Et,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",title:a,children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function dtt({archives:t,t:e}){return t.length===0?i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(Wi,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),i.jsx("p",{children:e("projectDetail.noPrints")})]}):i.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=>i.jsxs(fo,{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?i.jsx("img",{src:ge.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:i.jsx(Wi,{className:"w-8 h-8"})}),n.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:i.jsx(Vi,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&i.jsx("div",{className:"absolute top-1 right-1",children:i.jsx(pr,{className:"w-4 h-4 text-bambu-green"})}),i.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:i.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function mtt({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:a}=n[t]||n.normal;return i.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&i.jsx(jn,{className:"w-3 h-3"}),a]})}function QD(t,e){if(!t)return null;const n=Qn(t);if(!n)return null;const r=new Date,a=Math.ceil((n.getTime()-r.getTime())/(1e3*60*60*24));return a<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:a===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:a<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:a})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:a})}}function htt(){const{id:t}=gw(),e=ol(),{t:n}=Dt(),r=sn(),{showToast:a}=bn(),{hasPermission:s}=Ar(),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,m]=w.useState(""),p=parseInt(t||"0",10),{data:f,isLoading:y,error:v}=et({queryKey:["project",p],queryFn:()=>ge.getProject(p),enabled:p>0}),{data:b,isLoading:g}=et({queryKey:["project-archives",p],queryFn:()=>ge.getProjectArchives(p),enabled:p>0}),{data:_,isLoading:N}=et({queryKey:["project-bom",p],queryFn:()=>ge.getProjectBOM(p),enabled:p>0}),{data:C,isLoading:k}=et({queryKey:["project-timeline",p],queryFn:()=>ge.getProjectTimeline(p,20),enabled:p>0}),{data:P}=et({queryKey:["settings"],queryFn:ge.getSettings}),{data:T}=et({queryKey:["project-folders",p],queryFn:()=>ge.getLibraryFoldersByProject(p),enabled:p>0}),D=Wo(P?.currency||"USD"),A=P?.time_format||"system",R=gt({mutationFn:Me=>ge.updateProject(p,Me),onSuccess:()=>{r.invalidateQueries({queryKey:["project",p]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),a(n("projectDetail.toast.projectUpdated"),"success")},onError:Me=>{a(Me.message,"error")}}),G=()=>{m(f?.notes||""),u(!0)},z=()=>{R.mutate({notes:d})},Z=()=>{u(!1),m("")},[I,J]=w.useState(""),[ae,Y]=w.useState(1),[ue,de]=w.useState(""),[he,V]=w.useState(""),[ne,se]=w.useState(""),[pe,Te]=w.useState(!1),[q,X]=w.useState(!1),[j,E]=w.useState(null),[U,K]=w.useState(""),[H,re]=w.useState(1),[O,$]=w.useState(""),[ee,W]=w.useState(""),[ie,ce]=w.useState(""),[be,xe]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),oe=gt({mutationFn:Me=>ge.createBOMItem(p,Me),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),J(""),Y(1),de(""),V(""),se(""),Te(!1),a(n("projectDetail.toast.partAdded"),"success")},onError:Me=>a(Me.message,"error")}),L=gt({mutationFn:({itemId:Me,data:Xe})=>ge.updateBOMItem(p,Me,Xe),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),E(null)},onError:Me=>a(Me.message,"error")}),F=gt({mutationFn:Me=>ge.deleteBOMItem(p,Me),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),a(n("projectDetail.toast.partRemoved"),"success")},onError:Me=>a(Me.message,"error")}),te=Me=>{Me.preventDefault(),I.trim()&&oe.mutate({name:I.trim(),quantity_needed:ae,unit_price:ue?parseFloat(ue):void 0,sourcing_url:he.trim()||void 0,remarks:ne.trim()||void 0})},ve=Me=>{const Xe=Me.is_complete?0:Me.quantity_needed;L.mutate({itemId:Me.id,data:{quantity_acquired:Xe}})},fe=(Me,Xe)=>{xe({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Xe}),onConfirm:()=>{xe(ye=>({...ye,isOpen:!1})),F.mutate(Me)}})},me=Me=>{E(Me),K(Me.name),re(Me.quantity_needed),$(Me.unit_price?.toString()||""),W(Me.sourcing_url||""),ce(Me.remarks||"")},je=Me=>{Me.preventDefault(),!(!j||!U.trim())&&L.mutate({itemId:j.id,data:{name:U.trim(),quantity_needed:H,unit_price:O?parseFloat(O):void 0,sourcing_url:ee.trim()||void 0,remarks:ie.trim()||void 0}})},we=()=>{E(null)},Fe=async()=>{try{const{blob:Me,filename:Xe}=await ge.exportProjectZip(Number(p)),ye=URL.createObjectURL(Me),We=document.createElement("a");We.href=ye,We.download=Xe||`${f?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,We.click(),URL.revokeObjectURL(ye),a(n("projectDetail.toast.projectExported"),"success")}catch(Me){a(Me.message,"error")}},He=gt({mutationFn:()=>ge.createTemplateFromProject(p),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),a(n("projectDetail.toast.templateCreated"),"success")},onError:Me=>a(Me.message,"error")}),Oe=Me=>Df(Me,A,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(y)return i.jsx("div",{className:"flex items-center justify-center py-24",children:i.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!f)return i.jsxs("div",{className:"text-center py-24",children:[i.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),i.jsx(ze,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const _e=f.stats,Ae=_e?.progress_percent??0,Be=_e?.parts_progress_percent??0;return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(fo,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),i.jsx(fa,{className:"w-4 h-4"}),i.jsx("span",{className:"text-white",children:f.name})]}),i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:i.jsx($X,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:f.color||"#6b7280"}}),i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:f.name}),f.description&&i.jsx("p",{className:"text-bambu-gray mt-1",children:f.description})]})]}),i.jsx(utt,{status:f.status,t:n})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(ze,{variant:"secondary",onClick:Fe,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[i.jsx(fi,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),i.jsxs(ze,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[i.jsx(Pf,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(f.target_count||f.target_parts_count)&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4 space-y-4",children:[f.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[_e?.total_archives||0," / ",f.target_count," ",n("projectDetail.progress.printJobs")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ae,100)}%`,backgroundColor:Ae>=100?"#22c55e":f.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Ae.toFixed(0)})}),_e?.remaining_prints!=null&&_e.remaining_prints>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:_e.remaining_prints})})]})]}),f.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[_e?.completed_prints||0," / ",f.target_parts_count," ",n("projectDetail.progress.parts")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Be,100)}%`,backgroundColor:Be>=100?"#22c55e":f.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Be.toFixed(0)})}),_e?.remaining_parts!=null&&_e.remaining_parts>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:_e.remaining_parts})})]})]})]})}),_e&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(Pt,{children:i.jsx(Et,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:i.jsx(Wi,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),i.jsxs("p",{className:"text-xl font-semibold text-white",children:[_e.total_archives," ",i.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),_e.failed_prints>0&&i.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:_e.failed_prints})}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:_e.completed_prints})})]})]})})}),i.jsx(FY,{icon:Zn,label:n("projectDetail.stats.printTime"),value:axe(_e.total_print_time_hours),color:"text-yellow-400"}),i.jsx(FY,{icon:_r,label:n("projectDetail.stats.filamentUsed"),value:ctt(_e.total_filament_grams),color:"text-purple-400"})]}),_e&&(()=>{const Me=_e.estimated_cost+_e.total_energy_cost+_e.bom_cost;return _e.estimated_cost>0||Me>0||f.budget!==null})()&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[D,_e.estimated_cost.toFixed(2)]})]}),_e.total_energy_kwh>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[_e.total_energy_kwh.toFixed(3)," kWh",_e.total_energy_cost>0&&i.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",D,_e.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const Me=_e.estimated_cost+_e.total_energy_cost+_e.bom_cost;return Me<=0?null:i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),i.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[D,Me.toFixed(2)]}),_e.bom_cost>0&&i.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),f.budget!==null&&(()=>{const Me=_e.estimated_cost+_e.total_energy_cost+_e.bom_cost,Xe=f.budget-Me;return i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",i.jsxs("span",{className:"text-white font-semibold",children:[D,f.budget.toFixed(2)]})]}),i.jsxs("p",{className:`text-sm ${Xe>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",i.jsxs("span",{className:"font-semibold",children:[D,Xe.toFixed(2)]})]})]})})()]})]})}),f.children&&f.children.length>0&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[i.jsx(tfe,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:f.children.length})]}),i.jsx("div",{className:"space-y-2",children:f.children.map(Me=>i.jsxs(fo,{to:`/projects/${Me.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Me.color||"#6b7280"}}),i.jsx("span",{className:"text-white",children:Me.name}),i.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${Me.status==="completed"?"bg-status-ok/20 text-status-ok":Me.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:Me.status})]}),Me.progress_percent!==null&&i.jsxs("span",{className:"text-sm text-bambu-gray",children:[Me.progress_percent.toFixed(0),"%"]})]},Me.id))})]})}),f.parent_id&&f.parent_name&&i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Gi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),i.jsx(fo,{to:`/projects/${f.parent_id}`,className:"text-bambu-green hover:underline",children:f.parent_name})]}),(f.tags||f.due_date||f.priority!=="normal")&&i.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[f.priority&&f.priority!=="normal"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),i.jsx(mtt,{priority:f.priority,t:n})]}),f.due_date&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Xr,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-sm text-white",children:jf(f.due_date,{year:"numeric",month:"short",day:"numeric"})}),QD(f.due_date,n)&&i.jsxs("span",{className:`text-xs ${QD(f.due_date,n).color}`,children:["(",QD(f.due_date,n).label,")"]})]}),f.tags&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Hd,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:f.tags.split(",").map((Me,Xe)=>i.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:Me.trim()},Xe))})]})]}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Bs,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(ze,{variant:"secondary",size:"sm",onClick:Z,disabled:R.isPending,children:[i.jsx(Ht,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),i.jsxs(ze,{size:"sm",onClick:z,disabled:R.isPending,children:[R.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin mr-1"}):i.jsx(as,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):i.jsxs(ze,{variant:"secondary",size:"sm",onClick:G,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[i.jsx(Pf,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?i.jsx(bL,{content:d,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):f.notes?i.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:yie.sanitize(f.notes)}}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ac,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),i.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[i.jsx(fo,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),T&&T.length>0?i.jsx("div",{className:"space-y-2",children:T.map(Me=>i.jsxs(fo,{to:`/files?folder=${Me.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx(Ac,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:Me.name}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:Me.file_count})})]})]}),i.jsx(fa,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},Me.id))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(tQ,{className:"w-5 h-5"}),n("projectDetail.bom.title"),_e&&_e.bom_total_items>0&&i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:_e.bom_completed_items,total:_e.bom_total_items}),")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[_&&_.some(Me=>Me.is_complete)&&i.jsx("button",{onClick:()=>X(!q),className:`text-xs px-2 py-1 rounded transition-colors ${q?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(q?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!pe&&i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>Te(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[i.jsx(ir,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),pe&&i.jsxs("form",{onSubmit:te,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:I,onChange:Me=>J(Me.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}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:ae,onChange:Me=>Y(parseInt(Me.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")}),i.jsx("input",{type:"number",step:"0.01",value:ue,onChange:Me=>de(Me.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:D})})]})]}),i.jsx("input",{type:"url",value:he,onChange:Me=>V(Me.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")}),i.jsx("input",{type:"text",value:ne,onChange:Me=>se(Me.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")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(ze,{type:"button",variant:"secondary",size:"sm",onClick:()=>Te(!1),children:n("common.cancel")}),i.jsx(ze,{type:"submit",size:"sm",disabled:!I.trim()||oe.isPending,children:oe.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),N?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):_&&_.length>0?i.jsxs("div",{className:"space-y-2",children:[_.filter(Me=>!q||!Me.is_complete).map(Me=>i.jsx("div",{className:`p-3 rounded-lg transition-colors ${Me.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:j?.id===Me.id?i.jsxs("form",{onSubmit:je,className:"space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:U,onChange:Xe=>K(Xe.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}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:H,onChange:Xe=>re(parseInt(Xe.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")}),i.jsx("input",{type:"number",step:"0.01",value:O,onChange:Xe=>$(Xe.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:D})})]})]}),i.jsx("input",{type:"url",value:ee,onChange:Xe=>W(Xe.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")}),i.jsx("input",{type:"text",value:ie,onChange:Xe=>ce(Xe.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")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(ze,{type:"button",variant:"secondary",size:"sm",onClick:we,children:n("common.cancel")}),i.jsx(ze,{type:"submit",size:"sm",disabled:!U.trim()||L.isPending,children:L.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("button",{onClick:()=>s("projects:update")&&ve(Me),disabled:L.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 ${Me.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:Me.is_complete&&i.jsx(pr,{className:"w-3 h-3"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsxs("p",{className:`text-sm font-medium ${Me.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[Me.name,i.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",Me.quantity_needed]})]}),Me.unit_price!==null&&i.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[D,(Me.unit_price*Me.quantity_needed).toFixed(2)]})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>s("projects:update")&&me(Me),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:i.jsx(Yi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("projects:update")&&fe(Me.id,Me.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:i.jsx(nn,{className:"w-4 h-4"})})]})]}),Me.sourcing_url&&i.jsxs("a",{href:Me.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:Xe=>Xe.stopPropagation(),children:[i.jsx(ni,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"truncate",children:(()=>{try{return new URL(Me.sourcing_url).hostname.replace("www.","")}catch{return Me.sourcing_url}})()})]}),Me.remarks&&i.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:Me.remarks})]})]})},Me.id)),_e&&_e.bom_cost>0&&i.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),i.jsxs("span",{className:"text-white font-medium",children:[D,_e.bom_cost.toFixed(2)]})]})]}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(_0,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),k?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):C&&C.length>0?i.jsx("div",{className:"space-y-3",children:C.slice(0,10).map((Me,Xe)=>i.jsxs("div",{className:"flex gap-3",children:[i.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${Me.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":Me.event_type==="print_failed"?"bg-status-error/20 text-status-error":Me.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Me.event_type==="print_completed"&&i.jsx(pr,{className:"w-4 h-4"}),Me.event_type==="print_failed"&&i.jsx(Vi,{className:"w-4 h-4"}),Me.event_type==="print_started"&&i.jsx(_r,{className:"w-4 h-4"}),Me.event_type==="queued"&&i.jsx(_3,{className:"w-4 h-4"}),Me.event_type==="project_created"&&i.jsx(ir,{className:"w-4 h-4"})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white",children:Me.title}),Me.description&&i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Me.description}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:Oe(Me.timestamp)})]})]},Xe))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!f.is_template&&i.jsx("div",{className:"flex justify-end",children:i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>He.mutate(),disabled:He.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[He.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(ko,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),_e&&(_e.queued_prints>0||_e.in_progress_prints>0)&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(_3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),i.jsx(fo,{to:`/queue?project=${p}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[_e.in_progress_prints>0&&i.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:_e.in_progress_prints})}),_e.queued_prints>0&&i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:_e.queued_prints})})]})]})}),i.jsxs("div",{children:[i.jsx("div",{className:"flex items-center justify-between mb-4",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Wi,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:b?.length||0})]})}),g?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):i.jsx(dtt,{archives:b||[],t:n})]}),o&&i.jsx(Woe,{t:n,currencySymbol:D,project:{...f,archive_count:_e?.total_archives||0,total_items:_e?.total_items||0,completed_count:_e?.completed_prints||0,failed_count:_e?.failed_prints||0,queue_count:_e?.queued_prints||0,progress_percent:_e?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:Me=>R.mutate(Me),isLoading:R.isPending}),be.isOpen&&i.jsx(Nn,{title:be.title,message:be.message,confirmText:n("common.delete"),variant:"danger",onConfirm:be.onConfirm,onCancel:()=>xe(Me=>({...Me,isOpen:!1}))})]})}function ptt({parentId:t,onClose:e,onSave:n,isLoading:r,t:a}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("fileManager.newFolder")})}),i.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.folderName")}),i.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:a("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(ze,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):a("common.create")})]})]})]})})}function ftt({type:t,currentName:e,onClose:n,onSave:r,isLoading:a,t:s}){const o=t==="file"?e.match(/(\.gcode\.3mf|\.3mf|\.gcode)$/i)?.[1]??"":"",l=t==="file"&&o?e.slice(0,-o.length):e,[c,u]=w.useState(l),d=m=>{m.preventDefault();const p=t==="file"?c.trim()+o:c.trim();c.trim()&&p!==e&&r(p)};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),i.jsxs("form",{onSubmit:d,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),i.jsxs("div",{className:"flex items-center bg-bambu-dark border border-bambu-dark-tertiary rounded focus-within:border-bambu-green",children:[i.jsx("input",{type:"text",value:c,onChange:m=>u(m.target.value),className:"flex-1 bg-transparent px-3 py-2 text-white placeholder-bambu-gray focus:outline-none min-w-0",autoFocus:!0,required:!0}),o&&i.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),i.jsx(ze,{type:"submit",disabled:!c.trim()||c.trim()===l||a,children:a?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function gtt({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:a,isLoading:s,t:o}){const[l,c]=w.useState(null),u=(m,p=0)=>{const f=[];for(const y of m)f.push({id:y.id,name:y.name,depth:p}),y.children.length>0&&f.push(...u(y.children,p+1));return f},d=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...u(t)];return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:d.map(m=>i.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[i.jsx(Ac,{className:"w-4 h-4"}),m.name,m.id===n&&i.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),i.jsx(ze,{onClick:()=>a(l),disabled:s,children:s?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function btt({folder:t,onClose:e,onLink:n,isLoading:r,t:a}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:u}=et({queryKey:["projects"],queryFn:()=>ge.getProjects()}),{data:d}=et({queryKey:["archives-for-link"],queryFn:()=>ge.getArchives(void 0,void 0,100)}),m=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ah,{className:"w-5 h-5 text-bambu-green"}),a("fileManager.linkFolder")]}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("fileManager.linkFolderDescription",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.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:[i.jsx(qX,{className:"w-4 h-4"}),a("fileManager.project")]}),i.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:[i.jsx(Vs,{className:"w-4 h-4"}),a("fileManager.archive")]})]}),i.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(y=>i.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:y.color||"#00ae42"}}),i.jsx("span",{className:"truncate",children:y.name})]},y.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noProjectsFound")}):d&&d.length>0?d.map(y=>i.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx(mf,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"truncate",children:y.print_name||y.filename})]},y.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noArchivesFound")})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&i.jsxs(ze,{variant:"danger",onClick:p,disabled:r,children:[i.jsx(N0,{className:"w-4 h-4 mr-2"}),a("fileManager.unlink")]}),i.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[i.jsx(ze,{variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(ze,{onClick:m,disabled:!l||r,children:r?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):a("fileManager.link")})]})]})]})})}function Koe({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:u}){const[d,m]=w.useState(!0),[p,f]=w.useState(!1),y=t.children.length>0,v=t.project_id||t.archive_id;return i.jsxs("div",{children:[i.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:[y?i.jsx("button",{onClick:b=>{b.stopPropagation(),m(!d)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(fa,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-90":""}`})}):i.jsx("div",{className:"w-4.5"}),i.jsx(Ac,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),i.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&i.jsxs("button",{onClick:b=>{b.stopPropagation(),a(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:[i.jsx(Ah,{className:"w-3 h-3"}),t.project_name?i.jsx(qX,{className:"w-3 h-3"}):i.jsx(Vs,{className:"w-3 h-3"})]}),t.file_count>0&&i.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&i.jsx("button",{onClick:b=>{b.stopPropagation(),a(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:i.jsx(Ah,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),i.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:b=>b.stopPropagation(),children:i.jsxs("div",{className:"relative",children:[i.jsx("button",{onClick:()=>f(!p),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:i.jsx(Nh,{className:"w-3.5 h-3.5 text-bambu-gray"})}),p&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>f(!1)}),i.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:[i.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),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[i.jsx(Yi,{className:"w-3.5 h-3.5"}),u("common.rename")]}),i.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")&&(a(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[i.jsx(Ah,{className:"w-3.5 h-3.5"}),u(v?"fileManager.changeLink":"fileManager.linkTo")]}),i.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),f(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[i.jsx(nn,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),y&&d&&i.jsx("div",{children:t.children.map(b=>i.jsx(Koe,{folder:b,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},b.id))})]})}function kL(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function xtt({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:a,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:u,onGenerateThumbnail:d,thumbnailVersion:m,hasPermission:p,canModify:f,authEnabled:y,t:v}){const[b,g]=w.useState(!1);return i.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:[i.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?i.jsx("img",{src:`${ge.getLibraryFileThumbnailUrl(t.id)}${m?`?v=${m}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):i.jsx(mf,{className:"w-12 h-12 text-bambu-gray/30"}),i.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()})]}),i.jsxs("div",{className:"p-3",children:[i.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),i.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[i.jsx("span",{children:xo(t.file_size)}),t.print_time_seconds&&i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Zn,{className:"w-3 h-3"}),Us(t.print_time_seconds)]})]}),t.sliced_for_model&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(_r,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&i.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),y&&t.created_by_username&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx($d,{className:"w-3 h-3"}),t.created_by_username]})]}),i.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[i.jsx("button",{onClick:()=>g(!b),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:i.jsx(Nh,{className:"w-4 h-4 text-bambu-gray"})}),b&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),i.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&&kL(t.filename)&&i.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),g(!1))},disabled:!p("printers:control"),title:p("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[i.jsx(_r,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&kL(t.filename)&&i.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),g(!1))},disabled:!p("queue:create"),title:p("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[i.jsx(Zn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&i.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),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:"You do not have permission to preview files",children:[i.jsx(ia,{className:"w-3.5 h-3.5"}),"3D Preview"]}),i.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),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[i.jsx(fi,{className:"w-3.5 h-3.5"}),v("common.download")]}),u&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(u(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[i.jsx(Yi,{className:"w-3.5 h-3.5"}),v("common.rename")]}),d&&t.file_type==="stl"&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(d(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[i.jsx(Ud,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","delete",t.created_by_id)&&(a(t.id),g(!1))},disabled:!f("library","delete",t.created_by_id),title:f("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[i.jsx(nn,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),i.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&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function ytt(){const{t}=Dt(),e=sn(),{showToast:n}=bn(),{hasPermission:r,hasAnyPermission:a,canModify:s,authEnabled:o}=Ar(),[l]=LL(),c=l.get("folder"),u=c?parseInt(c,10):null,[d,m]=w.useState(u),[p,f]=w.useState([]),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,N]=w.useState(!1),[C,k]=w.useState(null),[P,T]=w.useState(null),[D,A]=w.useState(null),[R,G]=w.useState(null),[z,Z]=w.useState(null),[I,J]=w.useState(null),[ae,Y]=w.useState({}),[ue,de]=w.useState(null),[he,V]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[ne,se]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[pe,Te]=w.useState(()=>{const qe=localStorage.getItem("library-sidebar-width");return qe?parseInt(qe,10):256}),[q,X]=w.useState(!1),j=w.useRef(null);w.useEffect(()=>{if(!q)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const qe=_t=>{if(!j.current)return;const rt=j.current.parentElement?.getBoundingClientRect();if(!rt)return;const Rt=_t.clientX-rt.left,qt=Math.min(500,Math.max(200,Rt));Te(qt)},Nt=()=>{X(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(pe))};return document.addEventListener("mousemove",qe),document.addEventListener("mouseup",Nt),()=>{document.removeEventListener("mousemove",qe),document.removeEventListener("mouseup",Nt),document.body.style.userSelect="",document.body.style.cursor=""}},[q,pe]);const[E,U]=w.useState(""),[K,H]=w.useState("all"),[re,O]=w.useState(""),[$,ee]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[W,ie]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),ce=uie();w.useEffect(()=>{const qe=l.get("folder");if(qe){const Nt=parseInt(qe,10);m(Nt)}},[l]);const{data:be}=et({queryKey:["settings"],queryFn:()=>ge.getSettings()}),{data:xe,isLoading:oe}=et({queryKey:["library-folders"],queryFn:()=>ge.getLibraryFolders()}),{data:L,isLoading:F}=et({queryKey:["library-files",d],queryFn:()=>ge.getLibraryFiles(d,d===null)}),{data:te}=et({queryKey:["library-stats"],queryFn:()=>ge.getLibraryStats()}),{data:ve}=et({queryKey:["users"],queryFn:()=>ge.getUsers()}),fe=w.useMemo(()=>{if(!L)return[];const qe=new Set(L.map(Nt=>Nt.file_type));return Array.from(qe).sort()},[L]),me=w.useMemo(()=>{if(!L)return[];let qe=[...L];if(E.trim()){const Nt=E.toLowerCase();qe=qe.filter(_t=>_t.filename.toLowerCase().includes(Nt)||_t.print_name&&_t.print_name.toLowerCase().includes(Nt))}if(K!=="all"&&(qe=qe.filter(Nt=>Nt.file_type===K)),re.trim()){const Nt=re.toLowerCase();qe=qe.filter(_t=>_t.created_by_username&&_t.created_by_username.toLowerCase().includes(Nt))}return qe.sort((Nt,_t)=>{let rt=0;switch($){case"name":rt=(Nt.print_name||Nt.filename).localeCompare(_t.print_name||_t.filename);break;case"date":rt=(Qn(Nt.created_at)?.getTime()??0)-(Qn(_t.created_at)?.getTime()??0);break;case"size":rt=Nt.file_size-_t.file_size;break;case"type":rt=Nt.file_type.localeCompare(_t.file_type);break;case"prints":rt=Nt.print_count-_t.print_count;break}return W==="asc"?rt:-rt}),qe},[L,E,K,re,$,W]),je=w.useMemo(()=>{if(!te||!be)return!1;const qe=(be.library_disk_warning_gb||5)*1024*1024*1024;return te.disk_free_bytesge.createLibraryFolder(qe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:qe=>n(qe.message,"error")}),Fe=gt({mutationFn:qe=>ge.deleteLibraryFolder(qe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===P?.id&&m(null),T(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:qe=>{T(null),n(qe.message,"error")}}),He=gt({mutationFn:qe=>ge.deleteLibraryFile(qe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),f(qe=>qe.filter(Nt=>Nt!==P?.id)),T(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:qe=>{T(null),n(qe.message,"error")}}),Oe=gt({mutationFn:qe=>ge.bulkDeleteLibrary(qe,[]),onSuccess:(qe,Nt)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:Nt.length}),"success"),f([]),T(null)},onError:qe=>{T(null),n(qe.message,"error")}}),_e=gt({mutationFn:({fileIds:qe,folderId:Nt})=>ge.moveLibraryFiles(qe,Nt),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),f([]),g(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:qe=>n(qe.message,"error")}),Ae=gt({mutationFn:({id:qe,data:Nt})=>ge.updateLibraryFolder(qe,Nt),onSuccess:(qe,Nt)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),k(null);const _t=Nt.data.project_id===0&&Nt.data.archive_id===0;n(t(_t?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:qe=>n(qe.message,"error")}),Be=gt({mutationFn:({id:qe,filename:Nt})=>ge.updateLibraryFile(qe,{filename:Nt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),J(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:qe=>{J(null),n(qe.message,"error")}}),Me=gt({mutationFn:({id:qe,name:Nt})=>ge.updateLibraryFolder(qe,{name:Nt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),J(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:qe=>{J(null),n(qe.message,"error")}}),Xe=gt({mutationFn:()=>ge.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:qe=>{if(e.invalidateQueries({queryKey:["library-files"]}),qe.succeeded>0){const Nt=Date.now(),_t={};qe.results.forEach(rt=>{rt.success&&(_t[rt.file_id]=Nt)}),Y(rt=>({...rt,..._t}))}qe.succeeded>0&&qe.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:qe.succeeded}),"success"):qe.succeeded>0&&qe.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:qe.succeeded,failed:qe.failed}),"success"):qe.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:qe.results[0]?.error||"Unknown error"}),"error")},onError:qe=>n(qe.message,"error")}),ye=gt({mutationFn:qe=>ge.batchGenerateStlThumbnails({file_ids:[qe]}),onSuccess:qe=>{if(e.invalidateQueries({queryKey:["library-files"]}),qe.succeeded>0){const Nt=qe.results[0]?.file_id;Nt&&Y(_t=>({..._t,[Nt]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:qe.results[0]?.error||"Unknown error"}),"error")},onError:qe=>n(qe.message,"error")}),We=w.useCallback(qe=>{const Nt=qe.toLowerCase();return Nt.endsWith(".gcode")||Nt.includes(".gcode.")},[]),Pe=w.useMemo(()=>L?L.filter(qe=>p.includes(qe.id)&&We(qe.filename)):[],[L,p,We]),Ke=w.useCallback(qe=>{f(Nt=>Nt.includes(qe)?Nt.filter(_t=>_t!==qe):[...Nt,qe])},[]),Ve=w.useCallback(()=>{me.length>0&&f(me.map(qe=>qe.id))},[me]),ke=w.useCallback(()=>{f([])},[]),Ce=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},$e=qe=>{ge.downloadLibraryFile(qe).catch(Nt=>{console.error("Library file download failed:",Nt)})},nt=()=>{P&&(P.type==="file"?He.mutate(P.id):P.type==="folder"?Fe.mutate(P.id):P.type==="bulk"&&Oe.mutate(p))},xt=Fe.isPending||He.isPending||Oe.isPending,vt=qe=>{V(qe),localStorage.setItem("library-view-mode",qe)},mt=oe||F;return i.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(Ac,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[i.jsx("button",{onClick:()=>vt("grid"),className:`p-1.5 rounded transition-colors ${he==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:i.jsx(ww,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>vt("list"),className:`p-1.5 rounded transition-colors ${he==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:i.jsx(sT,{className:"w-4 h-4"})})]}),i.jsxs(ze,{variant:"secondary",onClick:()=>Xe.mutate(),disabled:Xe.isPending||!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[Xe.isPending?i.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}):i.jsx(Ud,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),i.jsxs(ze,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[i.jsx(Jpe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),i.jsxs(ze,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(yi,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),je&&te&&be&&i.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[i.jsx(jn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),i.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:xo(te.disk_free_bytes),total:xo(te.disk_total_bytes),threshold:be.library_disk_warning_gb})})]})]}),te&&i.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:[i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(iT,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),i.jsx("span",{className:"text-white font-medium",children:te.total_files})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Ac,{className:"w-4 h-4 text-blue-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),i.jsx("span",{className:"text-white font-medium",children:te.total_folders})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Vx,{className:"w-4 h-4 text-amber-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),i.jsx("span",{className:"text-white font-medium",children:xo(te.total_size_bytes)})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),i.jsx("span",{className:`font-medium ${je?"text-amber-500":"text-white"}`,children:xo(te.disk_free_bytes)})]})]}),i.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[i.jsx("div",{className:"lg:hidden",children:i.jsxs("select",{value:d??"",onChange:qe=>m(qe.target.value?parseInt(qe.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:[i.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),xe&&(()=>{const qe=(Nt,_t=0)=>{const rt=[];for(const Rt of Nt)rt.push({id:Rt.id,name:Rt.name,fileCount:Rt.file_count,depth:_t}),Rt.children.length>0&&rt.push(...qe(Rt.children,_t+1));return rt};return qe(xe).map(Nt=>i.jsxs("option",{value:Nt.id,children:["│ ".repeat(Nt.depth),"📂 ",Nt.name," ",Nt.fileCount>0?`(${Nt.fileCount})`:""]},Nt.id))})()]})}),i.jsxs("div",{ref:j,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:`${pe}px`},children:[i.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 ${q?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:qe=>{qe.preventDefault(),X(!0)},onDoubleClick:()=>{Te(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:i.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${q?"opacity-100":""}`,children:[i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),i.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),i.jsx("button",{onClick:()=>{const qe=!ne;se(qe),localStorage.setItem("library-wrap-folders",String(qe))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${ne?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(ne?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[i.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:()=>m(null),children:[i.jsx(mf,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),xe?.map(qe=>i.jsx(Koe,{folder:qe,selectedFolderId:d,onSelect:m,onDelete:Nt=>T({type:"folder",id:Nt}),onLink:k,onRename:Nt=>J({type:"folder",id:Nt.id,name:Nt.name}),wrapNames:ne,hasPermission:r,t},qe.id))]})]}),i.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[L&&L.length>0&&i.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:[i.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:E,onChange:qe=>U(qe.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"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(aT,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),i.jsxs("select",{value:K,onChange:qe=>H(qe.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:[i.jsx("option",{value:"all",children:t("fileManager.allTypes")}),fe.map(qe=>i.jsx("option",{value:qe,children:qe.toUpperCase()},qe))]})]}),o&&i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:re,onChange:qe=>O(qe.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 ${re?"pr-7":""}`,style:re?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),re&&i.jsx("button",{onClick:()=>O(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:i.jsx(Ht,{className:"w-3 h-3"})}),i.jsx("datalist",{id:"usernames-list",children:ve?.map(qe=>i.jsx("option",{value:qe.username},qe.id))})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("select",{value:$,onChange:qe=>{const Nt=qe.target.value;ee(Nt),localStorage.setItem("library-sort-field",Nt)},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:[i.jsx("option",{value:"name",children:t("common.name")}),i.jsx("option",{value:"date",children:t("common.date")}),i.jsx("option",{value:"size",children:t("fileManager.size")}),i.jsx("option",{value:"type",children:t("common.type")}),i.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),i.jsx("button",{onClick:()=>ie(qe=>{const Nt=qe==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",Nt),Nt}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(W==="asc"?"fileManager.ascending":"fileManager.descending"),children:W==="asc"?i.jsx(yhe,{className:"w-4 h-4 text-white"}):i.jsx(mhe,{className:"w-4 h-4 text-white"})})]}),(E||K!=="all"||re)&&i.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:me.length,total:L.length})})]}),me.length>0&&i.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===me.length&&p.length>0?i.jsxs(ze,{variant:"secondary",size:"sm",onClick:ke,children:[i.jsx(rl,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):i.jsxs(ze,{variant:"secondary",size:"sm",onClick:Ve,children:[i.jsx(Ks,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),p.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:p.length})}),i.jsx("div",{className:"hidden sm:block flex-1"}),i.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Pe.length===1&&i.jsxs(ze,{variant:"primary",size:"sm",onClick:()=>G(Pe[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[i.jsx(Co,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Pe.length===1&&i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>Z(Pe[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[i.jsx(Zn,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>g(!0),disabled:!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[i.jsx(cge,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),i.jsxs(ze,{variant:"danger",size:"sm",onClick:()=>{p.length===1?T({type:"file",id:p[0]}):T({type:"bulk",id:0,count:p.length})},disabled:!a("library:delete_own","library:delete_all"),title:a("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[i.jsx(nn,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),i.jsxs(ze,{variant:"secondary",size:"sm",onClick:ke,children:[i.jsx(Ht,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),mt?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):L?.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(mf,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(d!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(d!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),i.jsxs(ze,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(ir,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):me.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(Rr,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),i.jsx(ze,{variant:"secondary",onClick:()=>{U(""),H("all")},children:t("fileManager.clearFilters")})]}):he==="grid"?i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.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:me.map(qe=>i.jsx(xtt,{file:qe,isSelected:p.includes(qe.id),isMobile:ce,t,onSelect:Ke,onDelete:Nt=>T({type:"file",id:Nt}),onDownload:$e,onAddToQueue:Nt=>{const _t=L?.find(rt=>rt.id===Nt);_t&&Z(_t)},onPrint:A,onPreview3d:de,onRename:Nt=>J({type:"file",id:Nt.id,name:Nt.filename}),onGenerateThumbnail:Nt=>ye.mutate(Nt.id),thumbnailVersion:ae[qe.id],hasPermission:r,canModify:s,authEnabled:o},qe.id))})}):i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.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:[i.jsx("div",{className:"w-6"}),i.jsx("div",{children:t("common.name")}),o&&i.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),i.jsx("div",{children:t("common.type")}),i.jsx("div",{children:t("fileManager.size")}),i.jsx("div",{children:t("fileManager.prints")}),i.jsx("div",{})]}),me.map(qe=>i.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(qe.id)?"bg-bambu-green/10":""}`,onClick:()=>Ke(qe.id),children:[i.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${p.includes(qe.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:p.includes(qe.id)&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsxs("div",{className:"relative group/thumb",children:[i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:qe.thumbnail_path?i.jsx("img",{src:`${ge.getLibraryFileThumbnailUrl(qe.id)}${ae[qe.id]?`?v=${ae[qe.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(mf,{className:"w-5 h-5 text-bambu-gray/50"})})}),qe.thumbnail_path&&i.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:i.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:i.jsx("img",{src:`${ge.getLibraryFileThumbnailUrl(qe.id)}${ae[qe.id]?`?v=${ae[qe.id]}`:""}`,alt:qe.filename,className:"w-full h-full object-contain"})})})]}),i.jsx("div",{className:"min-w-0",children:i.jsx("div",{className:"text-sm text-white truncate",children:qe.print_name||qe.filename})})]}),o&&i.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:qe.created_by_username?i.jsxs(i.Fragment,{children:[i.jsx($d,{className:"w-3 h-3"}),i.jsx("span",{className:"truncate",children:qe.created_by_username})]}):"-"}),i.jsx("div",{children:i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${qe.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":qe.file_type==="gcode"?"bg-blue-500/20 text-blue-400":qe.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:qe.file_type.toUpperCase()})}),i.jsx("div",{className:"text-sm text-bambu-gray",children:xo(qe.file_size)}),i.jsx("div",{className:"text-sm text-bambu-gray",children:qe.print_count>0?`${qe.print_count}x`:"-"}),i.jsxs("div",{className:"flex items-center gap-1",onClick:Nt=>Nt.stopPropagation(),children:[kL(qe.filename)&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>r("printers:control")&&A(qe),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:i.jsx(_r,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{r("queue:create")&&Z(qe)},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:i.jsx(Zn,{className:"w-4 h-4"})})]}),(qe.file_type==="3mf"||qe.file_type==="gcode"||qe.file_type==="stl")&&i.jsx("button",{onClick:()=>r("library:read")&&de(qe),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:i.jsx(ia,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>r("library:read")&&$e(qe.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:i.jsx(fi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","update",qe.created_by_id)&&J({type:"file",id:qe.id,name:qe.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",qe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",qe.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",qe.created_by_id),children:i.jsx(Yi,{className:"w-4 h-4"})}),qe.file_type==="stl"&&i.jsx("button",{onClick:()=>s("library","update",qe.created_by_id)&&ye.mutate(qe.id),className:`p-1.5 rounded transition-colors ${s("library","update",qe.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",qe.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:ye.isPending||!s("library","update",qe.created_by_id),children:i.jsx(Ud,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","delete",qe.created_by_id)&&T({type:"file",id:qe.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",qe.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",qe.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",qe.created_by_id),children:i.jsx(nn,{className:"w-4 h-4"})})]})]},qe.id))]})})]})]}),y&&i.jsx(ptt,{parentId:d,onClose:()=>v(!1),onSave:qe=>we.mutate(qe),isLoading:we.isPending,t}),b&&xe&&i.jsx(gtt,{folders:xe,selectedFiles:p,currentFolderId:d,onClose:()=>g(!1),onMove:qe=>_e.mutate({fileIds:p,folderId:qe}),isLoading:_e.isPending,t}),_&&i.jsx(nie,{folderId:d,onClose:()=>N(!1),onUploadComplete:Ce}),C&&i.jsx(btt,{folder:C,onClose:()=>k(null),onLink:qe=>Ae.mutate({id:C.id,data:qe}),isLoading:Ae.isPending,t}),P&&i.jsx(Nn,{title:P.type==="folder"?t("fileManager.deleteFolder"):P.type==="bulk"?t("fileManager.deleteFilesCount",{count:P.count}):t("fileManager.deleteFile"),message:P.type==="folder"?t("fileManager.deleteFolderConfirm"):P.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:P.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:xt,loadingText:t("fileManager.deleting"),onConfirm:nt,onCancel:()=>T(null)}),D&&i.jsx(xu,{mode:"reprint",libraryFileId:D.id,archiveName:D.print_name||D.filename,onClose:()=>A(null),onSuccess:()=>{A(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),R&&i.jsx(xu,{mode:"reprint",libraryFileId:R.id,archiveName:R.print_name||R.filename,onClose:()=>G(null),onSuccess:()=>{G(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),z&&i.jsx(xu,{mode:"add-to-queue",libraryFileId:z.id,archiveName:z.print_name||z.filename,onClose:()=>Z(null),onSuccess:()=>{Z(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),ue&&i.jsx(LI,{libraryFileId:ue.id,title:ue.print_name||ue.filename,fileType:ue.file_type,onClose:()=>de(null)}),I&&i.jsx(ftt,{type:I.type,currentName:I.name,onClose:()=>J(null),onSave:qe=>{I.type==="file"?Be.mutate({id:I.id,filename:qe}):Me.mutate({id:I.id,name:qe})},isLoading:Be.isPending||Me.isPending,t})]})}const ZD=5,vtt=2e3,wtt=3e4,Stt=5e3;function _tt(){const{t}=Dt(),e=sn(),{showToast:n}=bn(),{hasPermission:r}=Ar(),{printerId:a}=gw(),s=parseInt(a||"0",10),[o,l]=w.useState("stream"),[c,u]=w.useState(!1),[d,m]=w.useState(!1),[p,f]=w.useState(!0),[y,v]=w.useState(Date.now()),[b,g]=w.useState(!1),[_,N]=w.useState(!1),[C,k]=w.useState(0),[P,T]=w.useState(!1),[D,A]=w.useState(0),[R,G]=w.useState(1),[z,Z]=w.useState({x:0,y:0}),[I,J]=w.useState(!1),[ae,Y]=w.useState({x:0,y:0}),[ue,de]=w.useState(null),[he,V]=w.useState(null),ne=w.useRef(null),se=w.useRef(null),pe=w.useRef(null),Te=w.useRef(null),q=w.useRef(null),{data:X}=et({queryKey:["printer",s],queryFn:()=>ge.getPrinter(s),enabled:s>0}),{data:j}=et({queryKey:["printerStatus",s],queryFn:()=>ge.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),E=gt({mutationFn:_e=>ge.setChamberLight(s,_e),onMutate:async _e=>{await e.cancelQueries({queryKey:["printerStatus",s]});const Ae=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],Be=>({...Be,chamber_light:_e})),{previousStatus:Ae}},onSuccess:(_e,Ae)=>{n(`Chamber light ${Ae?"on":"off"}`)},onError:(_e,Ae,Be)=>{Be?.previousStatus&&e.setQueryData(["printerStatus",s],Be.previousStatus),n(_e.message||t("printers.toast.failedToControlChamberLight"),"error")}}),U=(j?.state==="RUNNING"||j?.state==="PAUSE")&&(j?.printable_objects_count??0)>=2;w.useEffect(()=>(X&&(document.title=`${X.name} - Camera`),()=>{document.title="Bambuddy"}),[X]);const K=w.useRef(!1);w.useEffect(()=>{const _e=`/api/v1/printers/${s}/camera/stop`;K.current=!1;const Ae=()=>{if(s>0&&!K.current){K.current=!0;const Xe={},ye=qd();ye&&(Xe.Authorization=`Bearer ${ye}`),fetch(_e,{method:"POST",keepalive:!0,headers:Xe}).catch(()=>{})}},Be=()=>{Ae()};window.addEventListener("beforeunload",Be);const Me=ne.current;return()=>{window.removeEventListener("beforeunload",Be),Me&&(Me.src=""),Ae()}},[s]),w.useEffect(()=>{if(p&&!b){const Ae=setTimeout(()=>{f(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(Ae)}},[o,p,y,b]),w.useEffect(()=>{const _e=()=>{const Ae=!!document.fullscreenElement;N(Ae),G(1),Z({x:0,y:0}),o==="stream"&&!b&&(ne.current&&(ne.current.src=""),setTimeout(()=>{f(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",_e),()=>document.removeEventListener("fullscreenchange",_e)},[o,b]),w.useEffect(()=>{let _e;const Ae=()=>{clearTimeout(_e),_e=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Ae),()=>{clearTimeout(_e),window.removeEventListener("resize",Ae)}},[]),w.useEffect(()=>()=>{pe.current&&clearTimeout(pe.current),Te.current&&clearInterval(Te.current),q.current&&clearInterval(q.current)},[]);const H=w.useCallback(()=>{if(C>=ZD){T(!1),m(!0);return}const _e=Math.min(vtt*Math.pow(2,C),wtt);T(!0),A(Math.ceil(_e/1e3)),Te.current=setInterval(()=>{A(Ae=>Ae<=1?(Te.current&&clearInterval(Te.current),0):Ae-1)},1e3),pe.current=setTimeout(()=>{k(Ae=>Ae+1),T(!1),f(!0),m(!1),ne.current&&(ne.current.src=""),v(Date.now())},_e)},[C]);w.useEffect(()=>{if(o!=="stream"||p||P||b){q.current&&(clearInterval(q.current),q.current=null);return}return q.current=setInterval(async()=>{try{const _e=await ge.getCameraStatus(s);(_e.stalled||!_e.active&&!d)&&(console.log(`Stream issue detected: stalled=${_e.stalled}, active=${_e.active}, reconnecting...`),q.current&&(clearInterval(q.current),q.current=null),f(!1),H())}catch{}},Stt),()=>{q.current&&(clearInterval(q.current),q.current=null)}},[o,p,d,P,b,s,H]);const re=()=>{f(!1),o==="stream"&&C{if(f(!1),m(!1),k(0),T(!1),pe.current&&clearTimeout(pe.current),Te.current&&clearInterval(Te.current),ne.current&&!localStorage.getItem("cameraWindowState")){const _e=ne.current,Ae=_e.naturalWidth,Be=_e.naturalHeight;if(Ae>0&&Be>0){const ye=window.outerWidth-window.innerWidth,We=window.outerHeight-window.innerHeight,Pe=Ae+16+ye,Ke=Be+45+16+We;try{window.resizeTo(Pe,Ke)}catch{}}}},$=()=>{if(s>0){const _e={},Ae=qd();Ae&&(_e.Authorization=`Bearer ${Ae}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:_e}).catch(()=>{})}},ee=_e=>{o===_e||b||(g(!0),f(!0),m(!1),k(0),T(!1),G(1),Z({x:0,y:0}),pe.current&&clearTimeout(pe.current),Te.current&&clearInterval(Te.current),ne.current&&(ne.current.src=""),o==="stream"&&$(),setTimeout(()=>{l(_e),v(Date.now()),g(!1)},100))},W=()=>{b||(g(!0),f(!0),m(!1),k(0),T(!1),pe.current&&clearTimeout(pe.current),Te.current&&clearInterval(Te.current),ne.current&&(ne.current.src=""),o==="stream"&&$(),setTimeout(()=>{v(Date.now()),g(!1)},100))},ie=()=>{se.current&&(document.fullscreenElement?document.exitFullscreen():se.current.requestFullscreen())},ce=()=>{G(_e=>Math.min(_e+.5,4))},be=()=>{G(_e=>{const Ae=Math.max(_e-.5,1);return Ae===1&&Z({x:0,y:0}),Ae})},xe=_e=>{_e.preventDefault(),_e.deltaY<0?ce():be()},oe=_e=>{R>1&&(_e.preventDefault(),J(!0),Y({x:_e.clientX-z.x,y:_e.clientY-z.y}))},L=w.useCallback(()=>{if(!se.current)return{x:300,y:200};const _e=se.current.getBoundingClientRect(),Ae=_e.width*(R-1)/2,Be=_e.height*(R-1)/2;return{x:Math.max(50,Ae),y:Math.max(50,Be)}},[R]),F=_e=>{if(I&&R>1){const Ae=_e.clientX-ae.x,Be=_e.clientY-ae.y,Me=L();Z({x:Math.max(-Me.x,Math.min(Me.x,Ae)),y:Math.max(-Me.y,Math.min(Me.y,Be))})}},te=()=>{J(!1)},ve=_e=>{if(_e.length<2)return 0;const Ae=_e[0].clientX-_e[1].clientX,Be=_e[0].clientY-_e[1].clientY;return Math.sqrt(Ae*Ae+Be*Be)},fe=_e=>_e.length<2?{x:_e[0].clientX,y:_e[0].clientY}:{x:(_e[0].clientX+_e[1].clientX)/2,y:(_e[0].clientY+_e[1].clientY)/2},me=_e=>{_e.touches.length===2?(_e.preventDefault(),de(ve(_e.touches)),V(fe(_e.touches))):_e.touches.length===1&&R>1&&(_e.preventDefault(),J(!0),Y({x:_e.touches[0].clientX-z.x,y:_e.touches[0].clientY-z.y}))},je=_e=>{if(_e.touches.length===2&&ue!==null){_e.preventDefault();const Ae=ve(_e.touches),Be=Ae/ue;G(Xe=>{const ye=Math.max(1,Math.min(4,Xe*Be));return ye===1&&Z({x:0,y:0}),ye}),de(Ae);const Me=fe(_e.touches);if(he){const Xe=L();Z(ye=>({x:Math.max(-Xe.x,Math.min(Xe.x,ye.x+(Me.x-he.x))),y:Math.max(-Xe.y,Math.min(Xe.y,ye.y+(Me.y-he.y)))}))}V(Me)}else if(_e.touches.length===1&&I&&R>1){_e.preventDefault();const Ae=_e.touches[0].clientX-ae.x,Be=_e.touches[0].clientY-ae.y,Me=L();Z({x:Math.max(-Me.x,Math.min(Me.x,Ae)),y:Math.max(-Me.y,Math.min(Me.y,Be))})}},we=_e=>{_e.touches.length<2&&(de(null),V(null)),_e.touches.length===0&&J(!1)},Fe=()=>{G(1),Z({x:0,y:0})},He=b?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${y}`:`/api/v1/printers/${s}/camera/snapshot?t=${y}`,Oe=p||b||P;return s?i.jsxs("div",{ref:se,className:"min-h-screen bg-black flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[i.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(dx,{className:"w-4 h-4"}),X?.name||`Printer ${s}`]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[i.jsx("button",{onClick:()=>ee("stream"),disabled:Oe,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")}),i.jsx("button",{onClick:()=>ee("snapshot"),disabled:Oe,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")})]}),i.jsx("button",{onClick:()=>E.mutate(!j?.chamber_light),disabled:!j?.connected||E.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${j?.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:i.jsx(PO,{on:j?.chamber_light??!1,className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>u(!0),disabled:!U||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${U&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(U?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:i.jsx(NT,{className:"w-4 h-4 text-bambu-gray"})}),i.jsx("button",{onClick:W,disabled:Oe,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:i.jsx(Sr,{className:`w-4 h-4 text-bambu-gray ${Oe?"animate-spin":""}`})}),i.jsx("button",{onClick:ie,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?i.jsx(JX,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(Qfe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),i.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:xe,onMouseMove:F,onMouseUp:te,onMouseLeave:te,onTouchStart:me,onTouchMove:je,onTouchEnd:we,style:{touchAction:"none"},children:i.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(p||b)&&!P&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(Sr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),P&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(zh,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:D,attempt:C+1,max:ZD})}),i.jsx("button",{onClick:W,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&&!P&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(jn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),i.jsx("button",{onClick:W,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),i.jsx("img",{ref:ne,src:He,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${R}) translate(${z.x/R}px, ${z.y/R}px) rotate(${X?.camera_rotation||0}deg)`,...X?.camera_rotation===90||X?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:R>1?I?"grabbing":"grab":"default"},onError:He?re:void 0,onLoad:He?O:void 0,onMouseDown:oe,draggable:!1},y),i.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:[i.jsx("button",{onClick:be,disabled:R<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:i.jsx(JL,{className:"w-4 h-4 text-white"})}),i.jsxs("button",{onClick:Fe,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(R*100),"%"]}),i.jsx("button",{onClick:ce,disabled:R>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:i.jsx(ZL,{className:"w-4 h-4 text-white"})})]})]})}),i.jsx(MO,{printerId:s,isOpen:c,onClose:()=>u(!1)})]}):i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function Ntt(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),a=t.get("camera"),s=a!=="false"&&a!=="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 ktt(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 Ctt(t){switch(t){case"small":return{container:"p-3",text:"text-sm",textLarge:"text-lg",progressHeight:"h-2",icon:"w-3 h-3",gap:"gap-2",logoHeight:"h-12"};case"large":return{container:"p-6",text:"text-xl",textLarge:"text-3xl",progressHeight:"h-4",icon:"w-6 h-6",gap:"gap-4",logoHeight:"h-24"};default:return{container:"p-4",text:"text-base",textLarge:"text-xl",progressHeight:"h-3",icon:"w-4 h-4",gap:"gap-3",logoHeight:"h-16"}}}function Ttt(){const{printerId:t}=gw(),[e]=LL(),{t:n}=Dt(),r=sn(),a=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>Ntt(e),[e]),c=Ctt(l.size),{data:u}=et({queryKey:["printer",a],queryFn:()=>ge.getPrinter(a),enabled:a>0}),{data:d}=et({queryKey:["printerStatus",a],queryFn:()=>ge.getPrinterStatus(a),enabled:a>0,refetchInterval:2e3}),{data:m}=et({queryKey:["settings"],queryFn:ge.getSettings}),p=m?.time_format||"system";w.useEffect(()=>{if(!a)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,N=new WebSocket(_);return N.onmessage=C=>{try{const k=JSON.parse(C.data);k.type==="printer_status"&&k.printer_id===a&&r.setQueryData(["printerStatus",a],k.status)}catch{}},N.onerror=()=>{},()=>{N.close()}},[a,r]),w.useEffect(()=>(document.title=u?`${u.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[u,n]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!a)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!d)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const y=d.state==="RUNNING"||d.state==="PAUSE",v=d.progress||0,b=`/api/v1/printers/${a}/camera/stream?fps=${l.fps}&t=${s}`;return i.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&i.jsx("img",{src:b,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",style:u?.camera_rotation?{transform:`rotate(${u.camera_rotation}deg)`}:void 0,onError:f},s),i.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:i.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),i.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:i.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&u&&i.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[i.jsx(_r,{className:`${c.icon} text-white/70`}),i.jsx("span",{className:`${c.text} text-white font-medium`,children:u.name})]}),l.showFilename&&d.current_print&&i.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&&i.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:ktt(d,n)}),l.showProgress&&y&&i.jsxs("div",{className:"mb-3",children:[i.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[i.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),i.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),i.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:i.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),y&&(l.showLayers||l.showEta)&&i.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&&i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Gi,{className:c.icon}),i.jsxs("span",{className:c.text,children:[i.jsx("span",{className:"text-white",children:d.layer_num}),i.jsx("span",{className:"mx-1",children:"/"}),i.jsx("span",{children:d.total_layers})]})]}),l.showEta&&d.remaining_time!=null&&d.remaining_time>0&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Sd,{className:c.icon}),i.jsx("span",{className:`${c.text} text-white`,children:Us(d.remaining_time*60)})]}),i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Zn,{className:c.icon}),i.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",eO(d.remaining_time,p,n)]})]})]})]}),!y&&i.jsx("div",{className:`${c.text} text-white/70 py-2`,children:d.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function Att(){const{t}=Dt(),{id:e}=gw(),{mode:n}=ng(),{data:r,isLoading:a,error:s}=et({queryKey:["external-link",e],queryFn:()=>ge.getExternalLink(Number(e)),enabled:!!e});return a?i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[i.jsx(jn,{className:"w-12 h-12"}),i.jsx("p",{children:t("common.linkNotFound")})]}):i.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"})}function LY(){const{id:t}=gw(),e=ol(),n=sn(),{t:r}=Dt(),{showToast:a}=bn(),s=!!t,[o,l]=w.useState(""),[c,u]=w.useState(""),[d,m]=w.useState([]),[p,f]=w.useState(""),[y,v]=w.useState(!1),{data:b,isLoading:g}=et({queryKey:["group",t],queryFn:()=>ge.getGroup(Number(t)),enabled:s}),{data:_,isLoading:N}=et({queryKey:["permissions"],queryFn:()=>ge.getPermissions()});s&&b&&!y&&(l(b.name),u(b.description||""),m(b.permissions),v(!0));const C=gt({mutationFn:Y=>ge.createGroup(Y),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.created")),e("/settings?tab=users")},onError:Y=>{a(Y.message,"error")}}),k=gt({mutationFn:Y=>ge.updateGroup(Number(t),Y),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.updated")),e("/settings?tab=users")},onError:Y=>{a(Y.message,"error")}}),P=C.isPending||k.isPending,T=()=>{if(!o.trim()){a(r("groups.toast.enterGroupName"),"error");return}s?k.mutate({name:o!==b?.name?o:void 0,description:c,permissions:d}):C.mutate({name:o,description:c||void 0,permissions:d})},D=Y=>{m(ue=>ue.includes(Y)?ue.filter(de=>de!==Y):[...ue,Y])},A=(Y,ue)=>{const de=Y.permissions.map(he=>he.value);m(he=>{const V=he.filter(ne=>!de.includes(ne));return ue?[...V,...de]:V})},R=Y=>Y.permissions.every(ue=>d.includes(ue.value)),G=Y=>{const ue=Y.permissions.filter(de=>d.includes(de.value)).length;return ue>0&&ue{_&&m(_.all_permissions)},Z=()=>{m([])},I=p.toLowerCase(),J=w.useMemo(()=>_?I?_.categories.map(Y=>({...Y,permissions:Y.permissions.filter(ue=>ue.label.toLowerCase().includes(I))})).filter(Y=>Y.permissions.length>0):_.categories:[],[_,I]),ae=_?.all_permissions.length??0;return g||N?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:i.jsx($X,{className:"w-5 h-5"})}),i.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&i.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[i.jsx(jn,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),i.jsx("input",{type:"text",value:o,onChange:Y=>l(Y.target.value),disabled:s&&b?.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:r("groups.form.groupNamePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),i.jsx("input",{type:"text",value:c,onChange:Y=>u(Y.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:r("groups.form.descriptionPlaceholder")})]})]}),i.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:d.length})," / ",ae]}),i.jsx(ze,{size:"sm",variant:"ghost",onClick:z,children:r("groups.editor.selectAll")}),i.jsx(ze,{size:"sm",variant:"ghost",onClick:Z,children:r("groups.editor.clearAll")})]}),i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),i.jsx("input",{type:"text",value:p,onChange:Y=>f(Y.target.value),placeholder:r("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm 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 w-64"})]})]}),J.length===0?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:J.map(Y=>{const ue=_.categories.find(se=>se.name===Y.name),de=ue.permissions.filter(se=>d.includes(se.value)).length,he=ue.permissions.length,V=R(ue),ne=G(ue);return i.jsxs(Pt,{children:[i.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>A(ue,!V),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${V?"bg-bambu-green border-bambu-green":ne?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[V&&i.jsx(Zr,{className:"w-3 h-3 text-white"}),ne&&!V&&i.jsx(zN,{className:"w-3 h-3 text-white"})]}),i.jsx(C3,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-white font-medium text-sm",children:Y.name})]}),i.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[de,"/",he]})]}),i.jsx("div",{className:"p-3 space-y-1",children:Y.permissions.map(se=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d.includes(se.value),onChange:()=>D(se.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"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:se.label})]},se.value))})]},Y.name)})}),i.jsx("div",{className:"h-16"}),i.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[i.jsx(ze,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),i.jsx(ze,{onClick:T,disabled:P||!o.trim(),children:P?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(as,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const OY={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function Ptt(t,e=!1){const n={};return e?(t.material||(n.material="Material is required"),{isValid:Object.keys(n).length===0,errors:n}):(t.slicer_filament||(n.slicer_filament="Slicer preset is required"),t.material||(n.material="Material is required"),t.brand||(n.brand="Brand is required"),t.subtype||(n.subtype="Subtype is required"),{isValid:Object.keys(n).length===0,errors:n})}const Mtt=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Ett=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],b0=["Basic","Matte","Silk","Tough","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],Yoe=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"}],jtt=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],IY=[...Yoe,...jtt],Xoe="bambuddy-recent-colors",Dtt=8,Rtt=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function Ux(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let r="",a=-1;for(const c of n){const u=e.toUpperCase().indexOf(c.toUpperCase());if(u!==-1){r=c,a=u;break}}let s="";a>0&&(s=e.substring(0,a).trim(),s=s.replace(/[-_\s]+$/,""));let o="";a!==-1&&r&&(o=e.substring(a+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of b0)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of b0){const u=new RegExp(`\\s+${c}$`,"i");if(u.test(s)){l=c,s=s.replace(u,"").trim();break}}return{brand:s,material:r,variant:l}}function Ftt(t,e){const n=new Set(Ett);for(const r of t){const{brand:a}=Ux(r.name);a&&a.length>1&&n.add(a)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:a}=Ux(r.name);a&&a.length>1&&n.add(a)}return Array.from(n).sort((r,a)=>r.localeCompare(a))}function Ltt(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const a=r.name.replace(/@.*$/,"").trim(),s=n.get(a);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(a,{code:o,name:a,displayName:a,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,a)=>r.displayName.localeCompare(a.displayName))}function Ott(t,e,n){if(t.length>0){const r=[],a=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=a.get(o);l?l.allCodes.push(s.setting_id):a.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(a.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=Ltt(n);if(r.length>0)return r}return Rtt}function Itt(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(a=>a.code.toLowerCase()===r||a.allCodes.some(s=>s.toLowerCase()===r))}return n}function ztt(){try{const t=localStorage.getItem(Xoe);if(t)return JSON.parse(t)}catch{}return[]}function Utt(t,e){const n=e.filter(a=>a.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,Dtt);try{localStorage.setItem(Xoe,JSON.stringify(r))}catch{}return r}function JD(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),a=Ux(r);return!(!(a.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(a.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(a.brand.toLowerCase()))||e.subtype&&!(a.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(a.variant.toLowerCase())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function Btt({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:a,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:u,quickAdd:d,quantity:m,onQuantityChange:p,errors:f}){const{t:y}=Dt(),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[N,C]=w.useState(!1),[k,P]=w.useState(!1),[T,D]=w.useState(""),[A,R]=w.useState(""),[G,z]=w.useState(""),[Z,I]=w.useState(String(t.label_weight)),[J,ae]=w.useState(!1),Y=w.useRef(null),ue=w.useRef(null),de=w.useRef(null),he=w.useRef(null);w.useEffect(()=>{const q=X=>{Y.current&&!Y.current.contains(X.target)&&b(!1),he.current&&!he.current.contains(X.target)&&P(!1),ue.current&&!ue.current.contains(X.target)&&_(!1),de.current&&!de.current.contains(X.target)&&C(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[]);const V=w.useMemo(()=>{if(!a)return l;const q=a.toLowerCase();return l.filter(X=>X.displayName.toLowerCase().includes(q)||X.code.toLowerCase().includes(q))},[l,a]),ne=w.useMemo(()=>{if(!T)return c;const q=T.toLowerCase();return c.filter(j=>j.toLowerCase().includes(q)).sort((j,E)=>{const U=j.toLowerCase()===q,K=E.toLowerCase()===q;return U&&!K?-1:!U&&K?1:j.localeCompare(E)})},[c,T]),se=w.useMemo(()=>{if(!A)return b0;const q=A.toLowerCase();return b0.filter(X=>X.toLowerCase().includes(q))},[A]),pe=w.useMemo(()=>{if(!G)return u;const q=G.toLowerCase();return u.filter(j=>j.toLowerCase().includes(q)).sort((j,E)=>{const U=j.toLowerCase()===q,K=E.toLowerCase()===q;return U&&!K?-1:!U&&K?1:j.localeCompare(E)})},[G,u]);w.useEffect(()=>{J||I(String(t.label_weight))},[t.label_weight,J]);const Te=q=>{e("slicer_filament",q.code),s(q.displayName),b(!1);const X=Ux(q.name);X.material&&e("material",X.material),X.brand&&e("brand",X.brand),X.variant&&e("subtype",X.variant)};return i.jsxs("div",{className:"space-y-4",children:[!d&&i.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-3 h-3 animate-spin"})," ",y("inventory.loadingPresets")]}):n?i.jsxs(i.Fragment,{children:[i.jsx(qx,{className:"w-3 h-3 text-bambu-green"})," ",y("inventory.cloudConnected")]}):i.jsxs(i.Fragment,{children:[i.jsx(cpe,{className:"w-3 h-3"})," ",y("inventory.cloudNotConnected")]})}),!d&&i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.slicerPreset")," *"]}),i.jsxs("div",{className:"relative",ref:Y,children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.searchPresets"),value:a,onChange:q=>{s(q.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),v&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:V.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noPresetsFound")}):V.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===q.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Te(q),children:q.displayName},q.code))})]}),o&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[y("inventory.selectedPreset"),": ",i.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.material")," *"]}),i.jsxs("div",{className:"relative",ref:he,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.selectMaterial"),value:k?G:t.material,onChange:q=>{z(q.target.value),P(!0)},onFocus:()=>{P(!0),z("")}}),i.jsx(In,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),k&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[pe.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):pe.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",q),P(!1),z("")},children:q},q)),G&&!pe.includes(G)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",G),P(!1),z("")},children:y("inventory.useCustomMaterial",{material:G})})]})]}),f?.material&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.brand"),!d&&" *"]}),i.jsxs("div",{className:"relative",ref:ue,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.searchBrand"),value:g?T:t.brand,onChange:q=>{D(q.target.value),_(!0)},onFocus:()=>{_(!0),D("")}}),i.jsx(In,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),g&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ne.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):ne.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",q),_(!1),D("")},children:q},q)),T&&!ne.includes(T)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",T),_(!1),D("")},children:y("inventory.useCustomBrand",{brand:T})})]})]}),f?.brand&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.subtype"),!d&&" *"]}),i.jsxs("div",{className:"relative",ref:de,children:[i.jsx("input",{type:"text",value:N?A:t.subtype,onChange:q=>{R(q.target.value),C(!0)},onFocus:()=>{C(!0),R("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),i.jsx(In,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[se.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):se.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",q),C(!1),R("")},children:q},q)),A&&!b0.some(q=>q.toLowerCase()===A.toLowerCase().trim())&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",A),C(!1),R("")},children:y("inventory.useCustomBrand",{brand:A})})]})]}),f?.subtype&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.labelWeight")}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:Z,min:0,onFocus:()=>ae(!0),onChange:q=>I(q.target.value),onBlur:()=>{ae(!1);const q=Z.trim(),X=Number(q);if(!q||!Number.isFinite(X)||X<0){I(String(t.label_weight));return}const j=Math.round(X);e("label_weight",j),I(String(j))}}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),d&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.quantity")}),i.jsx("input",{type:"number",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:m,min:1,max:100,onChange:q=>{const X=Math.max(1,Math.min(100,parseInt(q.target.value)||1));p(X)}})]})]})}function Htt({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:a}){const{t:s}=Dt(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=t.rgba.replace("#","").substring(0,6),m=g=>d.toUpperCase()===g.toUpperCase(),p=(g,_)=>{e("rgba",g.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:g})},f=w.useMemo(()=>{if(a.length===0)return[];const g=t.brand?.trim(),_=t.material?.toLowerCase().trim(),N=t.subtype?.toLowerCase().trim();if(!g&&!_)return[];const C=g?g.toLowerCase().split(/[\s\-_]+/).filter(T=>T.length>=2):[],k=T=>{if(C.length===0)return!0;const D=T.toLowerCase();return C.some(A=>D.includes(A))};if(g&&!_){const T=a.filter(D=>k(D.manufacturer));if(T.length>0)return T.map(D=>({name:D.color_name,hex:D.hex_color.replace("#","").substring(0,6),manufacturer:D.manufacturer,material:typeof D.material=="string"?D.material:void 0}))}const P=_&&N?`${_} ${N}`:"";if(P){const T=a.filter(A=>k(A.manufacturer)&&A.material?.toLowerCase()===P);if(T.length>0)return T.map(A=>({name:A.color_name,hex:A.hex_color.replace("#","").substring(0,6),manufacturer:A.manufacturer,material:typeof A.material=="string"?A.material:void 0}));const D=P.replace(/\+$/,"");if(D!==P){const A=a.filter(R=>k(R.manufacturer)&&R.material?.toLowerCase()===D);if(A.length>0)return A.map(R=>({name:R.color_name,hex:R.hex_color.replace("#","").substring(0,6),manufacturer:R.manufacturer,material:typeof R.material=="string"?R.material:void 0}))}}if(_){const T=a.filter(D=>k(D.manufacturer)&&(!D.material||D.material.toLowerCase().startsWith(_)));if(T.length>0)return T.map(D=>({name:D.color_name,hex:D.hex_color.replace("#","").substring(0,6),manufacturer:D.manufacturer,material:typeof D.material=="string"?D.material:void 0}))}return[]},[a,t.brand,t.material,t.subtype]),y=w.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const g=c.toLowerCase();return f.filter(N=>N.name.toLowerCase().includes(g)||(N.manufacturer?.toLowerCase().includes(g)??!1)||(N.material?.toLowerCase().includes(g)??!1))},[c,f]),v=f.length>0,b=w.useMemo(()=>c?IY.filter(g=>g.name.toLowerCase().includes(c.toLowerCase())):o?IY:Yoe,[c,o]);return i.jsxs("div",{className:"space-y-3",children:[i.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${d}`}}),n.length>0&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[i.jsx(Zn,{className:"w-3 h-3"}),i.jsx("span",{children:s("inventory.recentColors")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(g=>i.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name},g.hex))})]}),i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:g=>u(g.target.value)})]}),v?i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.map(g=>i.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name})},`${g.hex}-${g.name}-${g.manufacturer??""}`)),y.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[i.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&i.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?i.jsxs(i.Fragment,{children:[s("inventory.showLess")," ",i.jsx(Vl,{className:"w-3 h-3"})]}):i.jsxs(i.Fragment,{children:[s("inventory.showAll")," ",i.jsx(In,{className:"w-3 h-3"})]})})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(g=>i.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:g.name})},g.hex)),b.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:g=>e("color_name",g.target.value)})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),i.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:d.toUpperCase(),onChange:g=>{const _=g.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),i.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${d}`,onChange:g=>{const _=g.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function $tt({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:a}){const{t:s}=Dt(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{const v=b=>{d.current&&!d.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(b=>b.weight===e);if(r){const b=t.find(g=>g.id===r);if(b&&b.weight===e)return}v.length===1?a(v[0].id):v.length===0&&r!==null&&a(null)},[e,t,r,a]);const p=w.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(v)||b.weight.toString().includes(v))},[t,c]),f=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),y=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(b=>b.id===r);if(v)return v.name}return f.length>0?f[0].name:""},[o,c,r,t,f]);return i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(Dge,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsxs("div",{className:"flex-1 min-w-0 relative",ref:d,children:[i.jsx("input",{ref:m,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:y,onFocus:()=>{l(!0),u("")},onChange:v=>{u(v.target.value),l(!0)}}),o&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:p.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>i.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{a(v.id),n(v.weight),l(!1),u("")},children:[i.jsx("span",{className:"truncate",children:v.name}),i.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),i.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[i.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:v=>{const b=parseInt(v.target.value);!isNaN(b)&&b>=0&&n(b)}}),i.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function qtt({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:a}=Dt(),{showToast:s}=bn(),[o,l]=w.useState(""),[c,u]=w.useState(!1),[d,m]=w.useState(""),[p,f]=w.useState(!1),y=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+y;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{p||m(String(y))},[p,y]),i.jsxs("div",{className:"space-y-4",children:[i.jsx($tt,{catalog:n,value:t.core_weight,onChange:b=>e("core_weight",b),catalogId:t.core_weight_catalog_id,onCatalogIdChange:b=>e("core_weight_catalog_id",b)}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.currentWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:d,min:0,max:t.label_weight,onFocus:()=>f(!0),onChange:b=>{m(b.target.value)},onBlur:()=>{f(!1);const b=d.trim(),g=Number(b);if(!b||!Number.isFinite(g)||g<0||g>t.label_weight){m(String(y));return}const _=Math.round(g);e("weight_used",Math.max(0,t.label_weight-_)),m(String(_))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.measuredWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:o,min:0,onFocus:()=>u(!0),onChange:b=>{l(b.target.value)},onBlur:()=>{u(!1);const b=o.trim(),g=Number(b),_=t.core_weight,N=t.core_weight+t.label_weight;if(!b||!Number.isFinite(g)||g<_||g>N){s(a("inventory.measuredWeightError",{min:_,max:N}),"error"),l(String(v));return}const C=Math.round(g),k=Math.max(0,Math.min(t.label_weight,C-t.core_weight));e("weight_used",Math.max(0,t.label_weight-k)),l(String(C))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.costPerKg","Cost per kg")}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),i.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:b=>{const g=b.target.value===""?null:parseFloat(b.target.value);e("cost_per_kg",g)},style:{paddingLeft:`${Math.max(2,r.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.note")}),i.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:a("inventory.notePlaceholder"),value:t.note,onChange:b=>e("note",b.target.value)})]})]})}function Vtt({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:a,setExpandedPrinters:s}){const{t:o}=Dt(),l=p=>{s(f=>{const y=new Set(f);return y.has(p)?y.delete(p):y.add(p),y})},c=(p,f,y)=>{const v=`${p}:${f}:${y??"null"}`,b=`${p}:${y??"null"}`;r(g=>{const _=new Set(g);if(_.has(v))_.delete(v);else{for(const N of Array.from(_)){const C=N.split(":");`${C[0]}:${C[2]}`===b&&_.delete(N)}_.add(v)}return _})},u=()=>{const p=new Set;for(const{printer:f,calibrations:y}of e){if(!f.connected)continue;const v=y.filter(g=>JD(g,t)),b=new Map;for(const g of v){const _=`${g.extruder_id??"null"}`;b.has(_)||b.set(_,[]),b.get(_).push(g)}for(const[g,_]of b)if(_.length>0){const C=[..._].sort((k,P)=>P.k_value-k.k_value)[0];p.add(`${f.id}:${C.cali_idx}:${g}`)}}r(p)};if(!t.material)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const d=e.reduce((p,{printer:f,calibrations:y})=>f.connected?p+y.filter(v=>JD(v,t)).length:p,0),m=(p,f)=>{const y=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=n.has(y);return i.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[i.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),i.jsx("div",{className:"flex items-center gap-2 shrink-0",children:i.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),d>0&&i.jsxs("button",{type:"button",onClick:u,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[i.jsx(hx,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",d,")"]})]}),i.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const y=a.has(String(p.id)),v=f.filter(C=>JD(C,t)),b=v.length,g=v.some(C=>C.extruder_id!==void 0&&C.extruder_id!==null&&C.extruder_id>0),_=v.filter(C=>C.extruder_id===1),N=v.filter(C=>C.extruder_id===0||C.extruder_id===void 0||C.extruder_id===null);return i.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{type:"button",onClick:()=>l(String(p.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[y?i.jsx(In,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(fa,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?i.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[b," ",o(b!==1?"inventory.matches":"inventory.match")]}):i.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),i.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),y&&i.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):g?i.jsxs(i.Fragment,{children:[_.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),i.jsx("div",{className:"space-y-2",children:_.map(C=>m(p,C))})]}),N.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),i.jsx("div",{className:"space-y-2",children:N.map(C=>m(p,C))})]})]}):i.jsx("div",{className:"space-y-2",children:v.map(C=>m(p,C))}):i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function Gtt(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const Wtt={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function Ktt({spoolId:t}){const{t:e}=Dt(),n=sn(),{showToast:r}=bn(),{data:a,isLoading:s}=et({queryKey:["spool-usage",t],queryFn:()=>ge.getSpoolUsageHistory(t)}),o=gt({mutationFn:()=>ge.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?i.jsx("div",{className:"flex justify-center py-4",children:i.jsx(ft,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!a||a.length===0?i.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[i.jsx(Zn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),i.jsxs(ze,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[i.jsx(nn,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:a.map(l=>i.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("span",{className:"text-bambu-gray",children:Gtt(l.created_at)}),l.print_name&&i.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[i.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),i.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),i.jsx("span",{className:Wtt[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function Ytt({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:a}){const{t:s}=Dt(),o=sn(),{showToast:l}=bn(),c=!!n,[u,d]=w.useState(OY),[m,p]=w.useState({}),[f,y]=w.useState("filament"),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[N,C]=w.useState(1),[k,P]=w.useState(!1),[T,D]=w.useState(!1),[A,R]=w.useState([]),[G,z]=w.useState(""),[Z,I]=w.useState([]),[J,ae]=w.useState([]),[Y,ue]=w.useState([]),[de,he]=w.useState([]),[V,ne]=w.useState([]),[se,pe]=w.useState(new Set),[Te,q]=w.useState(new Set),X=r.length>0?r:V,j=w.useMemo(()=>se.size,[se]);w.useEffect(()=>{he(ztt())},[]),w.useEffect(()=>{t&&((async()=>{D(!0);try{const me=await ge.getCloudStatus();if(P(me.is_authenticated),me.is_authenticated){const je=await ge.getFilamentPresets();R(je)}}catch(me){console.error("Failed to fetch cloud presets:",me),P(!1)}finally{D(!1)}})(),ge.getSpoolCatalog().then(I).catch(console.error),ge.getColorCatalog().then(ue).catch(console.error),ge.getLocalPresets().then(me=>ae(me.filament)).catch(console.error),r.length===0&&(async()=>{try{const me=await ge.getPrinters(),je=await Promise.all(me.map(Fe=>ge.getPrinterStatus(Fe.id).catch(()=>null))),we=[];for(let Fe=0;Fe({cali_idx:Me.slot_id,filament_id:Me.filament_id,setting_id:Me.setting_id||"",name:Me.name,k_value:parseFloat(Me.k_value)||0,n_coef:parseFloat(Me.n_coef)||0,extruder_id:Me.extruder_id,nozzle_diameter:Me.nozzle_diameter}))}catch{}we.push({printer:{...He,connected:_e},calibrations:Ae})}ne(we)}catch(me){console.error("Failed to fetch printer calibrations:",me)}})())},[t,r.length]);const E=w.useMemo(()=>Ott(A,new Set,J),[A,J]),U=w.useMemo(()=>{const fe=Ftt(A,J),me=Y.map(we=>we.manufacturer?.trim()).filter(we=>!!we),je=new Set([...fe,...me]);return Array.from(je).sort((we,Fe)=>we.localeCompare(Fe))},[A,J,Y]),K=w.useMemo(()=>{const fe=Y.map(je=>je.material?.trim()).filter(je=>!!je),me=new Set([...Mtt,...fe]);return Array.from(me).sort((je,we)=>je.localeCompare(we))},[Y]),H=w.useMemo(()=>{const fe=[];for(const me of Y){const je=me.manufacturer?.trim(),we=me.material?.trim();je&&we&&fe.push({brand:je,material:we})}for(const me of A){const je=Ux(me.name);je.brand&&je.material&&fe.push({brand:je.brand,material:je.material})}for(const me of J){const je=Ux(me.name),we=me.filament_vendor?.trim()||je.brand,Fe=je.material;we&&Fe&&fe.push({brand:we,material:Fe})}return fe},[A,Y,J]),re=w.useMemo(()=>{const fe=new Map;for(const me of H){const je=me.brand.toLowerCase(),we=me.material.toLowerCase();fe.has(je)||fe.set(je,new Set),fe.get(je).add(we)}return fe},[H]),O=w.useMemo(()=>{const fe=new Map;for(const me of H){const je=me.brand.toLowerCase(),we=me.material.toLowerCase();fe.has(we)||fe.set(we,new Set),fe.get(we).add(je)}return fe},[H]),$=w.useMemo(()=>{if(!u.material)return U;const fe=u.material.toLowerCase(),me=O.get(fe);return!me||me.size===0?U:U.filter(je=>me.has(je.toLowerCase()))},[U,u.material,O]),ee=w.useMemo(()=>{if(!u.brand)return K;const fe=u.brand.toLowerCase(),me=re.get(fe);return!me||me.size===0?K:K.filter(je=>me.has(je.toLowerCase()))},[K,u.brand,re]),W=w.useMemo(()=>Itt(u.slicer_filament,E),[u.slicer_filament,E]);w.useEffect(()=>{if(t){if(n)if(d({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),z(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const fe=new Set;for(const me of n.k_profiles)me.cali_idx!==null&&me.cali_idx!==void 0&&fe.add(`${me.printer_id}:${me.cali_idx}:${me.extruder??"null"}`);pe(fe)}else pe(new Set);else d(OY),z(""),pe(new Set),_(!1),C(1);p({}),y("filament"),b(!1)}},[t,n]),w.useEffect(()=>{t&&X.length>0&&q(new Set(X.map(fe=>String(fe.printer.id))))},[t,X]);const ie=(fe,me)=>{d(je=>({...je,[fe]:me})),fe==="weight_used"&&b(!0),m[fe]&&p(je=>({...je,[fe]:void 0}))},ce=fe=>{he(me=>Utt(fe,me))},be=gt({mutationFn:fe=>ge.createSpool(fe),onSuccess:async fe=>{se.size>0&&fe?.id&&await F(fe.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolCreated"),"success"),e()},onError:fe=>{l(fe.message,"error")}}),xe=gt({mutationFn:({data:fe,qty:me})=>ge.bulkCreateSpools(fe,me),onSuccess:async fe=>{if(se.size>0)for(const me of fe)await F(me.id);await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolsCreated",{count:fe.length}),"success"),e()},onError:fe=>{l(fe.message,"error")}}),oe=gt({mutationFn:fe=>ge.updateSpool(n.id,fe),onSuccess:async()=>{n?.id&&await F(n.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolUpdated"),"success"),e()},onError:fe=>{l(fe.message,"error")}}),L=gt({mutationFn:()=>ge.updateSpool(n.id,{tag_uid:null}),onSuccess:async()=>{await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.tagDeleted","Tag removed"),"success"),e()},onError:fe=>{l(fe.message,"error")}}),F=async fe=>{if(se.size===0){try{await ge.saveSpoolKProfiles(fe,[])}catch{}return}const me=[];for(const je of se){const[we,Fe,He]=je.split(":"),Oe=parseInt(we),_e=parseInt(Fe),Ae=He==="null"?0:parseInt(He),Be=X.find(Me=>Me.printer.id===Oe);if(Be){const Me=Be.calibrations.find(Xe=>Xe.cali_idx===_e);Me&&me.push({printer_id:Oe,extruder:Ae,nozzle_diameter:Me.nozzle_diameter||"0.4",k_value:Me.k_value,name:Me.name||null,cali_idx:Me.cali_idx,setting_id:Me.setting_id||null})}}if(me.length>0)try{await ge.saveSpoolKProfiles(fe,me)}catch(je){console.error("Failed to save K-profiles:",je)}};if(w.useEffect(()=>{if(!t)return;const fe=me=>{me.key==="Escape"&&e()};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[t,e]),!t)return null;const te=()=>{const fe=Ptt(u,g);if(!fe.isValid){p(fe.errors),(fe.errors.slicer_filament||fe.errors.material||fe.errors.brand||fe.errors.subtype)&&y("filament");return}const me=W?.displayName||G||null,je={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:me,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!c||v)&&(je.weight_used=u.weight_used),c?oe.mutate(je):N>1?xe.mutate({data:je,qty:N}):be.mutate(je)},ve=be.isPending||xe.isPending||oe.isPending||L.isPending;return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(c?"inventory.editSpool":"inventory.addSpool")}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),!c&&i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Pc,{className:"w-4 h-4 text-amber-400"}),i.jsx("span",{className:"text-sm text-white",children:s("inventory.quickAdd")})]}),i.jsx("button",{type:"button",onClick:()=>{_(!g),g||y("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${g?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${g?"translate-x-4":"translate-x-0.5"}`})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("button",{onClick:()=>y("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${f==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Sw,{className:"w-4 h-4"}),s("inventory.filamentInfoTab")]}),!g&&i.jsxs("button",{onClick:()=>y("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${f==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(She,{className:"w-4 h-4"}),s("inventory.paProfileTab"),j>0&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:j})]})]}),i.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:f==="filament"?i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.filamentInfo")}),i.jsx(Btt,{formData:u,updateField:ie,cloudAuthenticated:k,loadingCloudPresets:T,presetInputValue:G,setPresetInputValue:z,selectedPresetOption:W,filamentOptions:E,availableBrands:$,availableMaterials:ee,quickAdd:g,quantity:N,onQuantityChange:C,errors:m})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.color")}),i.jsx(Htt,{formData:u,updateField:ie,recentColors:de,onColorUsed:ce,catalogColors:Y})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.additional")}),i.jsx(qtt,{formData:u,updateField:ie,spoolCatalog:Z,currencySymbol:a})]}),c&&n&&i.jsx("div",{children:i.jsx(Ktt,{spoolId:n.id})})]}):i.jsx(Vtt,{formData:u,updateField:ie,printersWithCalibrations:X,selectedProfiles:se,setSelectedProfiles:pe,expandedPrinters:Te,setExpandedPrinters:q})}),i.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[c&&i.jsxs(ze,{variant:"secondary",onClick:()=>L.mutate(),disabled:ve||!n?.tag_uid,className:"mr-auto",children:[i.jsx(Hd,{className:"w-4 h-4"}),s("inventory.deleteTag","Delete Tag")]}),i.jsxs("div",{className:"flex gap-2 ml-auto",children:[i.jsx(ze,{variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(ze,{onClick:te,disabled:ve,children:ve?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),s("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(as,{className:"w-4 h-4"}),s(c?"common.save":"inventory.addSpool")]})})]})]})]})]})}function Xtt({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:a}){const{t:s}=Dt(),[o,l]=w.useState(n),[c,u]=w.useState(null),d=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(C=>({...C})))},[t,n]),w.useEffect(()=>{if(!t)return;const C=k=>{k.key==="Escape"&&e()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[t,e]),!t)return null;const m=C=>{l(k=>k.map((P,T)=>T===C?{...P,visible:!P.visible}:P))},p=(C,k)=>{k<0||k>=o.length||l(P=>{const T=[...P],[D]=T.splice(C,1);return T.splice(k,0,D),T})},f=(C,k)=>{d.current=k,u(k),C.dataTransfer.effectAllowed="move"},y=(C,k)=>{C.preventDefault(),C.dataTransfer.dropEffect="move";const P=d.current;P!==null&&P!==k&&(p(P,k),d.current=k,u(k))},v=C=>{C.preventDefault()},b=()=>{d.current=null,u(null)},g=()=>{l(r.map(C=>({...C})))},_=()=>{a(o),e()},N=o.filter(C=>C.visible).length;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsx(Pt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:C=>C.stopPropagation(),children:i.jsxs(Et,{className:"p-6 flex flex-col min-h-0",children:[i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),i.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),i.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),i.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((C,k)=>i.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===k?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${C.visible?"":"opacity-50"}`,draggable:!0,onDragStart:P=>f(P,k),onDragOver:P=>y(P,k),onDrop:v,onDragEnd:b,children:[i.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:i.jsx(Th,{className:"w-4 h-4"})}),i.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:C.label}),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{onClick:()=>p(k,k-1),disabled:k===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:i.jsx(Vl,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>p(k,k+1),disabled:k===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:i.jsx(In,{className:"w-4 h-4"})})]}),i.jsx("button",{onClick:()=>m(k),className:`p-1.5 rounded transition-colors ${C.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:C.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:C.visible?i.jsx(Tc,{className:"w-4 h-4"}):i.jsx(xw,{className:"w-4 h-4"})})]},C.id))}),i.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs(ze,{variant:"secondary",onClick:g,className:"mr-auto",children:[i.jsx(To,{className:"w-4 h-4"}),s("inventory.reset")]}),i.jsx(ze,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),i.jsx(ze,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}function zY(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.label_weight}`}const Qoe="bambuddy-inventory-columns",AN=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function Qtt(){try{const t=localStorage.getItem(Qoe);if(t){const e=JSON.parse(t),n=new Set(AN.map(o=>o.id)),r=new Set(e.map(o=>o.id)),a=e.filter(o=>n.has(o.id)),s=AN.filter(o=>!r.has(o.id));return[...a,...s]}}catch{}return AN.map(t=>({...t}))}function Ztt(t){try{localStorage.setItem(Qoe,JSON.stringify(t))}catch{}}function mu(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const Jtt={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function e3(t,e="system"){if(!t)return"-";const n=Qn(t);return n?A3(n,e):"-"}const ent={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},CL={id:({spool:t})=>i.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:e3(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:e3(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?e3(t.last_used,e):"Never"}),rgba:({spool:t})=>i.jsx("div",{className:"flex items-center justify-center",children:i.jsx("span",{className:"w-5 h-5 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:DI(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,a=n.ams_id===254||n.ams_id===255,s=!a&&n.ams_id>=128,o=FI(n.ams_id,n.tray_id,s,a);return i.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[r," ",o,n.ams_label?` (${n.ams_label})`:""]})},label_weight:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:mu(t.label_weight)}),net:({remaining:t})=>i.jsx("span",{className:"text-sm text-white",children:mu(t)}),gross:({spool:t,remaining:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:mu(e+t.core_weight)}),added_full:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?mu(t.weight_used):"-"}),printed_total:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?i.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return i.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const n=t.last_scale_weight;if(n==null)return i.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const r=t.core_weight||0,a=Math.max(0,t.label_weight-t.weight_used)+r;let s,o;n0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g +`+n+"}"}return String(t)}function Qet({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:a,hasPermission:s,t:o}){const{showToast:l}=bn(),c=sn(),[u,d]=w.useState(!1),{data:m,isLoading:p}=et({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ge.getCloudSettingDetail(t.setting_id)}),f=gt({mutationFn:()=>ge.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),y=hw(t.setting_id),v=M5(t.name,m?.setting?.inherits);return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:i.jsxs(Et,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),y&&i.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")})]}),i.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[i.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&i.jsxs(i.Fragment,{children:[i.jsx("span",{children:"•"}),i.jsx("span",{children:v.printer})]})]})]}),i.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?i.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:NL(m)}):i.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),u?i.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[i.jsx(jn,{className:"w-5 h-5"}),i.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:()=>d(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),i.jsxs(ze,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):i.jsx(nn,{className:"w-4 h-4"}),o("common.delete")]})]})]}):i.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),i.jsxs(ze,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[i.jsx(ko,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),y&&i.jsxs(i.Fragment,{children:[i.jsxs(ze,{variant:"secondary",onClick:a,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[i.jsx(Yi,{className:"w-4 h-4"}),o("common.edit")]}),i.jsx(ze,{variant:"danger",onClick:()=>d(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:i.jsx(nn,{className:"w-4 h-4"})})]})]})})]})})})}function qoe(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Voe(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Zet({onClose:t,onApply:e,t:n}){const{showToast:r}=bn(),[a,s]=w.useState(qoe),[o,l]=w.useState("all"),[c,u]=w.useState(null),[d,m]=w.useState(""),[p,f]=w.useState(""),[y,v]=w.useState("{}"),[b,g]=w.useState(null),[_,N]=w.useState(null),C=o==="all"?a:a.filter(Z=>Z.type===o),k=Z=>{s(Z),Voe(Z)},P=Z=>{const I=a.filter(J=>J.id!==Z);k(I),N(null),r(n("profiles.templates.toast.deleted"))},T=Z=>{u(Z.id),m(Z.name),f(Z.description),v(JSON.stringify(Z.settings,null,2)),g(null)},D=()=>{if(!(!c||!d.trim()))try{const Z=JSON.parse(y),I=a.map(J=>J.id===c?{...J,name:d.trim(),description:p.trim(),settings:Z}:J);k(I),u(null),r(n("profiles.templates.toast.updated"))}catch(Z){g(Z.message)}},A=()=>{u(null),m(""),f(""),v("{}"),g(null)},R=Z=>{const I=a.map(J=>J.id===Z?{...J,showInModal:!J.showInModal}:J);k(I)},G={filament:{label:n("profiles.presets.types.filament"),icon:rT,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:Bd,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:_r,color:"text-purple-400"}},z=_?a.find(Z=>Z.id===_):null;return w.useEffect(()=>{const Z=I=>{I.key==="Escape"&&(_?N(null):c?A():t())};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[_,c,t]),i.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[z&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:i.jsx(Pt,{className:"w-full max-w-md",children:i.jsxs(Et,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:i.jsx(jn,{className:"w-6 h-6 text-red-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),i.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:z.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),i.jsxs(ze,{onClick:()=>P(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[i.jsx(nn,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),i.jsx(Pt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:i.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(hx,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(Z=>i.jsx("button",{onClick:()=>l(Z),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===Z?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:Z==="all"?n("common.all"):G[Z].label},Z))]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:C.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(hx,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:n("profiles.templates.noTemplates")}),i.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):i.jsx("div",{className:"space-y-2",children:C.map(Z=>{const I=G[Z.type],J=I.icon;return c===Z.id?i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[i.jsx("input",{type:"text",value:d,onChange:ae=>m(ae.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}),i.jsx("input",{type:"text",value:p,onChange:ae=>f(ae.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"})]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),i.jsx("textarea",{value:y,onChange:ae=>{v(ae.target.value),g(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${b?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),b&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(ze,{size:"sm",onClick:D,disabled:!d.trim(),children:[i.jsx(as,{className:"w-4 h-4"}),"Save"]}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:A,children:"Cancel"})]})]},Z.id):i.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:[i.jsx(J,{className:`w-5 h-5 ${I.color} flex-shrink-0`}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:Z.name}),i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Z.description})]}),i.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(Z.settings).length})}),i.jsx("button",{onClick:()=>R(Z.id),className:`p-1 transition-colors ${Z.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:Z.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:Z.showInModal?i.jsx(Tc,{className:"w-4 h-4"}):i.jsx(xw,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>e(Z),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")}),i.jsx("button",{onClick:()=>T(Z),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:i.jsx(Yi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>N(Z.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:i.jsx(nn,{className:"w-4 h-4"})})]},Z.id)})})})]})})]})}function Goe({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:a,t:s}){const[o,l]=w.useState("changes"),[c,u]=w.useState(""),d=w.useMemo(()=>{const y=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const b of y){if(b==="inherits"||b==="version")continue;const g=e[b],_=n[b],N=b in e,C=b in n;let k;!N&&C?k="added":N&&!C?k="removed":JSON.stringify(g)!==JSON.stringify(_)?k="changed":k="same",v.push({key:b,left:g,right:_,status:k})}return v.sort((b,g)=>{const _={changed:0,added:1,removed:2,same:3};return _[b.status]!==_[g.status]?_[b.status]-_[g.status]:b.key.localeCompare(g.key)})},[e,n]),m=w.useMemo(()=>{let y=[...d];if(o==="changes"&&(y=y.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();y=y.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return y},[d,o,c]),p=w.useMemo(()=>({added:d.filter(y=>y.status==="added").length,removed:d.filter(y=>y.status==="removed").length,changed:d.filter(y=>y.status==="changed").length,same:d.filter(y=>y.status==="same").length}),[d]),f=y=>{if(y===void 0)return"—";if(y===null)return"null";if(Array.isArray(y))return y.length===0?"[]":y.length===1?String(y[0]):y.join(", ");if(typeof y=="object")return JSON.stringify(y);const v=String(y);if(v.includes("\\n")||v.length>100){const b=v.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const y=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:i.jsxs(Et,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Gb,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),i.jsx("p",{className:"text-white font-medium truncate",children:r})]}),i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),i.jsx("p",{className:"text-white font-medium truncate",children:a})]})]}),i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[i.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[i.jsx(ir,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(zN,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[i.jsx(v3,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[i.jsx(XM,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:c,onChange:y=>u(y.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&&i.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[i.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")}),i.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")})]})]})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(XM,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:i.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[i.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),i.jsx("th",{className:"text-left p-3 w-1/3",children:r}),i.jsx("th",{className:"text-left p-3 w-1/3",children:a})]})}),i.jsx("tbody",{children:m.map(y=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[y.status],b={added:i.jsx(ir,{className:"w-3.5 h-3.5 text-green-400"}),removed:i.jsx(zN,{className:"w-3.5 h-3.5 text-red-400"}),changed:i.jsx(v3,{className:"w-3.5 h-3.5 text-amber-400"}),same:i.jsx(XM,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[y.status];return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[i.jsx("td",{className:"p-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[b,i.jsx("span",{className:"text-sm text-white font-mono",children:y.key})]})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${y.status==="removed"?"text-red-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.left)})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${y.status==="added"?"text-green-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.right)})})]},y.key)})})]})})]})})})}function Jet({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:a}=bn(),s=sn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[u,d]=w.useState(e?.type||"filament"),[m,p]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,y]=w.useState(e?.base_id||""),[v,b]=w.useState(""),[g,_]=w.useState(e?.setting||{inherits:""}),[N,C]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[k,P]=w.useState(null),[T,D]=w.useState(""),[A,R]=w.useState(!1),[G,z]=w.useState(""),[Z,I]=w.useState(!1),[J,ae]=w.useState(qoe),[Y,ue]=w.useState(!1),[de,he]=w.useState(""),[V,ne]=w.useState(""),[se,pe]=w.useState(!0),[Te,q]=w.useState(null),[X,j]=w.useState(!1),E=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),U=w.useMemo(()=>E.filter(Ae=>hw(Ae.setting_id)),[E]),{data:K}=et({queryKey:["cloudFields",u],queryFn:()=>ge.getCloudFields(u==="print"?"process":u),staleTime:1e3*60*60}),{data:H}=et({queryKey:["allPresetDetails",u,U.map(Ae=>Ae.setting_id).join(",")],queryFn:async()=>{const Ae={};for(let Me=0;Me{try{const Pe=await ge.getCloudSettingDetail(We.setting_id);return{id:We.setting_id,detail:Pe}}catch{return null}}))).forEach(We=>{We&&(Ae[We.id]=We.detail)})}return Ae},enabled:U.length>0,staleTime:1e3*60*10}),{data:re,isLoading:O}=et({queryKey:["cloudSettingDetail",f],queryFn:()=>ge.getCloudSettingDetail(f),enabled:!!f});w.useEffect(()=>{l!=="json"&&C(JSON.stringify(g,null,2))},[g,l]);const $=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(Be=>!hw(Be.setting_id)).sort((Be,Me)=>Be.name.localeCompare(Me.name)),[n,u]);w.useEffect(()=>{if(!f)return;const Ae=$.find(Be=>Be.setting_id===f);Ae&&(b(Ae.name),o||(_({inherits:Ae.name}),C(JSON.stringify({inherits:Ae.name},null,2))))},[f,$,o]);const ee=w.useMemo(()=>{const Ae=K?.fields||[],Be=new Set(Ae.map(We=>We.key)),Me=new Set,Xe=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);H&&Object.values(H).forEach(We=>{We?.setting&&Object.keys(We.setting).forEach(Pe=>{!Be.has(Pe)&&!Xe.has(Pe)&&Me.add(Pe)})}),Object.keys(g).forEach(We=>{!Be.has(We)&&!Xe.has(We)&&Me.add(We)});const ye=Array.from(Me).sort().map(We=>({key:We,label:We.replace(/_/g," ").replace(/\b\w/g,Pe=>Pe.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Ae,...ye]},[K,H,g,r]),W=ee.filter(Ae=>Ae.label.toLowerCase().includes(T.toLowerCase())||Ae.key.toLowerCase().includes(T.toLowerCase())),ie=()=>{if(G.trim()){const Ae=G.trim().toLowerCase().replace(/\s+/g,"_");ce(Ae,""),z(""),I(!1),a(r("profiles.presets.toast.fieldAdded",{key:Ae}))}},ce=(Ae,Be)=>{_(Me=>{const Xe={...Me};return Be===""||Be===void 0?delete Xe[Ae]:Xe[Ae]=Be,Xe})},be=Ae=>{_(Be=>({...Be,...Ae.settings})),q(Ae.name),a(r("profiles.templates.toast.applied"))},xe=()=>{if(!de.trim())return;const Ae={...g};if(delete Ae.inherits,Object.keys(Ae).length===0){a(r("profiles.presets.noOverridesToSave"),"error");return}const Be={id:Date.now().toString(),name:de.trim(),description:V.trim()||r("profiles.presets.customTemplate"),type:u,settings:Ae,showInModal:se},Me=[...J,Be];ae(Me),Voe(Me),ue(!1),he(""),ne(""),pe(!0),a(r("profiles.templates.toast.created"))},oe=w.useMemo(()=>J.filter(Ae=>Ae.type===u&&Ae.showInModal),[u,J]),L=Ae=>{C(Ae);try{const Be=JSON.parse(Ae);_(Be),P(null)}catch(Be){P(Be.message)}},F=Ae=>{Ae.preventDefault(),R(!1);const Be=Ae.dataTransfer.files[0];if(Be&&Be.name.endsWith(".json")){const Me=new FileReader;Me.onload=Xe=>{try{const ye=Xe.target?.result,We=JSON.parse(ye),Pe=We.setting||We;_(Ke=>({...Ke,...Pe})),C(JSON.stringify({...g,...Pe},null,2)),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJsonFile"),"error")}},Me.readAsText(Be)}},te=gt({mutationFn:()=>{const Ae={...g},Be=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";Ae[Be]=`"${m}"`;const Me={type:u,name:m,base_id:f,setting:Ae};return ge.createCloudSetting(Me)},onSuccess:async()=>{a(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Ae=>a(Ae.message,"error")}),ve=gt({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return ge.updateCloudSetting(e.setting_id,{name:m,setting:g})},onSuccess:async()=>{a(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Ae=>a(Ae.message,"error")}),fe=o?ve:te,me=re?.setting?.inherits,je=me?$.find(Ae=>Ae.name===me):void 0,{data:we}=et({queryKey:["cloudSettingDetail",je?.setting_id],queryFn:()=>ge.getCloudSettingDetail(je.setting_id),enabled:!!je?.setting_id}),Fe=w.useMemo(()=>{const Ae=we?.setting||{},Be=re?.setting||{},Me=f&&H?.[f]?.setting?H[f].setting:{};return{...Ae,...Be,...Me}},[f,re,we,H]),He=Ae=>{if(Ae==null)return"";if(Array.isArray(Ae)){const Be=[...new Set(Ae.map(Me=>String(Me)))];return Be.length===1?Be[0]:Ae.join(", ")}return String(Ae)},Oe=Ae=>{const Be=g[Ae.key],Me=Fe[Ae.key],Xe=He(Me),ye=O?r("common.loading"):Xe||"",We="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(Ae.type==="boolean"){const Pe=Be==="1"||Be===void 0&&Me==="1";return i.jsx("button",{type:"button",onClick:()=>ce(Ae.key,Be==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Pe?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Pe?"translate-x-3.5":"translate-x-0.5"}`})})}return Ae.type==="select"?i.jsxs("select",{value:Be||"",onChange:Pe=>ce(Ae.key,Pe.target.value),className:We,children:[i.jsx("option",{value:"",children:ye}),Ae.options?.map(Pe=>i.jsx("option",{value:Pe.value,children:Pe.label},Pe.value))]}):i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:Ae.type==="number"?"number":"text",value:Be!==void 0?String(Be):"",onChange:Pe=>ce(Ae.key,Pe.target.value),step:Ae.step,min:Ae.min,max:Ae.max,placeholder:ye,className:We}),Ae.unit&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Ae.unit})]})},_e=w.useMemo(()=>re?.setting?re.setting:{},[re]);return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Ae=>{Ae.preventDefault(),R(!0)},onDragLeave:()=>R(!1),onDrop:F,children:[X&&f&&i.jsx(Goe,{onClose:()=>j(!1),leftPreset:_e,rightPreset:g,leftLabel:r("profiles.presets.baseLabel",{name:v||f}),rightLabel:r("profiles.presets.currentLabel",{name:m||r("profiles.presets.newPreset")}),t:r}),i.jsx(Pt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:i.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[f&&i.jsxs("button",{onClick:()=>j(!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:[i.jsx(Gb,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),i.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]})]}),A&&i.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:i.jsxs("div",{className:"text-center",children:[i.jsx(yi,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),i.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),i.jsxs("select",{value:u,onChange:Ae=>{d(Ae.target.value),y("")},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:[i.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),i.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),i.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),i.jsxs("select",{value:f,onChange:Ae=>y(Ae.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:[i.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),$.map(Ae=>i.jsx("option",{value:Ae.setting_id,children:Ae.name},Ae.setting_id))]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),i.jsx("input",{type:"text",value:m,onChange:Ae=>p(Ae.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("profiles.presets.myCustomPreset")})]})]}),v&&i.jsx("div",{className:"text-xs text-bambu-gray",children:i.jsxs("p",{className:"flex items-center gap-1",children:[i.jsx(Zr,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",i.jsx("span",{className:"text-white",children:v}),O&&i.jsx(ft,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[i.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:[i.jsx(X8,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),i.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:[i.jsx(sT,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),i.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:[i.jsx(WX,{className:"w-4 h-4"}),"JSON",k&&i.jsx(Li,{className:"w-3 h-3 text-red-400"})]}),i.jsx("div",{className:"flex-1 max-[640px]:hidden"}),i.jsxs("button",{onClick:()=>{const Ae={name:m,type:u,base_id:f,setting:g},Be=new Blob([JSON.stringify(Ae,null,2)],{type:"application/json"}),Me=URL.createObjectURL(Be),Xe=document.createElement("a");Xe.href=Me,Xe.download=`${m||"preset"}.json`,document.body.appendChild(Xe),Xe.click(),document.body.removeChild(Xe),URL.revokeObjectURL(Me),a(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:[i.jsx(fi,{className:"w-4 h-4"}),r("common.download")]}),i.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:[i.jsx(yi,{className:"w-4 h-4"}),r("common.upload")]}),i.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Ae=>{const Be=Ae.target.files?.[0];if(Be){const Me=new FileReader;Me.onload=Xe=>{try{const ye=JSON.parse(Xe.target?.result),We=ye.setting||ye;_(Pe=>({...Pe,...We})),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJson"),"error")}},Me.readAsText(Be)}}})]}),i.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(hx,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(g).filter(Ae=>Ae!=="inherits").length>0&&i.jsxs("button",{onClick:()=>ue(!Y),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[i.jsx(as,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),Y&&i.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[i.jsx("input",{type:"text",value:de,onChange:Ae=>he(Ae.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}),i.jsx("input",{type:"text",value:V,onChange:Ae=>ne(Ae.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"})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(ze,{size:"sm",onClick:xe,disabled:!de.trim(),children:[i.jsx(as,{className:"w-3 h-3"}),r("common.save")]}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:()=>ue(!1),children:r("common.cancel")})]}),i.jsxs("button",{onClick:()=>pe(!se),className:`flex items-center gap-1.5 text-xs transition-colors ${se?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[se?i.jsx(Tc,{className:"w-3.5 h-3.5"}):i.jsx(xw,{className:"w-3.5 h-3.5"}),r(se?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Te&&i.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:[i.jsx(Zr,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",i.jsx("span",{className:"font-medium",children:Te})]}),i.jsx("button",{onClick:()=>q(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[oe.map(Ae=>i.jsxs("button",{onClick:()=>be(Ae),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:Ae.name}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Ae.description})]},Ae.id)),oe.length===0&&i.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),i.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),i.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:ee.slice(0,10).map(Ae=>i.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[i.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Ae.label}),i.jsx("div",{className:"w-48 max-[640px]:w-full",children:Oe(Ae)})]},Ae.key))})]}),Object.keys(g).length>1&&i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(g).filter(([Ae])=>Ae!=="inherits").map(([Ae,Be])=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Ae,": ",String(Be).slice(0,20),i.jsx("button",{onClick:()=>ce(Ae,void 0),className:"hover:text-white",children:i.jsx(Ht,{className:"w-3 h-3"})})]},Ae))})]})]}),l==="fields"&&i.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:H?r("profiles.templates.fieldsCount",{count:ee.length}):r("common.loading")})]}),i.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:T,onChange:Ae=>D(Ae.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"})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[W.filter(Ae=>!(Ae.key in g)).map(Ae=>{const Be=Fe[Ae.key],Me=He(Be);return i.jsxs("div",{onClick:()=>{_(Xe=>({...Xe,[Ae.key]:Me||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white truncate",children:Ae.label}),i.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Ae.key})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Me&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Me,children:[Me.slice(0,20),Me.length>20?"...":""]}),i.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:i.jsx(ir,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Ae.key)}),W.filter(Ae=>!(Ae.key in g)).length===0&&i.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(T?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:Z?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:G,onChange:Ae=>z(Ae.target.value),onKeyDown:Ae=>Ae.key==="Enter"&&ie(),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}),i.jsx(ze,{size:"sm",onClick:ie,disabled:!G.trim(),children:i.jsx(ir,{className:"w-4 h-4"})}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:()=>{I(!1),z("")},children:i.jsx(Ht,{className:"w-4 h-4"})})]}):i.jsxs("button",{onClick:()=>I(!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:[i.jsx(ir,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(g).filter(Ae=>Ae!=="inherits").length})})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(g).filter(([Ae])=>Ae!=="inherits").map(([Ae,Be])=>{const Me=ee.find(Xe=>Xe.key===Ae);return i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium text-white",children:Me?.label||Ae}),i.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Ae})]}),i.jsx("button",{onClick:()=>ce(Ae,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),Me?Oe(Me):i.jsx("input",{type:"text",value:String(Be),onChange:Xe=>ce(Ae,Xe.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"})]},Ae)}),Object.keys(g).filter(Ae=>Ae!=="inherits").length===0&&i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(X8,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),i.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),i.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(g).filter(Ae=>Ae!=="inherits").length>0&&i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:i.jsxs("button",{onClick:()=>{ue(!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:[i.jsx(as,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&i.jsxs("div",{className:"space-y-2",children:[k&&i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(Li,{className:"w-4 h-4"}),k]}),i.jsx("textarea",{value:N,onChange:Ae=>L(Ae.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 ${k?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsxs(ze,{onClick:()=>fe.mutate(),disabled:fe.isPending||!m.trim()||!o&&!f||!!k,className:"flex-1",children:[fe.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):o?i.jsx(as,{className:"w-4 h-4"}):i.jsx(ir,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function ett({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:a,hasPermission:s,t:o}){const[l,c]=w.useState(""),[u,d]=w.useState("all"),[m,p]=w.useState("all"),[f,y]=w.useState("all"),[v,b]=w.useState("all"),[g,_]=w.useState("all"),[N,C]=w.useState("all"),[k,P]=w.useState(null),[T,D]=w.useState(!1),[A,R]=w.useState(!1),[G,z]=w.useState(null),[Z,I]=w.useState(null),[J,ae]=w.useState(null),[Y,ue]=w.useState(!1),[de,he]=w.useState([null,null]),[V,ne]=w.useState(!1),[se,pe]=w.useState(null),Te=sn(),q=w.useMemo(()=>[...t.filament.map(ie=>({...ie,type:"filament"})),...t.printer.map(ie=>({...ie,type:"printer"})),...t.process.map(ie=>({...ie,type:"process"}))].map(ie=>({...ie,meta:M5(ie.name)})),[t]),X=w.useMemo(()=>{const W=new Set,ie=new Set,ce=new Set;return q.forEach(be=>{be.meta.nozzle&&W.add(be.meta.nozzle),be.meta.filamentType&&ie.add(be.meta.filamentType),be.meta.layerHeight&&ce.add(be.meta.layerHeight)}),{printers:a.map(be=>({id:be.id.toString(),name:be.name})),nozzles:Array.from(W).sort((be,xe)=>parseFloat(be)-parseFloat(xe)),filaments:Array.from(ie).sort(),layerHeights:Array.from(ce).sort((be,xe)=>parseFloat(be)-parseFloat(xe))}},[q,a]),j=w.useMemo(()=>f==="all"?null:a.find(ie=>ie.id.toString()===f)?.model||null,[f,a]),E=w.useMemo(()=>q.filter(W=>u==="all"||W.type===u).filter(W=>{if(m==="all")return!0;const ie=hw(W.setting_id);return m==="custom"?ie:!ie}).filter(W=>{if(f==="all"||!j)return!0;const ie=W.meta.printer?.toLowerCase()||"",ce=j.toLowerCase();return ie.includes(ce)||ce.includes(ie)}).filter(W=>v==="all"||W.meta.nozzle===v).filter(W=>g==="all"||W.meta.filamentType===g).filter(W=>N==="all"||W.meta.layerHeight===N).filter(W=>l===""||W.name.toLowerCase().includes(l.toLowerCase())).sort((W,ie)=>W.name.localeCompare(ie.name)),[q,u,m,f,j,v,g,N,l]),U=W=>{if(Y){const ie=de[0]?.setting_id===W.setting_id,ce=de[1]?.setting_id===W.setting_id;if(ie)he([de[1],null]);else if(ce)he([de[0],null]);else if(!de[0])he([W,null]);else if(de[1]){if(de[0].type!==W.type)return;he([de[0],W])}else{if(de[0].type!==W.type)return;he([de[0],W])}}else P(W)},K=W=>{if(de[0]?.setting_id===W.setting_id)return 0;if(de[1]?.setting_id===W.setting_id)return 1},H=async W=>{try{const ie=await ge.getCloudSettingDetail(W.setting_id),ce=W.type==="process"?"print":W.type;z({type:ce,name:W.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{}}),P(null)}catch(ie){console.error("Failed to fetch preset details for duplication:",ie)}},re=async W=>{try{Te.removeQueries({queryKey:["cloudSettingDetail",W.setting_id]});const ie=await ge.getCloudSettingDetail(W.setting_id),ce=W.type==="process"?"print":W.type;I({type:ce,name:W.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{},setting_id:W.setting_id}),P(null)}catch(ie){console.error("Failed to fetch preset details for editing:",ie)}},O=()=>{d("all"),p("all"),y("all"),b("all"),_("all"),C("all"),c("")},$=u!=="all"||m!=="all"||f!=="all"||v!=="all"||g!=="all"||N!=="all"||l!=="",ee=t.filament.length+t.printer.length+t.process.length;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-4 mb-6",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:l,onChange:W=>c(W.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"})]}),i.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[i.jsxs(ze,{variant:Y?"primary":"secondary",onClick:()=>{Y?(ue(!1),he([null,null])):ue(!0)},children:[i.jsx(Gb,{className:"w-4 h-4"}),o(Y?"common.cancel":"profiles.presets.compare")]}),i.jsxs(ze,{variant:"secondary",onClick:()=>R(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[i.jsx(hx,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),i.jsxs(ze,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[i.jsx(Sr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),i.jsxs(ze,{onClick:()=>D(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[i.jsx(ir,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(aT,{className:"w-4 h-4 text-bambu-gray"}),i.jsx(Tb,{label:o("profiles.cloudView.filters.type"),value:u,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:ee},{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:W=>d(W)}),i.jsx(Tb,{label:o("profiles.cloudView.filters.owner"),value:m,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:W=>p(W)}),X.printers.length>0&&i.jsx(Tb,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...X.printers.map(W=>({value:W.id,label:W.name}))],onChange:y}),X.nozzles.length>0&&i.jsx(Tb,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...X.nozzles.map(W=>({value:W,label:W}))],onChange:b}),X.filaments.length>0&&(u==="all"||u==="filament")&&i.jsx(Tb,{label:o("profiles.cloudView.filters.filament"),value:g,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...X.filaments.map(W=>({value:W,label:W}))],onChange:_}),X.layerHeights.length>0&&(u==="all"||u==="process")&&i.jsx(Tb,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...X.layerHeights.map(W=>({value:W,label:W}))],onChange:C}),$&&i.jsx("button",{onClick:O,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),Y&&i.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(Gb,{className:"w-5 h-5 text-blue-400"}),i.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),i.jsx("span",{className:"text-bambu-gray",children:de[0]?o("profiles.cloudView.selectAnotherPreset",{type:de[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${de[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[0]?de[0].name:o("profiles.cloudView.selectFirst")}),i.jsx(v3,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${de[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[1]?de[1].name:o("profiles.cloudView.selectSecond")})]}),de[0]&&de[1]&&i.jsxs(ze,{size:"sm",onClick:async()=>{try{const[W,ie]=await Promise.all([ge.getCloudSettingDetail(de[0].setting_id),ge.getCloudSettingDetail(de[1].setting_id)]);pe([W.setting||{},ie.setting||{}]),ne(!0)}catch{}},children:[i.jsx(Gb,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),i.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(Zn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",C0(e.toISOString(),"system",o)]}),i.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:E.length,total:ee})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),i.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),E.length===0?i.jsxs("div",{className:"text-center py-16",children:[i.jsx(Gi,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),i.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),$&&i.jsx("button",{onClick:O,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(rT,{className:"w-4 h-4 text-amber-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(W=>W.type==="filament").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(W=>W.type==="filament").map(W=>i.jsx(YD,{setting:W,onClick:()=>U(W),onDuplicate:()=>H(W),compareMode:Y,isCompareSelected:K(W)!==void 0,compareIndex:K(W),compareDisabled:Y&&!!de[0]&&de[0].type!==W.type,t:o},W.setting_id)),E.filter(W=>W.type==="filament").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(Bd,{className:"w-4 h-4 text-blue-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(W=>W.type==="process").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(W=>W.type==="process").map(W=>i.jsx(YD,{setting:W,onClick:()=>U(W),onDuplicate:()=>H(W),compareMode:Y,isCompareSelected:K(W)!==void 0,compareIndex:K(W),compareDisabled:Y&&!!de[0]&&de[0].type!==W.type,t:o},W.setting_id)),E.filter(W=>W.type==="process").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(_r,{className:"w-4 h-4 text-purple-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(W=>W.type==="printer").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(W=>W.type==="printer").map(W=>i.jsx(YD,{setting:W,onClick:()=>U(W),onDuplicate:()=>H(W),compareMode:Y,isCompareSelected:K(W)!==void 0,compareIndex:K(W),compareDisabled:Y&&!!de[0]&&de[0].type!==W.type,t:o},W.setting_id)),E.filter(W=>W.type==="printer").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),k&&i.jsx(Qet,{setting:k,onClose:()=>P(null),onDeleted:()=>P(null),onDuplicate:()=>H(k),onEdit:()=>re(k),hasPermission:s,t:o}),(T||G||Z||J)&&i.jsx(Jet,{onClose:()=>{D(!1),z(null),I(null),ae(null)},initialData:Z||G||(J?{type:J.type,name:"",base_id:"",setting:J.setting}:void 0),allPresets:t,t:o}),A&&i.jsx(Zet,{onClose:()=>R(!1),onApply:W=>{ae({type:W.type,setting:W.settings}),R(!1)},t:o}),V&&se&&de[0]&&de[1]&&i.jsx(Goe,{onClose:()=>{ne(!1),pe(null)},leftPreset:se[0],rightPreset:se[1],leftLabel:de[0].name,rightLabel:de[1].name,t:o})]})}function ttt(){const{t}=Dt(),e=sn(),{showToast:n}=bn(),{hasPermission:r}=Ar(),[a,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:u}=et({queryKey:["cloudStatus"],queryFn:ge.getCloudStatus}),{data:d=[]}=et({queryKey:["printers"],queryFn:ge.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:y}=et({queryKey:["cloudSettings"],queryFn:()=>ge.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{y&&l(new Date(y))},[y]);const v=gt({mutationFn:ge.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return u?i.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"p-6 lg:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),i.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[i.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 ${a==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(qx,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),i.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 ${a==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(Vx,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),i.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 ${a==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(yw,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),a==="cloud"&&i.jsxs(i.Fragment,{children:[c?.is_authenticated&&i.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",i.jsx("span",{className:"text-white",children:c.email})]})]}),i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[i.jsx(N3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?i.jsx(ett,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:d,hasPermission:r,t}):i.jsxs("div",{className:"text-center py-16",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),i.jsx(ze,{onClick:()=>f(),children:t("profiles.retry")})]}):i.jsx(Yet,{onSuccess:b,t})]}),a==="local"&&i.jsx(Ket,{}),a==="kprofiles"&&i.jsx(qet,{}),i.jsx(Xet,{})]})}const Vv={Droplet:rT,Flame:qp,Ruler:Mge,Sparkles:hx,Square:rl,Cable:VL,Wrench:Ef,Calendar:Xr,Timer:Sd,Cog:ype,Fan:KX,Zap:Pc,Wind:oQ,Thermometer:mT,Layers:Gi,Box:ia,Target:iQ,RefreshCw:Sr,Settings:dT,Filter:aT,CircleDot:epe};function g0(t){return t&&Vv[t]||Ef}function Ab(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 a=Math.round(t);return n?n("maintenance.days",{count:a}):`${a} days`}if(t<180){const a=Math.round(t/7);return a===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:a}):`${a} 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 a=r/7;return a<12?`${a<2?a.toFixed(1):Math.round(a)}w`:`${Math.round(a/4)}mo`}}function XD(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 ntt(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),a=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,m=n.includes("P2S");switch(t){case"Lubricate Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||a?"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":m?"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":a?"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":m?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||a?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return r||a?"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 rtt({item:t,onPerform:e,onToggle:n,hasPermission:r,t:a}){const s=g0(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const f=t.days_since_maintenance??0;return Math.max(0,Math.min(100,f/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),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",m=()=>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 a("common.disabled");if(o==="days"){const f=t.days_until_due??0;return t.is_due?a("maintenance.overdueBy",{duration:Ab(Math.abs(f),"days",a)}):t.is_warning?a("maintenance.dueIn",{duration:Ab(f,"days",a)}):a("maintenance.timeLeft",{duration:Ab(f,"days",a)})}else return t.is_due?a("maintenance.overdueBy",{duration:Ab(Math.abs(t.hours_until_due),"hours",a)}):t.is_warning?a("maintenance.dueIn",{duration:Ab(t.hours_until_due,"hours",a)}):a("maintenance.timeLeft",{duration:Ab(t.hours_until_due,"hours",a)})};return i.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:i.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[i.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[i.jsx(s,{className:`w-5 h-5 ${u()}`}),t.enabled&&(t.is_due||t.is_warning)&&i.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`})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&i.jsx("span",{title:a("maintenance.timeBasedInterval"),children:i.jsx(Xr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||ntt(t.maintenance_type_name,t.printer_model);return f?i.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:a("maintenance.viewDocumentation"),onClick:y=>y.stopPropagation(),children:i.jsx(ni,{className:"w-3.5 h-3.5"})}):null})()]}),i.jsx("div",{className:"mt-2 mb-1.5",children:i.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${d()}`,style:{width:`${c}%`}})})}),i.jsxs("div",{className:`text-xs flex items-center gap-1 ${u()}`,children:[t.is_due&&i.jsx(jn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&i.jsx(Zn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&i.jsx(Zr,{className:"w-3 h-3"}),p()]})]}),i.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[i.jsx("span",{title:r("maintenance:update")?void 0:a("maintenance.noPermissionUpdate"),children:i.jsx(zn,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!r("maintenance:update")})}),i.jsxs(ze,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:a("maintenance.noPermissionPerform"),className:"!px-3",children:[i.jsx(To,{className:"w-3.5 h-3.5"}),a("common.reset")]})]})]})})}function itt({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:a,t:s}){const[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,m]=w.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((v,b)=>v.is_due&&!b.is_due?-1:!v.is_due&&b.is_due?1:v.is_warning&&!b.is_warning?-1:!v.is_warning&&b.is_warning?1:v.maintenance_type_id-b.maintenance_type_id),f=p.find(v=>v.enabled&&(v.is_due||v.is_warning)),y=()=>{const v=parseFloat(d);!isNaN(v)&&v>=0&&(r(t.printer_id,v),u(!1))};return i.jsxs(Pt,{className:"overflow-hidden",children:[i.jsxs("div",{className:"p-5",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&i.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:[i.jsx(jn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&i.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:[i.jsx(Zn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&i.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:[i.jsx(Zr,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),i.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?i.jsx(Vl,{className:"w-4 h-4"}):i.jsx(In,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),i.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:i.jsx(Sd,{className:"w-4 h-4 text-bambu-gray"})}),c?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",value:d,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&y(),v.key==="Escape"&&u(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),i.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),i.jsx(ze,{size:"sm",onClick:y,children:s("common.save")}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:()=>u(!1),children:s("common.cancel")})]}):i.jsxs("button",{onClick:()=>{a("maintenance:update")&&(m(Math.round(t.total_print_hours).toString()),u(!0))},className:`group ${a("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:a("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[i.jsxs("div",{className:`text-sm font-medium text-white ${a("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),i.jsx(Pf,{className:`w-3 h-3 text-bambu-gray ${a("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),i.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),i.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=g0(f.maintenance_type_icon);return i.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),i.jsxs("div",{children:[i.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),i.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&i.jsx(Et,{className:"pt-0 border-t border-bambu-dark-tertiary",children:i.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>i.jsx(rtt,{item:v,onPerform:e,onToggle:n,hasPermission:a,t:s},v.id))})})]})}function att({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:a,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:u,hasPermission:d,t:m}){const[p,f]=w.useState(null),[y,v]=w.useState(""),[b,g]=w.useState("hours"),[_,N]=w.useState(!1),[C,k]=w.useState(""),[P,T]=w.useState("100"),[D,A]=w.useState("hours"),[R,G]=w.useState("Wrench"),[z,Z]=w.useState(""),[I,J]=w.useState(new Set),[ae,Y]=w.useState(null),[ue,de]=w.useState(null),he=w.useMemo(()=>t?t.map(L=>({id:L.printer_id,name:L.printer_name})):[],[t]),V=L=>t?t.filter(F=>F.maintenance_items.some(te=>te.maintenance_type_id===L)).map(F=>({printerId:F.printer_id,printerName:F.printer_name,itemId:F.maintenance_items.find(te=>te.maintenance_type_id===L)?.id})):[],ne=L=>{if(!t)return[];const F=new Set(V(L).map(te=>te.printerId));return he.filter(te=>!F.has(te.id))},[se,pe]=w.useState(null),[Te,q]=w.useState(""),[X,j]=w.useState(""),[E,U]=w.useState("hours"),[K,H]=w.useState("Wrench"),[re,O]=w.useState(""),$=L=>{pe(L),q(L.name),j(L.default_interval_hours.toString()),U(L.interval_type||"hours"),H(L.icon||"Wrench"),O(L.wiki_url||"")},ee=()=>{se&&Te.trim()&&parseFloat(X)>0&&(a(se.id,{name:Te.trim(),default_interval_hours:parseFloat(X),interval_type:E,icon:K,wiki_url:re.trim()||null}),pe(null))},W=(L,F,te)=>{const ve=parseFloat(y);if(!isNaN(ve)&&ve>0){const fe=Math.abs(ve-F)<.01?null:ve;n(L,{custom_interval_hours:fe,custom_interval_type:b!==te?b:null})}f(null)},ie=L=>{L.preventDefault(),C.trim()&&parseFloat(P)>0&&I.size>0&&(r({name:C.trim(),default_interval_hours:parseFloat(P),interval_type:D,icon:R,wiki_url:z.trim()||null},Array.from(I)),k(""),T("100"),A("hours"),Z(""),J(new Set),N(!1))},ce=L=>{J(F=>{const te=new Set(F);return te.has(L)?te.delete(L):te.add(L),te})},be=t?.map(L=>({printerId:L.printer_id,printerName:L.printer_name,items:L.maintenance_items.sort((F,te)=>F.maintenance_type_id-te.maintenance_type_id)})).sort((L,F)=>L.printerName.localeCompare(F.printerName))||[],xe=e.filter(L=>L.is_system),oe=e.filter(L=>!L.is_system);return i.jsxs("div",{className:"space-y-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ze,{variant:"secondary",onClick:o,disabled:!d("maintenance:delete")||l,title:d("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),i.jsxs(ze,{onClick:()=>N(!_),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[i.jsx(ir,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),_&&i.jsx(Pt,{className:"mb-6",children:i.jsx(Et,{className:"py-4",children:i.jsxs("form",{onSubmit:ie,children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"lg:col-span-2",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),i.jsx("input",{type:"text",value:C,onChange:L=>k(L.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:m("maintenance.exampleName"),autoFocus:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),i.jsxs("select",{value:D,onChange:L=>{A(L.target.value),L.target.value==="days"?T("30"):T("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:[i.jsx("option",{value:"hours",children:m("maintenance.printHours")}),i.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:D==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),i.jsx("input",{type:"number",value:P,onChange:L=>T(L.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"})]})]}),i.jsx("div",{className:"mt-4 flex items-end justify-between",children:i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),i.jsx("div",{className:"flex gap-1",children:Object.keys(Vv).map(L=>{const F=Vv[L];return i.jsx("button",{type:"button",onClick:()=>G(L),className:`p-2 rounded-lg transition-colors ${R===L?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:i.jsx(F,{className:"w-4 h-4"})},L)})})]})}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),i.jsx("input",{type:"url",value:z,onChange:L=>Z(L.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/..."})]}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:he.map(L=>i.jsx("button",{type:"button",onClick:()=>ce(L.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${I.has(L.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:L.name},L.id))}),I.size===0&&i.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),i.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:()=>{N(!1),J(new Set)},children:m("common.cancel")}),i.jsx(ze,{type:"submit",disabled:!C.trim()||I.size===0,children:m("maintenance.addType")})]})]})})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[xe.map(L=>{const F=g0(L.icon),te=L.interval_type||"hours";return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:i.jsx(F,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[te==="days"?i.jsx(Xr,{className:"w-3 h-3"}):i.jsx(Sd,{className:"w-3 h-3"}),XD(L.default_interval_hours,te,m)]})]}),i.jsx("button",{onClick:()=>{d("maintenance:delete")&&de(L)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(nn,{className:"w-4 h-4"})})]})},L.id)}),oe.map(L=>{const F=g0(L.icon),te=L.interval_type||"hours";if(se?.id===L.id)return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx("input",{type:"text",value:Te,onChange:we=>q(we.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:m("common.name"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("select",{value:E,onChange:we=>U(we.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:[i.jsx("option",{value:"hours",children:m("maintenance.printHours")}),i.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:X,onChange:we=>j(we.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"})]}),i.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(Vv).map(we=>{const Fe=Vv[we];return i.jsx("button",{type:"button",onClick:()=>H(we),className:`p-1.5 rounded transition-colors ${K===we?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:i.jsx(Fe,{className:"w-3.5 h-3.5"})},we)})}),i.jsx("input",{type:"url",value:re,onChange:we=>O(we.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:m("maintenance.documentationLink")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{size:"sm",onClick:ee,disabled:!Te.trim(),children:m("common.save")}),i.jsx(ze,{size:"sm",variant:"secondary",onClick:()=>pe(null),children:m("common.cancel")})]})]})},L.id);const fe=V(L.id),me=ne(L.id),je=ae===L.id;return i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:i.jsx(F,{className:"w-5 h-5 text-bambu-green"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:m("maintenance.custom")})]}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[te==="days"?i.jsx(Xr,{className:"w-3 h-3"}):i.jsx(Sd,{className:"w-3 h-3"}),XD(L.default_interval_hours,te,m)]})]}),i.jsxs("button",{onClick:()=>Y(je?null:L.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${fe.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:m("maintenance.printersAssignedClick",{count:fe.length}),children:[i.jsx(_r,{className:"w-3 h-3"}),i.jsx("span",{className:"text-xs font-medium",children:fe.length}),i.jsx(In,{className:`w-3 h-3 transition-transform ${je?"rotate-180":""}`})]}),i.jsx("button",{onClick:()=>$(L),disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:m("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${d("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Pf,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:L.name}))&&s(L.id)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(nn,{className:"w-4 h-4"})})]}),je&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),fe.length===0?i.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):i.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:fe.map(we=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[we.printerName,i.jsx("button",{onClick:()=>we.itemId&&u(we.itemId),disabled:!d("maintenance:delete"),title:d("maintenance:delete")?m("maintenance.removeFromPrinter"):m("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${d("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},we.printerId))}),me.length>0&&i.jsxs("div",{className:"flex flex-wrap gap-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),me.map(we=>i.jsxs("button",{onClick:()=>c(we.id,L.id),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:m("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${d("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",we.name]},we.id))]})]})]},L.id)})]})]}),be.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"mb-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),i.jsx("div",{className:"space-y-4",children:be.map(L=>i.jsx(Pt,{children:i.jsxs(Et,{className:"py-4",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:L.printerName}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:L.items.map(F=>{const te=g0(F.maintenance_type_icon),ve=e.find(Fe=>Fe.id===F.maintenance_type_id),fe=ve?.default_interval_hours||F.interval_hours,me=ve?.interval_type||"hours",je=F.interval_type||"hours",we=p===F.id;return i.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[i.jsx(te,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:F.maintenance_type_name}),we?i.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?i.jsx(Xr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):i.jsx(Sd,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),i.jsxs("select",{value:b,onChange:Fe=>g(Fe.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[i.jsx("option",{value:"hours",children:m("maintenance.printHours")}),i.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:y,onChange:Fe=>v(Fe.target.value),onKeyDown:Fe=>{Fe.key==="Enter"&&W(F.id,fe,me),Fe.key==="Escape"&&f(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),i.jsx(ze,{size:"sm",onClick:()=>W(F.id,fe,me),children:"OK"})]}):i.jsxs("button",{onClick:()=>{d("maintenance:update")&&(f(F.id),v(F.interval_hours.toString()),g(je))},disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:m("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${d("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[je==="days"?i.jsx(Xr,{className:"w-3 h-3"}):i.jsx(Sd,{className:"w-3 h-3"}),XD(F.interval_hours,je,m),i.jsx(Pf,{className:"w-3 h-3 text-bambu-gray"})]})]},F.id)})})]})},L.printerId))})]}),be.length===0&&i.jsx(Pt,{children:i.jsxs(Et,{className:"text-center py-12",children:[i.jsx(Zn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),ue&&i.jsx(Nn,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:ue.name}),confirmText:m("common.delete"),cancelText:m("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(ue.id),de(null)},onCancel:()=>de(null)})]})}function stt(){const{t}=Dt(),e=sn(),{showToast:n}=bn(),{hasPermission:r}=Ar(),[a,s]=w.useState("status"),{data:o,isLoading:l}=et({queryKey:["maintenanceOverview"],queryFn:ge.getMaintenanceOverview}),{data:c}=et({queryKey:["maintenanceTypes"],queryFn:ge.getMaintenanceTypes}),u=gt({mutationFn:({id:P,notes:T})=>ge.performMaintenance(P,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:P=>{n(P.message,"error")}}),d=gt({mutationFn:({id:P,data:T})=>ge.updateMaintenanceItem(P,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:P=>{n(P.message,"error")}}),m=gt({mutationFn:({id:P,data:T})=>ge.updateMaintenanceType(P,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:P=>{n(P.message,"error")}}),p=gt({mutationFn:ge.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:P=>{n(P.message,"error")}}),f=gt({mutationFn:ge.restoreDefaultMaintenanceTypes,onSuccess:P=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:P.restored}))},onError:P=>{n(P.message,"error")}}),y=gt({mutationFn:({printerId:P,hours:T})=>ge.setPrinterHours(P,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:P=>{n(P.message,"error")}}),v=gt({mutationFn:({printerId:P,typeId:T})=>ge.assignMaintenanceType(P,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:P=>{n(P.message,"error")}}),b=gt({mutationFn:ge.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:P=>{n(P.message,"error")}}),g=P=>{u.mutate({id:P})},_=(P,T)=>{d.mutate({id:P,data:{enabled:T}})},N=(P,T)=>{y.mutate({printerId:P,hours:T})};if(l)return i.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})});const C=o?.reduce((P,T)=>P+T.due_count,0)||0,k=o?.reduce((P,T)=>P+T.warning_count,0)||0;return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),i.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:a==="status"?i.jsxs(i.Fragment,{children:[C>0&&i.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:C})}),C>0&&k>0&&" · ",k>0&&i.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:k})}),C===0&&k===0&&i.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),i.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),i.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),a==="status"?i.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((P,T)=>{const D=P.due_count*10+P.warning_count,A=T.due_count*10+T.warning_count;return D!==A?A-D:P.printer_name.localeCompare(T.printer_name)}).map(P=>i.jsx(itt,{overview:P,onPerform:g,onToggle:_,onSetHours:N,hasPermission:r,t},P.printer_id)):i.jsx(Pt,{children:i.jsxs(Et,{className:"text-center py-16",children:[i.jsx(Ef,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),i.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):i.jsx(att,{overview:o,types:c||[],onUpdateInterval:(P,T)=>d.mutate({id:P,data:T}),onAddType:async(P,T)=>{const D=await ge.createMaintenanceType(P);for(const A of T)await ge.assignMaintenanceType(A,D.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(P,T)=>m.mutate({id:P,data:T}),onDeleteType:P=>p.mutate(P),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(P,T)=>v.mutate({printerId:P,typeId:T}),onRemoveItem:P=>b.mutate(P),hasPermission:r,t})]})}const RY=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Woe({project:t,onClose:e,onSave:n,isLoading:r,currencySymbol:a,t:s}){const[o,l]=w.useState(t?.name||""),[c,u]=w.useState(t?.description||""),[d,m]=w.useState(t?.color||RY[0]),[p,f]=w.useState(t?.target_count?.toString()||""),[y,v]=w.useState(t?.target_parts_count?.toString()||""),[b,g]=w.useState(t?.status||"active"),[_,N]=w.useState(t?.tags||""),[C,k]=w.useState(t?.due_date?.split("T")[0]||""),[P,T]=w.useState(t?.priority||"normal"),[D,A]=w.useState(t?.budget?.toString()||""),R=G=>{G.preventDefault(),n({name:o.trim(),description:c.trim()||void 0,color:d,target_count:p?parseInt(p,10):void 0,target_parts_count:y?parseInt(y,10):void 0,tags:_.trim()||void 0,due_date:C||void 0,priority:P,budget:D.trim()?parseFloat(D):null,...t&&{status:b}})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),i.jsxs("form",{onSubmit:R,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),i.jsx("input",{type:"text",value:o,onChange:G=>l(G.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:s("projects.namePlaceholder"),required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),i.jsx("textarea",{value:c,onChange:G=>u(G.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:s("projects.descriptionPlaceholder"),rows:2})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),i.jsx("div",{className:"flex gap-2 flex-wrap",children:RY.map(G=>i.jsx("button",{type:"button",onClick:()=>m(G),className:`w-8 h-8 rounded-full transition-transform ${d===G?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:G}},G))})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),i.jsx("input",{type:"number",value:p,onChange:G=>f(G.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:s("projects.targetPlatesPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),i.jsx("input",{type:"number",value:y,onChange:G=>v(G.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:s("projects.targetPartsPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),i.jsx("input",{type:"text",value:_,onChange:G=>N(G.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:s("projects.tagsPlaceholder")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),i.jsx("input",{type:"date",value:C,onChange:G=>k(G.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),i.jsxs("select",{value:P,onChange:G=>T(G.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:[i.jsx("option",{value:"low",children:s("projects.priorityLow")}),i.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),i.jsx("option",{value:"high",children:s("projects.priorityHigh")}),i.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),i.jsxs("div",{className:"relative",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:a}),i.jsx("input",{type:"number",step:"0.01",min:"0",value:D,onChange:G=>A(G.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded pl-8 pr-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"0.00"})]})]}),t&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),i.jsxs("select",{value:b,onChange:G=>g(G.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:[i.jsx("option",{value:"active",children:s("projects.statusActive")}),i.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),i.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(ze,{type:"submit",disabled:!o.trim()||r,children:r?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function ott({project:t,onClick:e,onEdit:n,onDelete:r,hasPermission:a,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,m]=w.useState(!1),f=c?{icon:vc,color:"text-bambu-green",bg:"bg-bambu-green/10"}:u?{icon:Vs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Zn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:vs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return i.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:[i.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`}}),i.jsxs("div",{className:"p-5 pl-6",children:[i.jsxs("div",{className:"flex items-start justify-between mb-4",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:i.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?i.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?i.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?i.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&&i.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&&i.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&&i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const y=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(Boolean),v=[...new Set(y)],b=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),g=[...new Set(b)];return v.length===0&&g.length===0?null:i.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>i.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),g.length>0&&i.jsxs("div",{className:"flex items-center gap-0.5",children:[g.slice(0,5).map(_=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),g.length>5&&i.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",g.length-5]})]})]})})()]})]}),i.jsxs("div",{className:"relative",onClick:y=>y.stopPropagation(),children:[i.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:()=>m(!d),children:i.jsx(Nh,{className:"w-4 h-4"})}),d&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),i.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:[i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:update")&&(n(),m(!1))},disabled:!a("projects:update"),title:a("projects:update")?void 0:s("projects.noEditPermission"),children:[i.jsx(Pf,{className:"w-4 h-4"}),s("common.edit")]}),i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:delete")&&(r(),m(!1))},disabled:!a("projects:delete"),title:a("projects:delete")?void 0:s("projects.noDeletePermission"),children:[i.jsx(nn,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),i.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?i.jsxs("div",{className:"space-y-3",children:[t.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),i.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.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&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),i.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.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&&i.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?i.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(Vs,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[i.jsx(jn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[i.jsx(Zn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):i.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&i.jsxs("div",{className:"mb-4",children:[i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(y=>i.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:y.print_name||"Unknown",children:[y.thumbnail_path?i.jsx("img",{src:ge.getArchiveThumbnail(y.id),alt:y.print_name||"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:i.jsx(Wi,{className:"w-6 h-6"})}),y.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:i.jsx(jn,{className:"w-4 h-4 text-white"})})]},y.id))}),t.archive_count>4&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),i.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[i.jsx(Gi,{className:"w-3.5 h-3.5 text-blue-400"}),i.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[i.jsx(Wi,{className:"w-3.5 h-3.5 text-bambu-green"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[i.jsx(jn,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[i.jsx(_3,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.queue_count})]})]}),i.jsx(fa,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function ltt(){const{t}=Dt(),e=ol(),n=sn(),{showToast:r}=bn(),{hasPermission:a}=Ar(),[s,o]=w.useState(!1),[l,c]=w.useState(),[u,d]=w.useState("active"),[m,p]=w.useState(null),{data:f}=et({queryKey:["settings"],queryFn:ge.getSettings}),y=Wo(f?.currency||"USD"),{data:v,isLoading:b}=et({queryKey:["projects",u==="all"?void 0:u],queryFn:()=>ge.getProjects(u==="all"?void 0:u)}),g=gt({mutationFn:J=>ge.createProject(J),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:J=>{r(J.message,"error")}}),_=gt({mutationFn:({id:J,data:ae})=>ge.updateProject(J,ae),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:J=>{r(J.message,"error")}}),N=gt({mutationFn:J=>ge.deleteProject(J),onSuccess:()=>{p(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:J=>{p(null),r(J.message,"error")}}),C=gt({mutationFn:J=>ge.importProject(J),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:J=>{r(J.message,"error")}}),k=w.useRef(null),P=async()=>{try{const J=await ge.getProjects(),ae=await Promise.all(J.map(async he=>await ge.exportProjectJson(he.id))),Y=new Blob([JSON.stringify(ae,null,2)],{type:"application/json"}),ue=URL.createObjectURL(Y),de=document.createElement("a");de.href=ue,de.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,de.click(),URL.revokeObjectURL(ue),r(t("projects.toast.exported"),"success")}catch(J){r(J.message,"error")}},T=()=>{k.current?.click()},D=async J=>{const ae=J.target.files?.[0];if(ae){try{if(ae.name.toLowerCase().endsWith(".zip"))await ge.importProjectFile(ae),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const ue=await ae.text(),de=JSON.parse(ue),he=Array.isArray(de)?de:[de];for(const V of he)await C.mutateAsync(V);he.length>1&&r(t("projects.toast.multipleImported",{count:he.length}),"success")}}catch(Y){r(`${t("projects.toast.importFailed")}: ${Y.message}`,"error")}J.target.value=""}},A=J=>{l?_.mutate({id:l.id,data:J}):g.mutate(J)},R=J=>{c(J),o(!0)},G=J=>{e(`/projects/${J.id}`)},z=J=>{p(J)},Z=()=>{m!==null&&N.mutate(m)},I=v?.reduce((J,ae)=>(J[ae.status]=(J[ae.status]||0)+1,J.all=(J.all||0)+1,J),{})||{};return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsx("input",{ref:k,type:"file",accept:".json,.zip",onChange:D,className:"hidden"}),i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(vs,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(ze,{variant:"secondary",onClick:T,disabled:!a("projects:create"),title:a("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[i.jsx(yi,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),i.jsxs(ze,{variant:"secondary",onClick:P,disabled:!a("projects:read"),title:a("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[i.jsx(fi,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),i.jsxs(ze,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(ir,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),i.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Zn},{key:"completed",label:t("projects.statusCompleted"),icon:vc},{key:"archived",label:t("projects.statusArchived"),icon:Vs},{key:"all",label:t("common.all"),icon:vs}].map(({key:J,label:ae,icon:Y})=>i.jsxs("button",{onClick:()=>d(J),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===J?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Y,{className:"w-4 h-4"}),i.jsx("span",{children:ae}),I[J]>0&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===J?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:I[J]})]},J))}),b?i.jsx("div",{className:"flex items-center justify-center py-20",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(vs,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:u==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:u})}),i.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"&&i.jsxs(ze,{onClick:()=>o(!0),disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(ir,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(J=>i.jsx(ott,{project:J,onClick:()=>G(J),onEdit:()=>R(J),onDelete:()=>z(J.id),hasPermission:a,t},J.id))}),m!==null&&i.jsx(Nn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:Z,onCancel:()=>p(null)}),s&&i.jsx(Woe,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:A,isLoading:g.isPending||_.isPending,currencySymbol:y,t})]})}function ctt(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function utt({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,a={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return i.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:a[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function FY({icon:t,label:e,value:n,subValue:r,hint:a,color:s="text-bambu-gray"}){return i.jsx(Pt,{children:i.jsx(Et,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",title:a,children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function dtt({archives:t,t:e}){return t.length===0?i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(Wi,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),i.jsx("p",{children:e("projectDetail.noPrints")})]}):i.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=>i.jsxs(fo,{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?i.jsx("img",{src:ge.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:i.jsx(Wi,{className:"w-8 h-8"})}),n.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:i.jsx(Vi,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&i.jsx("div",{className:"absolute top-1 right-1",children:i.jsx(pr,{className:"w-4 h-4 text-bambu-green"})}),i.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:i.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function mtt({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:a}=n[t]||n.normal;return i.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&i.jsx(jn,{className:"w-3 h-3"}),a]})}function QD(t,e){if(!t)return null;const n=Qn(t);if(!n)return null;const r=new Date,a=Math.ceil((n.getTime()-r.getTime())/(1e3*60*60*24));return a<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:a===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:a<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:a})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:a})}}function htt(){const{id:t}=gw(),e=ol(),{t:n}=Dt(),r=sn(),{showToast:a}=bn(),{hasPermission:s}=Ar(),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,m]=w.useState(""),p=parseInt(t||"0",10),{data:f,isLoading:y,error:v}=et({queryKey:["project",p],queryFn:()=>ge.getProject(p),enabled:p>0}),{data:b,isLoading:g}=et({queryKey:["project-archives",p],queryFn:()=>ge.getProjectArchives(p),enabled:p>0}),{data:_,isLoading:N}=et({queryKey:["project-bom",p],queryFn:()=>ge.getProjectBOM(p),enabled:p>0}),{data:C,isLoading:k}=et({queryKey:["project-timeline",p],queryFn:()=>ge.getProjectTimeline(p,20),enabled:p>0}),{data:P}=et({queryKey:["settings"],queryFn:ge.getSettings}),{data:T}=et({queryKey:["project-folders",p],queryFn:()=>ge.getLibraryFoldersByProject(p),enabled:p>0}),D=Wo(P?.currency||"USD"),A=P?.time_format||"system",R=gt({mutationFn:Me=>ge.updateProject(p,Me),onSuccess:()=>{r.invalidateQueries({queryKey:["project",p]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),a(n("projectDetail.toast.projectUpdated"),"success")},onError:Me=>{a(Me.message,"error")}}),G=()=>{m(f?.notes||""),u(!0)},z=()=>{R.mutate({notes:d})},Z=()=>{u(!1),m("")},[I,J]=w.useState(""),[ae,Y]=w.useState(1),[ue,de]=w.useState(""),[he,V]=w.useState(""),[ne,se]=w.useState(""),[pe,Te]=w.useState(!1),[q,X]=w.useState(!1),[j,E]=w.useState(null),[U,K]=w.useState(""),[H,re]=w.useState(1),[O,$]=w.useState(""),[ee,W]=w.useState(""),[ie,ce]=w.useState(""),[be,xe]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),oe=gt({mutationFn:Me=>ge.createBOMItem(p,Me),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),J(""),Y(1),de(""),V(""),se(""),Te(!1),a(n("projectDetail.toast.partAdded"),"success")},onError:Me=>a(Me.message,"error")}),L=gt({mutationFn:({itemId:Me,data:Xe})=>ge.updateBOMItem(p,Me,Xe),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),E(null)},onError:Me=>a(Me.message,"error")}),F=gt({mutationFn:Me=>ge.deleteBOMItem(p,Me),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),a(n("projectDetail.toast.partRemoved"),"success")},onError:Me=>a(Me.message,"error")}),te=Me=>{Me.preventDefault(),I.trim()&&oe.mutate({name:I.trim(),quantity_needed:ae,unit_price:ue?parseFloat(ue):void 0,sourcing_url:he.trim()||void 0,remarks:ne.trim()||void 0})},ve=Me=>{const Xe=Me.is_complete?0:Me.quantity_needed;L.mutate({itemId:Me.id,data:{quantity_acquired:Xe}})},fe=(Me,Xe)=>{xe({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Xe}),onConfirm:()=>{xe(ye=>({...ye,isOpen:!1})),F.mutate(Me)}})},me=Me=>{E(Me),K(Me.name),re(Me.quantity_needed),$(Me.unit_price?.toString()||""),W(Me.sourcing_url||""),ce(Me.remarks||"")},je=Me=>{Me.preventDefault(),!(!j||!U.trim())&&L.mutate({itemId:j.id,data:{name:U.trim(),quantity_needed:H,unit_price:O?parseFloat(O):void 0,sourcing_url:ee.trim()||void 0,remarks:ie.trim()||void 0}})},we=()=>{E(null)},Fe=async()=>{try{const{blob:Me,filename:Xe}=await ge.exportProjectZip(Number(p)),ye=URL.createObjectURL(Me),We=document.createElement("a");We.href=ye,We.download=Xe||`${f?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,We.click(),URL.revokeObjectURL(ye),a(n("projectDetail.toast.projectExported"),"success")}catch(Me){a(Me.message,"error")}},He=gt({mutationFn:()=>ge.createTemplateFromProject(p),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),a(n("projectDetail.toast.templateCreated"),"success")},onError:Me=>a(Me.message,"error")}),Oe=Me=>Df(Me,A,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(y)return i.jsx("div",{className:"flex items-center justify-center py-24",children:i.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!f)return i.jsxs("div",{className:"text-center py-24",children:[i.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),i.jsx(ze,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const _e=f.stats,Ae=_e?.progress_percent??0,Be=_e?.parts_progress_percent??0;return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(fo,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),i.jsx(fa,{className:"w-4 h-4"}),i.jsx("span",{className:"text-white",children:f.name})]}),i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:i.jsx($X,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:f.color||"#6b7280"}}),i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:f.name}),f.description&&i.jsx("p",{className:"text-bambu-gray mt-1",children:f.description})]})]}),i.jsx(utt,{status:f.status,t:n})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(ze,{variant:"secondary",onClick:Fe,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[i.jsx(fi,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),i.jsxs(ze,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[i.jsx(Pf,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(f.target_count||f.target_parts_count)&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4 space-y-4",children:[f.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[_e?.total_archives||0," / ",f.target_count," ",n("projectDetail.progress.printJobs")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ae,100)}%`,backgroundColor:Ae>=100?"#22c55e":f.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Ae.toFixed(0)})}),_e?.remaining_prints!=null&&_e.remaining_prints>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:_e.remaining_prints})})]})]}),f.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[_e?.completed_prints||0," / ",f.target_parts_count," ",n("projectDetail.progress.parts")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Be,100)}%`,backgroundColor:Be>=100?"#22c55e":f.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Be.toFixed(0)})}),_e?.remaining_parts!=null&&_e.remaining_parts>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:_e.remaining_parts})})]})]})]})}),_e&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(Pt,{children:i.jsx(Et,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:i.jsx(Wi,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),i.jsxs("p",{className:"text-xl font-semibold text-white",children:[_e.total_archives," ",i.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),_e.failed_prints>0&&i.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:_e.failed_prints})}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:_e.completed_prints})})]})]})})}),i.jsx(FY,{icon:Zn,label:n("projectDetail.stats.printTime"),value:axe(_e.total_print_time_hours),color:"text-yellow-400"}),i.jsx(FY,{icon:_r,label:n("projectDetail.stats.filamentUsed"),value:ctt(_e.total_filament_grams),color:"text-purple-400"})]}),_e&&(()=>{const Me=_e.estimated_cost+_e.total_energy_cost+_e.bom_cost;return _e.estimated_cost>0||Me>0||f.budget!==null})()&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[D,_e.estimated_cost.toFixed(2)]})]}),_e.total_energy_kwh>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[_e.total_energy_kwh.toFixed(3)," kWh",_e.total_energy_cost>0&&i.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",D,_e.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const Me=_e.estimated_cost+_e.total_energy_cost+_e.bom_cost;return Me<=0?null:i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),i.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[D,Me.toFixed(2)]}),_e.bom_cost>0&&i.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),f.budget!==null&&(()=>{const Me=_e.estimated_cost+_e.total_energy_cost+_e.bom_cost,Xe=f.budget-Me;return i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",i.jsxs("span",{className:"text-white font-semibold",children:[D,f.budget.toFixed(2)]})]}),i.jsxs("p",{className:`text-sm ${Xe>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",i.jsxs("span",{className:"font-semibold",children:[D,Xe.toFixed(2)]})]})]})})()]})]})}),f.children&&f.children.length>0&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[i.jsx(tfe,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:f.children.length})]}),i.jsx("div",{className:"space-y-2",children:f.children.map(Me=>i.jsxs(fo,{to:`/projects/${Me.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Me.color||"#6b7280"}}),i.jsx("span",{className:"text-white",children:Me.name}),i.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${Me.status==="completed"?"bg-status-ok/20 text-status-ok":Me.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:Me.status})]}),Me.progress_percent!==null&&i.jsxs("span",{className:"text-sm text-bambu-gray",children:[Me.progress_percent.toFixed(0),"%"]})]},Me.id))})]})}),f.parent_id&&f.parent_name&&i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Gi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),i.jsx(fo,{to:`/projects/${f.parent_id}`,className:"text-bambu-green hover:underline",children:f.parent_name})]}),(f.tags||f.due_date||f.priority!=="normal")&&i.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[f.priority&&f.priority!=="normal"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),i.jsx(mtt,{priority:f.priority,t:n})]}),f.due_date&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Xr,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-sm text-white",children:jf(f.due_date,{year:"numeric",month:"short",day:"numeric"})}),QD(f.due_date,n)&&i.jsxs("span",{className:`text-xs ${QD(f.due_date,n).color}`,children:["(",QD(f.due_date,n).label,")"]})]}),f.tags&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Hd,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:f.tags.split(",").map((Me,Xe)=>i.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:Me.trim()},Xe))})]})]}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Bs,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(ze,{variant:"secondary",size:"sm",onClick:Z,disabled:R.isPending,children:[i.jsx(Ht,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),i.jsxs(ze,{size:"sm",onClick:z,disabled:R.isPending,children:[R.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin mr-1"}):i.jsx(as,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):i.jsxs(ze,{variant:"secondary",size:"sm",onClick:G,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[i.jsx(Pf,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?i.jsx(bL,{content:d,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):f.notes?i.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:yie.sanitize(f.notes)}}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ac,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),i.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[i.jsx(fo,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),T&&T.length>0?i.jsx("div",{className:"space-y-2",children:T.map(Me=>i.jsxs(fo,{to:`/files?folder=${Me.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx(Ac,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:Me.name}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:Me.file_count})})]})]}),i.jsx(fa,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},Me.id))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(tQ,{className:"w-5 h-5"}),n("projectDetail.bom.title"),_e&&_e.bom_total_items>0&&i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:_e.bom_completed_items,total:_e.bom_total_items}),")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[_&&_.some(Me=>Me.is_complete)&&i.jsx("button",{onClick:()=>X(!q),className:`text-xs px-2 py-1 rounded transition-colors ${q?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(q?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!pe&&i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>Te(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[i.jsx(ir,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),pe&&i.jsxs("form",{onSubmit:te,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:I,onChange:Me=>J(Me.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}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:ae,onChange:Me=>Y(parseInt(Me.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")}),i.jsx("input",{type:"number",step:"0.01",value:ue,onChange:Me=>de(Me.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:D})})]})]}),i.jsx("input",{type:"url",value:he,onChange:Me=>V(Me.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")}),i.jsx("input",{type:"text",value:ne,onChange:Me=>se(Me.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")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(ze,{type:"button",variant:"secondary",size:"sm",onClick:()=>Te(!1),children:n("common.cancel")}),i.jsx(ze,{type:"submit",size:"sm",disabled:!I.trim()||oe.isPending,children:oe.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),N?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):_&&_.length>0?i.jsxs("div",{className:"space-y-2",children:[_.filter(Me=>!q||!Me.is_complete).map(Me=>i.jsx("div",{className:`p-3 rounded-lg transition-colors ${Me.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:j?.id===Me.id?i.jsxs("form",{onSubmit:je,className:"space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:U,onChange:Xe=>K(Xe.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}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:H,onChange:Xe=>re(parseInt(Xe.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")}),i.jsx("input",{type:"number",step:"0.01",value:O,onChange:Xe=>$(Xe.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:D})})]})]}),i.jsx("input",{type:"url",value:ee,onChange:Xe=>W(Xe.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")}),i.jsx("input",{type:"text",value:ie,onChange:Xe=>ce(Xe.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")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(ze,{type:"button",variant:"secondary",size:"sm",onClick:we,children:n("common.cancel")}),i.jsx(ze,{type:"submit",size:"sm",disabled:!U.trim()||L.isPending,children:L.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("button",{onClick:()=>s("projects:update")&&ve(Me),disabled:L.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 ${Me.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:Me.is_complete&&i.jsx(pr,{className:"w-3 h-3"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsxs("p",{className:`text-sm font-medium ${Me.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[Me.name,i.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",Me.quantity_needed]})]}),Me.unit_price!==null&&i.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[D,(Me.unit_price*Me.quantity_needed).toFixed(2)]})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>s("projects:update")&&me(Me),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:i.jsx(Yi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("projects:update")&&fe(Me.id,Me.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:i.jsx(nn,{className:"w-4 h-4"})})]})]}),Me.sourcing_url&&i.jsxs("a",{href:Me.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:Xe=>Xe.stopPropagation(),children:[i.jsx(ni,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"truncate",children:(()=>{try{return new URL(Me.sourcing_url).hostname.replace("www.","")}catch{return Me.sourcing_url}})()})]}),Me.remarks&&i.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:Me.remarks})]})]})},Me.id)),_e&&_e.bom_cost>0&&i.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),i.jsxs("span",{className:"text-white font-medium",children:[D,_e.bom_cost.toFixed(2)]})]})]}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(_0,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),k?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):C&&C.length>0?i.jsx("div",{className:"space-y-3",children:C.slice(0,10).map((Me,Xe)=>i.jsxs("div",{className:"flex gap-3",children:[i.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${Me.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":Me.event_type==="print_failed"?"bg-status-error/20 text-status-error":Me.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Me.event_type==="print_completed"&&i.jsx(pr,{className:"w-4 h-4"}),Me.event_type==="print_failed"&&i.jsx(Vi,{className:"w-4 h-4"}),Me.event_type==="print_started"&&i.jsx(_r,{className:"w-4 h-4"}),Me.event_type==="queued"&&i.jsx(_3,{className:"w-4 h-4"}),Me.event_type==="project_created"&&i.jsx(ir,{className:"w-4 h-4"})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white",children:Me.title}),Me.description&&i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Me.description}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:Oe(Me.timestamp)})]})]},Xe))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!f.is_template&&i.jsx("div",{className:"flex justify-end",children:i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>He.mutate(),disabled:He.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[He.isPending?i.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(ko,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),_e&&(_e.queued_prints>0||_e.in_progress_prints>0)&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(_3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),i.jsx(fo,{to:`/queue?project=${p}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[_e.in_progress_prints>0&&i.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:_e.in_progress_prints})}),_e.queued_prints>0&&i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:_e.queued_prints})})]})]})}),i.jsxs("div",{children:[i.jsx("div",{className:"flex items-center justify-between mb-4",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Wi,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:b?.length||0})]})}),g?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):i.jsx(dtt,{archives:b||[],t:n})]}),o&&i.jsx(Woe,{t:n,currencySymbol:D,project:{...f,archive_count:_e?.total_archives||0,total_items:_e?.total_items||0,completed_count:_e?.completed_prints||0,failed_count:_e?.failed_prints||0,queue_count:_e?.queued_prints||0,progress_percent:_e?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:Me=>R.mutate(Me),isLoading:R.isPending}),be.isOpen&&i.jsx(Nn,{title:be.title,message:be.message,confirmText:n("common.delete"),variant:"danger",onConfirm:be.onConfirm,onCancel:()=>xe(Me=>({...Me,isOpen:!1}))})]})}function ptt({parentId:t,onClose:e,onSave:n,isLoading:r,t:a}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("fileManager.newFolder")})}),i.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.folderName")}),i.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:a("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(ze,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):a("common.create")})]})]})]})})}function ftt({type:t,currentName:e,onClose:n,onSave:r,isLoading:a,t:s}){const o=t==="file"?e.match(/(\.gcode\.3mf|\.3mf|\.gcode)$/i)?.[1]??"":"",l=t==="file"&&o?e.slice(0,-o.length):e,[c,u]=w.useState(l),d=m=>{m.preventDefault();const p=t==="file"?c.trim()+o:c.trim();c.trim()&&p!==e&&r(p)};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),i.jsxs("form",{onSubmit:d,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),i.jsxs("div",{className:"flex items-center bg-bambu-dark border border-bambu-dark-tertiary rounded focus-within:border-bambu-green",children:[i.jsx("input",{type:"text",value:c,onChange:m=>u(m.target.value),className:"flex-1 bg-transparent px-3 py-2 text-white placeholder-bambu-gray focus:outline-none min-w-0",autoFocus:!0,required:!0}),o&&i.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),i.jsx(ze,{type:"submit",disabled:!c.trim()||c.trim()===l||a,children:a?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function gtt({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:a,isLoading:s,t:o}){const[l,c]=w.useState(null),u=(m,p=0)=>{const f=[];for(const y of m)f.push({id:y.id,name:y.name,depth:p}),y.children.length>0&&f.push(...u(y.children,p+1));return f},d=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...u(t)];return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:d.map(m=>i.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[i.jsx(Ac,{className:"w-4 h-4"}),m.name,m.id===n&&i.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(ze,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),i.jsx(ze,{onClick:()=>a(l),disabled:s,children:s?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function btt({folder:t,onClose:e,onLink:n,isLoading:r,t:a}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:u}=et({queryKey:["projects"],queryFn:()=>ge.getProjects()}),{data:d}=et({queryKey:["archives-for-link"],queryFn:()=>ge.getArchives(void 0,void 0,100)}),m=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ah,{className:"w-5 h-5 text-bambu-green"}),a("fileManager.linkFolder")]}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("fileManager.linkFolderDescription",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.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:[i.jsx(qX,{className:"w-4 h-4"}),a("fileManager.project")]}),i.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:[i.jsx(Vs,{className:"w-4 h-4"}),a("fileManager.archive")]})]}),i.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(y=>i.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:y.color||"#00ae42"}}),i.jsx("span",{className:"truncate",children:y.name})]},y.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noProjectsFound")}):d&&d.length>0?d.map(y=>i.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx(mf,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"truncate",children:y.print_name||y.filename})]},y.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noArchivesFound")})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&i.jsxs(ze,{variant:"danger",onClick:p,disabled:r,children:[i.jsx(N0,{className:"w-4 h-4 mr-2"}),a("fileManager.unlink")]}),i.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[i.jsx(ze,{variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(ze,{onClick:m,disabled:!l||r,children:r?i.jsx(ft,{className:"w-4 h-4 animate-spin"}):a("fileManager.link")})]})]})]})})}function Koe({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:u}){const[d,m]=w.useState(!0),[p,f]=w.useState(!1),y=t.children.length>0,v=t.project_id||t.archive_id;return i.jsxs("div",{children:[i.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:[y?i.jsx("button",{onClick:b=>{b.stopPropagation(),m(!d)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(fa,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-90":""}`})}):i.jsx("div",{className:"w-4.5"}),i.jsx(Ac,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),i.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&i.jsxs("button",{onClick:b=>{b.stopPropagation(),a(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:[i.jsx(Ah,{className:"w-3 h-3"}),t.project_name?i.jsx(qX,{className:"w-3 h-3"}):i.jsx(Vs,{className:"w-3 h-3"})]}),t.file_count>0&&i.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&i.jsx("button",{onClick:b=>{b.stopPropagation(),a(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:i.jsx(Ah,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),i.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:b=>b.stopPropagation(),children:i.jsxs("div",{className:"relative",children:[i.jsx("button",{onClick:()=>f(!p),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:i.jsx(Nh,{className:"w-3.5 h-3.5 text-bambu-gray"})}),p&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>f(!1)}),i.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:[i.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),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[i.jsx(Yi,{className:"w-3.5 h-3.5"}),u("common.rename")]}),i.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")&&(a(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[i.jsx(Ah,{className:"w-3.5 h-3.5"}),u(v?"fileManager.changeLink":"fileManager.linkTo")]}),i.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),f(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[i.jsx(nn,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),y&&d&&i.jsx("div",{children:t.children.map(b=>i.jsx(Koe,{folder:b,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},b.id))})]})}function kL(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function xtt({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:a,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:u,onGenerateThumbnail:d,thumbnailVersion:m,hasPermission:p,canModify:f,authEnabled:y,t:v}){const[b,g]=w.useState(!1);return i.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:[i.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?i.jsx("img",{src:`${ge.getLibraryFileThumbnailUrl(t.id)}${m?`?v=${m}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):i.jsx(mf,{className:"w-12 h-12 text-bambu-gray/30"}),i.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()})]}),i.jsxs("div",{className:"p-3",children:[i.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),i.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[i.jsx("span",{children:xo(t.file_size)}),t.print_time_seconds&&i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Zn,{className:"w-3 h-3"}),Us(t.print_time_seconds)]})]}),t.sliced_for_model&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(_r,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&i.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),y&&t.created_by_username&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx($d,{className:"w-3 h-3"}),t.created_by_username]})]}),i.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[i.jsx("button",{onClick:()=>g(!b),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:i.jsx(Nh,{className:"w-4 h-4 text-bambu-gray"})}),b&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),i.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&&kL(t.filename)&&i.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),g(!1))},disabled:!p("printers:control"),title:p("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[i.jsx(_r,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&kL(t.filename)&&i.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),g(!1))},disabled:!p("queue:create"),title:p("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[i.jsx(Zn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&i.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),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:"You do not have permission to preview files",children:[i.jsx(ia,{className:"w-3.5 h-3.5"}),"3D Preview"]}),i.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),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[i.jsx(fi,{className:"w-3.5 h-3.5"}),v("common.download")]}),u&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(u(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[i.jsx(Yi,{className:"w-3.5 h-3.5"}),v("common.rename")]}),d&&t.file_type==="stl"&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(d(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[i.jsx(Ud,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","delete",t.created_by_id)&&(a(t.id),g(!1))},disabled:!f("library","delete",t.created_by_id),title:f("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[i.jsx(nn,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),i.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&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function ytt(){const{t}=Dt(),e=sn(),{showToast:n}=bn(),{hasPermission:r,hasAnyPermission:a,canModify:s,authEnabled:o}=Ar(),[l]=LL(),c=l.get("folder"),u=c?parseInt(c,10):null,[d,m]=w.useState(u),[p,f]=w.useState([]),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,N]=w.useState(!1),[C,k]=w.useState(null),[P,T]=w.useState(null),[D,A]=w.useState(null),[R,G]=w.useState(null),[z,Z]=w.useState(null),[I,J]=w.useState(null),[ae,Y]=w.useState({}),[ue,de]=w.useState(null),[he,V]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[ne,se]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[pe,Te]=w.useState(()=>{const qe=localStorage.getItem("library-sidebar-width");return qe?parseInt(qe,10):256}),[q,X]=w.useState(!1),j=w.useRef(null);w.useEffect(()=>{if(!q)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const qe=_t=>{if(!j.current)return;const rt=j.current.parentElement?.getBoundingClientRect();if(!rt)return;const Rt=_t.clientX-rt.left,qt=Math.min(500,Math.max(200,Rt));Te(qt)},Nt=()=>{X(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(pe))};return document.addEventListener("mousemove",qe),document.addEventListener("mouseup",Nt),()=>{document.removeEventListener("mousemove",qe),document.removeEventListener("mouseup",Nt),document.body.style.userSelect="",document.body.style.cursor=""}},[q,pe]);const[E,U]=w.useState(""),[K,H]=w.useState("all"),[re,O]=w.useState(""),[$,ee]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[W,ie]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),ce=uie();w.useEffect(()=>{const qe=l.get("folder");if(qe){const Nt=parseInt(qe,10);m(Nt)}},[l]);const{data:be}=et({queryKey:["settings"],queryFn:()=>ge.getSettings()}),{data:xe,isLoading:oe}=et({queryKey:["library-folders"],queryFn:()=>ge.getLibraryFolders()}),{data:L,isLoading:F}=et({queryKey:["library-files",d],queryFn:()=>ge.getLibraryFiles(d,d===null)}),{data:te}=et({queryKey:["library-stats"],queryFn:()=>ge.getLibraryStats()}),{data:ve}=et({queryKey:["users"],queryFn:()=>ge.getUsers()}),fe=w.useMemo(()=>{if(!L)return[];const qe=new Set(L.map(Nt=>Nt.file_type));return Array.from(qe).sort()},[L]),me=w.useMemo(()=>{if(!L)return[];let qe=[...L];if(E.trim()){const Nt=E.toLowerCase();qe=qe.filter(_t=>_t.filename.toLowerCase().includes(Nt)||_t.print_name&&_t.print_name.toLowerCase().includes(Nt))}if(K!=="all"&&(qe=qe.filter(Nt=>Nt.file_type===K)),re.trim()){const Nt=re.toLowerCase();qe=qe.filter(_t=>_t.created_by_username&&_t.created_by_username.toLowerCase().includes(Nt))}return qe.sort((Nt,_t)=>{let rt=0;switch($){case"name":rt=(Nt.print_name||Nt.filename).localeCompare(_t.print_name||_t.filename);break;case"date":rt=(Qn(Nt.created_at)?.getTime()??0)-(Qn(_t.created_at)?.getTime()??0);break;case"size":rt=Nt.file_size-_t.file_size;break;case"type":rt=Nt.file_type.localeCompare(_t.file_type);break;case"prints":rt=Nt.print_count-_t.print_count;break}return W==="asc"?rt:-rt}),qe},[L,E,K,re,$,W]),je=w.useMemo(()=>{if(!te||!be)return!1;const qe=(be.library_disk_warning_gb||5)*1024*1024*1024;return te.disk_free_bytesge.createLibraryFolder(qe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:qe=>n(qe.message,"error")}),Fe=gt({mutationFn:qe=>ge.deleteLibraryFolder(qe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===P?.id&&m(null),T(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:qe=>{T(null),n(qe.message,"error")}}),He=gt({mutationFn:qe=>ge.deleteLibraryFile(qe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),f(qe=>qe.filter(Nt=>Nt!==P?.id)),T(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:qe=>{T(null),n(qe.message,"error")}}),Oe=gt({mutationFn:qe=>ge.bulkDeleteLibrary(qe,[]),onSuccess:(qe,Nt)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:Nt.length}),"success"),f([]),T(null)},onError:qe=>{T(null),n(qe.message,"error")}}),_e=gt({mutationFn:({fileIds:qe,folderId:Nt})=>ge.moveLibraryFiles(qe,Nt),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),f([]),g(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:qe=>n(qe.message,"error")}),Ae=gt({mutationFn:({id:qe,data:Nt})=>ge.updateLibraryFolder(qe,Nt),onSuccess:(qe,Nt)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),k(null);const _t=Nt.data.project_id===0&&Nt.data.archive_id===0;n(t(_t?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:qe=>n(qe.message,"error")}),Be=gt({mutationFn:({id:qe,filename:Nt})=>ge.updateLibraryFile(qe,{filename:Nt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),J(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:qe=>{J(null),n(qe.message,"error")}}),Me=gt({mutationFn:({id:qe,name:Nt})=>ge.updateLibraryFolder(qe,{name:Nt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),J(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:qe=>{J(null),n(qe.message,"error")}}),Xe=gt({mutationFn:()=>ge.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:qe=>{if(e.invalidateQueries({queryKey:["library-files"]}),qe.succeeded>0){const Nt=Date.now(),_t={};qe.results.forEach(rt=>{rt.success&&(_t[rt.file_id]=Nt)}),Y(rt=>({...rt,..._t}))}qe.succeeded>0&&qe.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:qe.succeeded}),"success"):qe.succeeded>0&&qe.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:qe.succeeded,failed:qe.failed}),"success"):qe.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:qe.results[0]?.error||"Unknown error"}),"error")},onError:qe=>n(qe.message,"error")}),ye=gt({mutationFn:qe=>ge.batchGenerateStlThumbnails({file_ids:[qe]}),onSuccess:qe=>{if(e.invalidateQueries({queryKey:["library-files"]}),qe.succeeded>0){const Nt=qe.results[0]?.file_id;Nt&&Y(_t=>({..._t,[Nt]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:qe.results[0]?.error||"Unknown error"}),"error")},onError:qe=>n(qe.message,"error")}),We=w.useCallback(qe=>{const Nt=qe.toLowerCase();return Nt.endsWith(".gcode")||Nt.includes(".gcode.")},[]),Pe=w.useMemo(()=>L?L.filter(qe=>p.includes(qe.id)&&We(qe.filename)):[],[L,p,We]),Ke=w.useCallback(qe=>{f(Nt=>Nt.includes(qe)?Nt.filter(_t=>_t!==qe):[...Nt,qe])},[]),Ve=w.useCallback(()=>{me.length>0&&f(me.map(qe=>qe.id))},[me]),ke=w.useCallback(()=>{f([])},[]),Ce=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},$e=qe=>{ge.downloadLibraryFile(qe).catch(Nt=>{console.error("Library file download failed:",Nt)})},nt=()=>{P&&(P.type==="file"?He.mutate(P.id):P.type==="folder"?Fe.mutate(P.id):P.type==="bulk"&&Oe.mutate(p))},xt=Fe.isPending||He.isPending||Oe.isPending,vt=qe=>{V(qe),localStorage.setItem("library-view-mode",qe)},mt=oe||F;return i.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(Ac,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[i.jsx("button",{onClick:()=>vt("grid"),className:`p-1.5 rounded transition-colors ${he==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:i.jsx(ww,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>vt("list"),className:`p-1.5 rounded transition-colors ${he==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:i.jsx(sT,{className:"w-4 h-4"})})]}),i.jsxs(ze,{variant:"secondary",onClick:()=>Xe.mutate(),disabled:Xe.isPending||!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[Xe.isPending?i.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}):i.jsx(Ud,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),i.jsxs(ze,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[i.jsx(Jpe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),i.jsxs(ze,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(yi,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),je&&te&&be&&i.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[i.jsx(jn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),i.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:xo(te.disk_free_bytes),total:xo(te.disk_total_bytes),threshold:be.library_disk_warning_gb})})]})]}),te&&i.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:[i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(iT,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),i.jsx("span",{className:"text-white font-medium",children:te.total_files})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Ac,{className:"w-4 h-4 text-blue-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),i.jsx("span",{className:"text-white font-medium",children:te.total_folders})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Vx,{className:"w-4 h-4 text-amber-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),i.jsx("span",{className:"text-white font-medium",children:xo(te.total_size_bytes)})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),i.jsx("span",{className:`font-medium ${je?"text-amber-500":"text-white"}`,children:xo(te.disk_free_bytes)})]})]}),i.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[i.jsx("div",{className:"lg:hidden",children:i.jsxs("select",{value:d??"",onChange:qe=>m(qe.target.value?parseInt(qe.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:[i.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),xe&&(()=>{const qe=(Nt,_t=0)=>{const rt=[];for(const Rt of Nt)rt.push({id:Rt.id,name:Rt.name,fileCount:Rt.file_count,depth:_t}),Rt.children.length>0&&rt.push(...qe(Rt.children,_t+1));return rt};return qe(xe).map(Nt=>i.jsxs("option",{value:Nt.id,children:["│ ".repeat(Nt.depth),"📂 ",Nt.name," ",Nt.fileCount>0?`(${Nt.fileCount})`:""]},Nt.id))})()]})}),i.jsxs("div",{ref:j,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:`${pe}px`},children:[i.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 ${q?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:qe=>{qe.preventDefault(),X(!0)},onDoubleClick:()=>{Te(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:i.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${q?"opacity-100":""}`,children:[i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),i.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),i.jsx("button",{onClick:()=>{const qe=!ne;se(qe),localStorage.setItem("library-wrap-folders",String(qe))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${ne?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(ne?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[i.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:()=>m(null),children:[i.jsx(mf,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),xe?.map(qe=>i.jsx(Koe,{folder:qe,selectedFolderId:d,onSelect:m,onDelete:Nt=>T({type:"folder",id:Nt}),onLink:k,onRename:Nt=>J({type:"folder",id:Nt.id,name:Nt.name}),wrapNames:ne,hasPermission:r,t},qe.id))]})]}),i.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[L&&L.length>0&&i.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:[i.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:E,onChange:qe=>U(qe.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"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(aT,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),i.jsxs("select",{value:K,onChange:qe=>H(qe.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:[i.jsx("option",{value:"all",children:t("fileManager.allTypes")}),fe.map(qe=>i.jsx("option",{value:qe,children:qe.toUpperCase()},qe))]})]}),o&&i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:re,onChange:qe=>O(qe.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 ${re?"pr-7":""}`,style:re?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),re&&i.jsx("button",{onClick:()=>O(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:i.jsx(Ht,{className:"w-3 h-3"})}),i.jsx("datalist",{id:"usernames-list",children:ve?.map(qe=>i.jsx("option",{value:qe.username},qe.id))})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("select",{value:$,onChange:qe=>{const Nt=qe.target.value;ee(Nt),localStorage.setItem("library-sort-field",Nt)},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:[i.jsx("option",{value:"name",children:t("common.name")}),i.jsx("option",{value:"date",children:t("common.date")}),i.jsx("option",{value:"size",children:t("fileManager.size")}),i.jsx("option",{value:"type",children:t("common.type")}),i.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),i.jsx("button",{onClick:()=>ie(qe=>{const Nt=qe==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",Nt),Nt}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(W==="asc"?"fileManager.ascending":"fileManager.descending"),children:W==="asc"?i.jsx(yhe,{className:"w-4 h-4 text-white"}):i.jsx(mhe,{className:"w-4 h-4 text-white"})})]}),(E||K!=="all"||re)&&i.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:me.length,total:L.length})})]}),me.length>0&&i.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===me.length&&p.length>0?i.jsxs(ze,{variant:"secondary",size:"sm",onClick:ke,children:[i.jsx(rl,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):i.jsxs(ze,{variant:"secondary",size:"sm",onClick:Ve,children:[i.jsx(Ks,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),p.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:p.length})}),i.jsx("div",{className:"hidden sm:block flex-1"}),i.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Pe.length===1&&i.jsxs(ze,{variant:"primary",size:"sm",onClick:()=>G(Pe[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[i.jsx(Co,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Pe.length===1&&i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>Z(Pe[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[i.jsx(Zn,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),i.jsxs(ze,{variant:"secondary",size:"sm",onClick:()=>g(!0),disabled:!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[i.jsx(cge,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),i.jsxs(ze,{variant:"danger",size:"sm",onClick:()=>{p.length===1?T({type:"file",id:p[0]}):T({type:"bulk",id:0,count:p.length})},disabled:!a("library:delete_own","library:delete_all"),title:a("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[i.jsx(nn,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),i.jsxs(ze,{variant:"secondary",size:"sm",onClick:ke,children:[i.jsx(Ht,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),mt?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):L?.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(mf,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(d!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(d!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),i.jsxs(ze,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(ir,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):me.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(Rr,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),i.jsx(ze,{variant:"secondary",onClick:()=>{U(""),H("all")},children:t("fileManager.clearFilters")})]}):he==="grid"?i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.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:me.map(qe=>i.jsx(xtt,{file:qe,isSelected:p.includes(qe.id),isMobile:ce,t,onSelect:Ke,onDelete:Nt=>T({type:"file",id:Nt}),onDownload:$e,onAddToQueue:Nt=>{const _t=L?.find(rt=>rt.id===Nt);_t&&Z(_t)},onPrint:A,onPreview3d:de,onRename:Nt=>J({type:"file",id:Nt.id,name:Nt.filename}),onGenerateThumbnail:Nt=>ye.mutate(Nt.id),thumbnailVersion:ae[qe.id],hasPermission:r,canModify:s,authEnabled:o},qe.id))})}):i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.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:[i.jsx("div",{className:"w-6"}),i.jsx("div",{children:t("common.name")}),o&&i.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),i.jsx("div",{children:t("common.type")}),i.jsx("div",{children:t("fileManager.size")}),i.jsx("div",{children:t("fileManager.prints")}),i.jsx("div",{})]}),me.map(qe=>i.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(qe.id)?"bg-bambu-green/10":""}`,onClick:()=>Ke(qe.id),children:[i.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${p.includes(qe.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:p.includes(qe.id)&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsxs("div",{className:"relative group/thumb",children:[i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:qe.thumbnail_path?i.jsx("img",{src:`${ge.getLibraryFileThumbnailUrl(qe.id)}${ae[qe.id]?`?v=${ae[qe.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(mf,{className:"w-5 h-5 text-bambu-gray/50"})})}),qe.thumbnail_path&&i.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:i.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:i.jsx("img",{src:`${ge.getLibraryFileThumbnailUrl(qe.id)}${ae[qe.id]?`?v=${ae[qe.id]}`:""}`,alt:qe.filename,className:"w-full h-full object-contain"})})})]}),i.jsx("div",{className:"min-w-0",children:i.jsx("div",{className:"text-sm text-white truncate",children:qe.print_name||qe.filename})})]}),o&&i.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:qe.created_by_username?i.jsxs(i.Fragment,{children:[i.jsx($d,{className:"w-3 h-3"}),i.jsx("span",{className:"truncate",children:qe.created_by_username})]}):"-"}),i.jsx("div",{children:i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${qe.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":qe.file_type==="gcode"?"bg-blue-500/20 text-blue-400":qe.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:qe.file_type.toUpperCase()})}),i.jsx("div",{className:"text-sm text-bambu-gray",children:xo(qe.file_size)}),i.jsx("div",{className:"text-sm text-bambu-gray",children:qe.print_count>0?`${qe.print_count}x`:"-"}),i.jsxs("div",{className:"flex items-center gap-1",onClick:Nt=>Nt.stopPropagation(),children:[kL(qe.filename)&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>r("printers:control")&&A(qe),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:i.jsx(_r,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{r("queue:create")&&Z(qe)},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:i.jsx(Zn,{className:"w-4 h-4"})})]}),(qe.file_type==="3mf"||qe.file_type==="gcode"||qe.file_type==="stl")&&i.jsx("button",{onClick:()=>r("library:read")&&de(qe),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:i.jsx(ia,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>r("library:read")&&$e(qe.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:i.jsx(fi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","update",qe.created_by_id)&&J({type:"file",id:qe.id,name:qe.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",qe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",qe.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",qe.created_by_id),children:i.jsx(Yi,{className:"w-4 h-4"})}),qe.file_type==="stl"&&i.jsx("button",{onClick:()=>s("library","update",qe.created_by_id)&&ye.mutate(qe.id),className:`p-1.5 rounded transition-colors ${s("library","update",qe.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",qe.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:ye.isPending||!s("library","update",qe.created_by_id),children:i.jsx(Ud,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","delete",qe.created_by_id)&&T({type:"file",id:qe.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",qe.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",qe.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",qe.created_by_id),children:i.jsx(nn,{className:"w-4 h-4"})})]})]},qe.id))]})})]})]}),y&&i.jsx(ptt,{parentId:d,onClose:()=>v(!1),onSave:qe=>we.mutate(qe),isLoading:we.isPending,t}),b&&xe&&i.jsx(gtt,{folders:xe,selectedFiles:p,currentFolderId:d,onClose:()=>g(!1),onMove:qe=>_e.mutate({fileIds:p,folderId:qe}),isLoading:_e.isPending,t}),_&&i.jsx(nie,{folderId:d,onClose:()=>N(!1),onUploadComplete:Ce}),C&&i.jsx(btt,{folder:C,onClose:()=>k(null),onLink:qe=>Ae.mutate({id:C.id,data:qe}),isLoading:Ae.isPending,t}),P&&i.jsx(Nn,{title:P.type==="folder"?t("fileManager.deleteFolder"):P.type==="bulk"?t("fileManager.deleteFilesCount",{count:P.count}):t("fileManager.deleteFile"),message:P.type==="folder"?t("fileManager.deleteFolderConfirm"):P.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:P.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:xt,loadingText:t("fileManager.deleting"),onConfirm:nt,onCancel:()=>T(null)}),D&&i.jsx(xu,{mode:"reprint",libraryFileId:D.id,archiveName:D.print_name||D.filename,onClose:()=>A(null),onSuccess:()=>{A(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),R&&i.jsx(xu,{mode:"reprint",libraryFileId:R.id,archiveName:R.print_name||R.filename,onClose:()=>G(null),onSuccess:()=>{G(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),z&&i.jsx(xu,{mode:"add-to-queue",libraryFileId:z.id,archiveName:z.print_name||z.filename,onClose:()=>Z(null),onSuccess:()=>{Z(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),ue&&i.jsx(L4,{libraryFileId:ue.id,title:ue.print_name||ue.filename,fileType:ue.file_type,onClose:()=>de(null)}),I&&i.jsx(ftt,{type:I.type,currentName:I.name,onClose:()=>J(null),onSave:qe=>{I.type==="file"?Be.mutate({id:I.id,filename:qe}):Me.mutate({id:I.id,name:qe})},isLoading:Be.isPending||Me.isPending,t})]})}const ZD=5,vtt=2e3,wtt=3e4,Stt=5e3;function _tt(){const{t}=Dt(),e=sn(),{showToast:n}=bn(),{hasPermission:r}=Ar(),{printerId:a}=gw(),s=parseInt(a||"0",10),[o,l]=w.useState("stream"),[c,u]=w.useState(!1),[d,m]=w.useState(!1),[p,f]=w.useState(!0),[y,v]=w.useState(Date.now()),[b,g]=w.useState(!1),[_,N]=w.useState(!1),[C,k]=w.useState(0),[P,T]=w.useState(!1),[D,A]=w.useState(0),[R,G]=w.useState(1),[z,Z]=w.useState({x:0,y:0}),[I,J]=w.useState(!1),[ae,Y]=w.useState({x:0,y:0}),[ue,de]=w.useState(null),[he,V]=w.useState(null),ne=w.useRef(null),se=w.useRef(null),pe=w.useRef(null),Te=w.useRef(null),q=w.useRef(null),{data:X}=et({queryKey:["printer",s],queryFn:()=>ge.getPrinter(s),enabled:s>0}),{data:j}=et({queryKey:["printerStatus",s],queryFn:()=>ge.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),E=gt({mutationFn:_e=>ge.setChamberLight(s,_e),onMutate:async _e=>{await e.cancelQueries({queryKey:["printerStatus",s]});const Ae=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],Be=>({...Be,chamber_light:_e})),{previousStatus:Ae}},onSuccess:(_e,Ae)=>{n(`Chamber light ${Ae?"on":"off"}`)},onError:(_e,Ae,Be)=>{Be?.previousStatus&&e.setQueryData(["printerStatus",s],Be.previousStatus),n(_e.message||t("printers.toast.failedToControlChamberLight"),"error")}}),U=(j?.state==="RUNNING"||j?.state==="PAUSE")&&(j?.printable_objects_count??0)>=2;w.useEffect(()=>(X&&(document.title=`${X.name} - Camera`),()=>{document.title="Bambuddy"}),[X]);const K=w.useRef(!1);w.useEffect(()=>{const _e=`/api/v1/printers/${s}/camera/stop`;K.current=!1;const Ae=()=>{if(s>0&&!K.current){K.current=!0;const Xe={},ye=qd();ye&&(Xe.Authorization=`Bearer ${ye}`),fetch(_e,{method:"POST",keepalive:!0,headers:Xe}).catch(()=>{})}},Be=()=>{Ae()};window.addEventListener("beforeunload",Be);const Me=ne.current;return()=>{window.removeEventListener("beforeunload",Be),Me&&(Me.src=""),Ae()}},[s]),w.useEffect(()=>{if(p&&!b){const Ae=setTimeout(()=>{f(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(Ae)}},[o,p,y,b]),w.useEffect(()=>{const _e=()=>{const Ae=!!document.fullscreenElement;N(Ae),G(1),Z({x:0,y:0}),o==="stream"&&!b&&(ne.current&&(ne.current.src=""),setTimeout(()=>{f(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",_e),()=>document.removeEventListener("fullscreenchange",_e)},[o,b]),w.useEffect(()=>{let _e;const Ae=()=>{clearTimeout(_e),_e=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Ae),()=>{clearTimeout(_e),window.removeEventListener("resize",Ae)}},[]),w.useEffect(()=>()=>{pe.current&&clearTimeout(pe.current),Te.current&&clearInterval(Te.current),q.current&&clearInterval(q.current)},[]);const H=w.useCallback(()=>{if(C>=ZD){T(!1),m(!0);return}const _e=Math.min(vtt*Math.pow(2,C),wtt);T(!0),A(Math.ceil(_e/1e3)),Te.current=setInterval(()=>{A(Ae=>Ae<=1?(Te.current&&clearInterval(Te.current),0):Ae-1)},1e3),pe.current=setTimeout(()=>{k(Ae=>Ae+1),T(!1),f(!0),m(!1),ne.current&&(ne.current.src=""),v(Date.now())},_e)},[C]);w.useEffect(()=>{if(o!=="stream"||p||P||b){q.current&&(clearInterval(q.current),q.current=null);return}return q.current=setInterval(async()=>{try{const _e=await ge.getCameraStatus(s);(_e.stalled||!_e.active&&!d)&&(console.log(`Stream issue detected: stalled=${_e.stalled}, active=${_e.active}, reconnecting...`),q.current&&(clearInterval(q.current),q.current=null),f(!1),H())}catch{}},Stt),()=>{q.current&&(clearInterval(q.current),q.current=null)}},[o,p,d,P,b,s,H]);const re=()=>{f(!1),o==="stream"&&C{if(f(!1),m(!1),k(0),T(!1),pe.current&&clearTimeout(pe.current),Te.current&&clearInterval(Te.current),ne.current&&!localStorage.getItem("cameraWindowState")){const _e=ne.current,Ae=_e.naturalWidth,Be=_e.naturalHeight;if(Ae>0&&Be>0){const ye=window.outerWidth-window.innerWidth,We=window.outerHeight-window.innerHeight,Pe=Ae+16+ye,Ke=Be+45+16+We;try{window.resizeTo(Pe,Ke)}catch{}}}},$=()=>{if(s>0){const _e={},Ae=qd();Ae&&(_e.Authorization=`Bearer ${Ae}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:_e}).catch(()=>{})}},ee=_e=>{o===_e||b||(g(!0),f(!0),m(!1),k(0),T(!1),G(1),Z({x:0,y:0}),pe.current&&clearTimeout(pe.current),Te.current&&clearInterval(Te.current),ne.current&&(ne.current.src=""),o==="stream"&&$(),setTimeout(()=>{l(_e),v(Date.now()),g(!1)},100))},W=()=>{b||(g(!0),f(!0),m(!1),k(0),T(!1),pe.current&&clearTimeout(pe.current),Te.current&&clearInterval(Te.current),ne.current&&(ne.current.src=""),o==="stream"&&$(),setTimeout(()=>{v(Date.now()),g(!1)},100))},ie=()=>{se.current&&(document.fullscreenElement?document.exitFullscreen():se.current.requestFullscreen())},ce=()=>{G(_e=>Math.min(_e+.5,4))},be=()=>{G(_e=>{const Ae=Math.max(_e-.5,1);return Ae===1&&Z({x:0,y:0}),Ae})},xe=_e=>{_e.preventDefault(),_e.deltaY<0?ce():be()},oe=_e=>{R>1&&(_e.preventDefault(),J(!0),Y({x:_e.clientX-z.x,y:_e.clientY-z.y}))},L=w.useCallback(()=>{if(!se.current)return{x:300,y:200};const _e=se.current.getBoundingClientRect(),Ae=_e.width*(R-1)/2,Be=_e.height*(R-1)/2;return{x:Math.max(50,Ae),y:Math.max(50,Be)}},[R]),F=_e=>{if(I&&R>1){const Ae=_e.clientX-ae.x,Be=_e.clientY-ae.y,Me=L();Z({x:Math.max(-Me.x,Math.min(Me.x,Ae)),y:Math.max(-Me.y,Math.min(Me.y,Be))})}},te=()=>{J(!1)},ve=_e=>{if(_e.length<2)return 0;const Ae=_e[0].clientX-_e[1].clientX,Be=_e[0].clientY-_e[1].clientY;return Math.sqrt(Ae*Ae+Be*Be)},fe=_e=>_e.length<2?{x:_e[0].clientX,y:_e[0].clientY}:{x:(_e[0].clientX+_e[1].clientX)/2,y:(_e[0].clientY+_e[1].clientY)/2},me=_e=>{_e.touches.length===2?(_e.preventDefault(),de(ve(_e.touches)),V(fe(_e.touches))):_e.touches.length===1&&R>1&&(_e.preventDefault(),J(!0),Y({x:_e.touches[0].clientX-z.x,y:_e.touches[0].clientY-z.y}))},je=_e=>{if(_e.touches.length===2&&ue!==null){_e.preventDefault();const Ae=ve(_e.touches),Be=Ae/ue;G(Xe=>{const ye=Math.max(1,Math.min(4,Xe*Be));return ye===1&&Z({x:0,y:0}),ye}),de(Ae);const Me=fe(_e.touches);if(he){const Xe=L();Z(ye=>({x:Math.max(-Xe.x,Math.min(Xe.x,ye.x+(Me.x-he.x))),y:Math.max(-Xe.y,Math.min(Xe.y,ye.y+(Me.y-he.y)))}))}V(Me)}else if(_e.touches.length===1&&I&&R>1){_e.preventDefault();const Ae=_e.touches[0].clientX-ae.x,Be=_e.touches[0].clientY-ae.y,Me=L();Z({x:Math.max(-Me.x,Math.min(Me.x,Ae)),y:Math.max(-Me.y,Math.min(Me.y,Be))})}},we=_e=>{_e.touches.length<2&&(de(null),V(null)),_e.touches.length===0&&J(!1)},Fe=()=>{G(1),Z({x:0,y:0})},He=b?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${y}`:`/api/v1/printers/${s}/camera/snapshot?t=${y}`,Oe=p||b||P;return s?i.jsxs("div",{ref:se,className:"min-h-screen bg-black flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[i.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(dx,{className:"w-4 h-4"}),X?.name||`Printer ${s}`]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[i.jsx("button",{onClick:()=>ee("stream"),disabled:Oe,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")}),i.jsx("button",{onClick:()=>ee("snapshot"),disabled:Oe,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")})]}),i.jsx("button",{onClick:()=>E.mutate(!j?.chamber_light),disabled:!j?.connected||E.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${j?.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:i.jsx(PO,{on:j?.chamber_light??!1,className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>u(!0),disabled:!U||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${U&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(U?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:i.jsx(NT,{className:"w-4 h-4 text-bambu-gray"})}),i.jsx("button",{onClick:W,disabled:Oe,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:i.jsx(Sr,{className:`w-4 h-4 text-bambu-gray ${Oe?"animate-spin":""}`})}),i.jsx("button",{onClick:ie,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?i.jsx(JX,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(Qfe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),i.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:xe,onMouseMove:F,onMouseUp:te,onMouseLeave:te,onTouchStart:me,onTouchMove:je,onTouchEnd:we,style:{touchAction:"none"},children:i.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(p||b)&&!P&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(Sr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),P&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(zh,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:D,attempt:C+1,max:ZD})}),i.jsx("button",{onClick:W,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&&!P&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(jn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),i.jsx("button",{onClick:W,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),i.jsx("img",{ref:ne,src:He,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${R}) translate(${z.x/R}px, ${z.y/R}px) rotate(${X?.camera_rotation||0}deg)`,...X?.camera_rotation===90||X?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:R>1?I?"grabbing":"grab":"default"},onError:He?re:void 0,onLoad:He?O:void 0,onMouseDown:oe,draggable:!1},y),i.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:[i.jsx("button",{onClick:be,disabled:R<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:i.jsx(JL,{className:"w-4 h-4 text-white"})}),i.jsxs("button",{onClick:Fe,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(R*100),"%"]}),i.jsx("button",{onClick:ce,disabled:R>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:i.jsx(ZL,{className:"w-4 h-4 text-white"})})]})]})}),i.jsx(MO,{printerId:s,isOpen:c,onClose:()=>u(!1)})]}):i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function Ntt(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),a=t.get("camera"),s=a!=="false"&&a!=="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 ktt(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 Ctt(t){switch(t){case"small":return{container:"p-3",text:"text-sm",textLarge:"text-lg",progressHeight:"h-2",icon:"w-3 h-3",gap:"gap-2",logoHeight:"h-12"};case"large":return{container:"p-6",text:"text-xl",textLarge:"text-3xl",progressHeight:"h-4",icon:"w-6 h-6",gap:"gap-4",logoHeight:"h-24"};default:return{container:"p-4",text:"text-base",textLarge:"text-xl",progressHeight:"h-3",icon:"w-4 h-4",gap:"gap-3",logoHeight:"h-16"}}}function Ttt(){const{printerId:t}=gw(),[e]=LL(),{t:n}=Dt(),r=sn(),a=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>Ntt(e),[e]),c=Ctt(l.size),{data:u}=et({queryKey:["printer",a],queryFn:()=>ge.getPrinter(a),enabled:a>0}),{data:d}=et({queryKey:["printerStatus",a],queryFn:()=>ge.getPrinterStatus(a),enabled:a>0,refetchInterval:2e3}),{data:m}=et({queryKey:["settings"],queryFn:ge.getSettings}),p=m?.time_format||"system";w.useEffect(()=>{if(!a)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,N=new WebSocket(_);return N.onmessage=C=>{try{const k=JSON.parse(C.data);k.type==="printer_status"&&k.printer_id===a&&r.setQueryData(["printerStatus",a],k.status)}catch{}},N.onerror=()=>{},()=>{N.close()}},[a,r]),w.useEffect(()=>(document.title=u?`${u.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[u,n]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!a)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!d)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const y=d.state==="RUNNING"||d.state==="PAUSE",v=d.progress||0,b=`/api/v1/printers/${a}/camera/stream?fps=${l.fps}&t=${s}`;return i.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&i.jsx("img",{src:b,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",style:u?.camera_rotation?{transform:`rotate(${u.camera_rotation}deg)`}:void 0,onError:f},s),i.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:i.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),i.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:i.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&u&&i.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[i.jsx(_r,{className:`${c.icon} text-white/70`}),i.jsx("span",{className:`${c.text} text-white font-medium`,children:u.name})]}),l.showFilename&&d.current_print&&i.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&&i.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:ktt(d,n)}),l.showProgress&&y&&i.jsxs("div",{className:"mb-3",children:[i.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[i.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),i.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),i.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:i.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),y&&(l.showLayers||l.showEta)&&i.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&&i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Gi,{className:c.icon}),i.jsxs("span",{className:c.text,children:[i.jsx("span",{className:"text-white",children:d.layer_num}),i.jsx("span",{className:"mx-1",children:"/"}),i.jsx("span",{children:d.total_layers})]})]}),l.showEta&&d.remaining_time!=null&&d.remaining_time>0&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Sd,{className:c.icon}),i.jsx("span",{className:`${c.text} text-white`,children:Us(d.remaining_time*60)})]}),i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Zn,{className:c.icon}),i.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",eO(d.remaining_time,p,n)]})]})]})]}),!y&&i.jsx("div",{className:`${c.text} text-white/70 py-2`,children:d.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function Att(){const{t}=Dt(),{id:e}=gw(),{mode:n}=ng(),{data:r,isLoading:a,error:s}=et({queryKey:["external-link",e],queryFn:()=>ge.getExternalLink(Number(e)),enabled:!!e});return a?i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[i.jsx(jn,{className:"w-12 h-12"}),i.jsx("p",{children:t("common.linkNotFound")})]}):i.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"})}function LY(){const{id:t}=gw(),e=ol(),n=sn(),{t:r}=Dt(),{showToast:a}=bn(),s=!!t,[o,l]=w.useState(""),[c,u]=w.useState(""),[d,m]=w.useState([]),[p,f]=w.useState(""),[y,v]=w.useState(!1),{data:b,isLoading:g}=et({queryKey:["group",t],queryFn:()=>ge.getGroup(Number(t)),enabled:s}),{data:_,isLoading:N}=et({queryKey:["permissions"],queryFn:()=>ge.getPermissions()});s&&b&&!y&&(l(b.name),u(b.description||""),m(b.permissions),v(!0));const C=gt({mutationFn:Y=>ge.createGroup(Y),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.created")),e("/settings?tab=users")},onError:Y=>{a(Y.message,"error")}}),k=gt({mutationFn:Y=>ge.updateGroup(Number(t),Y),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.updated")),e("/settings?tab=users")},onError:Y=>{a(Y.message,"error")}}),P=C.isPending||k.isPending,T=()=>{if(!o.trim()){a(r("groups.toast.enterGroupName"),"error");return}s?k.mutate({name:o!==b?.name?o:void 0,description:c,permissions:d}):C.mutate({name:o,description:c||void 0,permissions:d})},D=Y=>{m(ue=>ue.includes(Y)?ue.filter(de=>de!==Y):[...ue,Y])},A=(Y,ue)=>{const de=Y.permissions.map(he=>he.value);m(he=>{const V=he.filter(ne=>!de.includes(ne));return ue?[...V,...de]:V})},R=Y=>Y.permissions.every(ue=>d.includes(ue.value)),G=Y=>{const ue=Y.permissions.filter(de=>d.includes(de.value)).length;return ue>0&&ue{_&&m(_.all_permissions)},Z=()=>{m([])},I=p.toLowerCase(),J=w.useMemo(()=>_?I?_.categories.map(Y=>({...Y,permissions:Y.permissions.filter(ue=>ue.label.toLowerCase().includes(I))})).filter(Y=>Y.permissions.length>0):_.categories:[],[_,I]),ae=_?.all_permissions.length??0;return g||N?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:i.jsx($X,{className:"w-5 h-5"})}),i.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&i.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[i.jsx(jn,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),i.jsx("input",{type:"text",value:o,onChange:Y=>l(Y.target.value),disabled:s&&b?.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:r("groups.form.groupNamePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),i.jsx("input",{type:"text",value:c,onChange:Y=>u(Y.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:r("groups.form.descriptionPlaceholder")})]})]}),i.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:d.length})," / ",ae]}),i.jsx(ze,{size:"sm",variant:"ghost",onClick:z,children:r("groups.editor.selectAll")}),i.jsx(ze,{size:"sm",variant:"ghost",onClick:Z,children:r("groups.editor.clearAll")})]}),i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),i.jsx("input",{type:"text",value:p,onChange:Y=>f(Y.target.value),placeholder:r("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm 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 w-64"})]})]}),J.length===0?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:J.map(Y=>{const ue=_.categories.find(se=>se.name===Y.name),de=ue.permissions.filter(se=>d.includes(se.value)).length,he=ue.permissions.length,V=R(ue),ne=G(ue);return i.jsxs(Pt,{children:[i.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>A(ue,!V),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${V?"bg-bambu-green border-bambu-green":ne?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[V&&i.jsx(Zr,{className:"w-3 h-3 text-white"}),ne&&!V&&i.jsx(zN,{className:"w-3 h-3 text-white"})]}),i.jsx(C3,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-white font-medium text-sm",children:Y.name})]}),i.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[de,"/",he]})]}),i.jsx("div",{className:"p-3 space-y-1",children:Y.permissions.map(se=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d.includes(se.value),onChange:()=>D(se.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"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:se.label})]},se.value))})]},Y.name)})}),i.jsx("div",{className:"h-16"}),i.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[i.jsx(ze,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),i.jsx(ze,{onClick:T,disabled:P||!o.trim(),children:P?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(as,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const OY={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function Ptt(t,e=!1){const n={};return e?(t.material||(n.material="Material is required"),{isValid:Object.keys(n).length===0,errors:n}):(t.slicer_filament||(n.slicer_filament="Slicer preset is required"),t.material||(n.material="Material is required"),t.brand||(n.brand="Brand is required"),t.subtype||(n.subtype="Subtype is required"),{isValid:Object.keys(n).length===0,errors:n})}const Mtt=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Ett=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],b0=["Basic","Matte","Silk","Tough","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],Yoe=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"}],jtt=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],IY=[...Yoe,...jtt],Xoe="bambuddy-recent-colors",Dtt=8,Rtt=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function Ux(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let r="",a=-1;for(const c of n){const u=e.toUpperCase().indexOf(c.toUpperCase());if(u!==-1){r=c,a=u;break}}let s="";a>0&&(s=e.substring(0,a).trim(),s=s.replace(/[-_\s]+$/,""));let o="";a!==-1&&r&&(o=e.substring(a+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of b0)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of b0){const u=new RegExp(`\\s+${c}$`,"i");if(u.test(s)){l=c,s=s.replace(u,"").trim();break}}return{brand:s,material:r,variant:l}}function Ftt(t,e){const n=new Set(Ett);for(const r of t){const{brand:a}=Ux(r.name);a&&a.length>1&&n.add(a)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:a}=Ux(r.name);a&&a.length>1&&n.add(a)}return Array.from(n).sort((r,a)=>r.localeCompare(a))}function Ltt(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const a=r.name.replace(/@.*$/,"").trim(),s=n.get(a);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(a,{code:o,name:a,displayName:a,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,a)=>r.displayName.localeCompare(a.displayName))}function Ott(t,e,n){if(t.length>0){const r=[],a=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=a.get(o);l?l.allCodes.push(s.setting_id):a.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(a.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=Ltt(n);if(r.length>0)return r}return Rtt}function Itt(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(a=>a.code.toLowerCase()===r||a.allCodes.some(s=>s.toLowerCase()===r))}return n}function ztt(){try{const t=localStorage.getItem(Xoe);if(t)return JSON.parse(t)}catch{}return[]}function Utt(t,e){const n=e.filter(a=>a.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,Dtt);try{localStorage.setItem(Xoe,JSON.stringify(r))}catch{}return r}function JD(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),a=Ux(r);return!(!(a.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(a.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(a.brand.toLowerCase()))||e.subtype&&!(a.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(a.variant.toLowerCase())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function Btt({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:a,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:u,quickAdd:d,quantity:m,onQuantityChange:p,errors:f}){const{t:y}=Dt(),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[N,C]=w.useState(!1),[k,P]=w.useState(!1),[T,D]=w.useState(""),[A,R]=w.useState(""),[G,z]=w.useState(""),[Z,I]=w.useState(String(t.label_weight)),[J,ae]=w.useState(!1),Y=w.useRef(null),ue=w.useRef(null),de=w.useRef(null),he=w.useRef(null);w.useEffect(()=>{const q=X=>{Y.current&&!Y.current.contains(X.target)&&b(!1),he.current&&!he.current.contains(X.target)&&P(!1),ue.current&&!ue.current.contains(X.target)&&_(!1),de.current&&!de.current.contains(X.target)&&C(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[]);const V=w.useMemo(()=>{if(!a)return l;const q=a.toLowerCase();return l.filter(X=>X.displayName.toLowerCase().includes(q)||X.code.toLowerCase().includes(q))},[l,a]),ne=w.useMemo(()=>{if(!T)return c;const q=T.toLowerCase();return c.filter(j=>j.toLowerCase().includes(q)).sort((j,E)=>{const U=j.toLowerCase()===q,K=E.toLowerCase()===q;return U&&!K?-1:!U&&K?1:j.localeCompare(E)})},[c,T]),se=w.useMemo(()=>{if(!A)return b0;const q=A.toLowerCase();return b0.filter(X=>X.toLowerCase().includes(q))},[A]),pe=w.useMemo(()=>{if(!G)return u;const q=G.toLowerCase();return u.filter(j=>j.toLowerCase().includes(q)).sort((j,E)=>{const U=j.toLowerCase()===q,K=E.toLowerCase()===q;return U&&!K?-1:!U&&K?1:j.localeCompare(E)})},[G,u]);w.useEffect(()=>{J||I(String(t.label_weight))},[t.label_weight,J]);const Te=q=>{e("slicer_filament",q.code),s(q.displayName),b(!1);const X=Ux(q.name);X.material&&e("material",X.material),X.brand&&e("brand",X.brand),X.variant&&e("subtype",X.variant)};return i.jsxs("div",{className:"space-y-4",children:[!d&&i.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-3 h-3 animate-spin"})," ",y("inventory.loadingPresets")]}):n?i.jsxs(i.Fragment,{children:[i.jsx(qx,{className:"w-3 h-3 text-bambu-green"})," ",y("inventory.cloudConnected")]}):i.jsxs(i.Fragment,{children:[i.jsx(cpe,{className:"w-3 h-3"})," ",y("inventory.cloudNotConnected")]})}),!d&&i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.slicerPreset")," *"]}),i.jsxs("div",{className:"relative",ref:Y,children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.searchPresets"),value:a,onChange:q=>{s(q.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),v&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:V.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noPresetsFound")}):V.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===q.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Te(q),children:q.displayName},q.code))})]}),o&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[y("inventory.selectedPreset"),": ",i.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.material")," *"]}),i.jsxs("div",{className:"relative",ref:he,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.selectMaterial"),value:k?G:t.material,onChange:q=>{z(q.target.value),P(!0)},onFocus:()=>{P(!0),z("")}}),i.jsx(In,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),k&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[pe.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):pe.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",q),P(!1),z("")},children:q},q)),G&&!pe.includes(G)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",G),P(!1),z("")},children:y("inventory.useCustomMaterial",{material:G})})]})]}),f?.material&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.brand"),!d&&" *"]}),i.jsxs("div",{className:"relative",ref:ue,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.searchBrand"),value:g?T:t.brand,onChange:q=>{D(q.target.value),_(!0)},onFocus:()=>{_(!0),D("")}}),i.jsx(In,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),g&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ne.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):ne.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",q),_(!1),D("")},children:q},q)),T&&!ne.includes(T)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",T),_(!1),D("")},children:y("inventory.useCustomBrand",{brand:T})})]})]}),f?.brand&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.subtype"),!d&&" *"]}),i.jsxs("div",{className:"relative",ref:de,children:[i.jsx("input",{type:"text",value:N?A:t.subtype,onChange:q=>{R(q.target.value),C(!0)},onFocus:()=>{C(!0),R("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),i.jsx(In,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[se.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):se.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",q),C(!1),R("")},children:q},q)),A&&!b0.some(q=>q.toLowerCase()===A.toLowerCase().trim())&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",A),C(!1),R("")},children:y("inventory.useCustomBrand",{brand:A})})]})]}),f?.subtype&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.labelWeight")}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:Z,min:0,onFocus:()=>ae(!0),onChange:q=>I(q.target.value),onBlur:()=>{ae(!1);const q=Z.trim(),X=Number(q);if(!q||!Number.isFinite(X)||X<0){I(String(t.label_weight));return}const j=Math.round(X);e("label_weight",j),I(String(j))}}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),d&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.quantity")}),i.jsx("input",{type:"number",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:m,min:1,max:100,onChange:q=>{const X=Math.max(1,Math.min(100,parseInt(q.target.value)||1));p(X)}})]})]})}function Htt({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:a}){const{t:s}=Dt(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=t.rgba.replace("#","").substring(0,6),m=g=>d.toUpperCase()===g.toUpperCase(),p=(g,_)=>{e("rgba",g.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:g})},f=w.useMemo(()=>{if(a.length===0)return[];const g=t.brand?.trim(),_=t.material?.toLowerCase().trim(),N=t.subtype?.toLowerCase().trim();if(!g&&!_)return[];const C=g?g.toLowerCase().split(/[\s\-_]+/).filter(T=>T.length>=2):[],k=T=>{if(C.length===0)return!0;const D=T.toLowerCase();return C.some(A=>D.includes(A))};if(g&&!_){const T=a.filter(D=>k(D.manufacturer));if(T.length>0)return T.map(D=>({name:D.color_name,hex:D.hex_color.replace("#","").substring(0,6),manufacturer:D.manufacturer,material:typeof D.material=="string"?D.material:void 0}))}const P=_&&N?`${_} ${N}`:"";if(P){const T=a.filter(A=>k(A.manufacturer)&&A.material?.toLowerCase()===P);if(T.length>0)return T.map(A=>({name:A.color_name,hex:A.hex_color.replace("#","").substring(0,6),manufacturer:A.manufacturer,material:typeof A.material=="string"?A.material:void 0}));const D=P.replace(/\+$/,"");if(D!==P){const A=a.filter(R=>k(R.manufacturer)&&R.material?.toLowerCase()===D);if(A.length>0)return A.map(R=>({name:R.color_name,hex:R.hex_color.replace("#","").substring(0,6),manufacturer:R.manufacturer,material:typeof R.material=="string"?R.material:void 0}))}}if(_){const T=a.filter(D=>k(D.manufacturer)&&(!D.material||D.material.toLowerCase().startsWith(_)));if(T.length>0)return T.map(D=>({name:D.color_name,hex:D.hex_color.replace("#","").substring(0,6),manufacturer:D.manufacturer,material:typeof D.material=="string"?D.material:void 0}))}return[]},[a,t.brand,t.material,t.subtype]),y=w.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const g=c.toLowerCase();return f.filter(N=>N.name.toLowerCase().includes(g)||(N.manufacturer?.toLowerCase().includes(g)??!1)||(N.material?.toLowerCase().includes(g)??!1))},[c,f]),v=f.length>0,b=w.useMemo(()=>c?IY.filter(g=>g.name.toLowerCase().includes(c.toLowerCase())):o?IY:Yoe,[c,o]);return i.jsxs("div",{className:"space-y-3",children:[i.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${d}`}}),n.length>0&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[i.jsx(Zn,{className:"w-3 h-3"}),i.jsx("span",{children:s("inventory.recentColors")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(g=>i.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name},g.hex))})]}),i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:g=>u(g.target.value)})]}),v?i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.map(g=>i.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name})},`${g.hex}-${g.name}-${g.manufacturer??""}`)),y.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[i.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&i.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?i.jsxs(i.Fragment,{children:[s("inventory.showLess")," ",i.jsx(Vl,{className:"w-3 h-3"})]}):i.jsxs(i.Fragment,{children:[s("inventory.showAll")," ",i.jsx(In,{className:"w-3 h-3"})]})})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(g=>i.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:g.name})},g.hex)),b.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:g=>e("color_name",g.target.value)})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),i.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:d.toUpperCase(),onChange:g=>{const _=g.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),i.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${d}`,onChange:g=>{const _=g.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function $tt({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:a}){const{t:s}=Dt(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{const v=b=>{d.current&&!d.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(b=>b.weight===e);if(r){const b=t.find(g=>g.id===r);if(b&&b.weight===e)return}v.length===1?a(v[0].id):v.length===0&&r!==null&&a(null)},[e,t,r,a]);const p=w.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(v)||b.weight.toString().includes(v))},[t,c]),f=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),y=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(b=>b.id===r);if(v)return v.name}return f.length>0?f[0].name:""},[o,c,r,t,f]);return i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(Dge,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsxs("div",{className:"flex-1 min-w-0 relative",ref:d,children:[i.jsx("input",{ref:m,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:y,onFocus:()=>{l(!0),u("")},onChange:v=>{u(v.target.value),l(!0)}}),o&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:p.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>i.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{a(v.id),n(v.weight),l(!1),u("")},children:[i.jsx("span",{className:"truncate",children:v.name}),i.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),i.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[i.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:v=>{const b=parseInt(v.target.value);!isNaN(b)&&b>=0&&n(b)}}),i.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function qtt({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:a}=Dt(),{showToast:s}=bn(),[o,l]=w.useState(""),[c,u]=w.useState(!1),[d,m]=w.useState(""),[p,f]=w.useState(!1),y=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+y;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{p||m(String(y))},[p,y]),i.jsxs("div",{className:"space-y-4",children:[i.jsx($tt,{catalog:n,value:t.core_weight,onChange:b=>e("core_weight",b),catalogId:t.core_weight_catalog_id,onCatalogIdChange:b=>e("core_weight_catalog_id",b)}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.currentWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:d,min:0,max:t.label_weight,onFocus:()=>f(!0),onChange:b=>{m(b.target.value)},onBlur:()=>{f(!1);const b=d.trim(),g=Number(b);if(!b||!Number.isFinite(g)||g<0||g>t.label_weight){m(String(y));return}const _=Math.round(g);e("weight_used",Math.max(0,t.label_weight-_)),m(String(_))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.measuredWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:o,min:0,onFocus:()=>u(!0),onChange:b=>{l(b.target.value)},onBlur:()=>{u(!1);const b=o.trim(),g=Number(b),_=t.core_weight,N=t.core_weight+t.label_weight;if(!b||!Number.isFinite(g)||g<_||g>N){s(a("inventory.measuredWeightError",{min:_,max:N}),"error"),l(String(v));return}const C=Math.round(g),k=Math.max(0,Math.min(t.label_weight,C-t.core_weight));e("weight_used",Math.max(0,t.label_weight-k)),l(String(C))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.costPerKg","Cost per kg")}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),i.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:b=>{const g=b.target.value===""?null:parseFloat(b.target.value);e("cost_per_kg",g)},style:{paddingLeft:`${Math.max(2,r.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.note")}),i.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:a("inventory.notePlaceholder"),value:t.note,onChange:b=>e("note",b.target.value)})]})]})}function Vtt({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:a,setExpandedPrinters:s}){const{t:o}=Dt(),l=p=>{s(f=>{const y=new Set(f);return y.has(p)?y.delete(p):y.add(p),y})},c=(p,f,y)=>{const v=`${p}:${f}:${y??"null"}`,b=`${p}:${y??"null"}`;r(g=>{const _=new Set(g);if(_.has(v))_.delete(v);else{for(const N of Array.from(_)){const C=N.split(":");`${C[0]}:${C[2]}`===b&&_.delete(N)}_.add(v)}return _})},u=()=>{const p=new Set;for(const{printer:f,calibrations:y}of e){if(!f.connected)continue;const v=y.filter(g=>JD(g,t)),b=new Map;for(const g of v){const _=`${g.extruder_id??"null"}`;b.has(_)||b.set(_,[]),b.get(_).push(g)}for(const[g,_]of b)if(_.length>0){const C=[..._].sort((k,P)=>P.k_value-k.k_value)[0];p.add(`${f.id}:${C.cali_idx}:${g}`)}}r(p)};if(!t.material)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const d=e.reduce((p,{printer:f,calibrations:y})=>f.connected?p+y.filter(v=>JD(v,t)).length:p,0),m=(p,f)=>{const y=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=n.has(y);return i.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[i.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),i.jsx("div",{className:"flex items-center gap-2 shrink-0",children:i.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),d>0&&i.jsxs("button",{type:"button",onClick:u,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[i.jsx(hx,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",d,")"]})]}),i.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const y=a.has(String(p.id)),v=f.filter(C=>JD(C,t)),b=v.length,g=v.some(C=>C.extruder_id!==void 0&&C.extruder_id!==null&&C.extruder_id>0),_=v.filter(C=>C.extruder_id===1),N=v.filter(C=>C.extruder_id===0||C.extruder_id===void 0||C.extruder_id===null);return i.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{type:"button",onClick:()=>l(String(p.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[y?i.jsx(In,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(fa,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?i.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[b," ",o(b!==1?"inventory.matches":"inventory.match")]}):i.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),i.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),y&&i.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):g?i.jsxs(i.Fragment,{children:[_.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),i.jsx("div",{className:"space-y-2",children:_.map(C=>m(p,C))})]}),N.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),i.jsx("div",{className:"space-y-2",children:N.map(C=>m(p,C))})]})]}):i.jsx("div",{className:"space-y-2",children:v.map(C=>m(p,C))}):i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function Gtt(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const Wtt={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function Ktt({spoolId:t}){const{t:e}=Dt(),n=sn(),{showToast:r}=bn(),{data:a,isLoading:s}=et({queryKey:["spool-usage",t],queryFn:()=>ge.getSpoolUsageHistory(t)}),o=gt({mutationFn:()=>ge.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?i.jsx("div",{className:"flex justify-center py-4",children:i.jsx(ft,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!a||a.length===0?i.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[i.jsx(Zn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),i.jsxs(ze,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[i.jsx(nn,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:a.map(l=>i.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("span",{className:"text-bambu-gray",children:Gtt(l.created_at)}),l.print_name&&i.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[i.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),i.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),i.jsx("span",{className:Wtt[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function Ytt({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:a}){const{t:s}=Dt(),o=sn(),{showToast:l}=bn(),c=!!n,[u,d]=w.useState(OY),[m,p]=w.useState({}),[f,y]=w.useState("filament"),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[N,C]=w.useState(1),[k,P]=w.useState(!1),[T,D]=w.useState(!1),[A,R]=w.useState([]),[G,z]=w.useState(""),[Z,I]=w.useState([]),[J,ae]=w.useState([]),[Y,ue]=w.useState([]),[de,he]=w.useState([]),[V,ne]=w.useState([]),[se,pe]=w.useState(new Set),[Te,q]=w.useState(new Set),X=r.length>0?r:V,j=w.useMemo(()=>se.size,[se]);w.useEffect(()=>{he(ztt())},[]),w.useEffect(()=>{t&&((async()=>{D(!0);try{const me=await ge.getCloudStatus();if(P(me.is_authenticated),me.is_authenticated){const je=await ge.getFilamentPresets();R(je)}}catch(me){console.error("Failed to fetch cloud presets:",me),P(!1)}finally{D(!1)}})(),ge.getSpoolCatalog().then(I).catch(console.error),ge.getColorCatalog().then(ue).catch(console.error),ge.getLocalPresets().then(me=>ae(me.filament)).catch(console.error),r.length===0&&(async()=>{try{const me=await ge.getPrinters(),je=await Promise.all(me.map(Fe=>ge.getPrinterStatus(Fe.id).catch(()=>null))),we=[];for(let Fe=0;Fe({cali_idx:Me.slot_id,filament_id:Me.filament_id,setting_id:Me.setting_id||"",name:Me.name,k_value:parseFloat(Me.k_value)||0,n_coef:parseFloat(Me.n_coef)||0,extruder_id:Me.extruder_id,nozzle_diameter:Me.nozzle_diameter}))}catch{}we.push({printer:{...He,connected:_e},calibrations:Ae})}ne(we)}catch(me){console.error("Failed to fetch printer calibrations:",me)}})())},[t,r.length]);const E=w.useMemo(()=>Ott(A,new Set,J),[A,J]),U=w.useMemo(()=>{const fe=Ftt(A,J),me=Y.map(we=>we.manufacturer?.trim()).filter(we=>!!we),je=new Set([...fe,...me]);return Array.from(je).sort((we,Fe)=>we.localeCompare(Fe))},[A,J,Y]),K=w.useMemo(()=>{const fe=Y.map(je=>je.material?.trim()).filter(je=>!!je),me=new Set([...Mtt,...fe]);return Array.from(me).sort((je,we)=>je.localeCompare(we))},[Y]),H=w.useMemo(()=>{const fe=[];for(const me of Y){const je=me.manufacturer?.trim(),we=me.material?.trim();je&&we&&fe.push({brand:je,material:we})}for(const me of A){const je=Ux(me.name);je.brand&&je.material&&fe.push({brand:je.brand,material:je.material})}for(const me of J){const je=Ux(me.name),we=me.filament_vendor?.trim()||je.brand,Fe=je.material;we&&Fe&&fe.push({brand:we,material:Fe})}return fe},[A,Y,J]),re=w.useMemo(()=>{const fe=new Map;for(const me of H){const je=me.brand.toLowerCase(),we=me.material.toLowerCase();fe.has(je)||fe.set(je,new Set),fe.get(je).add(we)}return fe},[H]),O=w.useMemo(()=>{const fe=new Map;for(const me of H){const je=me.brand.toLowerCase(),we=me.material.toLowerCase();fe.has(we)||fe.set(we,new Set),fe.get(we).add(je)}return fe},[H]),$=w.useMemo(()=>{if(!u.material)return U;const fe=u.material.toLowerCase(),me=O.get(fe);return!me||me.size===0?U:U.filter(je=>me.has(je.toLowerCase()))},[U,u.material,O]),ee=w.useMemo(()=>{if(!u.brand)return K;const fe=u.brand.toLowerCase(),me=re.get(fe);return!me||me.size===0?K:K.filter(je=>me.has(je.toLowerCase()))},[K,u.brand,re]),W=w.useMemo(()=>Itt(u.slicer_filament,E),[u.slicer_filament,E]);w.useEffect(()=>{if(t){if(n)if(d({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),z(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const fe=new Set;for(const me of n.k_profiles)me.cali_idx!==null&&me.cali_idx!==void 0&&fe.add(`${me.printer_id}:${me.cali_idx}:${me.extruder??"null"}`);pe(fe)}else pe(new Set);else d(OY),z(""),pe(new Set),_(!1),C(1);p({}),y("filament"),b(!1)}},[t,n]),w.useEffect(()=>{t&&X.length>0&&q(new Set(X.map(fe=>String(fe.printer.id))))},[t,X]);const ie=(fe,me)=>{d(je=>({...je,[fe]:me})),fe==="weight_used"&&b(!0),m[fe]&&p(je=>({...je,[fe]:void 0}))},ce=fe=>{he(me=>Utt(fe,me))},be=gt({mutationFn:fe=>ge.createSpool(fe),onSuccess:async fe=>{se.size>0&&fe?.id&&await F(fe.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolCreated"),"success"),e()},onError:fe=>{l(fe.message,"error")}}),xe=gt({mutationFn:({data:fe,qty:me})=>ge.bulkCreateSpools(fe,me),onSuccess:async fe=>{if(se.size>0)for(const me of fe)await F(me.id);await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolsCreated",{count:fe.length}),"success"),e()},onError:fe=>{l(fe.message,"error")}}),oe=gt({mutationFn:fe=>ge.updateSpool(n.id,fe),onSuccess:async()=>{n?.id&&await F(n.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolUpdated"),"success"),e()},onError:fe=>{l(fe.message,"error")}}),L=gt({mutationFn:()=>ge.updateSpool(n.id,{tag_uid:null}),onSuccess:async()=>{await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.tagDeleted","Tag removed"),"success"),e()},onError:fe=>{l(fe.message,"error")}}),F=async fe=>{if(se.size===0){try{await ge.saveSpoolKProfiles(fe,[])}catch{}return}const me=[];for(const je of se){const[we,Fe,He]=je.split(":"),Oe=parseInt(we),_e=parseInt(Fe),Ae=He==="null"?0:parseInt(He),Be=X.find(Me=>Me.printer.id===Oe);if(Be){const Me=Be.calibrations.find(Xe=>Xe.cali_idx===_e);Me&&me.push({printer_id:Oe,extruder:Ae,nozzle_diameter:Me.nozzle_diameter||"0.4",k_value:Me.k_value,name:Me.name||null,cali_idx:Me.cali_idx,setting_id:Me.setting_id||null})}}if(me.length>0)try{await ge.saveSpoolKProfiles(fe,me)}catch(je){console.error("Failed to save K-profiles:",je)}};if(w.useEffect(()=>{if(!t)return;const fe=me=>{me.key==="Escape"&&e()};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[t,e]),!t)return null;const te=()=>{const fe=Ptt(u,g);if(!fe.isValid){p(fe.errors),(fe.errors.slicer_filament||fe.errors.material||fe.errors.brand||fe.errors.subtype)&&y("filament");return}const me=W?.displayName||G||null,je={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:me,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!c||v)&&(je.weight_used=u.weight_used),c?oe.mutate(je):N>1?xe.mutate({data:je,qty:N}):be.mutate(je)},ve=be.isPending||xe.isPending||oe.isPending||L.isPending;return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(c?"inventory.editSpool":"inventory.addSpool")}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),!c&&i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Pc,{className:"w-4 h-4 text-amber-400"}),i.jsx("span",{className:"text-sm text-white",children:s("inventory.quickAdd")})]}),i.jsx("button",{type:"button",onClick:()=>{_(!g),g||y("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${g?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${g?"translate-x-4":"translate-x-0.5"}`})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("button",{onClick:()=>y("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${f==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Sw,{className:"w-4 h-4"}),s("inventory.filamentInfoTab")]}),!g&&i.jsxs("button",{onClick:()=>y("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${f==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(She,{className:"w-4 h-4"}),s("inventory.paProfileTab"),j>0&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:j})]})]}),i.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:f==="filament"?i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.filamentInfo")}),i.jsx(Btt,{formData:u,updateField:ie,cloudAuthenticated:k,loadingCloudPresets:T,presetInputValue:G,setPresetInputValue:z,selectedPresetOption:W,filamentOptions:E,availableBrands:$,availableMaterials:ee,quickAdd:g,quantity:N,onQuantityChange:C,errors:m})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.color")}),i.jsx(Htt,{formData:u,updateField:ie,recentColors:de,onColorUsed:ce,catalogColors:Y})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.additional")}),i.jsx(qtt,{formData:u,updateField:ie,spoolCatalog:Z,currencySymbol:a})]}),c&&n&&i.jsx("div",{children:i.jsx(Ktt,{spoolId:n.id})})]}):i.jsx(Vtt,{formData:u,updateField:ie,printersWithCalibrations:X,selectedProfiles:se,setSelectedProfiles:pe,expandedPrinters:Te,setExpandedPrinters:q})}),i.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[c&&i.jsxs(ze,{variant:"secondary",onClick:()=>L.mutate(),disabled:ve||!n?.tag_uid,className:"mr-auto",children:[i.jsx(Hd,{className:"w-4 h-4"}),s("inventory.deleteTag","Delete Tag")]}),i.jsxs("div",{className:"flex gap-2 ml-auto",children:[i.jsx(ze,{variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(ze,{onClick:te,disabled:ve,children:ve?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),s("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(as,{className:"w-4 h-4"}),s(c?"common.save":"inventory.addSpool")]})})]})]})]})]})}function Xtt({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:a}){const{t:s}=Dt(),[o,l]=w.useState(n),[c,u]=w.useState(null),d=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(C=>({...C})))},[t,n]),w.useEffect(()=>{if(!t)return;const C=k=>{k.key==="Escape"&&e()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[t,e]),!t)return null;const m=C=>{l(k=>k.map((P,T)=>T===C?{...P,visible:!P.visible}:P))},p=(C,k)=>{k<0||k>=o.length||l(P=>{const T=[...P],[D]=T.splice(C,1);return T.splice(k,0,D),T})},f=(C,k)=>{d.current=k,u(k),C.dataTransfer.effectAllowed="move"},y=(C,k)=>{C.preventDefault(),C.dataTransfer.dropEffect="move";const P=d.current;P!==null&&P!==k&&(p(P,k),d.current=k,u(k))},v=C=>{C.preventDefault()},b=()=>{d.current=null,u(null)},g=()=>{l(r.map(C=>({...C})))},_=()=>{a(o),e()},N=o.filter(C=>C.visible).length;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsx(Pt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:C=>C.stopPropagation(),children:i.jsxs(Et,{className:"p-6 flex flex-col min-h-0",children:[i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),i.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),i.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),i.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((C,k)=>i.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===k?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${C.visible?"":"opacity-50"}`,draggable:!0,onDragStart:P=>f(P,k),onDragOver:P=>y(P,k),onDrop:v,onDragEnd:b,children:[i.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:i.jsx(Th,{className:"w-4 h-4"})}),i.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:C.label}),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{onClick:()=>p(k,k-1),disabled:k===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:i.jsx(Vl,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>p(k,k+1),disabled:k===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:i.jsx(In,{className:"w-4 h-4"})})]}),i.jsx("button",{onClick:()=>m(k),className:`p-1.5 rounded transition-colors ${C.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:C.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:C.visible?i.jsx(Tc,{className:"w-4 h-4"}):i.jsx(xw,{className:"w-4 h-4"})})]},C.id))}),i.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs(ze,{variant:"secondary",onClick:g,className:"mr-auto",children:[i.jsx(To,{className:"w-4 h-4"}),s("inventory.reset")]}),i.jsx(ze,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),i.jsx(ze,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}function zY(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.label_weight}`}const Qoe="bambuddy-inventory-columns",AN=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function Qtt(){try{const t=localStorage.getItem(Qoe);if(t){const e=JSON.parse(t),n=new Set(AN.map(o=>o.id)),r=new Set(e.map(o=>o.id)),a=e.filter(o=>n.has(o.id)),s=AN.filter(o=>!r.has(o.id));return[...a,...s]}}catch{}return AN.map(t=>({...t}))}function Ztt(t){try{localStorage.setItem(Qoe,JSON.stringify(t))}catch{}}function mu(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const Jtt={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function e3(t,e="system"){if(!t)return"-";const n=Qn(t);return n?A3(n,e):"-"}const ent={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},CL={id:({spool:t})=>i.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:e3(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:e3(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?e3(t.last_used,e):"Never"}),rgba:({spool:t})=>i.jsx("div",{className:"flex items-center justify-center",children:i.jsx("span",{className:"w-5 h-5 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:D4(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,a=n.ams_id===254||n.ams_id===255,s=!a&&n.ams_id>=128,o=F4(n.ams_id,n.tray_id,s,a);return i.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[r," ",o,n.ams_label?` (${n.ams_label})`:""]})},label_weight:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:mu(t.label_weight)}),net:({remaining:t})=>i.jsx("span",{className:"text-sm text-white",children:mu(t)}),gross:({spool:t,remaining:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:mu(e+t.core_weight)}),added_full:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?mu(t.weight_used):"-"}),printed_total:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?i.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return i.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const n=t.last_scale_weight;if(n==null)return i.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const r=t.core_weight||0,a=Math.max(0,t.label_weight-t.weight_used)+r;let s,o;n0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g Calculated: ${Math.round(a)}g Difference: ${l}g (within tolerance)`:`Scale: ${Math.round(n)}g Calculated: ${Math.round(a)}g -Difference: ${l}g (mismatch!)`;return i.jsxs("div",{className:`flex items-center gap-1 text-sm font-medium ${o?"text-green-400":"text-yellow-400"}`,title:c,children:[i.jsxs("span",{children:[Math.round(n),"g"]}),o?i.jsx(Zr,{className:"w-3 h-3"}):i.jsxs(i.Fragment,{children:[i.jsx(jn,{className:"w-3 h-3"}),e&&i.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),u.preventDefault(),e(t)},className:"p-1 hover:bg-bambu-green/20 rounded transition-colors text-bambu-green",title:"Sync: trust scale weight and reset tracking",children:i.jsx(Sr,{className:"w-3.5 h-3.5"})})]})]})}},t3={id:t=>t.id,added_time:t=>t.created_at||"",encode_time:t=>t.encode_time||"",last_used_time:t=>t.last_used||"",material:t=>(t.material||"").toLowerCase(),subtype:t=>(t.subtype||"").toLowerCase(),color_name:t=>(t.color_name||"").toLowerCase(),brand:t=>(t.brand||"").toLowerCase(),slicer_filament:t=>(t.slicer_filament_name||t.slicer_filament||"").toLowerCase(),location:(t,e)=>{const n=e[t.id];if(!n)return"";const r=n.ams_id===254||n.ams_id===255,a=!r&&n.ams_id>=128,s=n.ams_label?` (${n.ams_label})`:"";return`${n.printer_name||""} ${FI(n.ams_id,n.tray_id,a,r)}${s}`},label_weight:t=>t.label_weight,net:t=>Math.max(0,t.label_weight-t.weight_used),gross:t=>Math.max(0,t.label_weight-t.weight_used)+t.core_weight,used:t=>t.weight_used,remaining:t=>t.label_weight>0?Math.max(0,t.label_weight-t.weight_used)/t.label_weight:0,note:t=>(t.note||"").toLowerCase(),data_origin:t=>(t.data_origin||"").toLowerCase(),tag_type:t=>(t.tag_type||"").toLowerCase(),stock:t=>t.slicer_filament?1:0,spool_name:t=>t.core_weight_catalog_id??0,cost_per_kg:t=>t.cost_per_kg??0,weight_check:t=>{if(t.last_scale_weight==null)return-1;const e=Math.max(0,t.label_weight-t.weight_used)+t.core_weight;return Math.abs(t.last_scale_weight-e)}},TL="bambuddy-inventory-sort";function tnt(){try{const t=localStorage.getItem(TL);if(t)return JSON.parse(t)}catch{}return null}function nnt(t){try{t?localStorage.setItem(TL,JSON.stringify(t)):localStorage.removeItem(TL)}catch{}}function rnt(){const{data:t}=et({queryKey:["spoolman-settings"],queryFn:ge.getSpoolmanSettings,staleTime:3e5});return t?.spoolman_enabled==="true"&&t?.spoolman_url?i.jsx("iframe",{src:t.spoolman_url,className:"h-full w-full border-0",title:"Spoolman",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"}):i.jsx(int,{})}function int(){const{t}=Dt(),e=sn(),{showToast:n}=bn(),[r,a]=w.useState(null),[s,o]=w.useState(null),[l,c]=w.useState("active"),[u,d]=w.useState("all"),[m,p]=w.useState(""),[f,y]=w.useState(""),[v,b]=w.useState(""),[g,_]=w.useState("all"),[N,C]=w.useState(""),[k,P]=w.useState("table"),[T,D]=w.useState(tnt),[A,R]=w.useState(Qtt),[G,z]=w.useState(!1),[Z,I]=w.useState(()=>{try{return localStorage.getItem("bambuddy-inventory-group")==="true"}catch{return!1}}),[J,ae]=w.useState(new Set),[Y,ue]=w.useState(0),[de,he]=w.useState(()=>{try{const ke=localStorage.getItem("bambuddy-inventory-pageSize");if(ke){const Ce=Number(ke);if([15,30,50,100,-1].includes(Ce))return Ce}}catch{}return 15}),{data:V}=et({queryKey:["settings"],queryFn:ge.getSettings}),ne=V?.date_format||"system",{data:se,isLoading:pe}=et({queryKey:["inventory-spools"],queryFn:()=>ge.getSpools(!0),refetchInterval:3e4}),{data:Te}=et({queryKey:["spool-assignments"],queryFn:()=>ge.getAssignments(),refetchInterval:3e4}),{data:q}=et({queryKey:["spool-catalog"],queryFn:()=>ge.getSpoolCatalog()}),X=gt({mutationFn:ke=>ge.deleteSpool(ke),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolDeleted"),"success")}}),j=gt({mutationFn:ke=>ge.archiveSpool(ke),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolArchived"),"success")}}),E=gt({mutationFn:ke=>ge.restoreSpool(ke),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolRestored"),"success")}}),U=async ke=>{if(ke.last_scale_weight!=null)try{await pa.updateSpoolWeight(ke.id,ke.last_scale_weight),e.invalidateQueries({queryKey:["inventory-spools"]});const Ce=[ke.brand,ke.material,ke.color_name].filter(Boolean).join(" ");n(`Synced "${Ce}" to scale weight`,"success")}catch{n("Failed to sync weight","error")}},K=V?.low_stock_threshold??20,[H,re]=w.useState(!1),[O,$]=w.useState(K.toString());w.useEffect(()=>{H||$(K.toString())},[K,H]);const ee=gt({mutationFn:ke=>ge.updateSettings({low_stock_threshold:ke}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]}),n(t("common.saved"),"success"),re(!1)},onError:()=>{n(t("inventory.lowStockThresholdError"),"error")}}),W=w.useMemo(()=>{if(!se)return null;let ke=0,Ce=0,$e=0,nt=0;const xt={};for(const vt of se){if(vt.archived_at)continue;nt++;const mt=Math.max(0,vt.label_weight-vt.weight_used);ke+=mt,Ce+=vt.weight_used,(vt.label_weight>0?mt/vt.label_weight*100:0){const ke={};for(const Ce of Te||[])ke[Ce.spool_id]=Ce;return ke},[Te]),xe=w.useMemo(()=>{const ke={};for(const Ce of q||[])ke[Ce.id]=Ce;return ke},[q]),oe=w.useMemo(()=>W?Object.entries(W.byMaterial).sort((ke,Ce)=>Ce[1].weight-ke[1].weight).slice(0,4):[],[W]),L=w.useMemo(()=>{let ke=se||[];if(l==="active"?ke=ke.filter(Ce=>!Ce.archived_at):ke=ke.filter(Ce=>!!Ce.archived_at),u==="used"?ke=ke.filter(Ce=>Ce.weight_used>0):u==="new"?ke=ke.filter(Ce=>Ce.weight_used===0):u==="lowstock"&&(ke=ke.filter(Ce=>{const $e=Math.max(0,Ce.label_weight-Ce.weight_used);return(Ce.label_weight>0?$e/Ce.label_weight*100:0)Ce.material===m)),f&&(ke=ke.filter(Ce=>Ce.brand===f)),v){const Ce=Number(v);ke=ke.filter($e=>$e.core_weight_catalog_id===Ce)}if(g==="stock"?ke=ke.filter(Ce=>!Ce.slicer_filament):g==="configured"&&(ke=ke.filter(Ce=>!!Ce.slicer_filament)),N){const Ce=N.toLowerCase();ke=ke.filter($e=>$e.brand?.toLowerCase().includes(Ce)||$e.material.toLowerCase().includes(Ce)||$e.color_name?.toLowerCase().includes(Ce)||$e.subtype?.toLowerCase().includes(Ce)||$e.note?.toLowerCase().includes(Ce)||$e.slicer_filament_name?.toLowerCase().includes(Ce))}return ke},[se,l,u,m,f,v,g,N,K]),F=()=>ue(0),te=[...new Set(se?.map(ke=>ke.material)||[])].sort(),ve=[...new Set(se?.map(ke=>ke.brand).filter(Boolean)||[])].sort(),fe=[...new Set(se?.map(ke=>ke.core_weight_catalog_id).filter(ke=>ke!=null)||[])].sort((ke,Ce)=>{const $e=(xe[ke]?.name||"").toLowerCase(),nt=(xe[Ce]?.name||"").toLowerCase();return $e.localeCompare(nt)}),me=l!=="active"||u!=="all"||!!m||!!f||!!v||g!=="all"||!!N,je=ke=>{R(ke),Ztt(ke)},we=w.useMemo(()=>A.filter(ke=>ke.visible).map(ke=>ke.id),[A]),Fe=ke=>{t3[ke]&&(D(Ce=>{let $e;return Ce?.column===ke?$e=Ce.direction==="asc"?{column:ke,direction:"desc"}:null:$e={column:ke,direction:"asc"},nnt($e),$e}),F())},He=w.useMemo(()=>{if(!T)return L;const ke=t3[T.column];return ke?[...L].sort(($e,nt)=>{const xt=ke($e,be),vt=ke(nt,be);return xtvt?T.direction==="asc"?1:-1:0}):L},[L,T,be]),Oe=w.useMemo(()=>{if(!Z)return He.map(nt=>({type:"single",spool:nt}));const ke=new Map;for(const nt of He)if(!(nt.weight_used>0||be[nt.id])){const xt=zY(nt),vt=ke.get(xt);vt?vt.push(nt):ke.set(xt,[nt])}const Ce=[],$e=new Set;for(const nt of He){if(nt.weight_used>0||be[nt.id]){Ce.push({type:"single",spool:nt});continue}const xt=zY(nt);if($e.has(xt))continue;$e.add(xt);const vt=ke.get(xt);vt.length===1?Ce.push({type:"single",spool:vt[0]}):Ce.push({type:"group",key:xt,spools:vt,representative:vt[0]})}return Ce},[He,Z,be]),_e=de===-1,Ae=Oe.length,Be=_e?Ae||1:de,Me=Math.max(1,Math.ceil(Ae/Be)),Xe=_e?0:Math.min(Y,Me-1),ye=_e?Oe:Oe.slice(Xe*Be,(Xe+1)*Be),We=()=>{const ke=!Z;I(ke),ae(new Set),F();try{localStorage.setItem("bambuddy-inventory-group",String(ke))}catch{}},Pe=ke=>{ae(Ce=>{const $e=new Set(Ce);return $e.has(ke)?$e.delete(ke):$e.add(ke),$e})},Ke=ke=>{he(ke),ue(0);try{localStorage.setItem("bambuddy-inventory-pageSize",String(ke))}catch{}},Ve=()=>{c("active"),d("all"),p(""),y(""),b(""),_("all"),C(""),F()};return i.jsxs("div",{className:"p-4 md:p-6 space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Wi,{className:"w-6 h-6 text-bambu-green"}),i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("inventory.title")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-9",children:(t("inventory.noSpools").split(".")[0],"")})]}),i.jsxs(ze,{onClick:()=>a({spool:null}),children:[i.jsx(ir,{className:"w-4 h-4"}),t("inventory.addSpool")]})]}),W&&!pe&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3",children:[i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(Wi,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalInventory")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:mu(W.totalWeight,!0)}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[W.totalSpools," ",W.totalSpools!==1?t("inventory.spools"):t("inventory.spool")]})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(XL,{className:"w-4 h-4 text-blue-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalConsumed")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:mu(W.totalConsumed,!0)}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.sinceTracking")})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(Gi,{className:"w-4 h-4 text-green-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.byMaterial")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:oe.map(([ke,Ce])=>i.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${Jtt[ke]||"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[ke," ",i.jsx("span",{className:"opacity-70",children:mu(Ce.weight,!0)})]},ke))})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(_r,{className:"w-4 h-4 text-purple-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.inPrinter")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:ie}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.loadedInAms")})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(jn,{className:"w-4 h-4 text-yellow-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.lowStock")})]}),i.jsx("div",{className:`text-xl font-bold ${W.lowStock>0?"text-yellow-400":"text-white"}`,children:W.lowStock}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1 flex items-center gap-2",children:H?i.jsxs("form",{onSubmit:ke=>{ke.preventDefault();const Ce=parseFloat(O);!isNaN(Ce)&&Ce>=.1&&Ce<=99.9?ee.mutate(Ce):n(t("inventory.lowStockThresholdError"),"error")},className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"<"}),i.jsx("input",{type:"text",inputMode:"decimal",pattern:"^\\d{0,2}(\\.\\d?)?$",maxLength:4,value:O,onChange:ke=>{const Ce=ke.target.value.replace(/[^\d.]/g,"");/^\d{0,2}(\.\d?)?$/.test(Ce)&&$(Ce)},className:"px-1.5 py-1 rounded border border-bambu-dark-tertiary text-xs text-white bg-bambu-dark-secondary focus:outline-none focus:border-bambu-green w-14 text-center",onWheel:ke=>ke.currentTarget.blur(),disabled:ee.isPending}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"%"}),i.jsx(ze,{type:"submit",size:"sm",disabled:ee.isPending,children:t("common.save")}),i.jsx(ze,{type:"button",size:"sm",variant:"ghost",onClick:()=>re(!1),disabled:ee.isPending,children:t("common.cancel")})]}):i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"text-bambu-gray",children:["< ",K,"%"]}),i.jsx("button",{className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:t("common.edit"),onClick:()=>{$(K.toString()),re(!0)},children:i.jsx(mh,{className:"w-4 h-4"})})]})})]})]}),i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between",children:[i.jsxs("div",{className:"relative flex-1 max-w-md",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),i.jsx("input",{type:"text",value:N,onChange:ke=>{C(ke.target.value),F()},placeholder:t("inventory.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),N&&i.jsx("button",{onClick:()=>{C(""),F()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[k==="table"&&i.jsxs("button",{onClick:()=>z(!0),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-bambu-gray border border-bambu-dark-tertiary rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t("inventory.configureColumns"),children:[i.jsx(wpe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.columns")})]}),i.jsxs("button",{onClick:We,className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium border rounded-lg transition-colors ${Z?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,title:t("inventory.groupSimilar"),children:[i.jsx(ffe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.groupSimilar")})]}),i.jsxs("div",{className:"flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>P("table"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${k==="table"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(sbe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.table")})]}),i.jsxs("button",{onClick:()=>P("cards"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${k==="cards"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(ww,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.cards")})]})]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsxs("button",{onClick:()=>{c("active"),F()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="active"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(Wi,{className:"w-3.5 h-3.5"}),t("inventory.active")]}),i.jsxs("button",{onClick:()=>{c("archived"),F()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="archived"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(Vs,{className:"w-3.5 h-3.5"}),t("inventory.archived")]})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsx("button",{onClick:()=>{d("all"),F()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),i.jsxs("button",{onClick:()=>{d("used"),F()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${u==="used"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(Zn,{className:"w-3.5 h-3.5"}),t("inventory.used")]}),i.jsx("button",{onClick:()=>{d("new"),F()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="new"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.new")}),i.jsxs("button",{onClick:()=>{d("lowstock"),F()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${u==="lowstock"?"bg-yellow-500/20 text-yellow-400":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(jn,{className:"w-3.5 h-3.5"}),t("inventory.lowStock")]})]}),i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsx("button",{onClick:()=>{_("all"),F()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${g==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),i.jsx("button",{onClick:()=>{_("stock"),F()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${g==="stock"?"bg-amber-500/20 text-amber-400":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.stock")}),i.jsx("button",{onClick:()=>{_("configured"),F()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${g==="configured"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.configured")})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("select",{value:m,onChange:ke=>{p(ke.target.value),F()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${m?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.material")}),te.map(ke=>i.jsx("option",{value:ke,children:ke},ke))]}),i.jsxs("select",{value:f,onChange:ke=>{y(ke.target.value),F()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${f?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.brand")}),ve.map(ke=>i.jsx("option",{value:ke,children:ke},ke))]}),fe.length>0&&i.jsxs("select",{value:v,onChange:ke=>{b(ke.target.value),F()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${v?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.spoolName")}),fe.map(ke=>i.jsx("option",{value:ke,children:xe[ke]?.name||`#${ke}`},ke))]}),me&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("button",{onClick:Ve,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:[i.jsx(Ht,{className:"w-3.5 h-3.5"}),t("inventory.clearFilters")]})]}),i.jsxs("span",{className:"ml-auto text-xs text-bambu-gray",children:[He.length," ",He.length!==1?t("inventory.spools"):t("inventory.spool"),Z&&Ae0?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:ye.map(ke=>{if(ke.type==="group"){const{key:vt,spools:mt,representative:qe}=ke,Nt=qe.rgba?`#${qe.rgba.substring(0,6)}`:"#808080",_t=J.has(vt);return i.jsxs("div",{className:"col-span-full",children:[i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-green/30 hover:border-bambu-green transition-colors cursor-pointer",onClick:()=>Pe(vt),children:[i.jsx("div",{className:"h-10 flex items-center px-4 gap-3",style:{backgroundColor:Nt},children:i.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:DI(qe.color_name,qe.rgba)||"-"})}),i.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(In,{className:`w-4 h-4 text-bambu-gray transition-transform ${_t?"":"-rotate-90"}`}),i.jsxs("div",{children:[i.jsxs("h3",{className:"font-semibold text-white",children:[qe.material,qe.subtype?` ${qe.subtype}`:""]}),i.jsx("p",{className:"text-sm text-bambu-gray",children:qe.brand||"-"})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:mu(qe.label_weight)}),i.jsx("span",{className:"text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full",children:t("inventory.groupedSpools",{count:mt.length})})]})]})]}),_t&&i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mt-2 ml-4",children:mt.map(rt=>{const Rt=Math.max(0,rt.label_weight-rt.weight_used),qt=rt.label_weight>0?Rt/rt.label_weight*100:0,Kt=rt.rgba?`#${rt.rgba.substring(0,6)}`:"#808080";return i.jsx(UY,{spool:rt,remaining:Rt,pct:qt,colorStyle:Kt,onClick:()=>a({spool:rt}),t},rt.id)})})]},`group-${vt}`)}const Ce=ke.spool,$e=Math.max(0,Ce.label_weight-Ce.weight_used),nt=Ce.label_weight>0?$e/Ce.label_weight*100:0,xt=Ce.rgba?`#${Ce.rgba.substring(0,6)}`:"#808080";return i.jsx(UY,{spool:Ce,remaining:$e,pct:nt,colorStyle:xt,onClick:()=>a({spool:Ce}),t},Ce.id)})}),i.jsx(ant,{pageIndex:Xe,pageSize:de,totalRows:Ae,totalPages:Me,onPageChange:ue,onPageSizeChange:Ke,t})]}):i.jsx(BY,{hasFilters:me,onAddSpool:()=>a({spool:null}),t}):ye.length>0?i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[we.map(ke=>{const Ce=!!t3[ke],$e=T?.column===ke;return i.jsx("th",{className:`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${ke==="remaining"?"min-w-[150px]":""} ${Ce?"cursor-pointer hover:text-bambu-green transition-colors":""} ${$e?"text-bambu-green":"text-bambu-gray"}`,onClick:Ce?()=>Fe(ke):void 0,children:i.jsxs("span",{className:"inline-flex items-center gap-1",children:[ent[ke]?.(t)??ke,Ce&&($e?T.direction==="asc"?i.jsx(Af,{className:"w-3 h-3"}):i.jsx(cx,{className:"w-3 h-3"}):i.jsx(qL,{className:"w-3 h-3 opacity-30"}))]})},ke)}),i.jsx("th",{className:"text-right py-3 px-4 text-xs font-medium text-bambu-gray uppercase tracking-wide",children:t("common.actions")})]})}),i.jsx("tbody",{children:ye.map(ke=>{if(ke.type==="group"){const{key:xt,spools:vt,representative:mt}=ke,qe=J.has(xt),Nt=Math.max(0,mt.label_weight-mt.weight_used),_t=mt.label_weight>0?Nt/mt.label_weight*100:0;return i.jsx(snt,{spools:vt,representative:mt,remaining:Nt,pct:_t,isExpanded:qe,onToggle:()=>Pe(xt),onEdit:rt=>a({spool:rt}),onArchive:rt=>o({type:"archive",spoolId:rt}),onDelete:rt=>o({type:"delete",spoolId:rt}),visibleColumns:we,assignmentMap:be,catalogMap:xe,currencySymbol:ce,dateFormat:ne,t,onSyncWeight:U},`group-${xt}`)}const Ce=ke.spool,$e=Math.max(0,Ce.label_weight-Ce.weight_used),nt=Ce.label_weight>0?$e/Ce.label_weight*100:0;return i.jsx(Zoe,{spool:Ce,remaining:$e,pct:nt,onEdit:()=>a({spool:Ce}),onRestore:()=>E.mutate(Ce.id),onArchive:()=>o({type:"archive",spoolId:Ce.id}),onDelete:()=>o({type:"delete",spoolId:Ce.id}),visibleColumns:we,assignmentMap:be,catalogMap:xe,currencySymbol:ce,dateFormat:ne,t,onSyncWeight:U},Ce.id)})})]})}),i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-bambu-dark-tertiary/50 border-t border-bambu-dark-tertiary text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:_e?`${Ae} ${t(Ae!==1?"inventory.spools":"inventory.spool")}`:i.jsxs(i.Fragment,{children:[t("inventory.showing")," ",Xe*Be+1," ",t("inventory.to")," ",Math.min((Xe+1)*Be,Ae)," ",t("inventory.of")," ",Ae," ",t("inventory.spools")]})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-gray",children:t("inventory.show")}),i.jsxs("select",{value:de,onChange:ke=>Ke(Number(ke.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(ke=>i.jsx("option",{value:ke,children:ke},ke)),i.jsx("option",{value:-1,children:t("inventory.all")})]}),!_e&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>ue(0),disabled:Xe===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"First page",children:i.jsx(VX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>ue(ke=>Math.max(0,ke-1)),disabled:Xe===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Cc,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[t("inventory.page")," ",Xe+1," ",t("inventory.of")," ",Me]}),i.jsx("button",{onClick:()=>ue(ke=>Math.min(Me-1,ke+1)),disabled:Xe>=Me-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(fa,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>ue(Me-1),disabled:Xe>=Me-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Last page",children:i.jsx(GX,{className:"w-4 h-4"})})]})]})]})]}):i.jsx(BY,{hasFilters:me,onAddSpool:()=>a({spool:null}),t}),r!==null&&i.jsx(Ytt,{isOpen:!0,onClose:()=>a(null),spool:r.spool,currencySymbol:ce}),s&&i.jsx(Nn,{title:s.type==="delete"?t("common.delete"):t("inventory.archive"),message:s.type==="delete"?t("inventory.deleteConfirm"):t("inventory.archiveConfirm"),confirmText:s.type==="delete"?t("common.delete"):t("inventory.archive"),variant:s.type==="delete"?"danger":"warning",onConfirm:()=>{s.type==="delete"?X.mutate(s.spoolId):j.mutate(s.spoolId),o(null)},onCancel:()=>o(null)}),i.jsx(Xtt,{isOpen:G,onClose:()=>z(!1),columns:A,defaultColumns:AN,onSave:je})]})}function ant({pageIndex:t,pageSize:e,totalRows:n,totalPages:r,onPageChange:a,onPageSizeChange:s,t:o}){const l=e===-1;if(r<=1&&!l)return null;const c=l?n||1:e;return i.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o(n!==1?"inventory.spools":"inventory.spool")}`:i.jsxs(i.Fragment,{children:[o("inventory.showing")," ",t*c+1," ",o("inventory.to")," ",Math.min((t+1)*c,n)," ",o("inventory.of")," ",n," ",o("inventory.spools")]})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-gray",children:o("inventory.show")}),i.jsxs("select",{value:e,onChange:u=>s(Number(u.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(u=>i.jsx("option",{value:u,children:u},u)),i.jsx("option",{value:-1,children:o("inventory.all")})]}),!l&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>a(0),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(VX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>a(Math.max(0,t-1)),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Cc,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("inventory.page")," ",t+1," ",o("inventory.of")," ",r]}),i.jsx("button",{onClick:()=>a(Math.min(r-1,t+1)),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(fa,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>a(r-1),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(GX,{className:"w-4 h-4"})})]})]})]})}function UY({spool:t,remaining:e,pct:n,colorStyle:r,onClick:a,t:s}){return i.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors cursor-pointer ${t.archived_at?"opacity-50":""}`,onClick:a,children:[i.jsx("div",{className:"h-14 flex items-center justify-center",style:{backgroundColor:r},children:i.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:DI(t.color_name,t.rgba)||"-"})}),i.jsxs("div",{className:"p-4 space-y-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"font-semibold text-white",children:[t.material,t.subtype?` ${t.subtype}`:""]}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t.brand||"-"})]}),i.jsxs("span",{className:"text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:["#",t.id]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[i.jsx("span",{children:s("inventory.remaining")}),i.jsxs("span",{children:[Math.round(n),"%"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${n>50?"bg-bambu-green":n>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(n,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(e),"g"]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[s("inventory.labelWeight"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:mu(t.label_weight)})]}),i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[s("inventory.weightUsed"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:t.weight_used>0?mu(t.weight_used):"-"})]})]}),t.note&&i.jsx("div",{className:"text-xs text-bambu-gray/60 pt-2 border-t border-bambu-dark-tertiary truncate",title:t.note,children:t.note})]})]})}function Zoe({spool:t,remaining:e,pct:n,onEdit:r,onRestore:a,onArchive:s,onDelete:o,visibleColumns:l,assignmentMap:c,catalogMap:u,currencySymbol:d,dateFormat:m,t:p,onSyncWeight:f}){return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer ${t.archived_at?"opacity-50":""}`,onClick:r,children:[l.map(y=>i.jsx("td",{className:"py-3 px-4",children:CL[y]?.({spool:t,remaining:e,pct:n,assignmentMap:c,catalogMap:u,currencySymbol:d,dateFormat:m,t:p,onSyncWeight:f})},y)),i.jsx("td",{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-center justify-end gap-1",onClick:y=>y.stopPropagation(),children:[i.jsx("button",{onClick:r,className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:p("common.edit"),children:i.jsx(mh,{className:"w-4 h-4"})}),t.archived_at?i.jsx("button",{onClick:a,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:p("inventory.restore"),children:i.jsx(To,{className:"w-4 h-4"})}):i.jsx("button",{onClick:s,className:"p-1.5 text-bambu-gray hover:text-yellow-400 rounded transition-colors",title:p("inventory.archive"),children:i.jsx(Vs,{className:"w-4 h-4"})}),i.jsx("button",{onClick:o,className:"p-1.5 text-bambu-gray hover:text-red-400 rounded transition-colors",title:p("common.delete"),children:i.jsx(nn,{className:"w-4 h-4"})})]})})]})}function snt({spools:t,representative:e,remaining:n,pct:r,isExpanded:a,onToggle:s,onEdit:o,onArchive:l,onDelete:c,visibleColumns:u,assignmentMap:d,catalogMap:m,currencySymbol:p,dateFormat:f,t:y,onSyncWeight:v}){return i.jsxs(i.Fragment,{children:[i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer bg-bambu-green/5",onClick:s,children:[u.map((b,g)=>i.jsx("td",{className:"py-3 px-4",children:g===0?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(In,{className:`w-4 h-4 text-bambu-gray transition-transform ${a?"":"-rotate-90"}`}),CL[b]?.({spool:e,remaining:n,pct:r,assignmentMap:d,catalogMap:m,currencySymbol:p,dateFormat:f,t:y,onSyncWeight:v})]}):b==="id"?i.jsx("span",{className:"text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full",children:y("inventory.groupedSpools",{count:t.length})}):CL[b]?.({spool:e,remaining:n,pct:r,assignmentMap:d,catalogMap:m,currencySymbol:p,dateFormat:f,t:y,onSyncWeight:v})},b)),i.jsx("td",{className:"py-3 px-4",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:t.map(b=>`#${b.id}`).join(", ")})})]}),a&&t.map(b=>{const g=Math.max(0,b.label_weight-b.weight_used),_=b.label_weight>0?g/b.label_weight*100:0;return i.jsx(Zoe,{spool:b,remaining:g,pct:_,onEdit:()=>o(b),onRestore:()=>{},onArchive:()=>l(b.id),onDelete:()=>c(b.id),visibleColumns:u,assignmentMap:d,catalogMap:m,currencySymbol:p,dateFormat:f,t:y,onSyncWeight:v},b.id)})]})}function BY({hasFilters:t,onAddSpool:e,t:n}){return i.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[i.jsxs("div",{className:"relative mb-6",children:[i.jsx("div",{className:"absolute inset-0 -m-4 bg-bambu-green/5 rounded-full blur-2xl"}),i.jsxs("div",{className:"relative flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-bambu-dark-secondary to-bambu-dark-tertiary border border-bambu-dark-tertiary shadow-lg",children:[i.jsx("div",{className:"absolute -top-1 -right-1 w-3 h-3 rounded-full bg-bambu-green/30"}),i.jsx("div",{className:"absolute -bottom-2 -left-2 w-2 h-2 rounded-full bg-bambu-green/20"}),t?i.jsx(Rr,{className:"w-10 h-10 text-bambu-gray/40",strokeWidth:1.5}):i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"w-14 h-14 rounded-full border-4 border-bambu-gray/20 flex items-center justify-center",children:i.jsx("div",{className:"w-6 h-6 rounded-full bg-bambu-gray/10 border-2 border-bambu-gray/20"})}),i.jsx("div",{className:"absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-bambu-green flex items-center justify-center shadow-md",children:i.jsx("span",{className:"text-white text-lg font-bold leading-none",children:"+"})})]})]})]}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2 text-center",children:t?n("inventory.noSpoolsMatch"):n("inventory.noSpools").split(".")[0]}),i.jsx("p",{className:"text-sm text-bambu-gray text-center max-w-sm mb-6",children:n(t?"inventory.noSpoolsMatchDesc":"inventory.noSpools")}),!t&&i.jsxs(ze,{onClick:e,children:[i.jsx(Wi,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})}const HY=["DEBUG","INFO","WARNING","ERROR"],n3={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},ont={DEBUG:ux,INFO:Hs,WARNING:jn,ERROR:Li};function lnt(){const t=sn(),[e,n]=w.useState(!0),[r,a]=w.useState(new Set),[s,o]=w.useState(""),[l,c]=w.useState("ALL"),[u,d]=w.useState(!1),[m,p]=w.useState(!1),f=w.useRef(null),{data:y,isLoading:v,refetch:b}=et({queryKey:["application-logs",l,s],queryFn:()=>Kb.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:m?2e3:!1,enabled:u});w.useEffect(()=>{u||p(!1)},[u]);const g=gt({mutationFn:()=>Kb.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});w.useEffect(()=>{e&&f.current&&y?.entries&&(f.current.scrollTop=f.current.scrollHeight)},[y?.entries,e]);const _=T=>{a(D=>{const A=new Set(D);return A.has(T)?A.delete(T):A.add(T),A})},N=T=>{const D=T.split(" ");return D.length>=2?D[1]:T},C=w.useMemo(()=>y?.entries??[],[y?.entries]),k=w.useMemo(()=>[...C].reverse(),[C]),P=({level:T})=>{const D=ont[T]||Hs;return i.jsx(D,{className:`w-3.5 h-3.5 ${n3[T]||"text-gray-400"}`})};return i.jsxs("div",{className:"bg-bambu-dark rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>d(!u),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/50 transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${m?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i.jsx(ux,{className:"w-5 h-5"})}),i.jsxs("div",{className:"text-left",children:[i.jsx("p",{className:"font-medium text-white",children:"Application Logs"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:m?`Live streaming - ${y?.filtered_count??0} entries`:"View and filter application logs"})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[m&&i.jsxs("span",{className:"flex items-center gap-1.5 px-2 py-1 bg-bambu-green/20 rounded text-bambu-green text-xs",children:[i.jsx("span",{className:"w-1.5 h-1.5 bg-bambu-green rounded-full animate-pulse"}),"Live"]}),u?i.jsx(Vl,{className:"w-5 h-5 text-bambu-gray"}):i.jsx(In,{className:"w-5 h-5 text-bambu-gray"})]})]}),u&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[m?i.jsxs("button",{onClick:T=>{T.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:[i.jsx(rl,{className:"w-4 h-4"}),"Stop"]}):i.jsxs("button",{onClick:T=>{T.stopPropagation(),p(!0),b()},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 rounded transition-colors",children:[i.jsx(Co,{className:"w-4 h-4"}),"Start"]}),i.jsxs("button",{onClick:()=>g.mutate(),disabled:g.isPending||C.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:[i.jsx(nn,{className:"w-4 h-4"}),"Clear"]}),i.jsx("button",{onClick:()=>b(),disabled:v,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:i.jsx(Sr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),i.jsx("div",{className:"flex-1"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:e,onChange:T=>n(T.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark-tertiary"}),"Auto-scroll"]}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[y?.filtered_count??0,"/",y?.total_in_file??0]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(Rr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:"Search message or logger name...",value:s,onChange:T=>o(T.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&&i.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark-secondary rounded border border-bambu-dark-tertiary",children:[i.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"}),HY.map((T,D)=>i.jsx("button",{onClick:()=>c(T),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${D===HY.length-1?"rounded-r":""} ${l===T?`${n3[T]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:T},T))]})]})]}),i.jsx("div",{ref:f,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:C.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-[300px] text-bambu-gray",children:[i.jsx("p",{className:"mb-2",children:"No log entries found"}),i.jsx("p",{className:"text-sm",children:"Log file may be empty or cleared"})]}):i.jsx("div",{className:"divide-y divide-bambu-dark-tertiary/30",children:k.map((T,D)=>{const A=r.has(D),R=T.message.includes(` +Difference: ${l}g (mismatch!)`;return i.jsxs("div",{className:`flex items-center gap-1 text-sm font-medium ${o?"text-green-400":"text-yellow-400"}`,title:c,children:[i.jsxs("span",{children:[Math.round(n),"g"]}),o?i.jsx(Zr,{className:"w-3 h-3"}):i.jsxs(i.Fragment,{children:[i.jsx(jn,{className:"w-3 h-3"}),e&&i.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),u.preventDefault(),e(t)},className:"p-1 hover:bg-bambu-green/20 rounded transition-colors text-bambu-green",title:"Sync: trust scale weight and reset tracking",children:i.jsx(Sr,{className:"w-3.5 h-3.5"})})]})]})}},t3={id:t=>t.id,added_time:t=>t.created_at||"",encode_time:t=>t.encode_time||"",last_used_time:t=>t.last_used||"",material:t=>(t.material||"").toLowerCase(),subtype:t=>(t.subtype||"").toLowerCase(),color_name:t=>(t.color_name||"").toLowerCase(),brand:t=>(t.brand||"").toLowerCase(),slicer_filament:t=>(t.slicer_filament_name||t.slicer_filament||"").toLowerCase(),location:(t,e)=>{const n=e[t.id];if(!n)return"";const r=n.ams_id===254||n.ams_id===255,a=!r&&n.ams_id>=128,s=n.ams_label?` (${n.ams_label})`:"";return`${n.printer_name||""} ${F4(n.ams_id,n.tray_id,a,r)}${s}`},label_weight:t=>t.label_weight,net:t=>Math.max(0,t.label_weight-t.weight_used),gross:t=>Math.max(0,t.label_weight-t.weight_used)+t.core_weight,used:t=>t.weight_used,remaining:t=>t.label_weight>0?Math.max(0,t.label_weight-t.weight_used)/t.label_weight:0,note:t=>(t.note||"").toLowerCase(),data_origin:t=>(t.data_origin||"").toLowerCase(),tag_type:t=>(t.tag_type||"").toLowerCase(),stock:t=>t.slicer_filament?1:0,spool_name:t=>t.core_weight_catalog_id??0,cost_per_kg:t=>t.cost_per_kg??0,weight_check:t=>{if(t.last_scale_weight==null)return-1;const e=Math.max(0,t.label_weight-t.weight_used)+t.core_weight;return Math.abs(t.last_scale_weight-e)}},TL="bambuddy-inventory-sort";function tnt(){try{const t=localStorage.getItem(TL);if(t)return JSON.parse(t)}catch{}return null}function nnt(t){try{t?localStorage.setItem(TL,JSON.stringify(t)):localStorage.removeItem(TL)}catch{}}function rnt(){const{data:t}=et({queryKey:["spoolman-settings"],queryFn:ge.getSpoolmanSettings,staleTime:3e5});return t?.spoolman_enabled==="true"&&t?.spoolman_url?i.jsx("iframe",{src:t.spoolman_url,className:"h-full w-full border-0",title:"Spoolman",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"}):i.jsx(int,{})}function int(){const{t}=Dt(),e=sn(),{showToast:n}=bn(),[r,a]=w.useState(null),[s,o]=w.useState(null),[l,c]=w.useState("active"),[u,d]=w.useState("all"),[m,p]=w.useState(""),[f,y]=w.useState(""),[v,b]=w.useState(""),[g,_]=w.useState("all"),[N,C]=w.useState(""),[k,P]=w.useState("table"),[T,D]=w.useState(tnt),[A,R]=w.useState(Qtt),[G,z]=w.useState(!1),[Z,I]=w.useState(()=>{try{return localStorage.getItem("bambuddy-inventory-group")==="true"}catch{return!1}}),[J,ae]=w.useState(new Set),[Y,ue]=w.useState(0),[de,he]=w.useState(()=>{try{const ke=localStorage.getItem("bambuddy-inventory-pageSize");if(ke){const Ce=Number(ke);if([15,30,50,100,-1].includes(Ce))return Ce}}catch{}return 15}),{data:V}=et({queryKey:["settings"],queryFn:ge.getSettings}),ne=V?.date_format||"system",{data:se,isLoading:pe}=et({queryKey:["inventory-spools"],queryFn:()=>ge.getSpools(!0),refetchInterval:3e4}),{data:Te}=et({queryKey:["spool-assignments"],queryFn:()=>ge.getAssignments(),refetchInterval:3e4}),{data:q}=et({queryKey:["spool-catalog"],queryFn:()=>ge.getSpoolCatalog()}),X=gt({mutationFn:ke=>ge.deleteSpool(ke),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolDeleted"),"success")}}),j=gt({mutationFn:ke=>ge.archiveSpool(ke),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolArchived"),"success")}}),E=gt({mutationFn:ke=>ge.restoreSpool(ke),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolRestored"),"success")}}),U=async ke=>{if(ke.last_scale_weight!=null)try{await pa.updateSpoolWeight(ke.id,ke.last_scale_weight),e.invalidateQueries({queryKey:["inventory-spools"]});const Ce=[ke.brand,ke.material,ke.color_name].filter(Boolean).join(" ");n(`Synced "${Ce}" to scale weight`,"success")}catch{n("Failed to sync weight","error")}},K=V?.low_stock_threshold??20,[H,re]=w.useState(!1),[O,$]=w.useState(K.toString());w.useEffect(()=>{H||$(K.toString())},[K,H]);const ee=gt({mutationFn:ke=>ge.updateSettings({low_stock_threshold:ke}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]}),n(t("common.saved"),"success"),re(!1)},onError:()=>{n(t("inventory.lowStockThresholdError"),"error")}}),W=w.useMemo(()=>{if(!se)return null;let ke=0,Ce=0,$e=0,nt=0;const xt={};for(const vt of se){if(vt.archived_at)continue;nt++;const mt=Math.max(0,vt.label_weight-vt.weight_used);ke+=mt,Ce+=vt.weight_used,(vt.label_weight>0?mt/vt.label_weight*100:0){const ke={};for(const Ce of Te||[])ke[Ce.spool_id]=Ce;return ke},[Te]),xe=w.useMemo(()=>{const ke={};for(const Ce of q||[])ke[Ce.id]=Ce;return ke},[q]),oe=w.useMemo(()=>W?Object.entries(W.byMaterial).sort((ke,Ce)=>Ce[1].weight-ke[1].weight).slice(0,4):[],[W]),L=w.useMemo(()=>{let ke=se||[];if(l==="active"?ke=ke.filter(Ce=>!Ce.archived_at):ke=ke.filter(Ce=>!!Ce.archived_at),u==="used"?ke=ke.filter(Ce=>Ce.weight_used>0):u==="new"?ke=ke.filter(Ce=>Ce.weight_used===0):u==="lowstock"&&(ke=ke.filter(Ce=>{const $e=Math.max(0,Ce.label_weight-Ce.weight_used);return(Ce.label_weight>0?$e/Ce.label_weight*100:0)Ce.material===m)),f&&(ke=ke.filter(Ce=>Ce.brand===f)),v){const Ce=Number(v);ke=ke.filter($e=>$e.core_weight_catalog_id===Ce)}if(g==="stock"?ke=ke.filter(Ce=>!Ce.slicer_filament):g==="configured"&&(ke=ke.filter(Ce=>!!Ce.slicer_filament)),N){const Ce=N.toLowerCase();ke=ke.filter($e=>$e.brand?.toLowerCase().includes(Ce)||$e.material.toLowerCase().includes(Ce)||$e.color_name?.toLowerCase().includes(Ce)||$e.subtype?.toLowerCase().includes(Ce)||$e.note?.toLowerCase().includes(Ce)||$e.slicer_filament_name?.toLowerCase().includes(Ce))}return ke},[se,l,u,m,f,v,g,N,K]),F=()=>ue(0),te=[...new Set(se?.map(ke=>ke.material)||[])].sort(),ve=[...new Set(se?.map(ke=>ke.brand).filter(Boolean)||[])].sort(),fe=[...new Set(se?.map(ke=>ke.core_weight_catalog_id).filter(ke=>ke!=null)||[])].sort((ke,Ce)=>{const $e=(xe[ke]?.name||"").toLowerCase(),nt=(xe[Ce]?.name||"").toLowerCase();return $e.localeCompare(nt)}),me=l!=="active"||u!=="all"||!!m||!!f||!!v||g!=="all"||!!N,je=ke=>{R(ke),Ztt(ke)},we=w.useMemo(()=>A.filter(ke=>ke.visible).map(ke=>ke.id),[A]),Fe=ke=>{t3[ke]&&(D(Ce=>{let $e;return Ce?.column===ke?$e=Ce.direction==="asc"?{column:ke,direction:"desc"}:null:$e={column:ke,direction:"asc"},nnt($e),$e}),F())},He=w.useMemo(()=>{if(!T)return L;const ke=t3[T.column];return ke?[...L].sort(($e,nt)=>{const xt=ke($e,be),vt=ke(nt,be);return xtvt?T.direction==="asc"?1:-1:0}):L},[L,T,be]),Oe=w.useMemo(()=>{if(!Z)return He.map(nt=>({type:"single",spool:nt}));const ke=new Map;for(const nt of He)if(!(nt.weight_used>0||be[nt.id])){const xt=zY(nt),vt=ke.get(xt);vt?vt.push(nt):ke.set(xt,[nt])}const Ce=[],$e=new Set;for(const nt of He){if(nt.weight_used>0||be[nt.id]){Ce.push({type:"single",spool:nt});continue}const xt=zY(nt);if($e.has(xt))continue;$e.add(xt);const vt=ke.get(xt);vt.length===1?Ce.push({type:"single",spool:vt[0]}):Ce.push({type:"group",key:xt,spools:vt,representative:vt[0]})}return Ce},[He,Z,be]),_e=de===-1,Ae=Oe.length,Be=_e?Ae||1:de,Me=Math.max(1,Math.ceil(Ae/Be)),Xe=_e?0:Math.min(Y,Me-1),ye=_e?Oe:Oe.slice(Xe*Be,(Xe+1)*Be),We=()=>{const ke=!Z;I(ke),ae(new Set),F();try{localStorage.setItem("bambuddy-inventory-group",String(ke))}catch{}},Pe=ke=>{ae(Ce=>{const $e=new Set(Ce);return $e.has(ke)?$e.delete(ke):$e.add(ke),$e})},Ke=ke=>{he(ke),ue(0);try{localStorage.setItem("bambuddy-inventory-pageSize",String(ke))}catch{}},Ve=()=>{c("active"),d("all"),p(""),y(""),b(""),_("all"),C(""),F()};return i.jsxs("div",{className:"p-4 md:p-6 space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Wi,{className:"w-6 h-6 text-bambu-green"}),i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("inventory.title")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-9",children:(t("inventory.noSpools").split(".")[0],"")})]}),i.jsxs(ze,{onClick:()=>a({spool:null}),children:[i.jsx(ir,{className:"w-4 h-4"}),t("inventory.addSpool")]})]}),W&&!pe&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3",children:[i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(Wi,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalInventory")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:mu(W.totalWeight,!0)}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[W.totalSpools," ",W.totalSpools!==1?t("inventory.spools"):t("inventory.spool")]})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(XL,{className:"w-4 h-4 text-blue-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalConsumed")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:mu(W.totalConsumed,!0)}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.sinceTracking")})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(Gi,{className:"w-4 h-4 text-green-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.byMaterial")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:oe.map(([ke,Ce])=>i.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${Jtt[ke]||"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[ke," ",i.jsx("span",{className:"opacity-70",children:mu(Ce.weight,!0)})]},ke))})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(_r,{className:"w-4 h-4 text-purple-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.inPrinter")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:ie}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.loadedInAms")})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(jn,{className:"w-4 h-4 text-yellow-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.lowStock")})]}),i.jsx("div",{className:`text-xl font-bold ${W.lowStock>0?"text-yellow-400":"text-white"}`,children:W.lowStock}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1 flex items-center gap-2",children:H?i.jsxs("form",{onSubmit:ke=>{ke.preventDefault();const Ce=parseFloat(O);!isNaN(Ce)&&Ce>=.1&&Ce<=99.9?ee.mutate(Ce):n(t("inventory.lowStockThresholdError"),"error")},className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"<"}),i.jsx("input",{type:"text",inputMode:"decimal",pattern:"^\\d{0,2}(\\.\\d?)?$",maxLength:4,value:O,onChange:ke=>{const Ce=ke.target.value.replace(/[^\d.]/g,"");/^\d{0,2}(\.\d?)?$/.test(Ce)&&$(Ce)},className:"px-1.5 py-1 rounded border border-bambu-dark-tertiary text-xs text-white bg-bambu-dark-secondary focus:outline-none focus:border-bambu-green w-14 text-center",onWheel:ke=>ke.currentTarget.blur(),disabled:ee.isPending}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"%"}),i.jsx(ze,{type:"submit",size:"sm",disabled:ee.isPending,children:t("common.save")}),i.jsx(ze,{type:"button",size:"sm",variant:"ghost",onClick:()=>re(!1),disabled:ee.isPending,children:t("common.cancel")})]}):i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"text-bambu-gray",children:["< ",K,"%"]}),i.jsx("button",{className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:t("common.edit"),onClick:()=>{$(K.toString()),re(!0)},children:i.jsx(mh,{className:"w-4 h-4"})})]})})]})]}),i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between",children:[i.jsxs("div",{className:"relative flex-1 max-w-md",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),i.jsx("input",{type:"text",value:N,onChange:ke=>{C(ke.target.value),F()},placeholder:t("inventory.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),N&&i.jsx("button",{onClick:()=>{C(""),F()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[k==="table"&&i.jsxs("button",{onClick:()=>z(!0),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-bambu-gray border border-bambu-dark-tertiary rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t("inventory.configureColumns"),children:[i.jsx(wpe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.columns")})]}),i.jsxs("button",{onClick:We,className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium border rounded-lg transition-colors ${Z?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,title:t("inventory.groupSimilar"),children:[i.jsx(ffe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.groupSimilar")})]}),i.jsxs("div",{className:"flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>P("table"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${k==="table"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(sbe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.table")})]}),i.jsxs("button",{onClick:()=>P("cards"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${k==="cards"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(ww,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.cards")})]})]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsxs("button",{onClick:()=>{c("active"),F()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="active"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(Wi,{className:"w-3.5 h-3.5"}),t("inventory.active")]}),i.jsxs("button",{onClick:()=>{c("archived"),F()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="archived"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(Vs,{className:"w-3.5 h-3.5"}),t("inventory.archived")]})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsx("button",{onClick:()=>{d("all"),F()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),i.jsxs("button",{onClick:()=>{d("used"),F()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${u==="used"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(Zn,{className:"w-3.5 h-3.5"}),t("inventory.used")]}),i.jsx("button",{onClick:()=>{d("new"),F()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="new"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.new")}),i.jsxs("button",{onClick:()=>{d("lowstock"),F()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${u==="lowstock"?"bg-yellow-500/20 text-yellow-400":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(jn,{className:"w-3.5 h-3.5"}),t("inventory.lowStock")]})]}),i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsx("button",{onClick:()=>{_("all"),F()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${g==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),i.jsx("button",{onClick:()=>{_("stock"),F()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${g==="stock"?"bg-amber-500/20 text-amber-400":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.stock")}),i.jsx("button",{onClick:()=>{_("configured"),F()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${g==="configured"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.configured")})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("select",{value:m,onChange:ke=>{p(ke.target.value),F()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${m?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.material")}),te.map(ke=>i.jsx("option",{value:ke,children:ke},ke))]}),i.jsxs("select",{value:f,onChange:ke=>{y(ke.target.value),F()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${f?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.brand")}),ve.map(ke=>i.jsx("option",{value:ke,children:ke},ke))]}),fe.length>0&&i.jsxs("select",{value:v,onChange:ke=>{b(ke.target.value),F()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${v?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.spoolName")}),fe.map(ke=>i.jsx("option",{value:ke,children:xe[ke]?.name||`#${ke}`},ke))]}),me&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("button",{onClick:Ve,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:[i.jsx(Ht,{className:"w-3.5 h-3.5"}),t("inventory.clearFilters")]})]}),i.jsxs("span",{className:"ml-auto text-xs text-bambu-gray",children:[He.length," ",He.length!==1?t("inventory.spools"):t("inventory.spool"),Z&&Ae0?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:ye.map(ke=>{if(ke.type==="group"){const{key:vt,spools:mt,representative:qe}=ke,Nt=qe.rgba?`#${qe.rgba.substring(0,6)}`:"#808080",_t=J.has(vt);return i.jsxs("div",{className:"col-span-full",children:[i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-green/30 hover:border-bambu-green transition-colors cursor-pointer",onClick:()=>Pe(vt),children:[i.jsx("div",{className:"h-10 flex items-center px-4 gap-3",style:{backgroundColor:Nt},children:i.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:D4(qe.color_name,qe.rgba)||"-"})}),i.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(In,{className:`w-4 h-4 text-bambu-gray transition-transform ${_t?"":"-rotate-90"}`}),i.jsxs("div",{children:[i.jsxs("h3",{className:"font-semibold text-white",children:[qe.material,qe.subtype?` ${qe.subtype}`:""]}),i.jsx("p",{className:"text-sm text-bambu-gray",children:qe.brand||"-"})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:mu(qe.label_weight)}),i.jsx("span",{className:"text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full",children:t("inventory.groupedSpools",{count:mt.length})})]})]})]}),_t&&i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mt-2 ml-4",children:mt.map(rt=>{const Rt=Math.max(0,rt.label_weight-rt.weight_used),qt=rt.label_weight>0?Rt/rt.label_weight*100:0,Kt=rt.rgba?`#${rt.rgba.substring(0,6)}`:"#808080";return i.jsx(UY,{spool:rt,remaining:Rt,pct:qt,colorStyle:Kt,onClick:()=>a({spool:rt}),t},rt.id)})})]},`group-${vt}`)}const Ce=ke.spool,$e=Math.max(0,Ce.label_weight-Ce.weight_used),nt=Ce.label_weight>0?$e/Ce.label_weight*100:0,xt=Ce.rgba?`#${Ce.rgba.substring(0,6)}`:"#808080";return i.jsx(UY,{spool:Ce,remaining:$e,pct:nt,colorStyle:xt,onClick:()=>a({spool:Ce}),t},Ce.id)})}),i.jsx(ant,{pageIndex:Xe,pageSize:de,totalRows:Ae,totalPages:Me,onPageChange:ue,onPageSizeChange:Ke,t})]}):i.jsx(BY,{hasFilters:me,onAddSpool:()=>a({spool:null}),t}):ye.length>0?i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[we.map(ke=>{const Ce=!!t3[ke],$e=T?.column===ke;return i.jsx("th",{className:`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${ke==="remaining"?"min-w-[150px]":""} ${Ce?"cursor-pointer hover:text-bambu-green transition-colors":""} ${$e?"text-bambu-green":"text-bambu-gray"}`,onClick:Ce?()=>Fe(ke):void 0,children:i.jsxs("span",{className:"inline-flex items-center gap-1",children:[ent[ke]?.(t)??ke,Ce&&($e?T.direction==="asc"?i.jsx(Af,{className:"w-3 h-3"}):i.jsx(cx,{className:"w-3 h-3"}):i.jsx(qL,{className:"w-3 h-3 opacity-30"}))]})},ke)}),i.jsx("th",{className:"text-right py-3 px-4 text-xs font-medium text-bambu-gray uppercase tracking-wide",children:t("common.actions")})]})}),i.jsx("tbody",{children:ye.map(ke=>{if(ke.type==="group"){const{key:xt,spools:vt,representative:mt}=ke,qe=J.has(xt),Nt=Math.max(0,mt.label_weight-mt.weight_used),_t=mt.label_weight>0?Nt/mt.label_weight*100:0;return i.jsx(snt,{spools:vt,representative:mt,remaining:Nt,pct:_t,isExpanded:qe,onToggle:()=>Pe(xt),onEdit:rt=>a({spool:rt}),onArchive:rt=>o({type:"archive",spoolId:rt}),onDelete:rt=>o({type:"delete",spoolId:rt}),visibleColumns:we,assignmentMap:be,catalogMap:xe,currencySymbol:ce,dateFormat:ne,t,onSyncWeight:U},`group-${xt}`)}const Ce=ke.spool,$e=Math.max(0,Ce.label_weight-Ce.weight_used),nt=Ce.label_weight>0?$e/Ce.label_weight*100:0;return i.jsx(Zoe,{spool:Ce,remaining:$e,pct:nt,onEdit:()=>a({spool:Ce}),onRestore:()=>E.mutate(Ce.id),onArchive:()=>o({type:"archive",spoolId:Ce.id}),onDelete:()=>o({type:"delete",spoolId:Ce.id}),visibleColumns:we,assignmentMap:be,catalogMap:xe,currencySymbol:ce,dateFormat:ne,t,onSyncWeight:U},Ce.id)})})]})}),i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-bambu-dark-tertiary/50 border-t border-bambu-dark-tertiary text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:_e?`${Ae} ${t(Ae!==1?"inventory.spools":"inventory.spool")}`:i.jsxs(i.Fragment,{children:[t("inventory.showing")," ",Xe*Be+1," ",t("inventory.to")," ",Math.min((Xe+1)*Be,Ae)," ",t("inventory.of")," ",Ae," ",t("inventory.spools")]})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-gray",children:t("inventory.show")}),i.jsxs("select",{value:de,onChange:ke=>Ke(Number(ke.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(ke=>i.jsx("option",{value:ke,children:ke},ke)),i.jsx("option",{value:-1,children:t("inventory.all")})]}),!_e&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>ue(0),disabled:Xe===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"First page",children:i.jsx(VX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>ue(ke=>Math.max(0,ke-1)),disabled:Xe===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Cc,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[t("inventory.page")," ",Xe+1," ",t("inventory.of")," ",Me]}),i.jsx("button",{onClick:()=>ue(ke=>Math.min(Me-1,ke+1)),disabled:Xe>=Me-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(fa,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>ue(Me-1),disabled:Xe>=Me-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Last page",children:i.jsx(GX,{className:"w-4 h-4"})})]})]})]})]}):i.jsx(BY,{hasFilters:me,onAddSpool:()=>a({spool:null}),t}),r!==null&&i.jsx(Ytt,{isOpen:!0,onClose:()=>a(null),spool:r.spool,currencySymbol:ce}),s&&i.jsx(Nn,{title:s.type==="delete"?t("common.delete"):t("inventory.archive"),message:s.type==="delete"?t("inventory.deleteConfirm"):t("inventory.archiveConfirm"),confirmText:s.type==="delete"?t("common.delete"):t("inventory.archive"),variant:s.type==="delete"?"danger":"warning",onConfirm:()=>{s.type==="delete"?X.mutate(s.spoolId):j.mutate(s.spoolId),o(null)},onCancel:()=>o(null)}),i.jsx(Xtt,{isOpen:G,onClose:()=>z(!1),columns:A,defaultColumns:AN,onSave:je})]})}function ant({pageIndex:t,pageSize:e,totalRows:n,totalPages:r,onPageChange:a,onPageSizeChange:s,t:o}){const l=e===-1;if(r<=1&&!l)return null;const c=l?n||1:e;return i.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o(n!==1?"inventory.spools":"inventory.spool")}`:i.jsxs(i.Fragment,{children:[o("inventory.showing")," ",t*c+1," ",o("inventory.to")," ",Math.min((t+1)*c,n)," ",o("inventory.of")," ",n," ",o("inventory.spools")]})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-gray",children:o("inventory.show")}),i.jsxs("select",{value:e,onChange:u=>s(Number(u.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(u=>i.jsx("option",{value:u,children:u},u)),i.jsx("option",{value:-1,children:o("inventory.all")})]}),!l&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>a(0),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(VX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>a(Math.max(0,t-1)),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Cc,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("inventory.page")," ",t+1," ",o("inventory.of")," ",r]}),i.jsx("button",{onClick:()=>a(Math.min(r-1,t+1)),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(fa,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>a(r-1),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(GX,{className:"w-4 h-4"})})]})]})]})}function UY({spool:t,remaining:e,pct:n,colorStyle:r,onClick:a,t:s}){return i.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors cursor-pointer ${t.archived_at?"opacity-50":""}`,onClick:a,children:[i.jsx("div",{className:"h-14 flex items-center justify-center",style:{backgroundColor:r},children:i.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:D4(t.color_name,t.rgba)||"-"})}),i.jsxs("div",{className:"p-4 space-y-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"font-semibold text-white",children:[t.material,t.subtype?` ${t.subtype}`:""]}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t.brand||"-"})]}),i.jsxs("span",{className:"text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:["#",t.id]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[i.jsx("span",{children:s("inventory.remaining")}),i.jsxs("span",{children:[Math.round(n),"%"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${n>50?"bg-bambu-green":n>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(n,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(e),"g"]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[s("inventory.labelWeight"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:mu(t.label_weight)})]}),i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[s("inventory.weightUsed"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:t.weight_used>0?mu(t.weight_used):"-"})]})]}),t.note&&i.jsx("div",{className:"text-xs text-bambu-gray/60 pt-2 border-t border-bambu-dark-tertiary truncate",title:t.note,children:t.note})]})]})}function Zoe({spool:t,remaining:e,pct:n,onEdit:r,onRestore:a,onArchive:s,onDelete:o,visibleColumns:l,assignmentMap:c,catalogMap:u,currencySymbol:d,dateFormat:m,t:p,onSyncWeight:f}){return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer ${t.archived_at?"opacity-50":""}`,onClick:r,children:[l.map(y=>i.jsx("td",{className:"py-3 px-4",children:CL[y]?.({spool:t,remaining:e,pct:n,assignmentMap:c,catalogMap:u,currencySymbol:d,dateFormat:m,t:p,onSyncWeight:f})},y)),i.jsx("td",{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-center justify-end gap-1",onClick:y=>y.stopPropagation(),children:[i.jsx("button",{onClick:r,className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:p("common.edit"),children:i.jsx(mh,{className:"w-4 h-4"})}),t.archived_at?i.jsx("button",{onClick:a,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:p("inventory.restore"),children:i.jsx(To,{className:"w-4 h-4"})}):i.jsx("button",{onClick:s,className:"p-1.5 text-bambu-gray hover:text-yellow-400 rounded transition-colors",title:p("inventory.archive"),children:i.jsx(Vs,{className:"w-4 h-4"})}),i.jsx("button",{onClick:o,className:"p-1.5 text-bambu-gray hover:text-red-400 rounded transition-colors",title:p("common.delete"),children:i.jsx(nn,{className:"w-4 h-4"})})]})})]})}function snt({spools:t,representative:e,remaining:n,pct:r,isExpanded:a,onToggle:s,onEdit:o,onArchive:l,onDelete:c,visibleColumns:u,assignmentMap:d,catalogMap:m,currencySymbol:p,dateFormat:f,t:y,onSyncWeight:v}){return i.jsxs(i.Fragment,{children:[i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer bg-bambu-green/5",onClick:s,children:[u.map((b,g)=>i.jsx("td",{className:"py-3 px-4",children:g===0?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(In,{className:`w-4 h-4 text-bambu-gray transition-transform ${a?"":"-rotate-90"}`}),CL[b]?.({spool:e,remaining:n,pct:r,assignmentMap:d,catalogMap:m,currencySymbol:p,dateFormat:f,t:y,onSyncWeight:v})]}):b==="id"?i.jsx("span",{className:"text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full",children:y("inventory.groupedSpools",{count:t.length})}):CL[b]?.({spool:e,remaining:n,pct:r,assignmentMap:d,catalogMap:m,currencySymbol:p,dateFormat:f,t:y,onSyncWeight:v})},b)),i.jsx("td",{className:"py-3 px-4",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:t.map(b=>`#${b.id}`).join(", ")})})]}),a&&t.map(b=>{const g=Math.max(0,b.label_weight-b.weight_used),_=b.label_weight>0?g/b.label_weight*100:0;return i.jsx(Zoe,{spool:b,remaining:g,pct:_,onEdit:()=>o(b),onRestore:()=>{},onArchive:()=>l(b.id),onDelete:()=>c(b.id),visibleColumns:u,assignmentMap:d,catalogMap:m,currencySymbol:p,dateFormat:f,t:y,onSyncWeight:v},b.id)})]})}function BY({hasFilters:t,onAddSpool:e,t:n}){return i.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[i.jsxs("div",{className:"relative mb-6",children:[i.jsx("div",{className:"absolute inset-0 -m-4 bg-bambu-green/5 rounded-full blur-2xl"}),i.jsxs("div",{className:"relative flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-bambu-dark-secondary to-bambu-dark-tertiary border border-bambu-dark-tertiary shadow-lg",children:[i.jsx("div",{className:"absolute -top-1 -right-1 w-3 h-3 rounded-full bg-bambu-green/30"}),i.jsx("div",{className:"absolute -bottom-2 -left-2 w-2 h-2 rounded-full bg-bambu-green/20"}),t?i.jsx(Rr,{className:"w-10 h-10 text-bambu-gray/40",strokeWidth:1.5}):i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"w-14 h-14 rounded-full border-4 border-bambu-gray/20 flex items-center justify-center",children:i.jsx("div",{className:"w-6 h-6 rounded-full bg-bambu-gray/10 border-2 border-bambu-gray/20"})}),i.jsx("div",{className:"absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-bambu-green flex items-center justify-center shadow-md",children:i.jsx("span",{className:"text-white text-lg font-bold leading-none",children:"+"})})]})]})]}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2 text-center",children:t?n("inventory.noSpoolsMatch"):n("inventory.noSpools").split(".")[0]}),i.jsx("p",{className:"text-sm text-bambu-gray text-center max-w-sm mb-6",children:n(t?"inventory.noSpoolsMatchDesc":"inventory.noSpools")}),!t&&i.jsxs(ze,{onClick:e,children:[i.jsx(Wi,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})}const HY=["DEBUG","INFO","WARNING","ERROR"],n3={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},ont={DEBUG:ux,INFO:Hs,WARNING:jn,ERROR:Li};function lnt(){const t=sn(),[e,n]=w.useState(!0),[r,a]=w.useState(new Set),[s,o]=w.useState(""),[l,c]=w.useState("ALL"),[u,d]=w.useState(!1),[m,p]=w.useState(!1),f=w.useRef(null),{data:y,isLoading:v,refetch:b}=et({queryKey:["application-logs",l,s],queryFn:()=>Kb.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:m?2e3:!1,enabled:u});w.useEffect(()=>{u||p(!1)},[u]);const g=gt({mutationFn:()=>Kb.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});w.useEffect(()=>{e&&f.current&&y?.entries&&(f.current.scrollTop=f.current.scrollHeight)},[y?.entries,e]);const _=T=>{a(D=>{const A=new Set(D);return A.has(T)?A.delete(T):A.add(T),A})},N=T=>{const D=T.split(" ");return D.length>=2?D[1]:T},C=w.useMemo(()=>y?.entries??[],[y?.entries]),k=w.useMemo(()=>[...C].reverse(),[C]),P=({level:T})=>{const D=ont[T]||Hs;return i.jsx(D,{className:`w-3.5 h-3.5 ${n3[T]||"text-gray-400"}`})};return i.jsxs("div",{className:"bg-bambu-dark rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>d(!u),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/50 transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${m?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i.jsx(ux,{className:"w-5 h-5"})}),i.jsxs("div",{className:"text-left",children:[i.jsx("p",{className:"font-medium text-white",children:"Application Logs"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:m?`Live streaming - ${y?.filtered_count??0} entries`:"View and filter application logs"})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[m&&i.jsxs("span",{className:"flex items-center gap-1.5 px-2 py-1 bg-bambu-green/20 rounded text-bambu-green text-xs",children:[i.jsx("span",{className:"w-1.5 h-1.5 bg-bambu-green rounded-full animate-pulse"}),"Live"]}),u?i.jsx(Vl,{className:"w-5 h-5 text-bambu-gray"}):i.jsx(In,{className:"w-5 h-5 text-bambu-gray"})]})]}),u&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[m?i.jsxs("button",{onClick:T=>{T.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:[i.jsx(rl,{className:"w-4 h-4"}),"Stop"]}):i.jsxs("button",{onClick:T=>{T.stopPropagation(),p(!0),b()},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 rounded transition-colors",children:[i.jsx(Co,{className:"w-4 h-4"}),"Start"]}),i.jsxs("button",{onClick:()=>g.mutate(),disabled:g.isPending||C.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:[i.jsx(nn,{className:"w-4 h-4"}),"Clear"]}),i.jsx("button",{onClick:()=>b(),disabled:v,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:i.jsx(Sr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),i.jsx("div",{className:"flex-1"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:e,onChange:T=>n(T.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark-tertiary"}),"Auto-scroll"]}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[y?.filtered_count??0,"/",y?.total_in_file??0]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(Rr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:"Search message or logger name...",value:s,onChange:T=>o(T.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&&i.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark-secondary rounded border border-bambu-dark-tertiary",children:[i.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"}),HY.map((T,D)=>i.jsx("button",{onClick:()=>c(T),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${D===HY.length-1?"rounded-r":""} ${l===T?`${n3[T]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:T},T))]})]})]}),i.jsx("div",{ref:f,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:C.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-[300px] text-bambu-gray",children:[i.jsx("p",{className:"mb-2",children:"No log entries found"}),i.jsx("p",{className:"text-sm",children:"Log file may be empty or cleared"})]}):i.jsx("div",{className:"divide-y divide-bambu-dark-tertiary/30",children:k.map((T,D)=>{const A=r.has(D),R=T.message.includes(` `);return i.jsx("div",{className:`p-2 cursor-pointer hover:bg-bambu-dark-secondary/50 transition-colors ${A?"bg-bambu-dark-secondary/30":""}`,onClick:()=>R&&_(D),children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("span",{className:"text-bambu-gray/70 shrink-0 w-20",children:N(T.timestamp)}),i.jsx("span",{className:"shrink-0",children:i.jsx(P,{level:T.level})}),i.jsxs("span",{className:"text-purple-400/80 shrink-0 max-w-[200px] truncate",title:T.logger_name,children:["[",T.logger_name,"]"]}),i.jsx("span",{className:`flex-1 ${n3[T.level]||"text-white/80"} ${!A&&R?"truncate":""}`,children:A?i.jsx("pre",{className:"whitespace-pre-wrap break-all",children:T.message}):T.message.split(` `)[0]}),R&&i.jsx("span",{className:"text-bambu-gray/50 shrink-0",children:A?i.jsx(Vl,{className:"w-3.5 h-3.5"}):i.jsx(In,{className:"w-3.5 h-3.5"})})]})},D)})})}),i.jsx("div",{className:"flex items-center justify-between p-3 border-t border-bambu-dark-tertiary text-sm text-bambu-gray",children:m?i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),"Auto-refreshing every 2 seconds"]}):i.jsx("span",{children:"Click Start to enable live log streaming"})})]})]})}function cnt(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 Ai({icon:t,label:e,value:n,subValue:r,color:a="text-bambu-green"}){return i.jsxs("div",{className:"flex items-start gap-3 p-4 bg-bambu-dark rounded-lg",children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark-tertiary ${a}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-lg font-semibold text-white truncate",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:r})]})]})}function $Y({percent:t,color:e="bg-bambu-green"}){return i.jsx("div",{className:"w-full h-2 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full ${e} transition-all duration-300`,style:{width:`${Math.min(100,t)}%`}})})}function Wm({title:t,icon:e,children:n}){return i.jsxs(Pt,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[i.jsx(e,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t})]}),n]})}function unt(){const{t}=Dt(),e=sn(),[n,r]=w.useState(null),[a,s]=w.useState(!1),[o,l]=w.useState(!1),{data:c,isLoading:u,refetch:d,isFetching:m}=et({queryKey:["systemInfo"],queryFn:ge.getSystemInfo,refetchInterval:3e4}),{data:p}=et({queryKey:["debugLogging"],queryFn:Kb.getDebugLoggingState,staleTime:10*1e3,refetchInterval:10*1e3}),{data:f}=et({queryKey:["settings"],queryFn:ge.getSettings}),{data:y}=et({queryKey:["library-stats"],queryFn:ge.getLibraryStats}),v=f?.time_format||"system",b=async()=>{l(!0);try{const C=await Kb.setDebugLogging(!p?.enabled);e.setQueryData(["debugLogging"],C)}catch(C){console.error("Failed to toggle debug logging:",C)}finally{l(!1)}},g=async()=>{r(null),s(!0);try{await Kb.downloadSupportBundle()}catch(C){r(C instanceof Error?C.message:"Failed to download support bundle")}finally{s(!1)}};if(u)return i.jsx("div",{className:"flex items-center justify-center h-64",children:i.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(!c)return i.jsx("div",{className:"p-6 text-center text-bambu-gray",children:t("system.failedToLoad","Failed to load system information")});const _=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 i.jsxs("div",{className:"p-6 space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("system.title","System Information")}),i.jsx("p",{className:"text-bambu-gray mt-1",children:t("system.subtitle","Monitor system resources and database statistics")})]}),i.jsxs("button",{onClick:()=>d(),disabled:m,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:[i.jsx(Sr,{className:`w-4 h-4 ${m?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),i.jsx(Wm,{title:t("system.application","Application"),icon:Op,children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsx(Ai,{icon:Op,label:t("system.version","Version"),value:`v${c.app.version}`}),i.jsx(Ai,{icon:Zn,label:t("system.uptime","System Uptime"),value:c.system.uptime_formatted}),i.jsx(Ai,{icon:Op,label:t("system.hostname","Hostname"),value:c.system.hostname})]})}),i.jsx(Wm,{title:t("support.title","Support & Troubleshooting"),icon:wfe,children:i.jsxs("div",{className:"space-y-4",children:[i.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.")}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${p?.enabled?"bg-amber-500/20 text-amber-500":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i.jsx(ux,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium text-white",children:t("support.debugLogging","Debug Logging")}),i.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&&i.jsxs("span",{className:"text-amber-400 ml-2",children:["(",Math.floor(p.duration_seconds/60),"m ",p.duration_seconds%60,"s)"]})]})]})]}),i.jsxs("button",{onClick:b,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&&i.jsx(ft,{className:"w-4 h-4 animate-spin"}),p?.enabled?t("support.disableDebug","Disable"):t("support.enableDebug","Enable")]})]}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-green",children:i.jsx(fi,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium text-white",children:t("support.supportBundle","Support Bundle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.supportBundleDescription","Download system info and logs as a ZIP file")})]})]}),i.jsxs("button",{onClick:g,disabled:a||!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:[a&&i.jsx(ft,{className:"w-4 h-4 animate-spin"}),t("common.download","Download")]})]}),n&&i.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&&i.jsx("div",{className:"p-4 bg-bambu-dark-tertiary/50 rounded-lg",children:i.jsxs("p",{className:"text-sm text-bambu-gray",children:[i.jsx("span",{className:"text-amber-400 font-medium",children:t("support.instructions","To report an issue:")}),i.jsx("br",{}),"1. ",t("support.step1","Enable debug logging"),i.jsx("br",{}),"2. ",t("support.step2","Reproduce the issue"),i.jsx("br",{}),"3. ",t("support.step3","Download the support bundle"),i.jsx("br",{}),"4. ",t("support.step4","Attach the ZIP file to your issue report")]})}),i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg space-y-3",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:t("support.privacyTitle","What's in the support bundle?")}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-sm",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-bambu-green font-medium mb-1",children:t("support.collected","Collected:")}),i.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[i.jsxs("li",{children:["• ",t("support.collectItem1","App version and debug mode")]}),i.jsxs("li",{children:["• ",t("support.collectItem2","OS, architecture, Python version")]}),i.jsxs("li",{children:["• ",t("support.collectItem3","Database statistics (counts only)")]}),i.jsxs("li",{children:["• ",t("support.collectItem4","Printer models and nozzle counts")]}),i.jsxs("li",{children:["• ",t("support.collectItem5","Non-sensitive settings (themes, formats)")]}),i.jsxs("li",{children:["• ",t("support.collectItem6","Debug logs (sanitized)")]}),i.jsxs("li",{children:["• ",t("support.collectItem7","Printer connectivity and firmware versions")]}),i.jsxs("li",{children:["• ",t("support.collectItem8","Integration status (Spoolman, MQTT, HA)")]}),i.jsxs("li",{children:["• ",t("support.collectItem9","Network interfaces (subnets only)")]}),i.jsxs("li",{children:["• ",t("support.collectItem10","Python package versions")]}),i.jsxs("li",{children:["• ",t("support.collectItem11","Database health checks")]}),i.jsxs("li",{children:["• ",t("support.collectItem12","Docker environment details")]})]})]}),i.jsxs("div",{children:[i.jsx("p",{className:"text-red-400 font-medium mb-1",children:t("support.notCollected","NOT collected:")}),i.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[i.jsxs("li",{children:["• ",t("support.notItem1","Printer names and serial numbers")]}),i.jsxs("li",{children:["• ",t("support.notItem2","Access codes and passwords")]}),i.jsxs("li",{children:["• ",t("support.notItem3","Email addresses")]}),i.jsxs("li",{children:["• ",t("support.notItem4","API keys and tokens")]}),i.jsxs("li",{children:["• ",t("support.notItem5","Webhook URLs")]}),i.jsxs("li",{children:["• ",t("support.notItem6","Your hostname or username")]}),i.jsxs("li",{children:["• ",t("support.notItem7","IP addresses")]})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:t("support.privacyNote","Email addresses in logs are replaced with [EMAIL], printer names with [PRINTER], serial numbers with [SERIAL], and IP addresses with [IP].")})]}),i.jsx(lnt,{})]})}),i.jsxs(Wm,{title:t("system.database","Database"),icon:hu,children:[i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[i.jsx(Ai,{icon:Vs,label:t("system.totalArchives","Total Archives"),value:c.database.archives}),i.jsx(Ai,{icon:vc,label:t("system.completed","Completed"),value:c.database.archives_completed,color:"text-green-500"}),i.jsx(Ai,{icon:Vi,label:t("system.failed","Failed"),value:c.database.archives_failed,color:"text-red-500"}),i.jsx(Ai,{icon:ft,label:t("system.printing","Printing"),value:c.database.archives_printing,color:"text-yellow-500"})]}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(Ai,{icon:_r,label:t("system.printers","Printers"),value:c.database.printers}),i.jsx(Ai,{icon:Sw,label:t("system.filaments","Filaments"),value:c.database.filaments}),i.jsx(Ai,{icon:vs,label:t("system.projects","Projects"),value:c.database.projects}),i.jsx(Ai,{icon:Ul,label:t("system.smartPlugs","Smart Plugs"),value:c.database.smart_plugs})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[i.jsx(Ai,{icon:Zn,label:t("system.totalPrintTime","Total Print Time"),value:c.database.total_print_time_formatted}),i.jsx(Ai,{icon:Vs,label:t("system.totalFilament","Total Filament Used"),value:`${c.database.total_filament_kg} kg`,subValue:`${c.database.total_filament_grams.toLocaleString()} g`})]})]}),i.jsxs(Wm,{title:t("system.connectedPrinters","Connected Printers"),icon:_r,children:[i.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[i.jsx("div",{className:"text-3xl font-bold text-bambu-green",children:c.printers.connected}),i.jsx("div",{className:"text-bambu-gray",children:t("system.ofTotal","of {{total}} printers connected",{total:c.printers.total})})]}),c.printers.connected_list.length>0?i.jsx("div",{className:"space-y-2",children:c.printers.connected_list.map(C=>i.jsxs("div",{className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green"}),i.jsx("span",{className:"font-medium text-white",children:C.name})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[i.jsx("span",{children:C.model}),i.jsx("span",{className:`px-2 py-0.5 rounded ${C.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":C.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:C.state})]})]},C.id))}):i.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),i.jsx(Wm,{title:t("system.storage","Storage"),icon:Vx,children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:t("system.diskUsage","Disk Usage")}),i.jsxs("span",{className:"text-white",children:[c.storage.disk_used_formatted," / ",c.storage.disk_total_formatted]})]}),i.jsx($Y,{percent:c.storage.disk_percent_used,color:_}),i.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),"%)"]})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsx(Ai,{icon:Vs,label:t("system.archiveStorage","Archive Storage"),value:c.storage.archive_size_formatted}),i.jsx(Ai,{icon:hu,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),y&&i.jsx(Ai,{icon:Ac,label:t("system.fileManagerStorage","File Manager"),value:cnt(y.total_size_bytes),subValue:`${y.total_files} files, ${y.total_folders} folders`})]})]})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[i.jsx(Wm,{title:t("system.memory","Memory"),icon:Jfe,children:i.jsx("div",{className:"space-y-4",children:i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:t("system.memoryUsage","Memory Usage")}),i.jsxs("span",{className:"text-white",children:[c.memory.used_formatted," / ",c.memory.total_formatted]})]}),i.jsx($Y,{percent:c.memory.percent_used,color:N}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.memory.available_formatted," ",t("system.available","available")]})]})})}),i.jsx(Wm,{title:t("system.cpu","CPU"),icon:m_,children:i.jsx("div",{className:"space-y-4",children:i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsx(Ai,{icon:m_,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),i.jsx(Ai,{icon:m_,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),i.jsx(Wm,{title:t("system.systemDetails","System Details"),icon:Op,children:i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(Ai,{icon:Op,label:t("system.os","Operating System"),value:c.system.platform,subValue:c.system.platform_release}),i.jsx(Ai,{icon:m_,label:t("system.architecture","Architecture"),value:c.system.architecture}),i.jsx(Ai,{icon:Op,label:t("system.python","Python"),value:c.system.python_version}),i.jsx(Ai,{icon:Zn,label:t("system.bootTime","Boot Time"),value:Df(c.system.boot_time,v)})]})})]})}function dnt(){const t=ol(),{t:e}=Dt(),{login:n}=Ar(),{showToast:r}=bn(),{mode:a}=ng(),[s,o]=w.useState(""),[l,c]=w.useState(""),[u,d]=w.useState(!1),[m,p]=w.useState(""),{data:f}=et({queryKey:["advancedAuthStatus"],queryFn:()=>ge.getAdvancedAuthStatus()}),y=gt({mutationFn:()=>n(s,l),onSuccess:()=>{r(e("login.loginSuccess")),t("/")},onError:_=>{r(_.message||e("login.loginFailed"),"error")}}),v=gt({mutationFn:_=>ge.forgotPassword({email:_}),onSuccess:_=>{r(_.message,"success"),d(!1),p("")},onError:_=>{r(_.message,"error")}}),b=_=>{if(_.preventDefault(),!s||!l){r(e("login.enterCredentials"),"error");return}y.mutate()},g=_=>{if(_.preventDefault(),!m){r("Please enter your email address","error");return}v.mutate(m)};return i.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:[i.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:[i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"flex items-center justify-center mb-6",children:i.jsx("img",{src:a==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),i.jsx("h2",{className:"text-3xl font-bold text-white",children:e("login.title")}),i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("login.subtitle")})]}),i.jsxs("form",{className:"mt-8 space-y-6",onSubmit:b,children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{htmlFor:"username",className:"block text-sm font-medium text-white mb-2",children:f?.advanced_auth_enabled?e("login.usernameOrEmail")||"Username or Email":e("login.username")}),i.jsx("input",{id:"username",type:"text",required:!0,value:s,onChange:_=>o(_.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:f?.advanced_auth_enabled?e("login.usernameOrEmailPlaceholder")||"Enter your username or email":e("login.usernamePlaceholder"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-white mb-2",children:e("login.password")}),i.jsx("input",{id:"password",type:"password",required:!0,value:l,onChange:_=>c(_.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"})]})]}),i.jsx("div",{children:i.jsx("button",{type:"submit",disabled:y.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:y.isPending?e("login.signingIn"):e("login.signIn")})}),f?.advanced_auth_enabled&&i.jsx("div",{className:"text-center",children:i.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:e("login.forgotPassword")})})]})]}),u&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>d(!1),children:i.jsxs(Pt,{className:"w-full max-w-md",onClick:_=>_.stopPropagation(),children:[i.jsx(Bn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(mx,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:e("login.forgotPasswordTitle")})]}),i.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{d(!1),p("")},children:i.jsx(Ht,{className:"w-5 h-5"})})]})}),i.jsx(Et,{children:f?.advanced_auth_enabled?i.jsxs("form",{onSubmit:g,className:"space-y-4",children:[i.jsx("p",{className:"text-bambu-gray text-sm",children:e("login.forgotPasswordEmailMessage")||"Enter your email address and we'll send you a new password."}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"forgot-email",className:"block text-sm font-medium text-white mb-2",children:e("login.emailAddress")||"Email Address"}),i.jsx("input",{id:"forgot-email",type:"email",required:!0,value:m,onChange:_=>p(_.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"})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ze,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{d(!1),p("")},children:e("login.cancel")||"Cancel"}),i.jsx(ze,{type:"submit",className:"flex-1",disabled:v.isPending,children:v.isPending?e("login.sending")||"Sending...":e("login.sendResetEmail")||"Send Reset Email"})]})]}):i.jsxs("div",{className:"space-y-4",children:[i.jsx("p",{className:"text-bambu-gray",children:e("login.forgotPasswordMessage")}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4 space-y-2",children:[i.jsx("p",{className:"text-sm text-white font-medium",children:e("login.howToReset")}),i.jsxs("ol",{className:"text-sm text-bambu-gray space-y-1 list-decimal list-inside",children:[i.jsx("li",{children:e("login.resetStep1")}),i.jsx("li",{children:e("login.resetStep2")}),i.jsx("li",{children:e("login.resetStep3")}),i.jsx("li",{children:e("login.resetStep4")})]})]}),i.jsx(ze,{variant:"secondary",className:"w-full",onClick:()=>d(!1),children:e("login.gotIt")})]})})]})})]})}function mnt(){const t=ol(),{t:e}=Dt(),{showToast:n}=bn(),{mode:r}=ng(),{refreshAuth:a}=Ar(),[s,o]=w.useState(!1),[l,c]=w.useState(""),[u,d]=w.useState(""),[m,p]=w.useState(""),f=gt({mutationFn:()=>ge.setupAuth({auth_enabled:s,admin_username:s?l:void 0,admin_password:s?u:void 0}),onSuccess:async v=>{await a(),v.auth_enabled?v.admin_created?(n(e("setup.toast.authEnabledAdminCreated")),t("/login")):(n(e("setup.toast.authEnabledExistingAdmins")),t("/login")):(n(e("setup.toast.setupCompleted")),t("/"))},onError:v=>{n(v.message,"error")}}),y=v=>{if(v.preventDefault(),s&&(l||u)){if(!l||!u){n(e("setup.toast.enterBothCredentials"),"error");return}if(u!==m){n(e("setup.toast.passwordsDoNotMatch"),"error");return}if(u.length<6){n(e("setup.toast.passwordTooShort"),"error");return}}f.mutate()};return i.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:i.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:[i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"flex items-center justify-center mb-6",children:i.jsx("img",{src:r==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),i.jsx("h2",{className:"text-3xl font-bold text-white",children:e("setup.title")}),i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("setup.subtitle")})]}),i.jsxs("form",{className:"mt-8 space-y-6",onSubmit:y,children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center p-4 bg-bambu-dark-secondary/50 rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("input",{id:"auth-enabled",type:"checkbox",checked:s,onChange:v=>o(v.target.checked),className:"h-4 w-4 text-bambu-green focus:ring-bambu-green border-bambu-dark-tertiary rounded bg-bambu-dark-secondary"}),i.jsx("label",{htmlFor:"auth-enabled",className:"ml-3 block text-sm font-medium text-white",children:e("setup.enableAuth")})]}),s&&i.jsxs("div",{className:"space-y-4 mt-4",children:[i.jsx("div",{className:"p-3 bg-bambu-dark-secondary/50 border border-bambu-dark-tertiary rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(Hs,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"text-sm text-bambu-gray",children:[i.jsx("p",{className:"text-white font-medium mb-1",children:e("setup.adminAccount")}),i.jsx("p",{children:e("setup.adminAccountDesc")})]})]})}),i.jsxs("div",{children:[i.jsxs("label",{htmlFor:"admin-username",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminUsername")," ",i.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),i.jsx("input",{id:"admin-username",type:"text",value:l,onChange:v=>c(v.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("setup.adminUsernamePlaceholder"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsxs("label",{htmlFor:"admin-password",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminPassword")," ",i.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),i.jsx("input",{id:"admin-password",type:"password",value:u,onChange:v=>d(v.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("setup.adminPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]}),u&&i.jsxs("div",{children:[i.jsx("label",{htmlFor:"confirm-password",className:"block text-sm font-medium text-white mb-2",children:e("setup.confirmPassword")}),i.jsx("input",{id:"confirm-password",type:"password",value:m,onChange:v=>p(v.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("setup.confirmPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]})]})]}),i.jsx("div",{children:i.jsx("button",{type:"submit",disabled:f.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:f.isPending?e("setup.settingUp"):e("setup.completeSetup")})})]})]})})}function hnt(){const{t}=Dt(),{user:e}=Ar(),{showToast:n}=bn(),r=sn(),a=ol(),[s,o]=w.useState(!0),[l,c]=w.useState(!0),[u,d]=w.useState(!0),[m,p]=w.useState(!0),[f,y]=w.useState(!1),{data:v,isLoading:b}=et({queryKey:["advancedAuthStatus"],queryFn:ge.getAdvancedAuthStatus,staleTime:300*1e3}),{data:g,isLoading:_}=et({queryKey:["settings"],queryFn:ge.getSettings,staleTime:300*1e3}),{data:N,isLoading:C}=et({queryKey:["user-email-preferences"],queryFn:()=>ge.getUserEmailPreferences()});w.useEffect(()=>{(v&&!v.advanced_auth_enabled||g&&!g.user_notifications_enabled)&&a("/settings",{replace:!0})},[v,g,a]),w.useEffect(()=>{N&&(o(N.notify_print_start),c(N.notify_print_complete),d(N.notify_print_failed),p(N.notify_print_stopped),y(!1))},[N]);const k=gt({mutationFn:()=>ge.updateUserEmailPreferences({notify_print_start:s,notify_print_complete:l,notify_print_failed:u,notify_print_stopped:m}),onSuccess:()=>{r.invalidateQueries({queryKey:["user-email-preferences"]}),y(!1),n(t("notifications.userEmail.saveSuccess"),"success")},onError:T=>{n(T.message||t("notifications.userEmail.saveError"),"error")}}),P=(T,D)=>{T(!D),y(!0)};return C||b||_?i.jsx("div",{className:"flex items-center justify-center h-64",children:i.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})}):i.jsxs("div",{className:"p-4 md:p-6 max-w-2xl mx-auto",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[i.jsx(_h,{className:"w-7 h-7 text-bambu-green"}),i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("notifications.userEmail.title")})]}),i.jsx(Pt,{className:"mb-6 border-blue-500/30 bg-blue-500/5",children:i.jsx(Et,{className:"py-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:i.jsx(mx,{className:"w-5 h-5 text-blue-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-white font-medium",children:t("notifications.userEmail.emailNotifications")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t("notifications.userEmail.emailNotificationsDesc")}),e?.email?i.jsxs("p",{className:"text-sm text-blue-400 mt-2",children:[t("notifications.userEmail.sendingTo"),": ",i.jsx("strong",{children:e.email})]}):i.jsx("p",{className:"text-sm text-yellow-400 mt-2",children:t("notifications.userEmail.noEmailWarning")})]})]})})}),i.jsxs(Pt,{className:"mb-6",children:[i.jsxs(Bn,{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("notifications.userEmail.printJobNotifications")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t("notifications.userEmail.printJobNotificationsDesc")})]}),i.jsxs(Et,{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${s?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:i.jsx(vc,{className:`w-5 h-5 ${s?"text-bambu-green":"text-bambu-gray"}`})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printJobStarts")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printJobStartsDesc")})]})]}),i.jsx("button",{onClick:()=>P(o,s),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${s?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,role:"switch","aria-checked":s,children:i.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${s?"translate-x-6":"translate-x-1"}`})})]}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${l?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:i.jsx(vc,{className:`w-5 h-5 ${l?"text-bambu-green":"text-bambu-gray"}`})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printJobFinishes")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printJobFinishesDesc")})]})]}),i.jsx("button",{onClick:()=>P(c,l),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${l?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,role:"switch","aria-checked":l,children:i.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l?"translate-x-6":"translate-x-1"}`})})]}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${u?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:i.jsx(vc,{className:`w-5 h-5 ${u?"text-bambu-green":"text-bambu-gray"}`})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printErrors")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printErrorsDesc")})]})]}),i.jsx("button",{onClick:()=>P(d,u),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${u?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,role:"switch","aria-checked":u,children:i.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${u?"translate-x-6":"translate-x-1"}`})})]}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${m?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:i.jsx(vc,{className:`w-5 h-5 ${m?"text-bambu-green":"text-bambu-gray"}`})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printJobStops")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printJobStopsDesc")})]})]}),i.jsx("button",{onClick:()=>P(p,m),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${m?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,role:"switch","aria-checked":m,children:i.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${m?"translate-x-6":"translate-x-1"}`})})]})]})]}),i.jsx("div",{className:"flex justify-end",children:i.jsx(ze,{onClick:()=>k.mutate(),disabled:!f||k.isPending||!e?.email,children:k.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ft,{className:"w-4 h-4 animate-spin"}),t("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(as,{className:"w-4 h-4"}),t("common.save")]})})})]})}function pnt(){const t=w.useRef(null),e=w.useRef(null),n=sn(),[r,a]=w.useState(!1),s=w.useRef(new Set),o=w.useRef(null),l=w.useRef(new Map),c=w.useRef(null),u=w.useRef([]),d=w.useRef(!1),m=w.useRef(()=>{}),p=w.useCallback(()=>{if(d.current||u.current.length===0)return;d.current=!0;const _=()=>{const N=u.current.shift();N?requestAnimationFrame(()=>{m.current(N),u.current.length>0?setTimeout(_,16):d.current=!1}):d.current=!1};_()},[]),f=w.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const N=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,C=new WebSocket(N);let k=null;C.onopen=()=>{console.log("[WebSocket] Connected"),a(!0),k=window.setInterval(()=>{C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:"ping"}))},3e4)},C.onmessage=P=>{try{const T=JSON.parse(P.data);T.type==="printer_status"&&T.printer_id!==void 0&&T.data?m.current(T):(u.current.push(T),p())}catch{}},C.onclose=P=>{console.log("[WebSocket] Closed",P.code,P.reason),k&&(clearInterval(k),k=null),a(!1),t.current=null,e.current=window.setTimeout(()=>{f()},3e3)},C.onerror=P=>{console.error("[WebSocket] Error",P),C.close()},t.current=C},[p]),y=w.useCallback((_,N)=>{const C=l.current.get(_)||{};l.current.set(_,{...C,...N}),c.current||(c.current=window.setTimeout(()=>{const k=new Map(l.current);l.current.clear(),c.current=null,requestAnimationFrame(()=>{k.forEach((P,T)=>{n.setQueryData(["printerStatus",T],D=>{const A={...D,...P};return A.wifi_signal==null&&D?.wifi_signal!=null&&(A.wifi_signal=D.wifi_signal),A})})})},100))},[n]),v=w.useCallback(_=>{s.current.add(_),o.current&&clearTimeout(o.current),o.current=window.setTimeout(()=>{const N=Array.from(s.current);s.current.clear(),o.current=null;let C=0;N.forEach(k=>{setTimeout(()=>{requestAnimationFrame(()=>{n.invalidateQueries({queryKey:[k]})})},C),C+=500})},3e3)},[n]),b=w.useCallback(_=>{switch(_.type){case"printer_status":_.printer_id!==void 0&&_.data&&y(_.printer_id,_.data);break;case"print_start":_.printer_id!==void 0&&n.invalidateQueries({queryKey:["printerStatus",_.printer_id]});break;case"print_complete":v("archives"),v("archiveStats");break;case"archive_created":v("archives"),v("archiveStats");break;case"archive_updated":v("archives");break;case"pong":break;case"plate_not_empty":window.dispatchEvent(new CustomEvent("plate-not-empty",{detail:{printer_id:_.printer_id,printer_name:_.printer_name,message:_.message}}));break;case"spool_auto_assigned":v("inventory-spools"),v("spool-assignments");break;case"spool_usage_logged":v("inventory-spools");break;case"unknown_tag":window.dispatchEvent(new CustomEvent("unknown-tag",{detail:{printer_id:_.printer_id,ams_id:_.ams_id,tray_id:_.tray_id,tag_uid:_.tag_uid,tray_uuid:_.tray_uuid}}));break;case"background_dispatch":window.dispatchEvent(new CustomEvent("background-dispatch",{detail:_.data||{}}));break;case"spoolbuddy_weight":window.dispatchEvent(new CustomEvent("spoolbuddy-weight",{detail:_}));break;case"spoolbuddy_tag_matched":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-matched",{detail:_})),v("inventory-spools");break;case"spoolbuddy_unknown_tag":window.dispatchEvent(new CustomEvent("spoolbuddy-unknown-tag",{detail:_}));break;case"spoolbuddy_tag_removed":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-removed",{detail:_}));break;case"spoolbuddy_tag_written":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-written",{detail:_})),v("inventory-spools");break;case"spoolbuddy_tag_write_failed":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-write-failed",{detail:_}));break;case"spoolbuddy_online":window.dispatchEvent(new CustomEvent("spoolbuddy-online",{detail:_})),v("spoolbuddy-devices"),v("spoolbuddy-update-check");break;case"spoolbuddy_offline":window.dispatchEvent(new CustomEvent("spoolbuddy-offline",{detail:_})),v("spoolbuddy-devices");break;case"spoolbuddy_update":v("spoolbuddy-devices"),v("spoolbuddy-update-check");break}},[n,v,y]);w.useEffect(()=>{m.current=b},[b]),w.useEffect(()=>(f(),()=>{e.current&&clearTimeout(e.current),o.current&&clearTimeout(o.current),c.current&&clearTimeout(c.current),t.current&&t.current.close()}),[f]);const g=w.useCallback(_=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(_))},[]);return{isConnected:r,sendMessage:g}}function fnt({selectedPrinterId:t,onPrinterChange:e,deviceOnline:n}){const{t:r}=Dt(),[a,s]=w.useState(new Date),{data:o=[]}=et({queryKey:["printers"],queryFn:()=>ge.getPrinters()}),l=tg({queries:o.map(d=>({queryKey:["printerStatus",d.id],queryFn:()=>ge.getPrinterStatus(d.id),refetchInterval:1e4}))}),c=w.useMemo(()=>o.filter((d,m)=>l[m]?.data?.connected),[o,l]);w.useEffect(()=>{const d=c.some(m=>m.id===t);(!t||!d)&&c.length>0&&e(c[0].id)},[c,t,e]);const{data:u}=et({queryKey:["settings"],queryFn:ge.getSettings});return w.useEffect(()=>{const d=setInterval(()=>s(new Date),1e3);return()=>clearInterval(d)},[]),i.jsxs("div",{className:"h-12 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary flex items-center px-3 gap-4 shrink-0",children:[i.jsx("div",{className:"flex items-center shrink-0",children:i.jsx("img",{src:"/img/spoolbuddy_logo_dark_small.png",alt:"SpoolBuddy",width:113,height:28,className:"h-7 w-auto"})}),i.jsx("div",{className:"flex-1 flex justify-center",children:i.jsx("select",{value:t??"",onChange:d=>e(Number(d.target.value)),className:"bg-bambu-dark text-white text-base px-4 py-2 rounded border border-bambu-dark-tertiary focus:outline-none focus:border-bambu-green min-w-[180px]",children:c.length===0?i.jsx("option",{value:"",children:r("spoolbuddy.status.noPrinters","No printers online")}):c.map(d=>i.jsx("option",{value:d.id,children:d.name},d.id))})}),i.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i.jsx("div",{className:"flex items-center",title:n?r("spoolbuddy.status.backend","Backend"):r("spoolbuddy.status.offline","Offline"),children:n?i.jsx("div",{className:"flex items-end gap-0.5 h-4",children:[1,2,3,4].map(d=>i.jsx("div",{className:`w-1 rounded-sm ${d<=4?"bg-white":"bg-bambu-dark-tertiary"}`,style:{height:`${d*4}px`}},d))}):i.jsx(zh,{className:"w-5 h-5 text-red-400"})}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:`w-3 h-3 rounded-full ${n?"bg-bambu-green shadow-[0_0_6px_rgba(34,197,94,0.5)]":"bg-bambu-gray"}`}),i.jsx("span",{className:"text-sm text-white/50",children:n?r("spoolbuddy.status.backend","Backend"):r("spoolbuddy.status.offline","Offline")})]}),i.jsx("span",{className:"text-white/50 text-base font-mono min-w-[50px] text-right",children:hQ(a,u?.time_format||"system")})]})]})}const gnt=[{to:"/spoolbuddy",labelKey:"spoolbuddy.nav.dashboard",fallback:"Dashboard",icon:i.jsx("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"})})},{to:"/spoolbuddy/ams",labelKey:"spoolbuddy.nav.ams",fallback:"AMS",icon:i.jsx("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})},{to:"/spoolbuddy/write-tag",labelKey:"spoolbuddy.nav.writeTag",fallback:"Write",icon:i.jsxs("svg",{className:"w-6 h-6",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:[i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.288 15.038a5.25 5.25 0 017.424 0M5.106 11.856c3.807-3.808 9.98-3.808 13.788 0M1.924 8.674c5.565-5.565 14.587-5.565 20.152 0"}),i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12.53 18.22l-.53.53-.53-.53a.75.75 0 011.06 0z"})]})},{to:"/spoolbuddy/settings",labelKey:"spoolbuddy.nav.settings",fallback:"Settings",icon:i.jsxs("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}];function bnt(){const{t}=Dt();return i.jsx("nav",{className:"h-14 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-stretch shrink-0",children:gnt.map(e=>i.jsxs(Ib,{to:e.to,end:e.to==="/spoolbuddy",className:({isActive:n})=>`flex-1 flex flex-col items-center justify-center gap-1 transition-colors ${n?"text-bambu-green bg-bambu-dark":"text-white/50 hover:text-white/70 hover:bg-bambu-dark-tertiary"}`,children:[e.icon,i.jsx("span",{className:"text-xs font-medium",children:t(e.labelKey,e.fallback)})]},e.to))})}function xnt({alert:t}){const{t:e}=Dt(),n=t?t.type==="error"?"bg-red-500":t.type==="warning"?"bg-amber-500":"bg-bambu-green":"bg-bambu-green",r=t?t.type==="error"?"border-red-500":t.type==="warning"?"border-amber-500":"border-bambu-dark-tertiary":"border-bambu-dark-tertiary";return i.jsxs("div",{className:`h-9 bg-bambu-dark-secondary border-t-2 ${r} flex items-center px-3 gap-3 shrink-0`,children:[i.jsx("div",{className:`w-3.5 h-3.5 rounded-full ${n} animate-pulse`}),i.jsx("div",{className:"flex-1 text-sm text-white/50 truncate",children:t?i.jsx("span",{children:t.message}):i.jsx("span",{className:"text-bambu-green",children:e("spoolbuddy.status.systemReady","System Ready")})})]})}const ynt={weight:null,weightStable:!1,rawAdc:null,matchedSpool:null,unknownTagUid:null,deviceOnline:!1,deviceId:null};function vnt(t,e){switch(e.type){case"WEIGHT_UPDATE":return{...t,weight:e.weight,weightStable:e.stable,rawAdc:e.rawAdc,deviceId:e.deviceId,deviceOnline:!0};case"TAG_MATCHED":return{...t,matchedSpool:e.spool,unknownTagUid:null,deviceId:e.deviceId};case"UNKNOWN_TAG":return{...t,matchedSpool:null,unknownTagUid:e.tagUid,deviceId:e.deviceId};case"TAG_REMOVED":return{...t,matchedSpool:null,unknownTagUid:null};case"DEVICE_ONLINE":return{...t,deviceOnline:!0,deviceId:e.deviceId};case"DEVICE_OFFLINE":return{...t,deviceOnline:!1,weight:null,weightStable:!1,rawAdc:null};default:return t}}function wnt(){const[t,e]=w.useReducer(vnt,ynt),n=w.useCallback(d=>{const m=d.detail;e({type:"WEIGHT_UPDATE",weight:m.weight_grams??m.data?.weight_grams,stable:m.stable??m.data?.stable??!1,rawAdc:m.raw_adc??m.data?.raw_adc??null,deviceId:m.device_id??m.data?.device_id??""})},[]),r=w.useCallback(d=>{const m=d.detail,p=m.spool??m.data?.spool;p&&e({type:"TAG_MATCHED",spool:{id:p.id,tag_uid:m.tag_uid??m.data?.tag_uid??"",material:p.material??"",subtype:p.subtype??null,color_name:p.color_name??null,rgba:p.rgba??null,brand:p.brand??null,label_weight:p.label_weight??0,core_weight:p.core_weight??0,weight_used:p.weight_used??0},deviceId:m.device_id??m.data?.device_id??""})},[]),a=w.useCallback(d=>{const m=d.detail;e({type:"UNKNOWN_TAG",tagUid:m.tag_uid??m.data?.tag_uid??"",deviceId:m.device_id??m.data?.device_id??""})},[]),s=w.useCallback(d=>{const m=d.detail;e({type:"TAG_REMOVED",deviceId:m.device_id??m.data?.device_id??""})},[]),o=w.useCallback(d=>{const m=d.detail;e({type:"DEVICE_ONLINE",deviceId:m.device_id??m.data?.device_id??""})},[]),l=w.useCallback(d=>{const m=d.detail;e({type:"DEVICE_OFFLINE",deviceId:m.device_id??m.data?.device_id??""})},[]);w.useEffect(()=>(window.addEventListener("spoolbuddy-weight",n),window.addEventListener("spoolbuddy-tag-matched",r),window.addEventListener("spoolbuddy-unknown-tag",a),window.addEventListener("spoolbuddy-tag-removed",s),window.addEventListener("spoolbuddy-online",o),window.addEventListener("spoolbuddy-offline",l),()=>{window.removeEventListener("spoolbuddy-weight",n),window.removeEventListener("spoolbuddy-tag-matched",r),window.removeEventListener("spoolbuddy-unknown-tag",a),window.removeEventListener("spoolbuddy-tag-removed",s),window.removeEventListener("spoolbuddy-online",o),window.removeEventListener("spoolbuddy-offline",l)}),[n,r,a,s,o,l]);const c=t.matchedSpool?Math.max(0,t.matchedSpool.label_weight-t.matchedSpool.weight_used):null,u=t.weight!==null&&t.matchedSpool?Math.max(0,t.weight-t.matchedSpool.core_weight):null;return{...t,remainingWeight:c,netWeight:u}}var PN={exports:{}};var Snt=PN.exports,qY;function _nt(){return qY||(qY=1,(function(t,e){(function(n,r){t.exports=r(Jf())})(Snt,(function(n){return(function(){var r={981:function(){typeof Element>"u"||"remove"in Element.prototype||(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)}),typeof self<"u"&&"document"in self&&((!("classList"in document.createElement("_"))||document.createElementNS&&!("classList"in document.createElementNS("http://www.w3.org/2000/svg","g")))&&(function(l){if("Element"in l){var c="classList",u="prototype",d=l.Element[u],m=Object,p=String[u].trim||function(){return this.replace(/^\s+|\s+$/g,"")},f=Array[u].indexOf||function(C){for(var k=0,P=this.length;k1?arguments[1]:void 0)}},7916:function(q,X,j){var E=j(6080),U=j(9565),K=j(8981),H=j(6319),re=j(4209),O=j(3517),$=j(6198),ee=j(4659),W=j(4527),ie=j(81),ce=j(851),be=Array;q.exports=function(xe){var oe=K(xe),L=O(this),F=arguments.length,te=F>1?arguments[1]:void 0,ve=te!==void 0;ve&&(te=E(te,F>2?arguments[2]:void 0));var fe,me,je,we,Fe,He,Oe=ce(oe),_e=0;if(!Oe||this===be&&re(Oe))for(fe=$(oe),me=L?new this(fe):be(fe);fe>_e;_e++)He=ve?te(oe[_e],_e):oe[_e],ee(me,_e,He);else for(me=L?new this:[],Fe=(we=ie(oe,Oe)).next;!(je=U(Fe,we)).done;_e++)He=ve?H(we,te,[je.value,_e],!0):je.value,ee(me,_e,He);return W(me,_e),me}},9617:function(q,X,j){var E=j(5397),U=j(5610),K=j(6198),H=function(re){return function(O,$,ee){var W=E(O),ie=K(W);if(ie===0)return!re&&-1;var ce,be=U(ee,ie);if(re&&$!=$){for(;ie>be;)if((ce=W[be++])!=ce)return!0}else for(;ie>be;be++)if((re||be in W)&&W[be]===$)return re||be||0;return!re&&-1}};q.exports={includes:H(!0),indexOf:H(!1)}},9213:function(q,X,j){var E=j(6080),U=j(7055),K=j(8981),H=j(6198),re=j(1469),O=j(4659),$=function(ee){var W=ee===1,ie=ee===2,ce=ee===3,be=ee===4,xe=ee===6,oe=ee===7,L=ee===5||xe;return function(F,te,ve){for(var fe,me,je=K(F),we=U(je),Fe=H(we),He=E(te,ve),Oe=0,_e=0,Ae=W?re(F,Fe):ie||oe?re(F,0):void 0;Fe>Oe;Oe++)if((L||Oe in we)&&(me=He(fe=we[Oe],Oe,je),ee))if(W)O(Ae,Oe,me);else if(me)switch(ee){case 3:return!0;case 5:return fe;case 6:return Oe;case 2:O(Ae,_e++,fe)}else switch(ee){case 4:return!1;case 7:O(Ae,_e++,fe)}return xe?-1:ce||be?be:Ae}};q.exports={forEach:$(0),map:$(1),filter:$(2),some:$(3),every:$(4),find:$(5),findIndex:$(6),filterReject:$(7)}},597:function(q,X,j){var E=j(9039),U=j(8227),K=j(9519),H=U("species");q.exports=function(re){return K>=51||!E((function(){var O=[];return(O.constructor={})[H]=function(){return{foo:1}},O[re](Boolean).foo!==1}))}},4598:function(q,X,j){var E=j(9039);q.exports=function(U,K){var H=[][U];return!!H&&E((function(){H.call(null,K||function(){return 1},1)}))}},926:function(q,X,j){var E=j(9306),U=j(8981),K=j(7055),H=j(6198),re=TypeError,O="Reduce of empty array with no initial value",$=function(ee){return function(W,ie,ce,be){var xe=U(W),oe=K(xe),L=H(xe);if(E(ie),L===0&&ce<2)throw new re(O);var F=ee?L-1:0,te=ee?-1:1;if(ce<2)for(;;){if(F in oe){be=oe[F],F+=te;break}if(F+=te,ee?F<0:L<=F)throw new re(O)}for(;ee?F>=0:L>F;F+=te)F in oe&&(be=ie(be,oe[F],F,xe));return be}};q.exports={left:$(!1),right:$(!0)}},4527:function(q,X,j){var E=j(3724),U=j(4376),K=TypeError,H=Object.getOwnPropertyDescriptor,re=E&&!(function(){if(this!==void 0)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(O){return O instanceof TypeError}})();q.exports=re?function(O,$){if(U(O)&&!H(O,"length").writable)throw new K("Cannot set read only .length");return O.length=$}:function(O,$){return O.length=$}},7680:function(q,X,j){var E=j(9504);q.exports=E([].slice)},4488:function(q,X,j){var E=j(7680),U=Math.floor,K=function(H,re){var O=H.length;if(O<8)for(var $,ee,W=1;W0;)H[ee]=H[--ee];ee!==W++&&(H[ee]=$)}else for(var ie=U(O/2),ce=K(E(H,0,ie),re),be=K(E(H,ie),re),xe=ce.length,oe=be.length,L=0,F=0;L9007199254740991)throw X("Maximum allowed index exceeded");return j}},7400:function(q){q.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},9296:function(q,X,j){var E=j(4055)("span").classList,U=E&&E.constructor&&E.constructor.prototype;q.exports=U===Object.prototype?void 0:U},8727:function(q){q.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},3709:function(q,X,j){var E=j(2839).match(/firefox\/(\d+)/i);q.exports=!!E&&+E[1]},3763:function(q,X,j){var E=j(2839);q.exports=/MSIE|Trident/.test(E)},6193:function(q,X,j){var E=j(4215);q.exports=E==="NODE"},2839:function(q,X,j){var E=j(4576).navigator,U=E&&E.userAgent;q.exports=U?String(U):""},9519:function(q,X,j){var E,U,K=j(4576),H=j(2839),re=K.process,O=K.Deno,$=re&&re.versions||O&&O.version,ee=$&&$.v8;ee&&(U=(E=ee.split("."))[0]>0&&E[0]<4?1:+(E[0]+E[1])),!U&&H&&(!(E=H.match(/Edge\/(\d+)/))||E[1]>=74)&&(E=H.match(/Chrome\/(\d+)/))&&(U=+E[1]),q.exports=U},3607:function(q,X,j){var E=j(2839).match(/AppleWebKit\/(\d+)\./);q.exports=!!E&&+E[1]},4215:function(q,X,j){var E=j(4576),U=j(2839),K=j(2195),H=function(re){return U.slice(0,re.length)===re};q.exports=H("Bun/")?"BUN":H("Cloudflare-Workers")?"CLOUDFLARE":H("Deno/")?"DENO":H("Node.js/")?"NODE":E.Bun&&typeof Bun.version=="string"?"BUN":E.Deno&&typeof Deno.version=="object"?"DENO":K(E.process)==="process"?"NODE":E.window&&E.document?"BROWSER":"REST"},6518:function(q,X,j){var E=j(4576),U=j(7347).f,K=j(6699),H=j(6840),re=j(9433),O=j(7740),$=j(2796);q.exports=function(ee,W){var ie,ce,be,xe,oe,L=ee.target,F=ee.global,te=ee.stat;if(ie=F?E:te?E[L]||re(L,{}):E[L]&&E[L].prototype)for(ce in W){if(xe=W[ce],be=ee.dontCallGetSet?(oe=U(ie,ce))&&oe.value:ie[ce],!$(F?ce:L+(te?".":"#")+ce,ee.forced)&&be!==void 0){if(typeof xe==typeof be)continue;O(xe,be)}(ee.sham||be&&be.sham)&&K(xe,"sham",!0),H(ie,ce,xe,ee)}}},9039:function(q){q.exports=function(X){try{return!!X()}catch{return!0}}},9228:function(q,X,j){j(7495);var E=j(9565),U=j(6840),K=j(7323),H=j(9039),re=j(8227),O=j(6699),$=re("species"),ee=RegExp.prototype;q.exports=function(W,ie,ce,be){var xe=re(W),oe=!H((function(){var ve={};return ve[xe]=function(){return 7},""[W](ve)!==7})),L=oe&&!H((function(){var ve=!1,fe=/a/;if(W==="split"){var me={};me[$]=function(){return fe},(fe={constructor:me,flags:""})[xe]=/./[xe]}return fe.exec=function(){return ve=!0,null},fe[xe](""),!ve}));if(!oe||!L||ce){var F=/./[xe],te=ie(xe,""[W],(function(ve,fe,me,je,we){var Fe=fe.exec;return Fe===K||Fe===ee.exec?oe&&!we?{done:!0,value:E(F,fe,me,je)}:{done:!0,value:E(ve,me,fe,je)}:{done:!1}}));U(String.prototype,W,te[0]),U(ee,xe,te[1])}be&&O(ee[xe],"sham",!0)}},8745:function(q,X,j){var E=j(616),U=Function.prototype,K=U.apply,H=U.call;q.exports=typeof Reflect=="object"&&Reflect.apply||(E?H.bind(K):function(){return H.apply(K,arguments)})},6080:function(q,X,j){var E=j(7476),U=j(9306),K=j(616),H=E(E.bind);q.exports=function(re,O){return U(re),O===void 0?re:K?H(re,O):function(){return re.apply(O,arguments)}}},616:function(q,X,j){var E=j(9039);q.exports=!E((function(){var U=(function(){}).bind();return typeof U!="function"||U.hasOwnProperty("prototype")}))},566:function(q,X,j){var E=j(9504),U=j(9306),K=j(34),H=j(9297),re=j(7680),O=j(616),$=Function,ee=E([].concat),W=E([].join),ie={};q.exports=O?$.bind:function(ce){var be=U(this),xe=be.prototype,oe=re(arguments,1),L=function(){var F=ee(oe,re(arguments));return this instanceof L?(function(te,ve,fe){if(!H(ie,ve)){for(var me=[],je=0;je]*>)/g,ee=/\$([$&'`]|\d{1,2})/g;q.exports=function(W,ie,ce,be,xe,oe){var L=ce+W.length,F=be.length,te=ee;return xe!==void 0&&(xe=U(xe),te=$),re(oe,te,(function(ve,fe){var me;switch(H(fe,0)){case"$":return"$";case"&":return W;case"`":return O(ie,0,ce);case"'":return O(ie,L);case"<":me=xe[O(fe,1,-1)];break;default:var je=+fe;if(je===0)return ve;if(je>F){var we=K(je/10);return we===0?ve:we<=F?be[we-1]===void 0?H(fe,1):be[we-1]+H(fe,1):ve}me=be[je-1]}return me===void 0?"":me}))}},4576:function(q,X,j){var E=function(U){return U&&U.Math===Math&&U};q.exports=E(typeof globalThis=="object"&&globalThis)||E(typeof window=="object"&&window)||E(typeof self=="object"&&self)||E(typeof j.g=="object"&&j.g)||E(typeof this=="object"&&this)||(function(){return this})()||Function("return this")()},9297:function(q,X,j){var E=j(9504),U=j(8981),K=E({}.hasOwnProperty);q.exports=Object.hasOwn||function(H,re){return K(U(H),re)}},421:function(q){q.exports={}},397:function(q,X,j){var E=j(7751);q.exports=E("document","documentElement")},5917:function(q,X,j){var E=j(3724),U=j(9039),K=j(4055);q.exports=!E&&!U((function(){return Object.defineProperty(K("div"),"a",{get:function(){return 7}}).a!==7}))},7055:function(q,X,j){var E=j(9504),U=j(9039),K=j(2195),H=Object,re=E("".split);q.exports=U((function(){return!H("z").propertyIsEnumerable(0)}))?function(O){return K(O)==="String"?re(O,""):H(O)}:H},3167:function(q,X,j){var E=j(4901),U=j(34),K=j(2967);q.exports=function(H,re,O){var $,ee;return K&&E($=re.constructor)&&$!==O&&U(ee=$.prototype)&&ee!==O.prototype&&K(H,ee),H}},3706:function(q,X,j){var E=j(9504),U=j(4901),K=j(7629),H=E(Function.toString);U(K.inspectSource)||(K.inspectSource=function(re){return H(re)}),q.exports=K.inspectSource},1181:function(q,X,j){var E,U,K,H=j(8622),re=j(4576),O=j(34),$=j(6699),ee=j(9297),W=j(7629),ie=j(6119),ce=j(421),be="Object already initialized",xe=re.TypeError,oe=re.WeakMap;if(H||W.state){var L=W.state||(W.state=new oe);L.get=L.get,L.has=L.has,L.set=L.set,E=function(te,ve){if(L.has(te))throw new xe(be);return ve.facade=te,L.set(te,ve),ve},U=function(te){return L.get(te)||{}},K=function(te){return L.has(te)}}else{var F=ie("state");ce[F]=!0,E=function(te,ve){if(ee(te,F))throw new xe(be);return ve.facade=te,$(te,F,ve),ve},U=function(te){return ee(te,F)?te[F]:{}},K=function(te){return ee(te,F)}}q.exports={set:E,get:U,has:K,enforce:function(te){return K(te)?U(te):E(te,{})},getterFor:function(te){return function(ve){var fe;if(!O(ve)||(fe=U(ve)).type!==te)throw new xe("Incompatible receiver, "+te+" required");return fe}}}},4209:function(q,X,j){var E=j(8227),U=j(6269),K=E("iterator"),H=Array.prototype;q.exports=function(re){return re!==void 0&&(U.Array===re||H[K]===re)}},4376:function(q,X,j){var E=j(2195);q.exports=Array.isArray||function(U){return E(U)==="Array"}},4901:function(q){var X=typeof document=="object"&&document.all;q.exports=X===void 0&&X!==void 0?function(j){return typeof j=="function"||j===X}:function(j){return typeof j=="function"}},3517:function(q,X,j){var E=j(9504),U=j(9039),K=j(4901),H=j(6955),re=j(7751),O=j(3706),$=function(){},ee=re("Reflect","construct"),W=/^\s*(?:class|function)\b/,ie=E(W.exec),ce=!W.test($),be=function(oe){if(!K(oe))return!1;try{return ee($,[],oe),!0}catch{return!1}},xe=function(oe){if(!K(oe))return!1;switch(H(oe)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ce||!!ie(W,O(oe))}catch{return!0}};xe.sham=!0,q.exports=!ee||U((function(){var oe;return be(be.call)||!be(Object)||!be((function(){oe=!0}))||oe}))?xe:be},2796:function(q,X,j){var E=j(9039),U=j(4901),K=/#|\.prototype\./,H=function(W,ie){var ce=O[re(W)];return ce===ee||ce!==$&&(U(ie)?E(ie):!!ie)},re=H.normalize=function(W){return String(W).replace(K,".").toLowerCase()},O=H.data={},$=H.NATIVE="N",ee=H.POLYFILL="P";q.exports=H},2087:function(q,X,j){var E=j(34),U=Math.floor;q.exports=Number.isInteger||function(K){return!E(K)&&isFinite(K)&&U(K)===K}},4117:function(q){q.exports=function(X){return X==null}},34:function(q,X,j){var E=j(4901);q.exports=function(U){return typeof U=="object"?U!==null:E(U)}},3925:function(q,X,j){var E=j(34);q.exports=function(U){return E(U)||U===null}},6395:function(q){q.exports=!1},5810:function(q,X,j){var E=j(34),U=j(1181).get;q.exports=function(K){if(!E(K))return!1;var H=U(K);return!!H&&H.type==="RawJSON"}},788:function(q,X,j){var E=j(34),U=j(2195),K=j(8227)("match");q.exports=function(H){var re;return E(H)&&((re=H[K])!==void 0?!!re:U(H)==="RegExp")}},757:function(q,X,j){var E=j(7751),U=j(4901),K=j(1625),H=j(7040),re=Object;q.exports=H?function(O){return typeof O=="symbol"}:function(O){var $=E("Symbol");return U($)&&K($.prototype,re(O))}},9539:function(q,X,j){var E=j(9565),U=j(8551),K=j(5966);q.exports=function(H,re,O){var $,ee;U(H);try{if(!($=K(H,"return"))){if(re==="throw")throw O;return O}$=E($,H)}catch(W){ee=!0,$=W}if(re==="throw")throw O;if(ee)throw $;return U($),O}},3994:function(q,X,j){var E=j(7657).IteratorPrototype,U=j(2360),K=j(6980),H=j(687),re=j(6269),O=function(){return this};q.exports=function($,ee,W,ie){var ce=ee+" Iterator";return $.prototype=U(E,{next:K(+!ie,W)}),H($,ce,!1,!0),re[ce]=O,$}},1088:function(q,X,j){var E=j(6518),U=j(9565),K=j(6395),H=j(350),re=j(4901),O=j(3994),$=j(2787),ee=j(2967),W=j(687),ie=j(6699),ce=j(6840),be=j(8227),xe=j(6269),oe=j(7657),L=H.PROPER,F=H.CONFIGURABLE,te=oe.IteratorPrototype,ve=oe.BUGGY_SAFARI_ITERATORS,fe=be("iterator"),me="keys",je="values",we="entries",Fe=function(){return this};q.exports=function(He,Oe,_e,Ae,Be,Me,Xe){O(_e,Oe,Ae);var ye,We,Pe,Ke=function(vt){if(vt===Be&&nt)return nt;if(!ve&&vt&&vt in Ce)return Ce[vt];switch(vt){case me:case je:case we:return function(){return new _e(this,vt)}}return function(){return new _e(this)}},Ve=Oe+" Iterator",ke=!1,Ce=He.prototype,$e=Ce[fe]||Ce["@@iterator"]||Be&&Ce[Be],nt=!ve&&$e||Ke(Be),xt=Oe==="Array"&&Ce.entries||$e;if(xt&&(ye=$(xt.call(new He)))!==Object.prototype&&ye.next&&(K||$(ye)===te||(ee?ee(ye,te):re(ye[fe])||ce(ye,fe,Fe)),W(ye,Ve,!0,!0),K&&(xe[Ve]=Fe)),L&&Be===je&&$e&&$e.name!==je&&(!K&&F?ie(Ce,"name",je):(ke=!0,nt=function(){return U($e,this)})),Be)if(We={values:Ke(je),keys:Me?nt:Ke(me),entries:Ke(we)},Xe)for(Pe in We)(ve||ke||!(Pe in Ce))&&ce(Ce,Pe,We[Pe]);else E({target:Oe,proto:!0,forced:ve||ke},We);return K&&!Xe||Ce[fe]===nt||ce(Ce,fe,nt,{name:Be}),xe[Oe]=nt,We}},7657:function(q,X,j){var E,U,K,H=j(9039),re=j(4901),O=j(34),$=j(2360),ee=j(2787),W=j(6840),ie=j(8227),ce=j(6395),be=ie("iterator"),xe=!1;[].keys&&("next"in(K=[].keys())?(U=ee(ee(K)))!==Object.prototype&&(E=U):xe=!0),!O(E)||H((function(){var oe={};return E[be].call(oe)!==oe}))?E={}:ce&&(E=$(E)),re(E[be])||W(E,be,(function(){return this})),q.exports={IteratorPrototype:E,BUGGY_SAFARI_ITERATORS:xe}},6269:function(q){q.exports={}},6198:function(q,X,j){var E=j(8014);q.exports=function(U){return E(U.length)}},283:function(q,X,j){var E=j(9504),U=j(9039),K=j(4901),H=j(9297),re=j(3724),O=j(350).CONFIGURABLE,$=j(3706),ee=j(1181),W=ee.enforce,ie=ee.get,ce=String,be=Object.defineProperty,xe=E("".slice),oe=E("".replace),L=E([].join),F=re&&!U((function(){return be((function(){}),"length",{value:8}).length!==8})),te=String(String).split("String"),ve=q.exports=function(fe,me,je){xe(ce(me),0,7)==="Symbol("&&(me="["+oe(ce(me),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),je&&je.getter&&(me="get "+me),je&&je.setter&&(me="set "+me),(!H(fe,"name")||O&&fe.name!==me)&&(re?be(fe,"name",{value:me,configurable:!0}):fe.name=me),F&&je&&H(je,"arity")&&fe.length!==je.arity&&be(fe,"length",{value:je.arity});try{je&&H(je,"constructor")&&je.constructor?re&&be(fe,"prototype",{writable:!1}):fe.prototype&&(fe.prototype=void 0)}catch{}var we=W(fe);return H(we,"source")||(we.source=L(te,typeof me=="string"?me:"")),fe};Function.prototype.toString=ve((function(){return K(this)&&ie(this).source||$(this)}),"toString")},741:function(q){var X=Math.ceil,j=Math.floor;q.exports=Math.trunc||function(E){var U=+E;return(U>0?j:X)(U)}},7819:function(q,X,j){var E=j(9039);q.exports=!E((function(){var U="9007199254740993",K=JSON.rawJSON(U);return!JSON.isRawJSON(K)||JSON.stringify(K)!==U}))},5749:function(q,X,j){var E=j(788),U=TypeError;q.exports=function(K){if(E(K))throw new U("The method doesn't accept regular expressions");return K}},4213:function(q,X,j){var E=j(3724),U=j(9504),K=j(9565),H=j(9039),re=j(1072),O=j(3717),$=j(8773),ee=j(8981),W=j(7055),ie=Object.assign,ce=Object.defineProperty,be=U([].concat);q.exports=!ie||H((function(){if(E&&ie({b:1},ie(ce({},"a",{enumerable:!0,get:function(){ce(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var xe={},oe={},L=Symbol("assign detection"),F="abcdefghijklmnopqrst";return xe[L]=7,F.split("").forEach((function(te){oe[te]=te})),ie({},xe)[L]!==7||re(ie({},oe)).join("")!==F}))?function(xe,oe){for(var L=ee(xe),F=arguments.length,te=1,ve=O.f,fe=$.f;F>te;)for(var me,je=W(arguments[te++]),we=ve?be(re(je),ve(je)):re(je),Fe=we.length,He=0;Fe>He;)me=we[He++],E&&!K(fe,je,me)||(L[me]=je[me]);return L}:ie},2360:function(q,X,j){var E,U=j(8551),K=j(6801),H=j(8727),re=j(421),O=j(397),$=j(4055),ee=j(6119),W="prototype",ie="script",ce=ee("IE_PROTO"),be=function(){},xe=function(F){return"<"+ie+">"+F+""},oe=function(F){F.write(xe("")),F.close();var te=F.parentWindow.Object;return F=null,te},L=function(){try{E=new ActiveXObject("htmlfile")}catch{}var F,te,ve;L=typeof document<"u"?document.domain&&E?oe(E):(te=$("iframe"),ve="java"+ie+":",te.style.display="none",O.appendChild(te),te.src=String(ve),(F=te.contentWindow.document).open(),F.write(xe("document.F=Object")),F.close(),F.F):oe(E);for(var fe=H.length;fe--;)delete L[W][H[fe]];return L()};re[ce]=!0,q.exports=Object.create||function(F,te){var ve;return F!==null?(be[W]=U(F),ve=new be,be[W]=null,ve[ce]=F):ve=L(),te===void 0?ve:K.f(ve,te)}},6801:function(q,X,j){var E=j(3724),U=j(8686),K=j(4913),H=j(8551),re=j(5397),O=j(1072);X.f=E&&!U?Object.defineProperties:function($,ee){H($);for(var W,ie=re(ee),ce=O(ee),be=ce.length,xe=0;be>xe;)K.f($,W=ce[xe++],ie[W]);return $}},4913:function(q,X,j){var E=j(3724),U=j(5917),K=j(8686),H=j(8551),re=j(6969),O=TypeError,$=Object.defineProperty,ee=Object.getOwnPropertyDescriptor,W="enumerable",ie="configurable",ce="writable";X.f=E?K?function(be,xe,oe){if(H(be),xe=re(xe),H(oe),typeof be=="function"&&xe==="prototype"&&"value"in oe&&ce in oe&&!oe[ce]){var L=ee(be,xe);L&&L[ce]&&(be[xe]=oe.value,oe={configurable:ie in oe?oe[ie]:L[ie],enumerable:W in oe?oe[W]:L[W],writable:!1})}return $(be,xe,oe)}:$:function(be,xe,oe){if(H(be),xe=re(xe),H(oe),U)try{return $(be,xe,oe)}catch{}if("get"in oe||"set"in oe)throw new O("Accessors not supported");return"value"in oe&&(be[xe]=oe.value),be}},7347:function(q,X,j){var E=j(3724),U=j(9565),K=j(8773),H=j(6980),re=j(5397),O=j(6969),$=j(9297),ee=j(5917),W=Object.getOwnPropertyDescriptor;X.f=E?W:function(ie,ce){if(ie=re(ie),ce=O(ce),ee)try{return W(ie,ce)}catch{}if($(ie,ce))return H(!U(K.f,ie,ce),ie[ce])}},298:function(q,X,j){var E=j(2195),U=j(5397),K=j(8480).f,H=j(7680),re=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];q.exports.f=function(O){return re&&E(O)==="Window"?(function($){try{return K($)}catch{return H(re)}})(O):K(U(O))}},8480:function(q,X,j){var E=j(1828),U=j(8727).concat("length","prototype");X.f=Object.getOwnPropertyNames||function(K){return E(K,U)}},3717:function(q,X){X.f=Object.getOwnPropertySymbols},2787:function(q,X,j){var E=j(9297),U=j(4901),K=j(8981),H=j(6119),re=j(2211),O=H("IE_PROTO"),$=Object,ee=$.prototype;q.exports=re?$.getPrototypeOf:function(W){var ie=K(W);if(E(ie,O))return ie[O];var ce=ie.constructor;return U(ce)&&ie instanceof ce?ce.prototype:ie instanceof $?ee:null}},1625:function(q,X,j){var E=j(9504);q.exports=E({}.isPrototypeOf)},1828:function(q,X,j){var E=j(9504),U=j(9297),K=j(5397),H=j(9617).indexOf,re=j(421),O=E([].push);q.exports=function($,ee){var W,ie=K($),ce=0,be=[];for(W in ie)!U(re,W)&&U(ie,W)&&O(be,W);for(;ee.length>ce;)U(ie,W=ee[ce++])&&(~H(be,W)||O(be,W));return be}},1072:function(q,X,j){var E=j(1828),U=j(8727);q.exports=Object.keys||function(K){return E(K,U)}},8773:function(q,X){var j={}.propertyIsEnumerable,E=Object.getOwnPropertyDescriptor,U=E&&!j.call({1:2},1);X.f=U?function(K){var H=E(this,K);return!!H&&H.enumerable}:j},2551:function(q,X,j){var E=j(6395),U=j(4576),K=j(9039),H=j(3607);q.exports=E||!K((function(){if(!(H&&H<535)){var re=Math.random();__defineSetter__.call(null,re,(function(){})),delete U[re]}}))},2967:function(q,X,j){var E=j(6706),U=j(34),K=j(7750),H=j(3506);q.exports=Object.setPrototypeOf||("__proto__"in{}?(function(){var re,O=!1,$={};try{(re=E(Object.prototype,"__proto__","set"))($,[]),O=$ instanceof Array}catch{}return function(ee,W){return K(ee),H(W),U(ee)&&(O?re(ee,W):ee.__proto__=W),ee}})():void 0)},3179:function(q,X,j){var E=j(2140),U=j(6955);q.exports=E?{}.toString:function(){return"[object "+U(this)+"]"}},4270:function(q,X,j){var E=j(9565),U=j(4901),K=j(34),H=TypeError;q.exports=function(re,O){var $,ee;if(O==="string"&&U($=re.toString)&&!K(ee=E($,re))||U($=re.valueOf)&&!K(ee=E($,re))||O!=="string"&&U($=re.toString)&&!K(ee=E($,re)))return ee;throw new H("Can't convert object to primitive value")}},5031:function(q,X,j){var E=j(7751),U=j(9504),K=j(8480),H=j(3717),re=j(8551),O=U([].concat);q.exports=E("Reflect","ownKeys")||function($){var ee=K.f(re($)),W=H.f;return W?O(ee,W($)):ee}},8235:function(q,X,j){var E=j(9504),U=j(9297),K=SyntaxError,H=parseInt,re=String.fromCharCode,O=E("".charAt),$=E("".slice),ee=E(/./.exec),W={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":` `,"\\r":"\r","\\t":" "},ie=/^[\da-f]{4}$/i,ce=/^[\u0000-\u001F]$/;q.exports=function(be,xe){for(var oe=!0,L="";xe0&&(!ye.multiline||ye.multiline&&F(Pe,ye.lastIndex-1)!==` @@ -8726,4 +8726,4 @@ Difference: ${l}g (mismatch!)`;return i.jsxs("div",{className:`flex items-center In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function f(q,X){if(q){if(typeof q=="string")return y(q,X);var j={}.toString.call(q).slice(8,-1);return j==="Object"&&q.constructor&&(j=q.constructor.name),j==="Map"||j==="Set"?Array.from(q):j==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(j)?y(q,X):void 0}}function y(q,X){(X==null||X>q.length)&&(X=q.length);for(var j=0,E=Array(X);j"u"||"remove"in Element.prototype||(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)}),typeof self<"u"&&"document"in self&&((!("classList"in document.createElement("_"))||document.createElementNS&&!("classList"in document.createElementNS("http://www.w3.org/2000/svg","g")))&&(function(q){if("Element"in q){var X="classList",j="prototype",E=q.Element[j],U=Object,K=String[j].trim||function(){return this.replace(/^\s+|\s+$/g,"")},H=Array[j].indexOf||function(ce){for(var be=0,xe=this.length;be2&&arguments[2]!==void 0&&arguments[2]?Object.assign({},this.getDefaultDiplay(),U):U||this.getDefaultDiplay())[E]||E}},{key:"getUpdatedInput",value:function(E,U,K){var H=arguments.length>3&&arguments[3]!==void 0?arguments[3]:K,re=arguments.length>4&&arguments[4]!==void 0&&arguments[4],O=this.getOptions(),$=[K,H,re],ee=U;return(E==="{bksp}"||E==="{backspace}")&&ee.length>0?ee=this.removeAt.apply(this,[ee].concat($)):(E==="{delete}"||E==="{forwarddelete}")&&ee.length>0?ee=this.removeForwardsAt.apply(this,[ee].concat($)):E==="{space}"?ee=this.addStringAt.apply(this,[ee," "].concat($)):E!=="{tab}"||typeof O.tabCharOnTab=="boolean"&&O.tabCharOnTab===!1?E!=="{enter}"&&E!=="{numpadenter}"||!O.newLineOnEnter?E.includes("numpad")&&Number.isInteger(Number(E[E.length-2]))?ee=this.addStringAt.apply(this,[ee,E[E.length-2]].concat($)):E==="{numpaddivide}"?ee=this.addStringAt.apply(this,[ee,"/"].concat($)):E==="{numpadmultiply}"?ee=this.addStringAt.apply(this,[ee,"*"].concat($)):E==="{numpadsubtract}"?ee=this.addStringAt.apply(this,[ee,"-"].concat($)):E==="{numpadadd}"?ee=this.addStringAt.apply(this,[ee,"+"].concat($)):E==="{numpaddecimal}"?ee=this.addStringAt.apply(this,[ee,"."].concat($)):E==="{"||E==="}"?ee=this.addStringAt.apply(this,[ee,E].concat($)):E.includes("{")||E.includes("}")||(ee=this.addStringAt.apply(this,[ee,E].concat($))):ee=this.addStringAt.apply(this,[ee,` `].concat($)):ee=this.addStringAt.apply(this,[ee," "].concat($)),O.debug&&console.log("Input will be: "+ee),ee}},{key:"updateCaretPos",value:function(E){var U=arguments.length>1&&arguments[1]!==void 0&&arguments[1],K=this.updateCaretPosAction(E,U);this.dispatch((function(H){H.setCaretPosition(K)}))}},{key:"updateCaretPosAction",value:function(E){var U=arguments.length>1&&arguments[1]!==void 0&&arguments[1],K=this.getOptions(),H=this.getCaretPosition();return H!=null&&(U?H>0&&(H-=E):H+=E),K.debug&&console.log("Caret at:",H),H}},{key:"addStringAt",value:function(E,U){var K,H=arguments.length>2&&arguments[2]!==void 0?arguments[2]:E.length,re=arguments.length>3&&arguments[3]!==void 0?arguments[3]:E.length,O=arguments.length>4&&arguments[4]!==void 0&&arguments[4];return H||H===0?(K=[E.slice(0,H),U,E.slice(re)].join(""),this.isMaxLengthReached()||O&&this.updateCaretPos(U.length)):K=E+U,K}},{key:"removeAt",value:function(E){var U,K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:E.length,H=arguments.length>2&&arguments[2]!==void 0?arguments[2]:E.length,re=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(K===0&&H===0)return E;if(K===H){var O=/([\uD800-\uDBFF][\uDC00-\uDFFF])/g;K&&K>=0?E.substring(K-2,K).match(O)?(U=E.substr(0,K-2)+E.substr(K),re&&this.updateCaretPos(2,!0)):(U=E.substr(0,K-1)+E.substr(K),re&&this.updateCaretPos(1,!0)):E.slice(-2).match(O)?(U=E.slice(0,-2),re&&this.updateCaretPos(2,!0)):(U=E.slice(0,-1),re&&this.updateCaretPos(1,!0))}else U=E.slice(0,K)+E.slice(H),re&&this.dispatch((function($){$.setCaretPosition(K)}));return U}},{key:"removeForwardsAt",value:function(E){var U,K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:E.length,H=arguments.length>2&&arguments[2]!==void 0?arguments[2]:E.length,re=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return E!=null&&E.length&&K!==null?(K===H?U=E.substring(K,K+2).match(/([\uD800-\uDBFF][\uDC00-\uDFFF])/g)?E.substr(0,K)+E.substr(K+2):E.substr(0,K)+E.substr(K+1):(U=E.slice(0,K)+E.slice(H),re&&this.dispatch((function(O){O.setCaretPosition(K)}))),U):E}},{key:"handleMaxLength",value:function(E,U){var K=this.getOptions(),H=K.maxLength,re=E[K.inputName||"default"],O=U.length-1>=H;if(U.length<=re.length)return!1;if(Number.isInteger(H))return K.debug&&console.log("maxLength (num) reached:",O),O?(this.maxLengthReached=!0,!0):(this.maxLengthReached=!1,!1);if(v(H)==="object"){var $=U.length-1>=H[K.inputName||"default"];return K.debug&&console.log("maxLength (obj) reached:",$),$?(this.maxLengthReached=!0,!0):(this.maxLengthReached=!1,!1)}}},{key:"isMaxLengthReached",value:function(){return!!this.maxLengthReached}},{key:"isTouchDevice",value:function(){return"ontouchstart"in window||navigator.maxTouchPoints}},{key:"pointerEventsSupported",value:function(){return!!window.PointerEvent}},{key:"camelCase",value:function(E){return E?E.toLowerCase().trim().split(/[.\-_\s]/g).reduce((function(U,K){return K.length?U+K[0].toUpperCase()+K.slice(1):U})):""}},{key:"chunkArray",value:function(E,U){return p(Array(Math.ceil(E.length/U))).map((function(K,H){return E.slice(U*H,U+U*H)}))}},{key:"escapeRegex",value:function(E){return E.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}},{key:"getRtlOffset",value:function(E,U){var K=E,H=U.indexOf("‫");return H=O.length?{done:!0}:{done:!1,value:O[W++]}},e:function(oe){throw oe},f:ie}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var ce,be=!0,xe=!1;return{s:function(){ee=ee.call(O)},n:function(){var oe=ee.next();return be=oe.done,oe},e:function(oe){xe=!0,ce=oe},f:function(){try{be||ee.return==null||ee.return()}finally{if(xe)throw ce}}}})(Object.getOwnPropertyNames(E.prototype));try{for(H.s();!(K=H.n()).done;){var re=K.value;re==="constructor"||re==="bindMethods"||(U[re]=U[re].bind(U))}}catch(O){H.e(O)}finally{H.f()}}}],X&&b(q.prototype,X),j&&b(q,j),Object.defineProperty(q,"prototype",{writable:!1}),q;var q,X,j})();g(N,"noop",(function(){}));var C=N;function k(q){return k=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(X){return typeof X}:function(X){return X&&typeof Symbol=="function"&&X.constructor===Symbol&&X!==Symbol.prototype?"symbol":typeof X},k(q)}function P(q,X){for(var j=0;j1?(U=K)===null||U===void 0?void 0:U.toLowerCase():K}},{key:"keyCodeToKey",value:function(E){return{8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",65:"A",66:"B",67:"C",68:"D",69:"E",70:"F",71:"G",72:"H",73:"I",74:"J",75:"K",76:"L",77:"M",78:"N",79:"O",80:"P",81:"Q",82:"R",83:"S",84:"T",85:"U",86:"V",87:"W",88:"X",89:"Y",90:"Z",91:"Meta",96:"Numpad0",97:"Numpad1",98:"Numpad2",99:"Numpad3",100:"Numpad4",101:"Numpad5",102:"Numpad6",103:"Numpad7",104:"Numpad8",105:"Numpad9",106:"NumpadMultiply",107:"NumpadAdd",109:"NumpadSubtract",110:"NumpadDecimal",111:"NumpadDivide",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"}[E]||""}}],X&&P(q.prototype,X),j&&P(q,j),Object.defineProperty(q,"prototype",{writable:!1}),q;var q,X,j})();function R(q){return R=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(X){return typeof X}:function(X){return X&&typeof Symbol=="function"&&X.constructor===Symbol&&X!==Symbol.prototype?"symbol":typeof X},R(q)}function G(q,X){for(var j=0;j0&&arguments[0]!==void 0?arguments[0]:fe();return ee(F,me)},W.appendChild(ve)}));var ie=O>0,ce=document.createElement("div");ce.classList.add("hg-candidate-box-prev"),ie&&ce.classList.add("hg-candidate-box-btn-active");var be=function(){ie&&K.renderPage({candidateListPages:H,targetElement:re,pageIndex:O-1,nbPages:$,onItemSelected:ee})};this.options.useTouchEvents?ce.ontouchstart=be:ce.onclick=be,this.candidateBoxElement.appendChild(ce),this.candidateBoxElement.appendChild(W);var xe=O<$-1,oe=document.createElement("div");oe.classList.add("hg-candidate-box-next"),xe&&oe.classList.add("hg-candidate-box-btn-active");var L=function(){xe&&K.renderPage({candidateListPages:H,targetElement:re,pageIndex:O+1,nbPages:$,onItemSelected:ee})};this.options.useTouchEvents?oe.ontouchstart=L:oe.onclick=L,this.candidateBoxElement.appendChild(oe),re.prepend(this.candidateBoxElement)}}],X&&G(q.prototype,X),j&&G(q,j),Object.defineProperty(q,"prototype",{writable:!1}),q;var q,X,j})(),J=I;function ae(q){return(function(X){if(Array.isArray(X))return Y(X)})(q)||(function(X){if(typeof Symbol<"u"&&X[Symbol.iterator]!=null||X["@@iterator"]!=null)return Array.from(X)})(q)||(function(X,j){if(X){if(typeof X=="string")return Y(X,j);var E={}.toString.call(X).slice(8,-1);return E==="Object"&&X.constructor&&(E=X.constructor.name),E==="Map"||E==="Set"?Array.from(X):E==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(E)?Y(X,j):void 0}})(q)||(function(){throw new TypeError(`Invalid attempt to spread non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function Y(q,X){(X==null||X>q.length)&&(X=q.length);for(var j=0,E=Array(X);j1&&arguments[1]!==void 0?arguments[1]:E;this.caretPosition=E,this.caretPositionEnd=U}},{key:"getInputCandidates",value:function(E){var U=this,K=this.options,H=K.layoutCandidates,re=K.layoutCandidatesCaseSensitiveMatch;if(!H||ue(H)!=="object")return{};var O=Object.keys(H).filter((function(W){var ie=E.substring(0,U.getCaretPositionEnd()||0)||E,ce=new RegExp("".concat(U.utilities.escapeRegex(W),"$"),re?"g":"gi");return!!ae(ie.matchAll(ce)).length}));if(O.length>1){var $=O.sort((function(W,ie){return ie.length-W.length}))[0];return{candidateKey:$,candidateValue:H[$]}}if(O.length){var ee=O[0];return{candidateKey:ee,candidateValue:H[ee]}}return{}}},{key:"showCandidatesBox",value:function(E,U,K){var H=this;this.candidateBox&&this.candidateBox.show({candidateValue:U,targetElement:K,onSelect:function(re,O){var $=H.options,ee=$.layoutCandidatesCaseSensitiveMatch,W=$.disableCandidateNormalization,ie=$.enableLayoutCandidatesKeyPress,ce=re;W||(ce=re.normalize("NFD")),typeof H.options.beforeInputUpdate=="function"&&H.options.beforeInputUpdate(H);var be=H.getInput(H.options.inputName,!0),xe=H.getCaretPositionEnd()||0,oe=be.substring(0,xe||0)||be,L=new RegExp("".concat(H.utilities.escapeRegex(E),"$"),ee?"g":"gi"),F=oe.replace(L,ce),te=be.replace(oe,F),ve=F.length-oe.length,fe=(xe||be.length)+ve;fe<0&&(fe=0),H.setInput(te,H.options.inputName,!0),H.setCaretPosition(fe),ie&&typeof H.options.onKeyPress=="function"&&H.options.onKeyPress(re,O),typeof H.options.onChange=="function"&&H.options.onChange(H.getInput(H.options.inputName,!0),O),typeof H.options.onChangeAll=="function"&&H.options.onChangeAll(H.getAllInputs(),O)}})}},{key:"handleButtonClicked",value:function(E,U){var K=this.options,H=K.inputName,re=H===void 0?this.defaultName:H,O=K.debug;if(E!=="{//}"){this.input[re]||(this.input[re]=""),typeof this.options.beforeInputUpdate=="function"&&this.options.beforeInputUpdate(this);var $=this.utilities.getUpdatedInput(E,this.input[re],this.caretPosition,this.caretPositionEnd);if(this.utilities.isStandardButton(E)&&this.activeInputElement&&this.input[re]&&this.input[re]===$&&this.caretPosition===0&&this.caretPositionEnd===$.length)return this.setInput("",this.options.inputName,!0),this.setCaretPosition(0),this.activeInputElement.value="",this.activeInputElement.setSelectionRange(0,0),void this.handleButtonClicked(E,U);if(typeof this.options.onKeyPress=="function"&&this.options.onKeyPress(E,U),this.input[re]!==$&&(!this.options.inputPattern||this.options.inputPattern&&this.inputPatternIsValid($))){if(this.options.maxLength&&this.utilities.handleMaxLength(this.input,$))return;var ee=this.utilities.getUpdatedInput(E,this.input[re],this.caretPosition,this.caretPositionEnd,!0);if(this.setInput(ee,this.options.inputName,!0),O&&console.log("Input changed:",this.getAllInputs()),this.options.debug&&console.log("Caret at: ",this.getCaretPosition(),this.getCaretPositionEnd(),"(".concat(this.keyboardDOMClass,")"),U?.type),this.options.syncInstanceInputs&&this.syncInstanceInputs(),typeof this.options.onChange=="function"&&this.options.onChange(this.getInput(this.options.inputName,!0),U),typeof this.options.onChangeAll=="function"&&this.options.onChangeAll(this.getAllInputs(),U),U!=null&&U.target&&this.options.enableLayoutCandidates){var W,ie=this.getInputCandidates($),ce=ie.candidateKey,be=ie.candidateValue;ce&&be?this.showCandidatesBox(ce,be,this.keyboardDOM):(W=this.candidateBox)===null||W===void 0||W.destroy()}}this.caretPositionEnd&&this.caretPosition!==this.caretPositionEnd&&(this.setCaretPosition(this.caretPositionEnd,this.caretPositionEnd),this.activeInputElement&&this.activeInputElement.setSelectionRange(this.caretPositionEnd,this.caretPositionEnd),this.options.debug&&console.log("Caret position aligned",this.caretPosition)),O&&console.log("Key pressed:",E)}}},{key:"getMouseHold",value:function(){return this.isMouseHold}},{key:"setMouseHold",value:function(E){this.options.syncInstanceInputs?this.dispatch((function(U){U.isMouseHold=E})):this.isMouseHold=E}},{key:"handleButtonMouseDown",value:function(E,U){var K=this;U&&(this.options.preventMouseDownDefault&&U.preventDefault(),this.options.stopMouseDownPropagation&&U.stopPropagation(),U.target.classList.add(this.activeButtonClass)),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdTimeout&&clearTimeout(this.holdTimeout),this.setMouseHold(!0),this.options.disableButtonHold||(this.holdTimeout=window.setTimeout((function(){(K.getMouseHold()&&(!E.includes("{")&&!E.includes("}")||E==="{delete}"||E==="{backspace}"||E==="{bksp}"||E==="{space}"||E==="{tab}")||E==="{arrowright}"||E==="{arrowleft}"||E==="{arrowup}"||E==="{arrowdown}")&&(K.options.debug&&console.log("Button held:",E),K.handleButtonHold(E)),clearTimeout(K.holdTimeout)}),500))}},{key:"handleButtonMouseUp",value:function(E,U){var K=this;U&&(this.options.preventMouseUpDefault&&U.preventDefault&&U.preventDefault(),this.options.stopMouseUpPropagation&&U.stopPropagation&&U.stopPropagation(),!(U.target===this.keyboardDOM||U.target&&this.keyboardDOM.contains(U.target)||this.candidateBox&&this.candidateBox.candidateBoxElement&&(U.target===this.candidateBox.candidateBoxElement||U.target&&this.candidateBox.candidateBoxElement.contains(U.target)))&&this.candidateBox&&this.candidateBox.destroy()),this.recurseButtons((function(H){H.classList.remove(K.activeButtonClass)})),this.setMouseHold(!1),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),E&&typeof this.options.onKeyReleased=="function"&&this.options.onKeyReleased(E,U)}},{key:"handleKeyboardContainerMouseDown",value:function(E){this.options.preventMouseDownDefault&&E.preventDefault()}},{key:"handleButtonHold",value:function(E){var U=this;this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdInteractionTimeout=window.setTimeout((function(){U.getMouseHold()?(U.handleButtonClicked(E),U.handleButtonHold(E)):clearTimeout(U.holdInteractionTimeout)}),100)}},{key:"syncInstanceInputs",value:function(){var E=this;this.dispatch((function(U){U.replaceInput(E.input),U.setCaretPosition(E.caretPosition,E.caretPositionEnd)}))}},{key:"clearInput",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName;this.input[E]="",this.setCaretPosition(0),this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"getInput",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName,U=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return this.options.syncInstanceInputs&&!U&&this.syncInstanceInputs(),this.options.rtl?"‫"+this.input[E].replace("‫","").replace("‬","")+"‬":this.input[E]}},{key:"getAllInputs",value:function(){var E=this,U={};return Object.keys(this.input).forEach((function(K){U[K]=E.getInput(K,!0)})),U}},{key:"setInput",value:function(E){var U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.inputName||this.defaultName,K=arguments.length>2?arguments[2]:void 0;this.input[U]=E,!K&&this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"replaceInput",value:function(E){this.input=E}},{key:"setOptions",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},U=this.changedOptions(E);this.options=Object.assign(this.options,E),U.length&&(this.options.debug&&console.log("changedOptions",U),this.onSetOptions(U),this.render())}},{key:"changedOptions",value:function(E){var U=this;return Object.keys(E).filter((function(K){return JSON.stringify(E[K])!==JSON.stringify(U.options[K])}))}},{key:"onSetOptions",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];E.includes("layoutName")&&this.candidateBox&&this.candidateBox.destroy(),(E.includes("layoutCandidatesPageSize")||E.includes("layoutCandidates"))&&this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=new J({utilities:this.utilities,options:this.options}))}},{key:"resetRows",value:function(){this.keyboardRowsDOM&&this.keyboardRowsDOM.remove(),this.keyboardDOM.className=this.keyboardDOMClass,this.keyboardDOM.setAttribute("data-skInstance",this.currentInstanceName),this.buttonElements={}}},{key:"dispatch",value:function(E){if(!window.SimpleKeyboardInstances)throw console.warn("SimpleKeyboardInstances is not defined. Dispatch cannot be called."),new Error("INSTANCES_VAR_ERROR");return Object.keys(window.SimpleKeyboardInstances).forEach((function(U){E(window.SimpleKeyboardInstances[U],U)}))}},{key:"addButtonTheme",value:function(E,U){var K=this;U&&E&&(E.split(" ").forEach((function(H){U.split(" ").forEach((function(re){K.options.buttonTheme||(K.options.buttonTheme=[]);var O=!1;K.options.buttonTheme.map((function($){if($!=null&&$.class.split(" ").includes(re)){O=!0;var ee=$.buttons.split(" ");ee.includes(H)||(O=!0,ee.push(H),$.buttons=ee.join(" "))}return $})),O||K.options.buttonTheme.push({class:re,buttons:E})}))})),this.render())}},{key:"removeButtonTheme",value:function(E,U){var K=this;if(!E&&!U)return this.options.buttonTheme=[],void this.render();E&&Array.isArray(this.options.buttonTheme)&&this.options.buttonTheme.length&&(E.split(" ").forEach((function(H){var re;(re=K.options)===null||re===void 0||(re=re.buttonTheme)===null||re===void 0||re.map((function(O,$){if(O&&U&&U.includes(O.class)||!U){var ee,W,ie=(ee=O)===null||ee===void 0?void 0:ee.buttons.split(" ").filter((function(ce){return ce!==H}));O&&ie!=null&&ie.length?O.buttons=ie.join(" "):((W=K.options.buttonTheme)===null||W===void 0||W.splice($,1),O=null)}return O}))})),this.render())}},{key:"getButtonElement",value:function(E){var U,K=this.buttonElements[E];return K&&(U=K.length>1?K:K[0]),U}},{key:"inputPatternIsValid",value:function(E){var U,K=this.options.inputPattern;if((U=K instanceof RegExp?K:K[this.options.inputName||this.defaultName])&&E){var H=U.test(E);return this.options.debug&&console.log('inputPattern ("'.concat(U,'"): ').concat(H?"passed":"did not pass!")),H}return!0}},{key:"setEventListeners",value:function(){if(this.isFirstKeyboardInstance||!this.allKeyboardInstances){this.options.debug&&console.log("Caret handling started (".concat(this.keyboardDOMClass,")"));var E=this.options.physicalKeyboardHighlightPreventDefault,U=E!==void 0&&E;document.addEventListener("keyup",this.handleKeyUp,U),document.addEventListener("keydown",this.handleKeyDown,U),document.addEventListener("mouseup",this.handleMouseUp),document.addEventListener("touchend",this.handleTouchEnd),this.options.updateCaretOnSelectionChange&&document.addEventListener("selectionchange",this.handleSelectionChange),document.addEventListener("select",this.handleSelect)}}},{key:"handleKeyUp",value:function(E){this.caretEventHandler(E),this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyUp(E)}},{key:"handleKeyDown",value:function(E){this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyDown(E)}},{key:"handleMouseUp",value:function(E){this.caretEventHandler(E)}},{key:"handleTouchEnd",value:function(E){this.caretEventHandler(E)}},{key:"handleSelect",value:function(E){this.caretEventHandler(E)}},{key:"handleSelectionChange",value:function(E){navigator.userAgent.includes("Firefox")||this.caretEventHandler(E)}},{key:"caretEventHandler",value:function(E){var U,K=this;E.target.tagName&&(U=E.target.tagName.toLowerCase()),this.dispatch((function(H){var re=E.target===H.keyboardDOM||E.target&&H.keyboardDOM.contains(E.target);if(K.options.syncInstanceInputs&&Array.isArray(E.path)&&(re=E.path.some((function(ee){var W;return ee==null||(W=ee.hasAttribute)===null||W===void 0?void 0:W.call(ee,"data-skInstance")}))),(U==="textarea"||U==="input"&&["text","search","url","tel","password"].includes(E.target.type))&&!H.options.disableCaretPositioning){var O=E.target.selectionStart,$=E.target.selectionEnd;H.options.rtl&&(O=H.utilities.getRtlOffset(O,H.getInput()),$=H.utilities.getRtlOffset($,H.getInput())),H.setCaretPosition(O,$),H.activeInputElement=E.target,H.options.debug&&console.log("Caret at: ",H.getCaretPosition(),H.getCaretPositionEnd(),E&&E.target.tagName.toLowerCase(),"(".concat(H.keyboardDOMClass,")"),E?.type)}else!H.options.disableCaretPositioning&&re||E?.type==="selectionchange"||(H.setCaretPosition(null),H.activeInputElement=null,H.options.debug&&console.log('Caret position reset due to "'.concat(E?.type,'" event'),E))}))}},{key:"recurseButtons",value:function(E){var U=this;E&&Object.keys(this.buttonElements).forEach((function(K){return U.buttonElements[K].forEach(E)}))}},{key:"destroy",value:function(){this.options.debug&&console.log("Destroying simple-keyboard instance: ".concat(this.currentInstanceName));var E=this.options.physicalKeyboardHighlightPreventDefault,U=E!==void 0&&E;document.removeEventListener("keyup",this.handleKeyUp,U),document.removeEventListener("keydown",this.handleKeyDown,U),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("touchend",this.handleTouchEnd),document.removeEventListener("select",this.handleSelect),this.options.updateCaretOnSelectionChange&&document.removeEventListener("selectionchange",this.handleSelectionChange),document.onpointerup=null,document.ontouchend=null,document.ontouchcancel=null,document.onmouseup=null,this.recurseButtons((function(K){K&&(K.onpointerdown=null,K.onpointerup=null,K.onpointercancel=null,K.ontouchstart=null,K.ontouchend=null,K.ontouchcancel=null,K.onclick=null,K.onmousedown=null,K.onmouseup=null,K.remove(),K=null)})),this.keyboardDOM.onpointerdown=null,this.keyboardDOM.ontouchstart=null,this.keyboardDOM.onmousedown=null,this.resetRows(),this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=null),this.activeInputElement=null,this.keyboardDOM.removeAttribute("data-skInstance"),this.keyboardDOM.innerHTML="",window.SimpleKeyboardInstances[this.currentInstanceName]=null,delete window.SimpleKeyboardInstances[this.currentInstanceName],this.initialized=!1}},{key:"getButtonThemeClasses",value:function(E){var U=this.options.buttonTheme,K=[];return Array.isArray(U)&&U.forEach((function(H){if(H&&H.class&&typeof H.class=="string"&&H.buttons&&typeof H.buttons=="string"){var re=H.class.split(" ");H.buttons.split(" ").includes(E)&&(K=[].concat(ae(K),ae(re)))}else console.warn('Incorrect "buttonTheme". Please check the documentation.',H)})),K}},{key:"setDOMButtonAttributes",value:function(E,U){var K=this.options.buttonAttributes;Array.isArray(K)&&K.forEach((function(H){H.attribute&&typeof H.attribute=="string"&&H.value&&typeof H.value=="string"?H.buttons&&typeof H.buttons=="string"?H.buttons.split(" ").includes(E)&&U(H.attribute,H.value):U(H.attribute,H.value):console.warn('Incorrect "buttonAttributes". Please check the documentation.',H)}))}},{key:"onTouchDeviceDetected",value:function(){this.processAutoTouchEvents(),this.disableContextualWindow()}},{key:"disableContextualWindow",value:function(){window.oncontextmenu=function(E){var U;if((U=E.target.classList)!==null&&U!==void 0&&U.contains("hg-button"))return E.preventDefault(),E.stopPropagation(),!1}}},{key:"processAutoTouchEvents",value:function(){this.options.autoUseTouchEvents&&(this.options.useTouchEvents=!0,this.options.debug&&console.log("autoUseTouchEvents: Touch device detected, useTouchEvents enabled."))}},{key:"onInit",value:function(){this.options.debug&&console.log("".concat(this.keyboardDOMClass," Initialized")),this.setEventListeners(),typeof this.options.onInit=="function"&&this.options.onInit(this)}},{key:"beforeFirstRender",value:function(){this.utilities.isTouchDevice()&&this.onTouchDeviceDetected(),typeof this.options.beforeFirstRender=="function"&&this.options.beforeFirstRender(this),this.isFirstKeyboardInstance&&this.utilities.pointerEventsSupported()&&!this.options.useTouchEvents&&!this.options.useMouseEvents&&this.options.debug&&console.log("Using PointerEvents as it is supported by this browser"),this.options.useTouchEvents&&this.options.debug&&console.log("useTouchEvents has been enabled. Only touch events will be used.")}},{key:"beforeRender",value:function(){typeof this.options.beforeRender=="function"&&this.options.beforeRender(this)}},{key:"onRender",value:function(){typeof this.options.onRender=="function"&&this.options.onRender(this)}},{key:"onModulesLoaded",value:function(){typeof this.options.onModulesLoaded=="function"&&this.options.onModulesLoaded(this)}},{key:"loadModules",value:function(){var E=this;Array.isArray(this.options.modules)&&(this.options.modules.forEach((function(U){var K=E.utilities.isConstructor(U)?new U(E):U(E);K.init&&K.init(E)})),this.keyboardPluginClasses="modules-loaded",this.render(),this.onModulesLoaded())}},{key:"getModuleProp",value:function(E,U){return!!this.modules[E]&&this.modules[E][U]}},{key:"getModulesList",value:function(){return Object.keys(this.modules)}},{key:"parseRowDOMContainers",value:function(E,U,K,H){var re=this,O=Array.from(E.children),$=0;return O.length&&K.forEach((function(ee,W){var ie=H[W];if(!(ie&&ie>ee))return!1;var ce=ee-$,be=ie-$,xe=document.createElement("div");xe.className+="hg-button-container";var oe="".concat(re.options.layoutName,"-r").concat(U,"c").concat(W);xe.setAttribute("data-skUID",oe);var L=O.splice(ce,be-ce+1);$+=be-ce,L.forEach((function(F){return xe.appendChild(F)})),O.splice(ce,0,xe),E.innerHTML="",O.forEach((function(F){return E.appendChild(F)})),re.options.debug&&console.log("rowDOMContainer",L,ce,be,$+1)})),E}},{key:"render",value:function(){var E=this;this.resetRows(),this.initialized||this.beforeFirstRender(),this.beforeRender();var U="hg-layout-".concat(this.options.layoutName),K=this.options.layout||{default:["` 1 2 3 4 5 6 7 8 9 0 - = {bksp}","{tab} q w e r t y u i o p [ ] \\","{lock} a s d f g h j k l ; ' {enter}","{shift} z x c v b n m , . / {shift}",".com @ {space}"],shift:["~ ! @ # $ % ^ & * ( ) _ + {bksp}","{tab} Q W E R T Y U I O P { } |",'{lock} A S D F G H J K L : " {enter}',"{shift} Z X C V B N M < > ? {shift}",".com @ {space}"]},H=this.options.useTouchEvents||!1,re=H?"hg-touch-events":"",O=this.options.useMouseEvents||!1,$=this.options.disableRowButtonContainers;this.keyboardDOM.className=this.getKeyboardClassString(this.options.theme,U,this.keyboardPluginClasses,re),this.keyboardDOM.setAttribute("data-skInstance",this.currentInstanceName),this.keyboardRowsDOM=document.createElement("div"),this.keyboardRowsDOM.className="hg-rows",K[this.options.layoutName||this.defaultName].forEach((function(ee,W){var ie=ee.split(" ");E.options.excludeFromLayout&&E.options.excludeFromLayout[E.options.layoutName||E.defaultName]&&(ie=ie.filter((function(oe){return E.options.excludeFromLayout&&!E.options.excludeFromLayout[E.options.layoutName||E.defaultName].includes(oe)})));var ce=document.createElement("div");ce.className+="hg-row";var be=[],xe=[];ie.forEach((function(oe,L){var F,te=!$&&typeof oe=="string"&&oe.length>1&&oe.indexOf("[")===0,ve=!$&&typeof oe=="string"&&oe.length>1&&oe.indexOf("]")===oe.length-1;te&&(be.push(L),oe=oe.replace(/\[/g,"")),ve&&(xe.push(L),oe=oe.replace(/\]/g,""));var fe=E.utilities.getButtonClass(oe),me=E.utilities.getButtonDisplayName(oe,E.options.display,E.options.mergeDisplay),je=E.options.useButtonTag?"button":"div",we=document.createElement(je);we.className+="hg-button ".concat(fe),(F=we.classList).add.apply(F,ae(E.getButtonThemeClasses(oe))),E.setDOMButtonAttributes(oe,(function(Oe,_e){we.setAttribute(Oe,_e)})),E.activeButtonClass="hg-activeButton",!E.utilities.pointerEventsSupported()||H||O?H?(we.ontouchstart=function(Oe){E.handleButtonClicked(oe,Oe),E.handleButtonMouseDown(oe,Oe)},we.ontouchend=function(Oe){E.handleButtonMouseUp(oe,Oe)},we.ontouchcancel=function(Oe){E.handleButtonMouseUp(oe,Oe)}):(we.onclick=function(Oe){E.setMouseHold(!1),typeof E.options.onKeyReleased=="function"||E.options.useMouseEvents&&E.options.clickOnMouseDown||E.handleButtonClicked(oe,Oe)},we.onmousedown=function(Oe){(typeof E.options.onKeyReleased=="function"||E.options.useMouseEvents&&E.options.clickOnMouseDown)&&!E.isMouseHold&&E.handleButtonClicked(oe,Oe),E.handleButtonMouseDown(oe,Oe)},we.onmouseup=function(Oe){E.handleButtonMouseUp(oe,Oe)}):(we.onpointerdown=function(Oe){E.handleButtonClicked(oe,Oe),E.handleButtonMouseDown(oe,Oe)},we.onpointerup=function(Oe){E.handleButtonMouseUp(oe,Oe)},we.onpointercancel=function(Oe){E.handleButtonMouseUp(oe,Oe)}),we.setAttribute("data-skBtn",oe);var Fe="".concat(E.options.layoutName,"-r").concat(W,"b").concat(L);we.setAttribute("data-skBtnUID",Fe);var He=document.createElement("span");He.innerHTML=me,we.appendChild(He),E.buttonElements[oe]||(E.buttonElements[oe]=[]),E.buttonElements[oe].push(we),ce.appendChild(we)})),ce=E.parseRowDOMContainers(ce,W,be,xe),E.keyboardRowsDOM.appendChild(ce)})),this.keyboardDOM.appendChild(this.keyboardRowsDOM),this.onRender(),this.initialized||(this.initialized=!0,!this.utilities.pointerEventsSupported()||H||O?H?(document.ontouchend=function(ee){return E.handleButtonMouseUp(void 0,ee)},document.ontouchcancel=function(ee){return E.handleButtonMouseUp(void 0,ee)},this.keyboardDOM.ontouchstart=function(ee){return E.handleKeyboardContainerMouseDown(ee)}):H||(document.onmouseup=function(ee){return E.handleButtonMouseUp(void 0,ee)},this.keyboardDOM.onmousedown=function(ee){return E.handleKeyboardContainerMouseDown(ee)}):(document.onpointerup=function(ee){return E.handleButtonMouseUp(void 0,ee)},this.keyboardDOM.onpointerdown=function(ee){return E.handleKeyboardContainerMouseDown(ee)}),this.onInit())}}],X&&he(q.prototype,X),j&&he(q,j),Object.defineProperty(q,"prototype",{writable:!1}),q;var q,X,j})(),pe=se,Te=pe;return m})()},442:function(l){l.exports=n}},a={};function s(l){var c=a[l];if(c!==void 0)return c.exports;var u=a[l]={exports:{}};return r[l].call(u.exports,u,u.exports,s),u.exports}s.n=function(l){var c=l&&l.__esModule?function(){return l.default}:function(){return l};return s.d(c,{a:c}),c},s.d=function(l,c){for(var u in c)s.o(c,u)&&!s.o(l,u)&&Object.defineProperty(l,u,{enumerable:!0,get:c[u]})},s.o=function(l,c){return Object.prototype.hasOwnProperty.call(l,c)},s.r=function(l){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(l,"__esModule",{value:!0})};var o={};return(function(){s.r(o),s.d(o,{KeyboardReact:function(){return v},default:function(){return b}}),s(981);var l=s(442),c=s(548),u=s.n(c);function d(g){return d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(_){return typeof _}:function(_){return _&&typeof Symbol=="function"&&_.constructor===Symbol&&_!==Symbol.prototype?"symbol":typeof _},d(g)}function m(g,_){var N=Object.keys(g);if(Object.getOwnPropertySymbols){var C=Object.getOwnPropertySymbols(g);_&&(C=C.filter((function(k){return Object.getOwnPropertyDescriptor(g,k).enumerable}))),N.push.apply(N,C)}return N}function p(g){for(var _=1;_{if(a.current)return;const v=y.target;if(!v.closest('[data-vkb="false"]')){if(v instanceof HTMLInputElement){if(!Cnt.has(v.type))return}else if(!(v instanceof HTMLTextAreaElement))return;l.current=v,e(!0),o("default"),c.current?.setInput?.(l.current.value),setTimeout(()=>{v.scrollIntoView({behavior:"smooth",block:"center"})},100)}},[]),m=w.useCallback(()=>{setTimeout(()=>{const y=document.activeElement;y&&(u.current?.contains(y)||y===l.current)||(e(!1),l.current=null)},150)},[]);w.useEffect(()=>(document.addEventListener("focusin",d),document.addEventListener("focusout",m),()=>{document.removeEventListener("focusin",d),document.removeEventListener("focusout",m)}),[d,m]);const p=w.useCallback(()=>{a.current=!0,r(!0),l.current?.blur(),l.current=null,setTimeout(()=>{e(!1),r(!1),a.current=!1},400)},[]),f=w.useCallback(y=>{const v=l.current;if(v){if(y==="{shift}"){o(b=>b==="default"?"shift":"default");return}if(y==="{lock}"){o(b=>b==="default"?"shift":"default");return}if(y==="{close}"){p();return}y==="{bksp}"?r3(v,v.value.slice(0,-1)):y==="{space}"?r3(v,v.value+" "):(r3(v,v.value+y),s==="shift"&&o("default")),v.focus(),c.current?.setInput?.(v.value)}},[s,p]);return t?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-[9998] bg-transparent",onMouseDown:y=>{y.preventDefault(),y.stopPropagation(),n||p()},onTouchStart:y=>{y.preventDefault(),y.stopPropagation(),n||p()},onClick:y=>{y.preventDefault(),y.stopPropagation()}}),!n&&i.jsx("div",{ref:u,className:"fixed bottom-0 left-0 right-0 z-[9999]",onMouseDown:y=>y.preventDefault(),onTouchStart:y=>{y.target.closest(".hg-button")||y.preventDefault()},children:i.jsx(knt,{keyboardRef:y=>{c.current=y},layoutName:s,onKeyPress:f,theme:"simple-keyboard vkb-theme",layout:{default:["1 2 3 4 5 6 7 8 9 0 {bksp}","q w e r t y u i o p","{lock} a s d f g h j k l","{shift} z x c v b n m . @","{space} {close}"],shift:["! @ # $ % ^ & * ( ) {bksp}","Q W E R T Y U I O P","{lock} A S D F G H J K L","{shift} Z X C V B N M , _","{space} {close}"]},display:{"{bksp}":"⌫","{close}":"✕ Close","{shift}":"⇧","{lock}":"⇪","{space}":" "}})})]}):null}function Ant(){const[t,e]=w.useState(null),[n,r]=w.useState(null),[a,s]=w.useState(!1),[o,l]=w.useState(100),[c,u]=w.useState(0),d=w.useRef(Date.now()),{i18n:m}=Dt(),p=wnt(),{data:f}=et({queryKey:["settings"],queryFn:ge.getSettings});w.useEffect(()=>{f?.language&&f.language!==m.language&&m.changeLanguage(f.language)},[f?.language,m]);const{data:y=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>pa.getDevices(),refetchInterval:3e4}),v=y[0],b=w.useRef(!1);w.useEffect(()=>{v&&!b.current&&(l(v.display_brightness),u(v.display_blank_timeout),b.current=!0)},[v]),w.useEffect(()=>{const C=document.documentElement,k=C.classList.contains("dark");return C.classList.add("dark"),()=>{k||C.classList.remove("dark")}},[]);const{data:g}=et({queryKey:["spoolbuddy-update-check",v?.device_id],queryFn:()=>v?pa.checkDaemonUpdate(v.device_id):Promise.resolve(null),enabled:!!v,refetchInterval:300*1e3,staleTime:30*1e3});w.useEffect(()=>{p.deviceOnline?g?.update_available&&g.latest_version?r({type:"info",message:`Update available: v${g.latest_version}`}):r(null):r({type:"warning",message:"SpoolBuddy device disconnected"})},[p.deviceOnline,g]);const _=w.useCallback(()=>{d.current=Date.now(),s(!1)},[]);w.useEffect(()=>(window.addEventListener("pointerdown",_),window.addEventListener("keydown",_),()=>{window.removeEventListener("pointerdown",_),window.removeEventListener("keydown",_)}),[_]),w.useEffect(()=>{if(c<=0)return;const C=setInterval(()=>{Date.now()-d.current>=c*1e3&&s(!0)},1e3);return()=>clearInterval(C)},[c]);const N=o<100?{filter:`brightness(${o/100})`}:void 0;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"w-screen h-screen bg-bambu-dark text-white flex flex-col overflow-hidden",style:N,children:[i.jsx(fnt,{selectedPrinterId:t,onPrinterChange:e,deviceOnline:p.deviceOnline}),i.jsx("main",{className:"flex-1 overflow-y-auto",children:i.jsx(wX,{context:{selectedPrinterId:t,setSelectedPrinterId:e,sbState:p,setAlert:r,displayBrightness:o,setDisplayBrightness:l,displayBlankTimeout:c,setDisplayBlankTimeout:u}})}),i.jsx(xnt,{alert:n}),i.jsx(bnt,{}),i.jsx(Tnt,{})]}),a&&i.jsx("div",{className:"fixed inset-0 bg-black z-[9999]",onPointerDown:C=>{C.stopPropagation(),_()}})]})}function E5({color:t,isEmpty:e,size:n=32}){return e?i.jsx("div",{className:"rounded-full border-2 border-dashed border-zinc-500 flex items-center justify-center",style:{width:n,height:n},children:i.jsx("div",{className:"w-2 h-2 rounded-full bg-zinc-600"})}):i.jsxs("svg",{width:n,height:n,viewBox:"0 0 32 32",children:[i.jsx("circle",{cx:"16",cy:"16",r:"14",fill:t,stroke:"white",strokeWidth:"1.5",strokeOpacity:"0.7"}),i.jsx("circle",{cx:"16",cy:"16",r:"11",fill:t,style:{filter:"brightness(0.85)"}})]})}const Pnt="spoolbuddy-default-core-weight";function Joe(){try{const t=localStorage.getItem(Pnt);if(t){const e=parseInt(t,10);if(e>=0&&e<=500)return e}}catch{}return 250}function Mnt({spool:t,scaleWeight:e,onClose:n,onSyncWeight:r,onAssignToAms:a}){const{t:s}=Dt(),[o,l]=w.useState(!1),[c,u]=w.useState(!1),d=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080",m=t.core_weight&&t.core_weight>0?t.core_weight:Joe(),p=e!==null?Math.round(Math.max(0,e)):null,f=p!==null?Math.round(Math.max(0,p-m)):null,y=Math.round(t.label_weight||1e3),v=f!==null?Math.min(100,Math.round(f/y*100)):null,b=v!==null?v>50?"#22c55e":v>20?"#eab308":"#ef4444":"#808080",_=Math.max(0,(t.label_weight||0)-(t.weight_used||0))+m,N=p!==null?p-_:null,C=N!==null?Math.abs(N)<=50:null,k=async()=>{if(e!==null){l(!0);try{await pa.updateSpoolWeight(t.id,Math.round(e)),u(!0),r?.(),setTimeout(()=>u(!1),3e3)}catch(P){console.error("Failed to sync weight:",P)}finally{l(!1)}}};return i.jsxs("div",{className:"flex flex-col items-center space-y-4 max-w-md",children:[i.jsxs("div",{className:"flex items-start gap-5",children:[i.jsxs("div",{className:"relative shrink-0",children:[i.jsx(E5,{color:d,isEmpty:!1,size:100}),v!==null&&i.jsxs("div",{className:"absolute -bottom-2 -right-2 px-2 py-0.5 rounded-full text-xs font-bold text-white shadow-lg",style:{backgroundColor:b},children:[v,"%"]})]}),i.jsxs("div",{className:"flex-1 min-w-0 pt-1",children:[i.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:t.color_name||"Unknown color"}),i.jsxs("p",{className:"text-sm text-zinc-400",children:[t.brand," • ",t.material,t.subtype&&` ${t.subtype}`]}),f!==null&&i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-baseline gap-2",children:[i.jsxs("span",{className:"text-3xl font-bold font-mono text-zinc-100",children:[f,"g"]}),i.jsxs("span",{className:"text-sm text-zinc-500",children:["/ ",y,"g"]})]}),i.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:s("spoolbuddy.spool.remaining","Remaining")}),i.jsx("div",{className:"mt-2 max-w-xs",children:i.jsx("div",{className:"h-2 bg-zinc-700 rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${v}%`,backgroundColor:b}})})})]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-sm bg-zinc-800 rounded-lg p-4 w-full",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.grossWeight","Gross weight")}),i.jsx("span",{className:"font-mono text-zinc-300",children:p!==null?`${p}g`:"—"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.spool.coreWeight","Core")}),i.jsxs("span",{className:"font-mono text-zinc-300",children:[m,"g"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.spoolSize","Spool size")}),i.jsxs("span",{className:"font-mono text-zinc-300",children:[y,"g"]})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.spool.scaleWeight","Scale")}),p!==null?i.jsxs("span",{className:`flex items-center gap-1 font-mono ${C?"text-green-500":"text-yellow-500"}`,children:[p,"g",C?i.jsx(Zr,{className:"w-3.5 h-3.5"}):i.jsxs(i.Fragment,{children:[i.jsx(jn,{className:"w-3.5 h-3.5"}),i.jsx("button",{onClick:k,className:"p-1 hover:bg-green-500/20 rounded transition-colors text-green-500",title:s("spoolbuddy.dashboard.syncWeight","Sync Weight"),children:i.jsx(Sr,{className:"w-4 h-4"})})]})]}):i.jsx("span",{className:"text-zinc-500",children:"—"})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.tagId","Tag")}),i.jsx("span",{className:"font-mono text-xs text-zinc-400 truncate max-w-[120px]",title:t.tag_uid||"",children:t.tag_uid?t.tag_uid.slice(-8):"—"})]})]}),i.jsxs("div",{className:"flex gap-2 justify-center",children:[a&&i.jsx("button",{onClick:a,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:s("spoolbuddy.modal.assignToAms","Assign to AMS")}),i.jsx("button",{onClick:k,disabled:e===null||o,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${c?"bg-green-600/20 text-green-400":a?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 disabled:cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed"}`,children:o?"...":c?s("spoolbuddy.dashboard.weightSynced","Synced!"):s("spoolbuddy.dashboard.syncWeight","Sync Weight")}),n&&i.jsx("button",{onClick:n,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.close","Close")})]})]})}function Ent({tagUid:t,scaleWeight:e,coreWeight:n,onLinkSpool:r,onAddToInventory:a,onClose:s}){const{t:o}=Dt(),l=n??Joe(),c=e!==null?Math.round(Math.max(0,e)):null,u=c!==null?Math.round(Math.max(0,c-l)):null;return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-5",children:[i.jsx("div",{className:"w-20 h-20 rounded-2xl bg-green-500/15 flex items-center justify-center",children:i.jsx("svg",{className:"w-10 h-10 text-green-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"})})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:o("spoolbuddy.dashboard.newTag","New Tag Detected")}),i.jsx("p",{className:"text-sm text-zinc-500 font-mono mt-1",children:t})]}),c!==null&&i.jsxs("div",{className:"text-sm text-zinc-400",children:[i.jsxs("span",{className:"font-mono font-semibold",children:[c,"g"]})," ",o("spoolbuddy.dashboard.onScale","on scale"),u!==null&&u>0&&i.jsxs("span",{className:"text-zinc-500",children:[" • ~",u,"g filament"]})]}),i.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[a&&i.jsx("button",{onClick:a,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:o("spoolbuddy.modal.addToInventory","Add to Inventory")}),r&&i.jsxs("button",{onClick:r,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:[i.jsx("svg",{className:"w-4 h-4 inline-block mr-1.5 -mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"})}),o("spoolbuddy.dashboard.linkSpool","Link to Spool")]}),s&&i.jsx("button",{onClick:s,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:o("spoolbuddy.dashboard.close","Close")})]})]})}function jnt(t){return t?`#${t.slice(0,6)}`:"#808080"}function ele(t){return!t.tray_type||t.tray_type===""}function Dnt(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function Rnt({className:t}){return i.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:i.jsx("path",{d:"M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z",fill:"#C3C2C1"})})}function Fnt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z",fill:"#C3C2C1"}),i.jsx("path",{d:"M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z",fill:"#1F8FEB"})]})}function Lnt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z",fill:"#1F8FEB"}),i.jsx("path",{d:"M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z",fill:"#C3C2C1"})]})}function Ont({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"}),i.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function Int({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function znt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function tle({humidity:t,goodThreshold:e=40,fairThreshold:n=60}){let r,a;return t<=e?(r="#22a352",a=Rnt):t<=n?(r="#d4a017",a=Fnt):(r="#c62828",a=Lnt),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx(a,{className:"w-3 h-3.5"}),i.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:r},children:[t,"%"]})]})}function nle({temp:t,goodThreshold:e=28,fairThreshold:n=35}){let r,a;return t<=e?(r="#22a352",a=Ont):t<=n?(r="#d4a017",a=Int):(r="#c62828",a=znt),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx(a,{className:"w-3 h-3.5"}),i.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:r},children:[t,"°C"]})]})}function j5({side:t}){return i.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[9px] font-bold rounded",style:{backgroundColor:"#1a4d2e",color:"#00ae42"},children:t})}function Unt({tray:t,slotIndex:e,isActive:n,fillOverride:r,spoolmanFill:a,onClick:s}){const o=ele(t),l=jnt(t.tray_color),c=t.remain!==null&&t.remain!==void 0&&t.remain>=0?t.remain:null,u=r===0&&c!==null&&c>0?null:r,d=a??u??c;return i.jsxs("div",{className:`relative flex flex-col items-center p-2.5 rounded-lg transition-all ${n?"ring-2 ring-bambu-green":""} ${s?"cursor-pointer hover:bg-white/5":""}`,onClick:s,children:[i.jsxs("div",{className:"relative w-16 h-16 mb-1",children:[o?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:i.jsx("div",{className:"w-3 h-3 rounded-full bg-gray-600"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:l}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:l,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),n&&i.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-2.5 h-2.5 bg-bambu-green rounded-full"})]}),i.jsx("span",{className:"text-sm text-white/70 truncate max-w-full",children:o?"Empty":t.tray_type||"Unknown"}),!o&&d!==null&&d>=0&&i.jsx("div",{className:"w-full h-1 bg-bambu-dark-tertiary rounded-full overflow-hidden mt-1",children:i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${d}%`,backgroundColor:ix(d)}})}),i.jsx("span",{className:"absolute top-1 right-1 text-xs text-white/30",children:e+1})]})}function rle({unit:t,activeSlot:e,onConfigureSlot:n,isDualNozzle:r,nozzleSide:a,thresholds:s,fillOverrides:o,spoolmanFillOverrides:l}){const c=t.tray||[],u=t.is_ams_ht,d=u?1:4;return i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("span",{className:"text-white font-medium text-base",children:Dnt(t.id)}),r&&a&&i.jsx(j5,{side:a})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.temp!=null&&i.jsx(nle,{temp:t.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair}),t.humidity!=null&&i.jsx(tle,{humidity:t.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair})]})]}),i.jsx("div",{className:`grid ${u?"grid-cols-1 max-w-[100px] mx-auto":"grid-cols-4"} gap-2`,children:Array.from({length:d}).map((m,p)=>{const f=c[p]||{id:p,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null};return i.jsx(Unt,{tray:f,slotIndex:p,isActive:e===p,fillOverride:o?.[`${t.id}-${p}`]??null,spoolmanFill:l?.[`${t.id}-${p}`]??null,onClick:n?()=>n(t.id,p,ele(f)?null:f):void 0},p)})})]})}function Bnt(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function VY(t){return!t.tray_type||t.tray_type===""}function Hnt(t){return t?`#${t.slice(0,6)}`:"#808080"}function $nt({isOpen:t,onClose:e,spool:n,printerId:r}){const{t:a}=Dt(),s=sn(),[o,l]=w.useState(null),[c,u]=w.useState(null);w.useEffect(()=>{t&&(l(null),u(null))},[t]);const d=w.useCallback(J=>{J.key==="Escape"&&e()},[e]);w.useEffect(()=>(t&&document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)),[t,d]);const{data:m}=et({queryKey:["printerStatus",r],queryFn:()=>ge.getPrinterStatus(r),enabled:t&&r!==null,refetchInterval:5e3}),{data:p}=et({queryKey:["printer",r],queryFn:()=>ge.getPrinter(r),enabled:t&&r!==null}),{data:f}=et({queryKey:["settings"],queryFn:()=>ge.getSettings(),enabled:t,staleTime:300*1e3}),{data:y}=et({queryKey:["spool-assignments",r],queryFn:()=>ge.getAssignments(r),enabled:t&&r!==null,staleTime:30*1e3}),v=w.useMemo(()=>{const J={};if(!y)return J;for(const ae of y){const Y=ae.spool;if(Y&&Y.label_weight>0&&Y.weight_used!=null){const ue=Math.round(Math.max(0,Y.label_weight-Y.weight_used)/Y.label_weight*100);J[`${ae.ams_id}-${ae.tray_id}`]=ue}}return J},[y]),b=f?{humidityGood:Number(f.ams_humidity_good)||40,humidityFair:Number(f.ams_humidity_fair)||60,tempGood:Number(f.ams_temp_good)||28,tempFair:Number(f.ams_temp_fair)||35}:void 0,g=m?.connected??!1,_=w.useMemo(()=>m?.ams??[],[m?.ams]),N=w.useMemo(()=>_.filter(J=>!J.is_ams_ht),[_]),C=w.useMemo(()=>_.filter(J=>J.is_ams_ht),[_]),k=w.useMemo(()=>[...m?.vt_tray??[]].sort((J,ae)=>(J.id??254)-(ae.id??254)),[m?.vt_tray]),P=p?.nozzle_count===2||m?.temperatures?.nozzle_2!==void 0,T=w.useRef({});w.useEffect(()=>{m?.ams_extruder_map&&Object.keys(m.ams_extruder_map).length>0&&(T.current=m.ams_extruder_map)},[m?.ams_extruder_map]);const D=m?.ams_extruder_map&&Object.keys(m.ams_extruder_map).length>0?m.ams_extruder_map:T.current,A=w.useCallback(J=>{if(!P)return null;const ae=D[String(J)],Y=J>=128?J-128:J;return(ae!==void 0?ae:Y)===1?"L":"R"},[P,D]),R=gt({mutationFn:async({amsId:J,trayId:ae})=>{if(!r)throw new Error("No printer selected");await ge.assignSpool({spool_id:n.id,printer_id:r,ams_id:J,tray_id:ae})},onSuccess:()=>{u("success"),l(a("spoolbuddy.modal.assignSuccess","Assigned!")),s.invalidateQueries({queryKey:["slotPresets"]}),setTimeout(()=>e(),1500)},onError:J=>{u("error"),l(J instanceof Error?J.message:a("spoolbuddy.modal.assignError","Failed to assign spool."))}}),G=R.isPending,z=w.useCallback((J,ae)=>{G||(u("info"),l(a("spoolbuddy.modal.assigning","Configuring slot...")),R.mutate({amsId:J,trayId:ae}))},[G,R,a]),Z=w.useMemo(()=>{const J=[];for(const ae of C){const Y=ae.tray?.[0]||{id:0,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},ue=v[`${ae.id}-0`]??null,de=Y.remain!=null&&Y.remain>=0?Y.remain:null,he=ue===0&&de!==null&&de>0?null:ue;J.push({key:`ht-${ae.id}`,label:Bnt(ae.id),amsId:ae.id,trayId:0,tray:Y,isEmpty:VY(Y),nozzleSide:A(ae.id),effectiveFill:he??de})}for(const ae of k){const Y=ae.id??254,ue=Y-254,de=v[`255-${ue}`]??null,he=ae.remain!=null&&ae.remain>=0?ae.remain:null,V=de===0&&he!==null&&he>0?null:de;J.push({key:`ext-${Y}`,label:P?Y===254?a("printers.extL","Ext-L"):a("printers.extR","Ext-R"):a("printers.ext","Ext"),amsId:255,trayId:ue,tray:ae,isEmpty:VY(ae),nozzleSide:P?Y===254?"L":"R":null,effectiveFill:V??he})}return J},[C,k,P,a,A,v]);if(!t)return null;const I=n.rgba?`#${n.rgba.slice(0,6)}`:"#808080";return i.jsxs("div",{className:"fixed inset-0 z-[60] bg-bambu-dark flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-zinc-800 shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx("div",{className:"w-7 h-7 rounded-full shrink-0",style:{backgroundColor:I}}),i.jsx("div",{className:"min-w-0",children:i.jsxs("h2",{className:"text-sm font-semibold text-zinc-100 truncate",children:[a("spoolbuddy.modal.assignToAmsTitle","Assign to AMS"),i.jsxs("span",{className:"font-normal text-zinc-500 ml-2",children:[n.color_name||"Unknown"," • ",n.brand," ",n.material,n.subtype&&` ${n.subtype}`]})]})})]}),i.jsx("button",{onClick:e,disabled:G,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800 transition-colors shrink-0 disabled:opacity-50",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),o&&i.jsxs("div",{className:`mx-5 mt-3 p-3 rounded-lg flex items-center gap-3 border shrink-0 ${c==="info"?"bg-blue-500/10 border-blue-500/40":c==="success"?"bg-green-500/10 border-green-500/40":"bg-red-500/10 border-red-500/40"}`,children:[c==="info"&&i.jsx(ft,{className:"w-4 h-4 text-blue-400 animate-spin shrink-0"}),c==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-400 shrink-0"}),c==="error"&&i.jsx(Vi,{className:"w-4 h-4 text-red-400 shrink-0"}),i.jsx("span",{className:`text-sm ${c==="info"?"text-blue-300":c==="success"?"text-green-300":"text-red-300"}`,children:o})]}),i.jsx("div",{className:"flex-1 flex flex-col gap-3 p-4 min-h-0",children:!g&&r?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsx("div",{className:"text-center text-white/50",children:i.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):_.length===0&&k.length===0?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsxs("div",{className:"text-center text-white/50",children:[i.jsx(Gi,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),i.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.noData","No AMS detected")}),i.jsx("p",{className:"text-sm",children:a("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):i.jsxs(i.Fragment,{children:[N.length>0&&i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 flex-1 min-h-0",children:N.map(J=>i.jsx(rle,{unit:J,activeSlot:null,onConfigureSlot:(ae,Y)=>z(J.id,Y),isDualNozzle:P,nozzleSide:A(J.id),thresholds:b,fillOverrides:v},J.id))}),Z.length>0&&i.jsx("div",{className:"flex gap-2 shrink-0",children:Z.map(({key:J,label:ae,amsId:Y,trayId:ue,tray:de,isEmpty:he,nozzleSide:V,effectiveFill:ne})=>{const se=Hnt(de.tray_color);return i.jsxs("div",{onClick:()=>z(Y,ue),className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-2 ${G?"opacity-50 pointer-events-none":""}`,children:[i.jsx("div",{className:"relative w-10 h-10 shrink-0",children:he?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:i.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:se}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:se,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]})}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"text-xs text-white/50 font-medium",children:ae}),V&&i.jsx(j5,{side:V})]}),i.jsx("div",{className:"text-sm text-white/80 truncate",children:he?"Empty":de.tray_type||"?"})]}),!he&&ne!=null&&ne>=0&&i.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden shrink-0 flex flex-col-reverse",children:i.jsx("div",{className:"w-full rounded-full",style:{height:`${ne}%`,backgroundColor:ix(ne)}})})]},J)})})]})}),i.jsx("div",{className:"flex justify-end gap-3 px-5 py-3 border-t border-zinc-800 shrink-0",children:i.jsx("button",{onClick:e,disabled:G,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-800 text-zinc-300 hover:bg-zinc-700 transition-colors min-h-[44px] disabled:opacity-50",children:c==="success"?a("spoolbuddy.dashboard.close","Close"):a("spoolbuddy.modal.cancel","Cancel")})})]})}function qnt({isOpen:t,onClose:e,tagId:n,untaggedSpools:r,onLink:a}){const{t:s}=Dt(),[o,l]=w.useState(null),c=w.useCallback(()=>{l(null),e()},[e]),u=w.useCallback(m=>{m.key==="Escape"&&c()},[c]);if(w.useEffect(()=>(t&&(document.addEventListener("keydown",u),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",u),document.body.style.overflow=""}),[t,u]),!t)return null;const d=()=>{o&&(a(o),l(null))};return i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:c,children:i.jsxs("div",{className:"bg-zinc-800 rounded-xl shadow-2xl w-full max-w-lg mx-4 animate-slide-up",onClick:m=>m.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-zinc-700",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-base font-semibold text-zinc-100",children:s("spoolbuddy.dashboard.linkTagTitle","Link Tag to Spool")}),i.jsx("p",{className:"text-sm text-zinc-500 font-mono",children:n})]}),i.jsx("button",{onClick:c,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"px-5 py-4 space-y-3 max-h-[400px] overflow-y-auto",children:[i.jsx("p",{className:"text-sm text-zinc-400",children:s("spoolbuddy.dashboard.selectSpool","Select a spool to link this tag to:")}),r.length===0?i.jsx("div",{className:"text-center py-8 text-zinc-500",children:s("spoolbuddy.dashboard.noUntagged","No spools without tags found")}):i.jsx("div",{className:"space-y-2",children:r.map(m=>i.jsxs("button",{type:"button",onClick:()=>l(m),className:`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left ${o?.id===m.id?"border-green-500 bg-green-500/10":"border-zinc-700 hover:border-green-500/50 hover:bg-zinc-700/50"}`,children:[i.jsx(E5,{color:m.rgba?`#${m.rgba.slice(0,6)}`:"#808080",isEmpty:!1,size:40}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"font-medium text-zinc-100 truncate",children:m.color_name||"Unknown color"}),i.jsxs("div",{className:"text-sm text-zinc-400 truncate",children:[m.brand," • ",m.material,m.subtype&&` ${m.subtype}`]})]}),i.jsxs("div",{className:"text-sm font-mono text-zinc-500",children:[Math.max(0,m.label_weight-m.weight_used),"g"]})]},m.id))})]}),i.jsxs("div",{className:"flex justify-end gap-2 px-5 py-4 border-t border-zinc-700",children:[i.jsx("button",{onClick:c,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("common.cancel","Cancel")}),i.jsx("button",{onClick:d,disabled:!o,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.linkTag","Link Tag")})]})]})})}const GY=["#00AE42","#FF6B35","#3B82F6","#EF4444","#A855F7","#FBBF24","#14B8A6","#EC4899","#F97316","#22C55E"];function Vnt(){const{t}=Dt(),[e,n]=w.useState(0);w.useEffect(()=>{const a=setInterval(()=>{n(s=>(s+1)%GY.length)},2e3);return()=>clearInterval(a)},[]);const r=GY[e];return i.jsxs("div",{className:"flex flex-col items-center text-center",children:[i.jsxs("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:[i.jsx("div",{className:"absolute w-24 h-24 rounded-full border-2 border-green-500/30 animate-ping",style:{animationDuration:"2.5s"}}),i.jsx("div",{className:"absolute w-32 h-32 rounded-full border border-green-500/20 animate-ping",style:{animationDuration:"2.5s",animationDelay:"0.4s"}}),i.jsx("div",{className:"absolute w-40 h-40 rounded-full border border-green-500/10 animate-ping",style:{animationDuration:"2.5s",animationDelay:"0.8s"}}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute -inset-4 rounded-full blur-2xl opacity-30 transition-colors duration-1000",style:{backgroundColor:r}}),i.jsx("div",{className:"transition-all duration-1000",children:i.jsx(E5,{color:r,isEmpty:!1,size:100})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xl font-medium text-zinc-300",children:t("spoolbuddy.dashboard.readyToScan","Ready to scan")}),i.jsx("p",{className:"text-sm text-zinc-500",children:t("spoolbuddy.dashboard.idleMessage","Place a spool on the scale to identify it")})]}),i.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-zinc-600",children:[i.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),i.jsx("span",{children:t("spoolbuddy.dashboard.nfcHint","NFC tag will be read automatically")})]})]})}function Gnt(){const{t}=Dt();return i.jsxs("div",{className:"flex flex-col items-center text-center",children:[i.jsx("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:i.jsx("div",{className:"w-24 h-24 rounded-full bg-zinc-800 flex items-center justify-center",children:i.jsx("svg",{className:"w-12 h-12 text-zinc-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"M18.364 5.636a9 9 0 010 12.728m0 0l-12.728-12.728m12.728 12.728L5.636 5.636m12.728 0a9 9 0 00-12.728 0m0 12.728a9 9 0 010-12.728"})})})}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-lg font-medium text-zinc-500",children:t("spoolbuddy.status.deviceOffline","Device Offline")}),i.jsx("p",{className:"text-sm text-zinc-600",children:t("spoolbuddy.status.connectDisplay","Connect the SpoolBuddy display to scan spools")})]}),i.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-zinc-600",children:[i.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.14 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"})}),i.jsx("span",{children:t("spoolbuddy.status.waitingConnection","Waiting for device connection...")})]})]})}function Wnt(){const{sbState:t,selectedPrinterId:e}=fw(),{t:n}=Dt(),{data:r=[],refetch:a}=et({queryKey:["inventory-spools"],queryFn:()=>ge.getSpools(!1)}),{data:s=[]}=et({queryKey:["printers"],queryFn:()=>ge.getPrinters()}),o=tg({queries:s.map(V=>({queryKey:["printerStatus",V.id],queryFn:()=>ge.getPrinterStatus(V.id),refetchInterval:1e4}))}),[l,c]=w.useState(null),[u,d]=w.useState(null),[m,p]=w.useState(null),[f,y]=w.useState(!1),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[N,C]=w.useState(!1),k=t.matchedSpool?.tag_uid??t.unknownTagUid??null,P=t.weight,T=t.weightStable,D=w.useRef(null);P===null?D.current=null:(D.current===null||Math.abs(P-D.current)>=3||T)&&(D.current=P);const R=D.current,G=w.useMemo(()=>l?r.find(V=>V.tag_uid===l)??null:null,[l,r]),z=w.useMemo(()=>r.filter(V=>!V.tag_uid&&!V.archived_at),[r]);w.useEffect(()=>{if(k){const V=m===k;(l!==null&&l!==k||!V&&l!==k)&&(c(k),d(null),p(null)),!V&&P!==null&&T&&d(Math.round(Math.max(0,P)))}else m&&(c(null),p(null),d(null))},[k,P,T,l,m]);const Z=()=>{p(l)},I=async V=>{if(l)try{await ge.linkTagToSpool(V.id,{tag_uid:l,tag_type:"generic",data_origin:"nfc_link"}),y(!1),a()}catch(ne){console.error("Failed to link tag:",ne)}},J=async()=>{if(l){C(!0);try{const V=Y??u;await ge.createSpool({material:"PLA",subtype:null,color_name:null,rgba:null,brand:null,label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,nozzle_temp_min:null,nozzle_temp_max:null,note:null,added_full:null,last_used:null,encode_time:null,tag_uid:l,tray_uuid:null,data_origin:"spoolbuddy",tag_type:"generic",cost_per_kg:null,last_scale_weight:V,last_weighed_at:V!==null?new Date().toISOString():null}),_(!1),a()}catch(V){console.error("Failed to quick-add spool:",V)}finally{C(!1)}}},Y=P!==null&&(k===l||k===null&&l!==null)?P:null,ue=r.length,de=new Set(r.map(V=>V.material)).size,he=new Set(r.filter(V=>V.brand).map(V=>V.brand)).size;return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsxs("div",{className:"flex items-center gap-6 px-4 py-1.5 bg-zinc-800/50 rounded-xl border border-zinc-700/50 mb-3 shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xl font-bold text-zinc-100",children:ue}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.inventory.spools","Spools")})]}),i.jsx("div",{className:"w-px h-5 bg-zinc-700"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xl font-bold text-zinc-100",children:de}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.material","Materials")})]}),i.jsx("div",{className:"w-px h-5 bg-zinc-700"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xl font-bold text-zinc-100",children:he}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.brand","Brands")})]})]}),i.jsxs("div",{className:"flex-1 flex gap-4 min-h-0",children:[i.jsxs("div",{className:"w-5/12 flex flex-col min-h-0",children:[i.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-4",children:[i.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-3",children:n("spoolbuddy.dashboard.device","Device")}),i.jsxs("div",{className:"space-y-2.5",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${t.deviceOnline?"bg-green-500 animate-pulse":"bg-red-500"}`}),i.jsx("span",{className:"text-base text-zinc-400",children:t.deviceOnline?n("spoolbuddy.status.online","Online"):n("spoolbuddy.status.offline","Disconnected")})]}),i.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3"})}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.scaleWeight","Scale")})]}),i.jsx("span",{className:"text-lg font-mono font-semibold text-zinc-100",children:R!==null?`${Math.abs(R)<=20?0:Math.round(Math.max(0,R))}g`:"—"})]}),i.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"})}),i.jsx("span",{className:"text-sm text-zinc-500",children:"NFC"})]}),i.jsx("span",{className:`text-sm font-medium ${k?"text-green-500":"text-zinc-500"}`,children:k?n("spoolbuddy.dashboard.tagDetected","Tag detected"):n("spoolbuddy.dashboard.noTag","No tag")})]})]})]}),s.length>0&&i.jsxs("div",{className:"mt-3 border border-dashed border-zinc-700/50 rounded-xl p-4",children:[i.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-2.5",children:n("spoolbuddy.dashboard.printers","Printers")}),i.jsx("div",{className:"flex flex-wrap gap-2 overflow-hidden",children:s.map((V,ne)=>{const se=o[ne]?.data?.connected??!1;return i.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 bg-zinc-800/50 rounded-lg",title:`${V.name} — ${se?"Online":"Offline"}`,children:[i.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${se?"bg-green-500":"bg-zinc-600"}`}),i.jsx("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:V.name})]},V.id)})})]})]}),i.jsx("div",{className:"w-7/12 min-h-0",children:i.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-6 h-full flex flex-col",children:[i.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-4 shrink-0",children:n("spoolbuddy.dashboard.currentSpool","Current Spool")}),i.jsx("div",{className:"flex-1 flex items-center justify-center min-h-0",children:t.deviceOnline?G&&l&&m!==l?i.jsx(Mnt,{spool:{id:G.id,tag_uid:l,material:G.material,subtype:G.subtype,color_name:G.color_name,rgba:G.rgba,brand:G.brand,label_weight:G.label_weight,core_weight:G.core_weight,weight_used:G.weight_used},scaleWeight:Y??u,onSyncWeight:()=>a(),onAssignToAms:()=>b(!0),onClose:Z}):l&&!G&&m!==l?i.jsx(Ent,{tagUid:l,scaleWeight:Y??u,onLinkSpool:z.length>0?()=>y(!0):void 0,onAddToInventory:()=>_(!0),onClose:Z}):i.jsx(Vnt,{}):i.jsx(Gnt,{})})]})})]}),G&&l&&i.jsx($nt,{isOpen:v,onClose:()=>b(!1),spool:G,printerId:e}),l&&i.jsx(qnt,{isOpen:f,onClose:()=>y(!1),tagId:l,untaggedSpools:z,onLink:I}),g&&l&&i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",children:i.jsxs("div",{className:"bg-zinc-800 rounded-2xl p-6 mx-4 max-w-sm w-full border border-zinc-700",children:[i.jsx("h3",{className:"text-lg font-semibold text-zinc-100 mb-3",children:n("spoolbuddy.modal.addToInventory","Add to Inventory")}),i.jsxs("div",{className:"flex gap-2.5 p-3 bg-amber-500/10 border border-amber-500/20 rounded-lg mb-4",children:[i.jsx("svg",{className:"w-5 h-5 text-amber-500 shrink-0 mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),i.jsx("p",{className:"text-sm text-amber-200/80",children:n("spoolbuddy.modal.quickAddHint",'For best results, add the spool in the Bambuddy web interface first (with material, color, brand), then use "Link to Spool" here to assign the NFC tag.')})]}),i.jsx("p",{className:"text-sm text-zinc-400 mb-1",children:n("spoolbuddy.modal.quickAddDesc","This will create a basic PLA spool entry with this NFC tag. You can edit the details later in Bambuddy.")}),i.jsx("p",{className:"text-xs text-zinc-500 font-mono mb-5",children:l}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx("button",{onClick:()=>_(!1),className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:n("common.cancel","Cancel")}),i.jsx("button",{onClick:J,disabled:N,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-50 transition-colors min-h-[44px]",children:N?n("common.saving","Saving..."):n("spoolbuddy.modal.addAnyway","Add Anyway")})]})]})})]})}function WY(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function Knt(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",P1S:"P1S",P1P:"P1P",P2S:"P2S",A1:"A1","A1 Mini":"A1 Mini",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[t]||t:""}function Pb(t){return!t.tray_type||t.tray_type===""}function Ynt(t){return t?`#${t.slice(0,6)}`:"#808080"}function Xnt(){const{selectedPrinterId:t,setAlert:e}=fw(),{t:n}=Dt(),r=sn(),{data:a}=et({queryKey:["printerStatus",t],queryFn:()=>ge.getPrinterStatus(t),enabled:t!==null,staleTime:30*1e3}),{data:s}=et({queryKey:["printer",t],queryFn:()=>ge.getPrinter(t),enabled:t!==null,staleTime:60*1e3}),{data:o}=et({queryKey:["slotPresets",t],queryFn:()=>ge.getSlotPresets(t),enabled:t!==null,staleTime:120*1e3}),{data:l}=et({queryKey:["settings"],queryFn:()=>ge.getSettings(),staleTime:300*1e3}),{data:c}=et({queryKey:["spoolman-status"],queryFn:ge.getSpoolmanStatus,staleTime:60*1e3}),u=c?.enabled&&c?.connected,{data:d}=et({queryKey:["linked-spools"],queryFn:ge.getLinkedSpools,enabled:!!u,staleTime:30*1e3}),m=d?.linked,{data:p}=et({queryKey:["spool-assignments",t],queryFn:()=>ge.getAssignments(t),enabled:t!==null,staleTime:30*1e3}),f=w.useMemo(()=>{const V={};if(!p)return V;for(const ne of p){const se=ne.spool;if(se&&se.label_weight>0&&se.weight_used!=null){const pe=Math.round(Math.max(0,se.label_weight-se.weight_used)/se.label_weight*100);V[`${ne.ams_id}-${ne.tray_id}`]=pe}}return V},[p]),y=s?.serial_number??"",v=w.useCallback((V,ne,se)=>{if(!m||!y)return null;const pe=(se?.tray_uuid||se?.tag_uid||$p(y,V,ne))?.toUpperCase(),Te=pe?m[pe]:void 0;return yN(Te)},[m,y]),b=a?.connected??!1,g=w.useRef([]);w.useEffect(()=>{a?.ams&&a.ams.length>0&&(g.current=a.ams)},[a?.ams]);const _=w.useMemo(()=>{const V=a?.ams;return V&&V.length>0?V:g.current??[]},[a?.ams]),N=w.useMemo(()=>_.filter(V=>!V.is_ams_ht),[_]),C=w.useMemo(()=>_.filter(V=>V.is_ams_ht),[_]),k=w.useMemo(()=>{const V={};if(!m||!y)return V;for(const ne of N)for(let se=0;se<(ne.tray?.length??0);se++){const pe=ne.tray[se],Te=v(ne.id,se,Pb(pe)?null:pe);Te!==null&&(V[`${ne.id}-${se}`]=Te)}return V},[m,y,N,v]),P=w.useRef(void 0),T=a?.tray_now;T!==void 0&&T!==255?P.current=T:T===255&&(P.current=void 0);const D=T!==void 0&&T!==255?T:P.current,A=s?.nozzle_count===2||a?.temperatures?.nozzle_2!==void 0,R=w.useMemo(()=>[...a?.vt_tray??[]].sort((V,ne)=>(V.id??254)-(ne.id??254)),[a?.vt_tray]),G=l?{humidityGood:Number(l.ams_humidity_good)||40,humidityFair:Number(l.ams_humidity_fair)||60,tempGood:Number(l.ams_temp_good)||28,tempFair:Number(l.ams_temp_fair)||35}:void 0,z=w.useRef({});w.useEffect(()=>{a?.ams_extruder_map&&Object.keys(a.ams_extruder_map).length>0&&(z.current=a.ams_extruder_map)},[a?.ams_extruder_map]);const Z=a?.ams_extruder_map&&Object.keys(a.ams_extruder_map).length>0?a.ams_extruder_map:z.current,I=w.useCallback(V=>{if(!A)return null;const ne=Z[String(V)],se=V>=128?V-128:V;return(ne!==void 0?ne:se)===1?"L":"R"},[A,Z]),[J,ae]=w.useState(null),Y=w.useCallback(V=>D===void 0?null:V<=3&&Math.floor(D/4)===V?D%4:V>=128&&V<=135&&D===Ex(V,0,!1)?0:null,[D]),ue=w.useCallback((V,ne,se)=>{const pe=V>=128?(V-128)*4+ne+64:V*4+ne,Te=o?.[pe],q=Z[String(V)],X=V>=128?V-128:V,j=q!==void 0?q:X;ae({amsId:V,trayId:ne,trayCount:se&&V>=128?1:4,trayType:se?.tray_type||void 0,trayColor:se?.tray_color||void 0,traySubBrands:se?.tray_sub_brands||void 0,trayInfoIdx:se?.tray_info_idx||void 0,extruderId:A?j:void 0,caliIdx:se?.cali_idx,savedPresetId:Te?.preset_id})},[o,Z,A]),de=w.useCallback(V=>{const ne=V.id??254,se=ne-254,pe=o?.[1020+se];ae({amsId:255,trayId:se,trayCount:1,trayType:V.tray_type||void 0,trayColor:V.tray_color||void 0,traySubBrands:V.tray_sub_brands||void 0,trayInfoIdx:V.tray_info_idx||void 0,extruderId:A?ne===254?1:0:void 0,caliIdx:V.cali_idx,savedPresetId:pe?.preset_id})},[o,A]);w.useEffect(()=>{if(!b&&t){e({type:"warning",message:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")});return}for(const V of _)for(const ne of V.tray||[])if(ne.remain!==null&&ne.remain>=0&&ne.remain<15&&ne.tray_type){e({type:"warning",message:`Low Filament: ${ne.tray_type} (${WY(V.id)}) - ${ne.remain}% remaining`});return}e(null)},[_,b,t,e,n]);const he=w.useMemo(()=>{const V=[];for(const ne of C){const se=ne.tray?.[0]||{id:0,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},pe=v(ne.id,0,Pb(se)?null:se),Te=f[`${ne.id}-0`]??null,q=se.remain!=null&&se.remain>=0?se.remain:null,X=Te===0&&q!==null&&q>0?null:Te;V.push({key:`ht-${ne.id}`,label:WY(ne.id),tray:se,isEmpty:Pb(se),isActive:Y(ne.id)===0,temp:ne.temp,humidity:ne.humidity,nozzleSide:I(ne.id),effectiveFill:pe??X??q,onClick:()=>ue(ne.id,0,Pb(se)?null:se)})}for(const ne of R){const se=ne.id??254,pe=A&&D===254?se===254&&a?.active_extruder===1||se===255&&a?.active_extruder===0:D===se,Te=se-254,q=v(255,Te,Pb(ne)?null:ne),X=f[`255-${Te}`]??null,j=ne.remain!=null&&ne.remain>=0?ne.remain:null,E=X===0&&j!==null&&j>0?null:X;V.push({key:`ext-${se}`,label:A?se===254?n("printers.extL","Ext-L"):n("printers.extR","Ext-R"):n("printers.ext","Ext"),tray:ne,isEmpty:Pb(ne),isActive:pe,nozzleSide:null,effectiveFill:q??E??j,onClick:()=>de(ne)})}return V},[C,R,A,D,a?.active_extruder,n,Y,I,ue,de,f,v]);return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("div",{className:"flex-1 min-h-0",children:t?b?_.length===0&&R.length===0?i.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:i.jsxs("div",{className:"text-center text-white/50",children:[i.jsx(Gi,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),i.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noData","No AMS detected")}),i.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):i.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:N.map(V=>i.jsx(rle,{unit:V,activeSlot:Y(V.id),onConfigureSlot:ue,isDualNozzle:A,nozzleSide:I(V.id),thresholds:G,fillOverrides:f,spoolmanFillOverrides:k},V.id))}),he.length>0&&i.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:he.map(({key:V,label:ne,tray:se,isEmpty:pe,isActive:Te,temp:q,humidity:X,nozzleSide:j,effectiveFill:E,onClick:U})=>{const K=Ynt(se.tray_color);return i.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-3 ${Te?"ring-2 ring-bambu-green":""}`,onClick:U,children:[i.jsxs("div",{className:"relative w-10 h-10 flex-shrink-0",children:[pe?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:i.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:K}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:K,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),Te&&i.jsx("div",{className:"absolute -bottom-0.5 left-1/2 -translate-x-1/2 w-1.5 h-1.5 bg-bambu-green rounded-full"})]}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"text-xs text-white/50 font-medium truncate",children:ne}),j&&i.jsx(j5,{side:j})]}),i.jsx("div",{className:"text-sm text-white/80 truncate",children:pe?"Empty":se.tray_type||"?"}),(q!=null||X!=null)&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[q!=null&&i.jsx(nle,{temp:q,goodThreshold:G?.tempGood,fairThreshold:G?.tempFair}),X!=null&&i.jsx(tle,{humidity:X,goodThreshold:G?.humidityGood,fairThreshold:G?.humidityFair})]})]}),!pe&&E!=null&&E>=0&&i.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0 flex flex-col-reverse",children:i.jsx("div",{className:"w-full rounded-full",style:{height:`${E}%`,backgroundColor:ix(E)}})})]},V)})})]}):i.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:i.jsx("div",{className:"text-center text-white/50",children:i.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):i.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:i.jsxs("div",{className:"text-center text-white/50",children:[i.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noPrinter","No printer selected")}),i.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.selectPrinter","Select a printer from the top bar")})]})})}),J&&t&&i.jsx(tie,{isOpen:!!J,onClose:()=>ae(null),printerId:t,slotInfo:J,printerModel:Knt(s?.model??null)||void 0,fullScreen:!0,onSuccess:()=>{r.invalidateQueries({queryKey:["slotPresets",t]}),r.invalidateQueries({queryKey:["printerStatus",t]})}})]})}function Qnt(t){if(t<60)return`${t}s`;if(t<3600)return`${Math.floor(t/60)}m`;const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return`${e}h ${n}m`}function Znt(t){if(!t)return"-";try{const e=new Date(t);return e.toLocaleDateString(void 0,{month:"short",day:"numeric"})+" "+e.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}catch{return"-"}}const Jnt=[{label:"Off",value:0},{label:"1m",value:60},{label:"2m",value:120},{label:"5m",value:300},{label:"10m",value:600},{label:"30m",value:1800}];function ert({device:t}){const{t:e}=Dt();return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsx("div",{className:"flex items-center gap-3 mb-2",children:i.jsx("img",{src:"/img/spoolbuddy_logo_dark_small.png",alt:"SpoolBuddy",className:"h-7 w-auto"})}),i.jsx("p",{className:"text-xs text-zinc-500 mb-1",children:"Part of Bambuddy"}),i.jsx("span",{className:"text-xs text-zinc-500",children:"github.com/maziggy/bambuddy"})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.nfcReader","NFC Reader")}),i.jsxs("div",{className:"space-y-1.5 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.type","Type")}),i.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_reader_type||"N/A"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.connection","Connection")}),i.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_connection||"N/A"})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.status.status","Status")}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${t.nfc_ok?"bg-green-500":t.nfc_reader_type?"bg-red-500":"bg-zinc-600"}`}),i.jsx("span",{className:t.nfc_ok?"text-green-400":t.nfc_reader_type?"text-red-400":"text-zinc-500",children:t.nfc_ok?e("spoolbuddy.status.nfcReady","Ready"):t.nfc_reader_type?e("common.error","Error"):e("spoolbuddy.settings.notConnected","N/A")})]})]})]})]}),i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.deviceInfo","Device Info")}),i.jsxs("div",{className:"space-y-1.5 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.hostname","Host")}),i.jsx("span",{className:"text-zinc-300 truncate ml-2",children:t.hostname})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:"IP"}),i.jsx("span",{className:"text-zinc-300",children:t.ip_address})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.uptime","Uptime")}),i.jsx("span",{className:"text-zinc-300",children:Qnt(t.uptime_s)})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.status.status","Status")}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${t.online?"bg-green-500":"bg-zinc-600"}`}),i.jsx("span",{className:t.online?"text-green-400":"text-zinc-500",children:t.online?e("spoolbuddy.status.online","Online"):e("spoolbuddy.status.offline","Offline")})]})]})]})]})]}),i.jsxs("div",{className:"bg-zinc-800 rounded-lg px-3 py-2 flex justify-between items-center text-xs",children:[i.jsx("span",{className:"text-zinc-500",children:"Device ID"}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.device_id})]})]})}function trt({device:t,onBrightnessChange:e,onBlankTimeoutChange:n}){const{t:r}=Dt(),[a,s]=w.useState(t.display_brightness),[o,l]=w.useState(t.display_blank_timeout),[c,u]=w.useState(!1),d=w.useRef(void 0),m=w.useRef(void 0);w.useEffect(()=>{s(t.display_brightness),l(t.display_blank_timeout)},[t.display_brightness,t.display_blank_timeout]);const p=w.useCallback(()=>{u(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>u(!1),1500)},[]),f=w.useCallback((b,g)=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{pa.updateDisplay(t.device_id,b,g).then(()=>p()).catch(_=>console.error("Failed to update display:",_))},300)},[t.device_id,p]),y=b=>{s(b),e(b),f(b,o)},v=b=>{l(b),n(b),f(a,b)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:r("spoolbuddy.settings.brightness","Brightness")}),c&&i.jsxs("span",{className:"text-xs text-green-400 flex items-center gap-1 animate-pulse",children:[i.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}),r("spoolbuddy.settings.saved","Saved")]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("svg",{className:"w-4 h-4 text-zinc-500 flex-shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"})}),i.jsx("input",{type:"range",min:0,max:100,value:a,onChange:b=>y(parseInt(b.target.value)),className:"flex-1 h-2 bg-zinc-700 rounded-lg appearance-none cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-sm font-mono text-zinc-400 w-10 text-right",children:[a,"%"]})]}),!t.has_backlight&&i.jsx("p",{className:"text-xs text-zinc-600 mt-2",children:r("spoolbuddy.settings.noBacklight","No DSI backlight detected. Brightness control requires a DSI display.")})]}),i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1",children:r("spoolbuddy.settings.screenBlank","Screen Blank Timeout")}),i.jsx("p",{className:"text-xs text-zinc-500 mb-3",children:r("spoolbuddy.settings.screenBlankDesc","Screen turns off after inactivity. Touch to wake.")}),i.jsx("div",{className:"grid grid-cols-3 gap-2",children:Jnt.map(b=>i.jsx("button",{onClick:()=>v(b.value),className:`px-3 py-2 rounded-lg text-sm font-medium transition-colors min-h-[40px] ${o===b.value?"bg-green-600 text-white":"bg-zinc-700 text-zinc-300 hover:bg-zinc-600"}`,children:b.label},b.value))})]}),i.jsx("p",{className:"text-xs text-zinc-600 text-center",children:r("spoolbuddy.settings.displayNote","Brightness is applied as a software filter.")})]})}function nrt({step:t,labels:e}){return i.jsxs("div",{className:"flex flex-col items-center w-16 shrink-0 pt-1",children:[i.jsx("div",{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${t==="tare"?"bg-green-600 text-white":"bg-green-600/20 text-green-400"}`,children:t==="weight"?i.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}):"1"}),i.jsx("span",{className:`text-[10px] mt-0.5 ${t==="tare"?"text-green-400 font-medium":"text-green-400/60"}`,children:e.tare}),i.jsx("div",{className:`w-px h-5 my-1 ${t==="weight"?"bg-green-600/40":"bg-zinc-700"}`}),i.jsx("div",{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${t==="weight"?"bg-green-600 text-white":"bg-zinc-700 text-zinc-500"}`,children:"2"}),i.jsx("span",{className:`text-[10px] mt-0.5 ${t==="weight"?"text-green-400 font-medium":"text-zinc-600"}`,children:e.weight})]})}function rrt({device:t,weight:e,weightStable:n,rawAdc:r}){const{t:a}=Dt(),[s,o]=w.useState("idle"),[l,c]=w.useState("500"),[u,d]=w.useState(null),[m,p]=w.useState(!1),[f,y]=w.useState(null),v=_=>{_==="backspace"?c(N=>N.slice(0,-1)||""):_==="."&&!l.includes(".")?c(N=>N+"."):_>="0"&&_<="9"&&c(N=>N==="0"?_:N+_)},b=async()=>{p(!0),y(null);try{await pa.tare(t.device_id),y({type:"ok",msg:a("spoolbuddy.settings.tareSet","Tare command sent. Waiting for device...")})}catch{y({type:"error",msg:a("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{p(!1)}},g=async()=>{if(s==="tare"){p(!0),y(null);try{d(r),await pa.tare(t.device_id),y({type:"ok",msg:a("spoolbuddy.settings.zeroSet","Zero point set. Place known weight on scale.")}),o("weight")}catch{y({type:"error",msg:a("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{p(!1)}}else if(s==="weight"){const _=parseFloat(l);if(r===null||!_||_<=0)return;p(!0),y(null);try{await pa.setCalibrationFactor(t.device_id,_,r,u??void 0),y({type:"ok",msg:a("spoolbuddy.settings.calibrationDone","Calibration complete!")}),o("idle")}catch{y({type:"error",msg:a("spoolbuddy.settings.calibrationFailed","Calibration failed")})}finally{p(!1)}}};return s==="idle"?i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 mb-3",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),i.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]}),i.jsxs("div",{className:"text-xs text-zinc-500 text-right",children:[i.jsxs("span",{children:[a("spoolbuddy.settings.tareOffset","Tare"),": ",t.tare_offset]}),i.jsx("span",{className:"mx-1.5",children:"·"}),i.jsxs("span",{children:[a("spoolbuddy.settings.calFactor","Factor"),": ",t.calibration_factor.toFixed(2)]})]})]}),t.last_calibrated_at&&i.jsxs("div",{className:"text-xs text-zinc-600 mt-1",children:[a("spoolbuddy.settings.lastCalibrated","Last calibrated"),": ",Znt(t.last_calibrated_at)]})]}),f&&i.jsx("div",{className:`rounded-lg px-3 py-2 mb-3 text-sm ${f.type==="ok"?"bg-green-900/30 text-green-300 border border-green-800":"bg-red-900/30 text-red-300 border border-red-800"}`,children:f.msg}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:b,disabled:m,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px] flex items-center justify-center gap-2",children:[m&&i.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),a("spoolbuddy.weight.tare","Tare")]}),i.jsx("button",{onClick:()=>{o("tare"),y(null)},className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:a("spoolbuddy.weight.calibrate","Calibrate")})]})]}):i.jsxs("div",{className:"flex gap-3",children:[i.jsx(nrt,{step:s,labels:{tare:a("spoolbuddy.weight.tare","Tare"),weight:a("spoolbuddy.settings.knownWeight","Known weight")}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 rounded-lg px-3 py-1.5 mb-1.5",children:[i.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),i.jsx("span",{className:"text-sm font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"}),i.jsx("span",{className:`text-xs ml-auto ${n?"text-green-400":"text-amber-400"}`,children:n?a("spoolbuddy.settings.stable","Stable"):a("spoolbuddy.settings.settling","Settling...")})]}),f&&i.jsx("div",{className:`rounded-lg px-3 py-1.5 mb-1.5 text-xs ${f.type==="ok"?"bg-green-900/30 text-green-300 border border-green-800":"bg-red-900/30 text-red-300 border border-red-800"}`,children:f.msg}),s==="tare"?i.jsx("p",{className:"text-sm text-zinc-300 mb-3",children:a("spoolbuddy.settings.calStep1","Remove all items from the scale and press Set Zero.")}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[i.jsx("span",{className:"text-xs text-zinc-400 shrink-0",children:a("spoolbuddy.settings.knownWeight","Known weight")}),i.jsxs("div",{className:"flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1 text-right text-lg font-mono text-zinc-100",children:[l||"0",i.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),i.jsx("div",{className:"grid grid-cols-4 gap-1 mb-1.5",children:["7","8","9","backspace","4","5","6",".","1","2","3","0"].map(_=>i.jsx("button",{onClick:()=>v(_),className:`rounded text-lg font-medium transition-colors h-[48px] active:scale-95 ${_==="backspace"?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600":"bg-zinc-800 text-zinc-100 hover:bg-zinc-700 border border-zinc-700"}`,children:_==="backspace"?"⌫":_},_))})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>{o("idle"),y(null)},className:"flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors h-[40px]",children:a("common.cancel","Cancel")}),i.jsxs("button",{onClick:g,disabled:m,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors h-[40px] flex items-center justify-center gap-2",children:[m&&i.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),s==="tare"?a("spoolbuddy.settings.setZero","Set Zero"):a("spoolbuddy.settings.calibrateNow","Calibrate")]})]})]})]})}function irt({device:t}){const{t:e}=Dt(),[n,r]=w.useState(!1),[a,s]=w.useState(null),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,m]=w.useState(!1),p=w.useRef(!1),f=t.update_status==="pending"||t.update_status==="updating";w.useEffect(()=>{f?p.current=!0:p.current&&t.update_status==null&&(p.current=!1,window.location.reload())},[f,t.update_status]);const{data:y,refetch:v}=et({queryKey:["spoolbuddy-update-check",t.device_id],queryFn:()=>pa.checkDaemonUpdate(t.device_id),staleTime:30*1e3}),{data:b}=et({queryKey:["spoolbuddy-ssh-key"],queryFn:()=>pa.getSSHPublicKey(),enabled:o,staleTime:1/0}),g=async()=>{m(!0);try{await v()}finally{m(!1)}},_=async()=>{r(!0),s(null);try{await pa.triggerUpdate(t.device_id)}catch(k){s(k instanceof Error?k.message:"Failed to trigger update")}finally{r(!1)}},N=()=>{b?.public_key&&(navigator.clipboard.writeText(b.public_key),u(!0),setTimeout(()=>u(!1),2e3))},C=t.firmware_version||(y?.current_version&&y.current_version!=="0.0.0"?y.current_version:null);return i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 space-y-3",children:[i.jsxs("div",{className:"flex justify-between items-center text-sm",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.currentVersion","Current Version")}),i.jsx("span",{className:"text-zinc-200 font-mono",children:C||i.jsx("span",{className:"text-zinc-500 italic text-xs",children:e("spoolbuddy.settings.versionPending","Waiting for daemon...")})})]}),f&&i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsxs("svg",{className:"w-4 h-4 animate-spin text-green-400 flex-shrink-0",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),i.jsx("span",{className:"text-green-300 text-xs",children:t.update_message||e("spoolbuddy.settings.updateWaiting","Updating...")})]}),t.update_status==="error"&&i.jsx("p",{className:"text-xs text-red-300",children:t.update_message||e("spoolbuddy.settings.updateFailed","Update failed")}),a&&i.jsx("p",{className:"text-xs text-red-300",children:a}),y?.update_available?i.jsxs(i.Fragment,{children:[i.jsxs("p",{className:"text-xs text-green-300",children:[e("spoolbuddy.settings.updateAvailable","Update available"),": ",C," → ",y.latest_version]}),i.jsxs("button",{onClick:_,disabled:n||f||!t.online,className:"w-full px-3 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors flex items-center justify-center gap-2",children:[n&&i.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),t.online?e("spoolbuddy.settings.applyUpdate","Apply Update"):e("spoolbuddy.settings.deviceOffline","Device Offline")]})]}):y&&!f?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:g,disabled:d||n,className:"flex-1 px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 transition-colors flex items-center justify-center gap-1",children:[d&&i.jsxs("svg",{className:"w-3 h-3 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),e("spoolbuddy.settings.checkUpdates","Check for Updates")]}),i.jsxs("button",{onClick:_,disabled:n||f||!t.online,className:"px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-400 hover:bg-zinc-600 hover:text-zinc-200 disabled:opacity-40 transition-colors flex items-center justify-center gap-1",children:[n&&i.jsxs("svg",{className:"w-3 h-3 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),e("spoolbuddy.settings.forceUpdate","Force Update")]})]}):f?null:i.jsxs("button",{onClick:g,disabled:d,className:"w-full px-3 py-2 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors flex items-center justify-center gap-2",children:[d&&i.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),e("spoolbuddy.settings.checkUpdates","Check for Updates")]})]}),i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[i.jsxs("button",{onClick:()=>l(!o),className:"w-full flex justify-between items-center text-xs",children:[i.jsx("span",{className:"font-medium text-zinc-400",children:e("spoolbuddy.settings.sshSetup","SSH Setup")}),i.jsx("svg",{className:`w-3 h-3 text-zinc-500 transition-transform ${o?"rotate-180":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})]}),o&&i.jsxs("div",{className:"mt-2 space-y-2",children:[i.jsx("p",{className:"text-xs text-zinc-500",children:e("spoolbuddy.settings.sshDescription","SSH key is deployed automatically. For manual setup, add this key to ~/.ssh/authorized_keys on the device.")}),b?.public_key?i.jsxs("div",{className:"relative",children:[i.jsx("pre",{className:"bg-zinc-900 rounded p-2 text-[10px] text-zinc-400 font-mono break-all whitespace-pre-wrap",children:b.public_key}),i.jsx("button",{onClick:N,className:"absolute top-1 right-1 px-1.5 py-0.5 rounded text-[10px] bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors",children:c?e("common.copied","Copied!"):e("common.copy","Copy")})]}):i.jsx("span",{className:"text-[10px] text-zinc-500 italic",children:e("spoolbuddy.settings.sshKeyLoading","Loading...")})]})]})]})}function art(){const{sbState:t,setDisplayBrightness:e,setDisplayBlankTimeout:n}=fw(),{t:r}=Dt(),[a,s]=w.useState("device"),{data:o=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>pa.getDevices(),refetchInterval:1e4}),l=t.deviceId?o.find(u=>u.device_id===t.deviceId)??o[0]:o[0],c=[{id:"device",label:r("spoolbuddy.settings.tabDevice","Device")},{id:"display",label:r("spoolbuddy.settings.tabDisplay","Display")},{id:"scale",label:r("spoolbuddy.settings.tabScale","Scale")},{id:"updates",label:r("spoolbuddy.settings.tabUpdates","Updates")}];return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("h1",{className:"text-xl font-semibold text-zinc-100 mb-3",children:r("spoolbuddy.nav.settings","Settings")}),i.jsx("div",{className:"flex gap-1 bg-zinc-800/50 rounded-lg p-1 mb-4",children:c.map(u=>i.jsx("button",{onClick:()=>s(u.id),className:`flex-1 px-2 py-2 rounded-md text-sm font-medium transition-colors min-h-[36px] ${a===u.id?"bg-zinc-700 text-zinc-100":"text-zinc-500 hover:text-zinc-300"}`,children:u.label},u.id))}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:l?i.jsxs(i.Fragment,{children:[a==="device"&&i.jsx(ert,{device:l}),a==="display"&&i.jsx(trt,{device:l,onBrightnessChange:e,onBlankTimeoutChange:n}),a==="scale"&&i.jsx(rrt,{device:l,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}),a==="updates"&&i.jsx(irt,{device:l})]}):i.jsx("div",{className:"flex items-center justify-center h-32",children:i.jsx("div",{className:"text-center text-zinc-500",children:i.jsx("p",{className:"text-sm",children:r("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}function srt({device:t,weight:e,weightStable:n,rawAdc:r}){const{t:a}=Dt(),[s,o]=w.useState(!1),[l,c]=w.useState("idle"),[u,d]=w.useState("500"),[m,p]=w.useState(null),[f,y]=w.useState(!1),v=N=>{N==="backspace"?d(C=>C.slice(0,-1)||""):N==="."&&!u.includes(".")?d(C=>C+"."):N>="0"&&N<="9"&&d(C=>C==="0"?N:C+N)},b=async()=>{y(!0);try{await pa.tare(t.device_id)}catch(N){console.error("Failed to tare:",N)}finally{y(!1)}},g=()=>{c("tare")},_=async()=>{if(l==="tare"){o(!0);try{p(r),await pa.tare(t.device_id),c("weight")}catch(N){console.error("Failed to tare:",N)}finally{o(!1)}}else if(l==="weight"){const N=parseFloat(u);if(r===null||!N||N<=0)return;o(!0);try{await pa.setCalibrationFactor(t.device_id,N,r,m??void 0),c("idle")}catch(C){console.error("Failed to calibrate:",C)}finally{o(!1)}}};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-zinc-400",children:a("spoolbuddy.settings.currentWeight","Current weight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),i.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-3 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.settings.tareOffset","Tare offset")}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.tare_offset})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.settings.calFactor","Cal. factor")}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.calibration_factor.toFixed(2)})]})]})]}),l==="idle"?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:b,disabled:f,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px]",children:f?"...":a("spoolbuddy.weight.tare","Tare")}),i.jsx("button",{onClick:g,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:a("spoolbuddy.weight.calibrate","Calibrate")})]}):i.jsxs("div",{className:"bg-zinc-800 border border-zinc-700 rounded-lg p-3 space-y-2",children:[i.jsx("div",{className:"text-sm font-medium text-zinc-200",children:l==="tare"?a("spoolbuddy.settings.calStep1","Step 1: Remove all items from the scale"):a("spoolbuddy.settings.calStep2","Step 2: Place known weight on scale")}),l==="weight"&&i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-zinc-400",children:a("spoolbuddy.settings.knownWeight","Known weight (g)")}),i.jsxs("div",{className:"flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1.5 text-right text-base font-mono text-zinc-100",children:[u||"0",i.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),i.jsx("div",{className:"grid grid-cols-4 gap-1",children:["7","8","9","backspace","4","5","6",".","1","2","3","0"].map(N=>i.jsx("button",{onClick:()=>v(N),className:`py-2 rounded text-sm font-medium transition-colors min-h-[36px] ${N==="backspace"?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600":"bg-zinc-800 text-zinc-100 hover:bg-zinc-700 border border-zinc-700"}`,children:N==="backspace"?"⌫":N},N))})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>c("idle"),className:"flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[40px]",children:a("common.cancel","Cancel")}),i.jsx("button",{onClick:_,disabled:s,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors min-h-[40px]",children:s?"...":l==="tare"?a("spoolbuddy.settings.setZero","Set Zero"):a("spoolbuddy.settings.calibrateNow","Calibrate")})]})]})]})}function ort(){const{sbState:t}=fw(),{t:e}=Dt(),n=ol(),{data:r=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>pa.getDevices(),refetchInterval:1e4}),a=t.deviceId?r.find(s=>s.device_id===t.deviceId)??r[0]:r[0];return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("button",{onClick:()=>n("/spoolbuddy/settings"),className:"p-1.5 rounded-lg text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800 transition-colors",children:i.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 19l-7-7 7-7"})})}),i.jsx("h1",{className:"text-xl font-semibold text-zinc-100",children:e("spoolbuddy.settings.scaleCalibration","Scale Calibration")})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:a?i.jsx(srt,{device:a,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}):i.jsx("div",{className:"flex items-center justify-center h-32",children:i.jsx("div",{className:"text-center text-zinc-500",children:i.jsx("p",{className:"text-sm",children:e("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}const lrt=["PLA","PETG","ABS","ASA","TPU","PA","PC","PVA","HIPS"];function crt(){const{t}=Dt(),{sbState:e}=fw(),[n,r]=w.useState("existing"),[a,s]=w.useState(null),[o,l]=w.useState(""),[c,u]=w.useState("idle"),[d,m]=w.useState(""),[p,f]=w.useState(!1),[y,v]=w.useState(null),[b,g]=w.useState("PLA"),[_,N]=w.useState(""),[C,k]=w.useState("#00AE42"),[P,T]=w.useState(""),[D,A]=w.useState(1e3),[R,G]=w.useState(!1),{data:z=[],refetch:Z}=et({queryKey:["inventory-spools"],queryFn:()=>ge.getSpools(!1),refetchInterval:1e4}),{data:I=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>pa.getDevices(),refetchInterval:5e3}),J=I[0],ae=e.deviceOnline,Y=w.useMemo(()=>{let X;if(n==="existing")X=z.filter(j=>!j.tag_uid&&!j.archived_at);else if(n==="replace")X=z.filter(j=>j.tag_uid&&!j.archived_at);else return[];if(o){const j=o.toLowerCase();X=X.filter(E=>E.material?.toLowerCase().includes(j)||E.color_name?.toLowerCase().includes(j)||E.brand?.toLowerCase().includes(j)||E.subtype?.toLowerCase().includes(j))}return X},[z,n,o]),ue=w.useCallback(X=>{const j=X.detail;(j.sak??j.data?.sak)===0&&(f(!0),v(j.tag_uid??j.data?.tag_uid??null))},[]),de=w.useCallback(X=>{const j=X.detail;f(!0),v(j.tag_uid??j.data?.tag_uid??null)},[]),he=w.useCallback(()=>{f(!1),v(null)},[]),V=w.useCallback(X=>{const j=X.detail;(j.spool_id===a?.id||j.data?.spool_id===a?.id)&&(u("success"),m(t("spoolbuddy.writeTag.writeSuccess","Tag written successfully!")),Z(),setTimeout(()=>{u("idle"),s(null),m("")},5e3))},[a,t,Z]),ne=w.useCallback(X=>{const j=X.detail;(j.spool_id===a?.id||j.data?.spool_id===a?.id)&&(u("error"),m(j.message??j.data?.message??t("spoolbuddy.writeTag.writeFailed","Write failed")))},[a,t]);w.useEffect(()=>(window.addEventListener("spoolbuddy-unknown-tag",ue),window.addEventListener("spoolbuddy-tag-matched",de),window.addEventListener("spoolbuddy-tag-removed",he),window.addEventListener("spoolbuddy-tag-written",V),window.addEventListener("spoolbuddy-tag-write-failed",ne),()=>{window.removeEventListener("spoolbuddy-unknown-tag",ue),window.removeEventListener("spoolbuddy-tag-matched",de),window.removeEventListener("spoolbuddy-tag-removed",he),window.removeEventListener("spoolbuddy-tag-written",V),window.removeEventListener("spoolbuddy-tag-write-failed",ne)}),[ue,de,he,V,ne]),w.useEffect(()=>{s(null),u("idle"),m(""),l("")},[n]);const se=async()=>{if(!(!a||!J)){u("writing"),m(t("spoolbuddy.writeTag.waiting","Waiting for SpoolBuddy..."));try{await pa.writeTag(J.device_id,a.id)}catch{u("error"),m(t("spoolbuddy.writeTag.queueFailed","Failed to queue write command"))}}},pe=async()=>{if(J){try{await pa.cancelWrite(J.device_id)}catch{}u("idle"),m("")}},Te=async()=>{G(!0);try{const X=C.replace("#","")+"FF",j=await ge.createSpool({material:b,subtype:null,color_name:_||null,rgba:X,brand:P||null,label_weight:D,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,nozzle_temp_min:null,nozzle_temp_max:null,note:null,added_full:!0,last_used:null,encode_time:null,tag_uid:null,tray_uuid:null,data_origin:null,tag_type:null,cost_per_kg:null,last_scale_weight:null,last_weighed_at:null});s(j),Z()}catch{m(t("spoolbuddy.writeTag.createFailed","Failed to create spool")),u("error")}finally{G(!1)}},q=a&&ae&&c!=="writing"&&c!=="success";return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsx("div",{className:"flex border-b border-bambu-dark-tertiary shrink-0",children:[{key:"existing",label:t("spoolbuddy.writeTag.tabExisting","Existing Spool")},{key:"new",label:t("spoolbuddy.writeTag.tabNew","New Spool")},{key:"replace",label:t("spoolbuddy.writeTag.tabReplace","Replace Tag")}].map(X=>i.jsx("button",{onClick:()=>r(X.key),className:`flex-1 py-3 text-sm font-medium transition-colors ${n===X.key?"text-bambu-green border-b-2 border-bambu-green bg-bambu-dark":"text-zinc-400 hover:text-zinc-200 hover:bg-bambu-dark-tertiary"}`,children:X.label},X.key))}),i.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[i.jsx("div",{className:"flex-1 flex flex-col overflow-hidden border-r border-bambu-dark-tertiary",children:n==="new"?i.jsx(drt,{material:b,setMaterial:g,colorName:_,setColorName:N,colorHex:C,setColorHex:k,brand:P,setBrand:T,weight:D,setWeight:A,creating:R,onSubmit:Te,selectedSpool:a,t}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"p-3 shrink-0",children:i.jsx("input",{type:"text",value:o,onChange:X=>l(X.target.value),placeholder:t("spoolbuddy.writeTag.searchPlaceholder","Search by material, color, brand..."),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})}),i.jsx("div",{className:"flex-1 overflow-y-auto px-3 pb-3 space-y-2",children:Y.length===0?i.jsx("div",{className:"text-center text-zinc-500 py-8 text-sm",children:n==="existing"?t("spoolbuddy.writeTag.noUntaggedSpools","No spools without tags"):t("spoolbuddy.writeTag.noTaggedSpools","No spools with tags")}):Y.map(X=>i.jsx(urt,{spool:X,selected:a?.id===X.id,showTag:n==="replace",onClick:()=>{s(X),u("idle"),m("")}},X.id))})]})}),i.jsx("div",{className:"w-[340px] flex flex-col items-center justify-center p-6 shrink-0",children:i.jsx(mrt,{writeStatus:c,writeMessage:d,selectedSpool:a,tagOnReader:p,tagUid:y,deviceOnline:ae,canWrite:!!q,isReplace:n==="replace",onWrite:se,onCancel:pe,onRetry:()=>{u("idle"),m("")},t})})]})]})}function urt({spool:t,selected:e,showTag:n,onClick:r}){const a=t.rgba?`#${t.rgba.slice(0,6)}`:"#666",s=Math.max(0,t.label_weight-t.weight_used),o=t.label_weight>0?Math.round(s/t.label_weight*100):0;return i.jsxs("button",{onClick:r,className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${e?"bg-bambu-green/15 border border-bambu-green/50":"bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary border border-transparent"}`,children:[i.jsx("div",{className:"w-8 h-8 rounded-full shrink-0 border border-white/10",style:{backgroundColor:a}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("span",{className:"text-sm font-medium text-white truncate",children:[t.brand?`${t.brand} `:"",t.material,t.subtype?` ${t.subtype}`:""]})}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-zinc-400",children:[t.color_name&&i.jsx("span",{children:t.color_name}),i.jsxs("span",{children:[s,"g / ",t.label_weight,"g (",o,"%)"]})]}),n&&t.tag_uid&&i.jsx("div",{className:"text-xs text-zinc-500 mt-0.5 font-mono",children:t.tag_uid})]}),e&&i.jsx("svg",{className:"w-5 h-5 text-bambu-green shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})]})}function drt({material:t,setMaterial:e,colorName:n,setColorName:r,colorHex:a,setColorHex:s,brand:o,setBrand:l,weight:c,setWeight:u,creating:d,onSubmit:m,selectedSpool:p,t:f}){return p?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-6 text-center",children:[i.jsx("div",{className:"w-12 h-12 rounded-full mb-4 border border-white/10",style:{backgroundColor:p.rgba?`#${p.rgba.slice(0,6)}`:"#666"}}),i.jsxs("p",{className:"text-white font-medium",children:[p.brand?`${p.brand} `:"",p.material]}),p.color_name&&i.jsx("p",{className:"text-zinc-400 text-sm",children:p.color_name}),i.jsxs("p",{className:"text-zinc-500 text-xs mt-1",children:[p.label_weight,"g"]}),i.jsx("p",{className:"text-bambu-green text-sm mt-4",children:f("spoolbuddy.writeTag.spoolCreated","Spool created! Ready to write.")})]}):i.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:f("spoolbuddy.writeTag.material","Material")}),i.jsx("select",{value:t,onChange:y=>e(y.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",children:lrt.map(y=>i.jsx("option",{value:y,children:y},y))})]}),i.jsxs("div",{className:"flex gap-3",children:[i.jsxs("div",{className:"flex-1",children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:f("spoolbuddy.writeTag.colorName","Color Name")}),i.jsx("input",{type:"text",value:n,onChange:y=>r(y.target.value),placeholder:"Jade White",className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:f("spoolbuddy.writeTag.color","Color")}),i.jsx("input",{type:"color",value:a,onChange:y=>s(y.target.value),className:"w-10 h-9 bg-transparent border border-bambu-dark-tertiary rounded cursor-pointer"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:f("spoolbuddy.writeTag.brand","Brand")}),i.jsx("input",{type:"text",value:o,onChange:y=>l(y.target.value),placeholder:"Polymaker",className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:f("spoolbuddy.writeTag.weight","Weight (g)")}),i.jsx("input",{type:"number",value:c,onChange:y=>u(parseInt(y.target.value)||0),min:0,max:1e4,className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green"})]}),i.jsx("button",{onClick:m,disabled:d||!t,className:"w-full py-2.5 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded transition-colors",children:d?f("spoolbuddy.writeTag.creating","Creating..."):f("spoolbuddy.writeTag.createSpool","Create Spool")})]})}function mrt({writeStatus:t,writeMessage:e,selectedSpool:n,tagOnReader:r,tagUid:a,deviceOnline:s,canWrite:o,isReplace:l,onWrite:c,onCancel:u,onRetry:d,t:m}){if(t==="success")return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[i.jsx("div",{className:"w-16 h-16 rounded-full bg-green-500/20 flex items-center justify-center",children:i.jsx("svg",{className:"w-8 h-8 text-green-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}),i.jsx("p",{className:"text-green-400 font-medium",children:e}),n&&i.jsxs("p",{className:"text-zinc-400 text-sm",children:[n.brand?`${n.brand} `:"",n.material,n.color_name?` - ${n.color_name}`:""]})]});if(t==="error")return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[i.jsx("div",{className:"w-16 h-16 rounded-full bg-red-500/20 flex items-center justify-center",children:i.jsx("svg",{className:"w-8 h-8 text-red-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),i.jsx("p",{className:"text-red-400 font-medium",children:e}),i.jsx("button",{onClick:d,className:"px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-white text-sm rounded transition-colors",children:m("spoolbuddy.writeTag.tryAgain","Try Again")})]});if(t==="writing")return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[i.jsxs("div",{className:"relative w-16 h-16",children:[i.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-bambu-green/30 animate-ping"}),i.jsx("div",{className:"absolute inset-2 rounded-full border-2 border-bambu-green/50 animate-pulse"}),i.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:i.jsx(Ev,{className:"w-8 h-8 text-bambu-green"})})]}),i.jsx("p",{className:"text-bambu-green font-medium",children:m("spoolbuddy.writeTag.writing","Writing tag...")}),i.jsx("p",{className:"text-zinc-500 text-xs",children:e}),i.jsx("button",{onClick:u,className:"px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-zinc-400 text-sm rounded transition-colors",children:m("spoolbuddy.writeTag.cancel","Cancel")})]});if(!s)return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[i.jsx(Ev,{className:"w-12 h-12 text-zinc-600"}),i.jsx("p",{className:"text-zinc-500 text-sm",children:m("spoolbuddy.writeTag.deviceOffline","SpoolBuddy is offline")})]});if(!n)return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[i.jsx(Ev,{className:"w-12 h-12 text-zinc-600"}),i.jsx("p",{className:"text-zinc-400 text-sm",children:m("spoolbuddy.writeTag.selectSpool","Select a spool, then place a blank NTAG on the reader")})]});const p=n.rgba?`#${n.rgba.slice(0,6)}`:"#666";return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-4 w-full",children:[i.jsx("div",{className:"relative w-16 h-16",children:r?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"absolute inset-0 rounded-full bg-bambu-green/10"}),i.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:i.jsx(Ev,{className:"w-8 h-8 text-bambu-green"})})]}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-zinc-600 animate-pulse"}),i.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:i.jsx(Ev,{className:"w-8 h-8 text-zinc-500"})})]})}),r?i.jsxs("div",{className:"space-y-1",children:[i.jsx("p",{className:"text-bambu-green text-sm font-medium",children:m("spoolbuddy.writeTag.tagReady","Tag detected — ready to write")}),a&&i.jsx("p",{className:"text-zinc-500 text-xs font-mono",children:a})]}):i.jsx("p",{className:"text-zinc-400 text-sm",children:m("spoolbuddy.writeTag.placeTag","Place an NTAG on the reader")}),i.jsxs("div",{className:"w-full bg-bambu-dark-secondary rounded-lg p-3 space-y-2",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-8 h-8 rounded-full border border-white/10 shrink-0",style:{backgroundColor:p}}),i.jsxs("div",{className:"text-left min-w-0",children:[i.jsxs("p",{className:"text-white text-sm font-medium truncate",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&i.jsx("p",{className:"text-zinc-400 text-xs",children:n.color_name})]})]}),i.jsxs("div",{className:"text-xs text-zinc-500",children:[n.label_weight,"g"]})]}),l&&n.tag_uid&&i.jsx("p",{className:"text-yellow-500/80 text-xs",children:m("spoolbuddy.writeTag.replaceWarning","Old tag will be unlinked. New tag will replace it.")}),i.jsx("button",{onClick:c,disabled:!o,className:"w-full py-3 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors text-sm",children:l?m("spoolbuddy.writeTag.replaceTag","Replace Tag"):m("spoolbuddy.writeTag.writeTag","Write Tag")})]})}function Ev({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,children:[i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.288 15.038a5.25 5.25 0 017.424 0M5.106 11.856c3.807-3.808 9.98-3.808 13.788 0M1.924 8.674c5.565-5.565 14.587-5.565 20.152 0"}),i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12.53 18.22l-.53.53-.53-.53a.75.75 0 011.06 0z"})]})}const hrt=new Zme({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function KY({children:t}){return pnt(),i.jsx(i.Fragment,{children:t})}function YY({children:t}){const{authEnabled:e,loading:n,user:r}=Ar();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!r?i.jsx(lx,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function i3({children:t}){const{authEnabled:e,loading:n,user:r,isAdmin:a}=Ar();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?r?a?i.jsx(i.Fragment,{children:t}):i.jsx(lx,{to:"/",replace:!0}):i.jsx(lx,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function prt({children:t}){const{authEnabled:e,loading:n}=Ar();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?i.jsx(lx,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function frt(){return i.jsx(Vbe,{children:i.jsx(Jbe,{children:i.jsx(Jme,{client:hrt,children:i.jsx(Qbe,{children:i.jsx(xme,{children:i.jsxs(Wde,{children:[i.jsx(kr,{path:"/setup",element:i.jsx(prt,{children:i.jsx(mnt,{})})}),i.jsx(kr,{path:"/login",element:i.jsx(dnt,{})}),i.jsx(kr,{path:"/camera/:printerId",element:i.jsx(_tt,{})}),i.jsx(kr,{path:"/overlay/:printerId",element:i.jsx(Ttt,{})}),i.jsxs(kr,{element:i.jsx(YY,{children:i.jsx(KY,{children:i.jsx(Ant,{})})}),children:[i.jsx(kr,{path:"spoolbuddy",element:i.jsx(Wnt,{})}),i.jsx(kr,{path:"spoolbuddy/ams",element:i.jsx(Xnt,{})}),i.jsx(kr,{path:"spoolbuddy/write-tag",element:i.jsx(crt,{})}),i.jsx(kr,{path:"spoolbuddy/settings",element:i.jsx(art,{})}),i.jsx(kr,{path:"spoolbuddy/calibration",element:i.jsx(ort,{})})]}),i.jsxs(kr,{element:i.jsx(YY,{children:i.jsx(KY,{children:i.jsx(hxe,{})})}),children:[i.jsx(kr,{index:!0,element:i.jsx(fVe,{})}),i.jsx(kr,{path:"archives",element:i.jsx(oZe,{})}),i.jsx(kr,{path:"queue",element:i.jsx(VJe,{})}),i.jsx(kr,{path:"stats",element:i.jsx(uet,{})}),i.jsx(kr,{path:"profiles",element:i.jsx(ttt,{})}),i.jsx(kr,{path:"maintenance",element:i.jsx(stt,{})}),i.jsx(kr,{path:"projects",element:i.jsx(ltt,{})}),i.jsx(kr,{path:"projects/:id",element:i.jsx(htt,{})}),i.jsx(kr,{path:"inventory",element:i.jsx(rnt,{})}),i.jsx(kr,{path:"files",element:i.jsx(ytt,{})}),i.jsx(kr,{path:"settings",element:i.jsx(i3,{children:i.jsx(Bet,{})})}),i.jsx(kr,{path:"groups/new",element:i.jsx(i3,{children:i.jsx(LY,{})})}),i.jsx(kr,{path:"groups/:id/edit",element:i.jsx(i3,{children:i.jsx(LY,{})})}),i.jsx(kr,{path:"users",element:i.jsx(lx,{to:"/settings?tab=users",replace:!0})}),i.jsx(kr,{path:"groups",element:i.jsx(lx,{to:"/settings?tab=users",replace:!0})}),i.jsx(kr,{path:"system",element:i.jsx(unt,{})}),i.jsx(kr,{path:"notifications",element:i.jsx(hnt,{})}),i.jsx(kr,{path:"external/:id",element:i.jsx(Att,{})})]})]})})})})})})}Hce.createRoot(document.getElementById("root")).render(i.jsx(w.StrictMode,{children:i.jsx(frt,{})})); +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function Y(q,X){(X==null||X>q.length)&&(X=q.length);for(var j=0,E=Array(X);j1&&arguments[1]!==void 0?arguments[1]:E;this.caretPosition=E,this.caretPositionEnd=U}},{key:"getInputCandidates",value:function(E){var U=this,K=this.options,H=K.layoutCandidates,re=K.layoutCandidatesCaseSensitiveMatch;if(!H||ue(H)!=="object")return{};var O=Object.keys(H).filter((function(W){var ie=E.substring(0,U.getCaretPositionEnd()||0)||E,ce=new RegExp("".concat(U.utilities.escapeRegex(W),"$"),re?"g":"gi");return!!ae(ie.matchAll(ce)).length}));if(O.length>1){var $=O.sort((function(W,ie){return ie.length-W.length}))[0];return{candidateKey:$,candidateValue:H[$]}}if(O.length){var ee=O[0];return{candidateKey:ee,candidateValue:H[ee]}}return{}}},{key:"showCandidatesBox",value:function(E,U,K){var H=this;this.candidateBox&&this.candidateBox.show({candidateValue:U,targetElement:K,onSelect:function(re,O){var $=H.options,ee=$.layoutCandidatesCaseSensitiveMatch,W=$.disableCandidateNormalization,ie=$.enableLayoutCandidatesKeyPress,ce=re;W||(ce=re.normalize("NFD")),typeof H.options.beforeInputUpdate=="function"&&H.options.beforeInputUpdate(H);var be=H.getInput(H.options.inputName,!0),xe=H.getCaretPositionEnd()||0,oe=be.substring(0,xe||0)||be,L=new RegExp("".concat(H.utilities.escapeRegex(E),"$"),ee?"g":"gi"),F=oe.replace(L,ce),te=be.replace(oe,F),ve=F.length-oe.length,fe=(xe||be.length)+ve;fe<0&&(fe=0),H.setInput(te,H.options.inputName,!0),H.setCaretPosition(fe),ie&&typeof H.options.onKeyPress=="function"&&H.options.onKeyPress(re,O),typeof H.options.onChange=="function"&&H.options.onChange(H.getInput(H.options.inputName,!0),O),typeof H.options.onChangeAll=="function"&&H.options.onChangeAll(H.getAllInputs(),O)}})}},{key:"handleButtonClicked",value:function(E,U){var K=this.options,H=K.inputName,re=H===void 0?this.defaultName:H,O=K.debug;if(E!=="{//}"){this.input[re]||(this.input[re]=""),typeof this.options.beforeInputUpdate=="function"&&this.options.beforeInputUpdate(this);var $=this.utilities.getUpdatedInput(E,this.input[re],this.caretPosition,this.caretPositionEnd);if(this.utilities.isStandardButton(E)&&this.activeInputElement&&this.input[re]&&this.input[re]===$&&this.caretPosition===0&&this.caretPositionEnd===$.length)return this.setInput("",this.options.inputName,!0),this.setCaretPosition(0),this.activeInputElement.value="",this.activeInputElement.setSelectionRange(0,0),void this.handleButtonClicked(E,U);if(typeof this.options.onKeyPress=="function"&&this.options.onKeyPress(E,U),this.input[re]!==$&&(!this.options.inputPattern||this.options.inputPattern&&this.inputPatternIsValid($))){if(this.options.maxLength&&this.utilities.handleMaxLength(this.input,$))return;var ee=this.utilities.getUpdatedInput(E,this.input[re],this.caretPosition,this.caretPositionEnd,!0);if(this.setInput(ee,this.options.inputName,!0),O&&console.log("Input changed:",this.getAllInputs()),this.options.debug&&console.log("Caret at: ",this.getCaretPosition(),this.getCaretPositionEnd(),"(".concat(this.keyboardDOMClass,")"),U?.type),this.options.syncInstanceInputs&&this.syncInstanceInputs(),typeof this.options.onChange=="function"&&this.options.onChange(this.getInput(this.options.inputName,!0),U),typeof this.options.onChangeAll=="function"&&this.options.onChangeAll(this.getAllInputs(),U),U!=null&&U.target&&this.options.enableLayoutCandidates){var W,ie=this.getInputCandidates($),ce=ie.candidateKey,be=ie.candidateValue;ce&&be?this.showCandidatesBox(ce,be,this.keyboardDOM):(W=this.candidateBox)===null||W===void 0||W.destroy()}}this.caretPositionEnd&&this.caretPosition!==this.caretPositionEnd&&(this.setCaretPosition(this.caretPositionEnd,this.caretPositionEnd),this.activeInputElement&&this.activeInputElement.setSelectionRange(this.caretPositionEnd,this.caretPositionEnd),this.options.debug&&console.log("Caret position aligned",this.caretPosition)),O&&console.log("Key pressed:",E)}}},{key:"getMouseHold",value:function(){return this.isMouseHold}},{key:"setMouseHold",value:function(E){this.options.syncInstanceInputs?this.dispatch((function(U){U.isMouseHold=E})):this.isMouseHold=E}},{key:"handleButtonMouseDown",value:function(E,U){var K=this;U&&(this.options.preventMouseDownDefault&&U.preventDefault(),this.options.stopMouseDownPropagation&&U.stopPropagation(),U.target.classList.add(this.activeButtonClass)),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdTimeout&&clearTimeout(this.holdTimeout),this.setMouseHold(!0),this.options.disableButtonHold||(this.holdTimeout=window.setTimeout((function(){(K.getMouseHold()&&(!E.includes("{")&&!E.includes("}")||E==="{delete}"||E==="{backspace}"||E==="{bksp}"||E==="{space}"||E==="{tab}")||E==="{arrowright}"||E==="{arrowleft}"||E==="{arrowup}"||E==="{arrowdown}")&&(K.options.debug&&console.log("Button held:",E),K.handleButtonHold(E)),clearTimeout(K.holdTimeout)}),500))}},{key:"handleButtonMouseUp",value:function(E,U){var K=this;U&&(this.options.preventMouseUpDefault&&U.preventDefault&&U.preventDefault(),this.options.stopMouseUpPropagation&&U.stopPropagation&&U.stopPropagation(),!(U.target===this.keyboardDOM||U.target&&this.keyboardDOM.contains(U.target)||this.candidateBox&&this.candidateBox.candidateBoxElement&&(U.target===this.candidateBox.candidateBoxElement||U.target&&this.candidateBox.candidateBoxElement.contains(U.target)))&&this.candidateBox&&this.candidateBox.destroy()),this.recurseButtons((function(H){H.classList.remove(K.activeButtonClass)})),this.setMouseHold(!1),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),E&&typeof this.options.onKeyReleased=="function"&&this.options.onKeyReleased(E,U)}},{key:"handleKeyboardContainerMouseDown",value:function(E){this.options.preventMouseDownDefault&&E.preventDefault()}},{key:"handleButtonHold",value:function(E){var U=this;this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdInteractionTimeout=window.setTimeout((function(){U.getMouseHold()?(U.handleButtonClicked(E),U.handleButtonHold(E)):clearTimeout(U.holdInteractionTimeout)}),100)}},{key:"syncInstanceInputs",value:function(){var E=this;this.dispatch((function(U){U.replaceInput(E.input),U.setCaretPosition(E.caretPosition,E.caretPositionEnd)}))}},{key:"clearInput",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName;this.input[E]="",this.setCaretPosition(0),this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"getInput",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName,U=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return this.options.syncInstanceInputs&&!U&&this.syncInstanceInputs(),this.options.rtl?"‫"+this.input[E].replace("‫","").replace("‬","")+"‬":this.input[E]}},{key:"getAllInputs",value:function(){var E=this,U={};return Object.keys(this.input).forEach((function(K){U[K]=E.getInput(K,!0)})),U}},{key:"setInput",value:function(E){var U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.inputName||this.defaultName,K=arguments.length>2?arguments[2]:void 0;this.input[U]=E,!K&&this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"replaceInput",value:function(E){this.input=E}},{key:"setOptions",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},U=this.changedOptions(E);this.options=Object.assign(this.options,E),U.length&&(this.options.debug&&console.log("changedOptions",U),this.onSetOptions(U),this.render())}},{key:"changedOptions",value:function(E){var U=this;return Object.keys(E).filter((function(K){return JSON.stringify(E[K])!==JSON.stringify(U.options[K])}))}},{key:"onSetOptions",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];E.includes("layoutName")&&this.candidateBox&&this.candidateBox.destroy(),(E.includes("layoutCandidatesPageSize")||E.includes("layoutCandidates"))&&this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=new J({utilities:this.utilities,options:this.options}))}},{key:"resetRows",value:function(){this.keyboardRowsDOM&&this.keyboardRowsDOM.remove(),this.keyboardDOM.className=this.keyboardDOMClass,this.keyboardDOM.setAttribute("data-skInstance",this.currentInstanceName),this.buttonElements={}}},{key:"dispatch",value:function(E){if(!window.SimpleKeyboardInstances)throw console.warn("SimpleKeyboardInstances is not defined. Dispatch cannot be called."),new Error("INSTANCES_VAR_ERROR");return Object.keys(window.SimpleKeyboardInstances).forEach((function(U){E(window.SimpleKeyboardInstances[U],U)}))}},{key:"addButtonTheme",value:function(E,U){var K=this;U&&E&&(E.split(" ").forEach((function(H){U.split(" ").forEach((function(re){K.options.buttonTheme||(K.options.buttonTheme=[]);var O=!1;K.options.buttonTheme.map((function($){if($!=null&&$.class.split(" ").includes(re)){O=!0;var ee=$.buttons.split(" ");ee.includes(H)||(O=!0,ee.push(H),$.buttons=ee.join(" "))}return $})),O||K.options.buttonTheme.push({class:re,buttons:E})}))})),this.render())}},{key:"removeButtonTheme",value:function(E,U){var K=this;if(!E&&!U)return this.options.buttonTheme=[],void this.render();E&&Array.isArray(this.options.buttonTheme)&&this.options.buttonTheme.length&&(E.split(" ").forEach((function(H){var re;(re=K.options)===null||re===void 0||(re=re.buttonTheme)===null||re===void 0||re.map((function(O,$){if(O&&U&&U.includes(O.class)||!U){var ee,W,ie=(ee=O)===null||ee===void 0?void 0:ee.buttons.split(" ").filter((function(ce){return ce!==H}));O&&ie!=null&&ie.length?O.buttons=ie.join(" "):((W=K.options.buttonTheme)===null||W===void 0||W.splice($,1),O=null)}return O}))})),this.render())}},{key:"getButtonElement",value:function(E){var U,K=this.buttonElements[E];return K&&(U=K.length>1?K:K[0]),U}},{key:"inputPatternIsValid",value:function(E){var U,K=this.options.inputPattern;if((U=K instanceof RegExp?K:K[this.options.inputName||this.defaultName])&&E){var H=U.test(E);return this.options.debug&&console.log('inputPattern ("'.concat(U,'"): ').concat(H?"passed":"did not pass!")),H}return!0}},{key:"setEventListeners",value:function(){if(this.isFirstKeyboardInstance||!this.allKeyboardInstances){this.options.debug&&console.log("Caret handling started (".concat(this.keyboardDOMClass,")"));var E=this.options.physicalKeyboardHighlightPreventDefault,U=E!==void 0&&E;document.addEventListener("keyup",this.handleKeyUp,U),document.addEventListener("keydown",this.handleKeyDown,U),document.addEventListener("mouseup",this.handleMouseUp),document.addEventListener("touchend",this.handleTouchEnd),this.options.updateCaretOnSelectionChange&&document.addEventListener("selectionchange",this.handleSelectionChange),document.addEventListener("select",this.handleSelect)}}},{key:"handleKeyUp",value:function(E){this.caretEventHandler(E),this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyUp(E)}},{key:"handleKeyDown",value:function(E){this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyDown(E)}},{key:"handleMouseUp",value:function(E){this.caretEventHandler(E)}},{key:"handleTouchEnd",value:function(E){this.caretEventHandler(E)}},{key:"handleSelect",value:function(E){this.caretEventHandler(E)}},{key:"handleSelectionChange",value:function(E){navigator.userAgent.includes("Firefox")||this.caretEventHandler(E)}},{key:"caretEventHandler",value:function(E){var U,K=this;E.target.tagName&&(U=E.target.tagName.toLowerCase()),this.dispatch((function(H){var re=E.target===H.keyboardDOM||E.target&&H.keyboardDOM.contains(E.target);if(K.options.syncInstanceInputs&&Array.isArray(E.path)&&(re=E.path.some((function(ee){var W;return ee==null||(W=ee.hasAttribute)===null||W===void 0?void 0:W.call(ee,"data-skInstance")}))),(U==="textarea"||U==="input"&&["text","search","url","tel","password"].includes(E.target.type))&&!H.options.disableCaretPositioning){var O=E.target.selectionStart,$=E.target.selectionEnd;H.options.rtl&&(O=H.utilities.getRtlOffset(O,H.getInput()),$=H.utilities.getRtlOffset($,H.getInput())),H.setCaretPosition(O,$),H.activeInputElement=E.target,H.options.debug&&console.log("Caret at: ",H.getCaretPosition(),H.getCaretPositionEnd(),E&&E.target.tagName.toLowerCase(),"(".concat(H.keyboardDOMClass,")"),E?.type)}else!H.options.disableCaretPositioning&&re||E?.type==="selectionchange"||(H.setCaretPosition(null),H.activeInputElement=null,H.options.debug&&console.log('Caret position reset due to "'.concat(E?.type,'" event'),E))}))}},{key:"recurseButtons",value:function(E){var U=this;E&&Object.keys(this.buttonElements).forEach((function(K){return U.buttonElements[K].forEach(E)}))}},{key:"destroy",value:function(){this.options.debug&&console.log("Destroying simple-keyboard instance: ".concat(this.currentInstanceName));var E=this.options.physicalKeyboardHighlightPreventDefault,U=E!==void 0&&E;document.removeEventListener("keyup",this.handleKeyUp,U),document.removeEventListener("keydown",this.handleKeyDown,U),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("touchend",this.handleTouchEnd),document.removeEventListener("select",this.handleSelect),this.options.updateCaretOnSelectionChange&&document.removeEventListener("selectionchange",this.handleSelectionChange),document.onpointerup=null,document.ontouchend=null,document.ontouchcancel=null,document.onmouseup=null,this.recurseButtons((function(K){K&&(K.onpointerdown=null,K.onpointerup=null,K.onpointercancel=null,K.ontouchstart=null,K.ontouchend=null,K.ontouchcancel=null,K.onclick=null,K.onmousedown=null,K.onmouseup=null,K.remove(),K=null)})),this.keyboardDOM.onpointerdown=null,this.keyboardDOM.ontouchstart=null,this.keyboardDOM.onmousedown=null,this.resetRows(),this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=null),this.activeInputElement=null,this.keyboardDOM.removeAttribute("data-skInstance"),this.keyboardDOM.innerHTML="",window.SimpleKeyboardInstances[this.currentInstanceName]=null,delete window.SimpleKeyboardInstances[this.currentInstanceName],this.initialized=!1}},{key:"getButtonThemeClasses",value:function(E){var U=this.options.buttonTheme,K=[];return Array.isArray(U)&&U.forEach((function(H){if(H&&H.class&&typeof H.class=="string"&&H.buttons&&typeof H.buttons=="string"){var re=H.class.split(" ");H.buttons.split(" ").includes(E)&&(K=[].concat(ae(K),ae(re)))}else console.warn('Incorrect "buttonTheme". Please check the documentation.',H)})),K}},{key:"setDOMButtonAttributes",value:function(E,U){var K=this.options.buttonAttributes;Array.isArray(K)&&K.forEach((function(H){H.attribute&&typeof H.attribute=="string"&&H.value&&typeof H.value=="string"?H.buttons&&typeof H.buttons=="string"?H.buttons.split(" ").includes(E)&&U(H.attribute,H.value):U(H.attribute,H.value):console.warn('Incorrect "buttonAttributes". Please check the documentation.',H)}))}},{key:"onTouchDeviceDetected",value:function(){this.processAutoTouchEvents(),this.disableContextualWindow()}},{key:"disableContextualWindow",value:function(){window.oncontextmenu=function(E){var U;if((U=E.target.classList)!==null&&U!==void 0&&U.contains("hg-button"))return E.preventDefault(),E.stopPropagation(),!1}}},{key:"processAutoTouchEvents",value:function(){this.options.autoUseTouchEvents&&(this.options.useTouchEvents=!0,this.options.debug&&console.log("autoUseTouchEvents: Touch device detected, useTouchEvents enabled."))}},{key:"onInit",value:function(){this.options.debug&&console.log("".concat(this.keyboardDOMClass," Initialized")),this.setEventListeners(),typeof this.options.onInit=="function"&&this.options.onInit(this)}},{key:"beforeFirstRender",value:function(){this.utilities.isTouchDevice()&&this.onTouchDeviceDetected(),typeof this.options.beforeFirstRender=="function"&&this.options.beforeFirstRender(this),this.isFirstKeyboardInstance&&this.utilities.pointerEventsSupported()&&!this.options.useTouchEvents&&!this.options.useMouseEvents&&this.options.debug&&console.log("Using PointerEvents as it is supported by this browser"),this.options.useTouchEvents&&this.options.debug&&console.log("useTouchEvents has been enabled. Only touch events will be used.")}},{key:"beforeRender",value:function(){typeof this.options.beforeRender=="function"&&this.options.beforeRender(this)}},{key:"onRender",value:function(){typeof this.options.onRender=="function"&&this.options.onRender(this)}},{key:"onModulesLoaded",value:function(){typeof this.options.onModulesLoaded=="function"&&this.options.onModulesLoaded(this)}},{key:"loadModules",value:function(){var E=this;Array.isArray(this.options.modules)&&(this.options.modules.forEach((function(U){var K=E.utilities.isConstructor(U)?new U(E):U(E);K.init&&K.init(E)})),this.keyboardPluginClasses="modules-loaded",this.render(),this.onModulesLoaded())}},{key:"getModuleProp",value:function(E,U){return!!this.modules[E]&&this.modules[E][U]}},{key:"getModulesList",value:function(){return Object.keys(this.modules)}},{key:"parseRowDOMContainers",value:function(E,U,K,H){var re=this,O=Array.from(E.children),$=0;return O.length&&K.forEach((function(ee,W){var ie=H[W];if(!(ie&&ie>ee))return!1;var ce=ee-$,be=ie-$,xe=document.createElement("div");xe.className+="hg-button-container";var oe="".concat(re.options.layoutName,"-r").concat(U,"c").concat(W);xe.setAttribute("data-skUID",oe);var L=O.splice(ce,be-ce+1);$+=be-ce,L.forEach((function(F){return xe.appendChild(F)})),O.splice(ce,0,xe),E.innerHTML="",O.forEach((function(F){return E.appendChild(F)})),re.options.debug&&console.log("rowDOMContainer",L,ce,be,$+1)})),E}},{key:"render",value:function(){var E=this;this.resetRows(),this.initialized||this.beforeFirstRender(),this.beforeRender();var U="hg-layout-".concat(this.options.layoutName),K=this.options.layout||{default:["` 1 2 3 4 5 6 7 8 9 0 - = {bksp}","{tab} q w e r t y u i o p [ ] \\","{lock} a s d f g h j k l ; ' {enter}","{shift} z x c v b n m , . / {shift}",".com @ {space}"],shift:["~ ! @ # $ % ^ & * ( ) _ + {bksp}","{tab} Q W E R T Y U I O P { } |",'{lock} A S D F G H J K L : " {enter}',"{shift} Z X C V B N M < > ? {shift}",".com @ {space}"]},H=this.options.useTouchEvents||!1,re=H?"hg-touch-events":"",O=this.options.useMouseEvents||!1,$=this.options.disableRowButtonContainers;this.keyboardDOM.className=this.getKeyboardClassString(this.options.theme,U,this.keyboardPluginClasses,re),this.keyboardDOM.setAttribute("data-skInstance",this.currentInstanceName),this.keyboardRowsDOM=document.createElement("div"),this.keyboardRowsDOM.className="hg-rows",K[this.options.layoutName||this.defaultName].forEach((function(ee,W){var ie=ee.split(" ");E.options.excludeFromLayout&&E.options.excludeFromLayout[E.options.layoutName||E.defaultName]&&(ie=ie.filter((function(oe){return E.options.excludeFromLayout&&!E.options.excludeFromLayout[E.options.layoutName||E.defaultName].includes(oe)})));var ce=document.createElement("div");ce.className+="hg-row";var be=[],xe=[];ie.forEach((function(oe,L){var F,te=!$&&typeof oe=="string"&&oe.length>1&&oe.indexOf("[")===0,ve=!$&&typeof oe=="string"&&oe.length>1&&oe.indexOf("]")===oe.length-1;te&&(be.push(L),oe=oe.replace(/\[/g,"")),ve&&(xe.push(L),oe=oe.replace(/\]/g,""));var fe=E.utilities.getButtonClass(oe),me=E.utilities.getButtonDisplayName(oe,E.options.display,E.options.mergeDisplay),je=E.options.useButtonTag?"button":"div",we=document.createElement(je);we.className+="hg-button ".concat(fe),(F=we.classList).add.apply(F,ae(E.getButtonThemeClasses(oe))),E.setDOMButtonAttributes(oe,(function(Oe,_e){we.setAttribute(Oe,_e)})),E.activeButtonClass="hg-activeButton",!E.utilities.pointerEventsSupported()||H||O?H?(we.ontouchstart=function(Oe){E.handleButtonClicked(oe,Oe),E.handleButtonMouseDown(oe,Oe)},we.ontouchend=function(Oe){E.handleButtonMouseUp(oe,Oe)},we.ontouchcancel=function(Oe){E.handleButtonMouseUp(oe,Oe)}):(we.onclick=function(Oe){E.setMouseHold(!1),typeof E.options.onKeyReleased=="function"||E.options.useMouseEvents&&E.options.clickOnMouseDown||E.handleButtonClicked(oe,Oe)},we.onmousedown=function(Oe){(typeof E.options.onKeyReleased=="function"||E.options.useMouseEvents&&E.options.clickOnMouseDown)&&!E.isMouseHold&&E.handleButtonClicked(oe,Oe),E.handleButtonMouseDown(oe,Oe)},we.onmouseup=function(Oe){E.handleButtonMouseUp(oe,Oe)}):(we.onpointerdown=function(Oe){E.handleButtonClicked(oe,Oe),E.handleButtonMouseDown(oe,Oe)},we.onpointerup=function(Oe){E.handleButtonMouseUp(oe,Oe)},we.onpointercancel=function(Oe){E.handleButtonMouseUp(oe,Oe)}),we.setAttribute("data-skBtn",oe);var Fe="".concat(E.options.layoutName,"-r").concat(W,"b").concat(L);we.setAttribute("data-skBtnUID",Fe);var He=document.createElement("span");He.innerHTML=me,we.appendChild(He),E.buttonElements[oe]||(E.buttonElements[oe]=[]),E.buttonElements[oe].push(we),ce.appendChild(we)})),ce=E.parseRowDOMContainers(ce,W,be,xe),E.keyboardRowsDOM.appendChild(ce)})),this.keyboardDOM.appendChild(this.keyboardRowsDOM),this.onRender(),this.initialized||(this.initialized=!0,!this.utilities.pointerEventsSupported()||H||O?H?(document.ontouchend=function(ee){return E.handleButtonMouseUp(void 0,ee)},document.ontouchcancel=function(ee){return E.handleButtonMouseUp(void 0,ee)},this.keyboardDOM.ontouchstart=function(ee){return E.handleKeyboardContainerMouseDown(ee)}):H||(document.onmouseup=function(ee){return E.handleButtonMouseUp(void 0,ee)},this.keyboardDOM.onmousedown=function(ee){return E.handleKeyboardContainerMouseDown(ee)}):(document.onpointerup=function(ee){return E.handleButtonMouseUp(void 0,ee)},this.keyboardDOM.onpointerdown=function(ee){return E.handleKeyboardContainerMouseDown(ee)}),this.onInit())}}],X&&he(q.prototype,X),j&&he(q,j),Object.defineProperty(q,"prototype",{writable:!1}),q;var q,X,j})(),pe=se,Te=pe;return m})()},442:function(l){l.exports=n}},a={};function s(l){var c=a[l];if(c!==void 0)return c.exports;var u=a[l]={exports:{}};return r[l].call(u.exports,u,u.exports,s),u.exports}s.n=function(l){var c=l&&l.__esModule?function(){return l.default}:function(){return l};return s.d(c,{a:c}),c},s.d=function(l,c){for(var u in c)s.o(c,u)&&!s.o(l,u)&&Object.defineProperty(l,u,{enumerable:!0,get:c[u]})},s.o=function(l,c){return Object.prototype.hasOwnProperty.call(l,c)},s.r=function(l){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(l,"__esModule",{value:!0})};var o={};return(function(){s.r(o),s.d(o,{KeyboardReact:function(){return v},default:function(){return b}}),s(981);var l=s(442),c=s(548),u=s.n(c);function d(g){return d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(_){return typeof _}:function(_){return _&&typeof Symbol=="function"&&_.constructor===Symbol&&_!==Symbol.prototype?"symbol":typeof _},d(g)}function m(g,_){var N=Object.keys(g);if(Object.getOwnPropertySymbols){var C=Object.getOwnPropertySymbols(g);_&&(C=C.filter((function(k){return Object.getOwnPropertyDescriptor(g,k).enumerable}))),N.push.apply(N,C)}return N}function p(g){for(var _=1;_{if(a.current)return;const v=y.target;if(!v.closest('[data-vkb="false"]')){if(v instanceof HTMLInputElement){if(!Cnt.has(v.type))return}else if(!(v instanceof HTMLTextAreaElement))return;l.current=v,e(!0),o("default"),c.current?.setInput?.(l.current.value),setTimeout(()=>{v.scrollIntoView({behavior:"smooth",block:"center"})},100)}},[]),m=w.useCallback(()=>{setTimeout(()=>{const y=document.activeElement;y&&(u.current?.contains(y)||y===l.current)||(e(!1),l.current=null)},150)},[]);w.useEffect(()=>(document.addEventListener("focusin",d),document.addEventListener("focusout",m),()=>{document.removeEventListener("focusin",d),document.removeEventListener("focusout",m)}),[d,m]);const p=w.useCallback(()=>{a.current=!0,r(!0),l.current?.blur(),l.current=null,setTimeout(()=>{e(!1),r(!1),a.current=!1},400)},[]),f=w.useCallback(y=>{const v=l.current;if(v){if(y==="{shift}"){o(b=>b==="default"?"shift":"default");return}if(y==="{lock}"){o(b=>b==="default"?"shift":"default");return}if(y==="{close}"){p();return}y==="{bksp}"?r3(v,v.value.slice(0,-1)):y==="{space}"?r3(v,v.value+" "):(r3(v,v.value+y),s==="shift"&&o("default")),v.focus(),c.current?.setInput?.(v.value)}},[s,p]);return t?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-[9998] bg-transparent",onMouseDown:y=>{y.preventDefault(),y.stopPropagation(),n||p()},onTouchStart:y=>{y.preventDefault(),y.stopPropagation(),n||p()},onClick:y=>{y.preventDefault(),y.stopPropagation()}}),!n&&i.jsx("div",{ref:u,className:"fixed bottom-0 left-0 right-0 z-[9999]",onMouseDown:y=>y.preventDefault(),onTouchStart:y=>{y.target.closest(".hg-button")||y.preventDefault()},children:i.jsx(knt,{keyboardRef:y=>{c.current=y},layoutName:s,onKeyPress:f,theme:"simple-keyboard vkb-theme",layout:{default:["1 2 3 4 5 6 7 8 9 0 {bksp}","q w e r t y u i o p","{lock} a s d f g h j k l","{shift} z x c v b n m . @","{space} {close}"],shift:["! @ # $ % ^ & * ( ) {bksp}","Q W E R T Y U I O P","{lock} A S D F G H J K L","{shift} Z X C V B N M , _","{space} {close}"]},display:{"{bksp}":"⌫","{close}":"✕ Close","{shift}":"⇧","{lock}":"⇪","{space}":" "}})})]}):null}function Ant(){const[t,e]=w.useState(null),[n,r]=w.useState(null),[a,s]=w.useState(!1),[o,l]=w.useState(100),[c,u]=w.useState(0),d=w.useRef(Date.now()),{i18n:m}=Dt(),p=wnt(),{data:f}=et({queryKey:["settings"],queryFn:ge.getSettings});w.useEffect(()=>{f?.language&&f.language!==m.language&&m.changeLanguage(f.language)},[f?.language,m]);const{data:y=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>pa.getDevices(),refetchInterval:3e4}),v=y[0],b=w.useRef(!1);w.useEffect(()=>{v&&!b.current&&(l(v.display_brightness),u(v.display_blank_timeout),b.current=!0)},[v]),w.useEffect(()=>{const C=document.documentElement,k=C.classList.contains("dark");return C.classList.add("dark"),()=>{k||C.classList.remove("dark")}},[]);const{data:g}=et({queryKey:["spoolbuddy-update-check",v?.device_id],queryFn:()=>v?pa.checkDaemonUpdate(v.device_id):Promise.resolve(null),enabled:!!v,refetchInterval:300*1e3,staleTime:0});w.useEffect(()=>{p.deviceOnline?g?.update_available&&g.latest_version?r({type:"info",message:`Update available: v${g.latest_version}`}):r(null):r({type:"warning",message:"SpoolBuddy device disconnected"})},[p.deviceOnline,g]);const _=w.useCallback(()=>{d.current=Date.now(),s(!1)},[]);w.useEffect(()=>(window.addEventListener("pointerdown",_),window.addEventListener("keydown",_),()=>{window.removeEventListener("pointerdown",_),window.removeEventListener("keydown",_)}),[_]),w.useEffect(()=>{if(c<=0)return;const C=setInterval(()=>{Date.now()-d.current>=c*1e3&&s(!0)},1e3);return()=>clearInterval(C)},[c]);const N=o<100?{filter:`brightness(${o/100})`}:void 0;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"w-screen h-screen bg-bambu-dark text-white flex flex-col overflow-hidden",style:N,children:[i.jsx(fnt,{selectedPrinterId:t,onPrinterChange:e,deviceOnline:p.deviceOnline}),i.jsx("main",{className:"flex-1 overflow-y-auto",children:i.jsx(wX,{context:{selectedPrinterId:t,setSelectedPrinterId:e,sbState:p,setAlert:r,displayBrightness:o,setDisplayBrightness:l,displayBlankTimeout:c,setDisplayBlankTimeout:u}})}),i.jsx(xnt,{alert:n}),i.jsx(bnt,{}),i.jsx(Tnt,{})]}),a&&i.jsx("div",{className:"fixed inset-0 bg-black z-[9999]",onPointerDown:C=>{C.stopPropagation(),_()}})]})}function E5({color:t,isEmpty:e,size:n=32}){return e?i.jsx("div",{className:"rounded-full border-2 border-dashed border-zinc-500 flex items-center justify-center",style:{width:n,height:n},children:i.jsx("div",{className:"w-2 h-2 rounded-full bg-zinc-600"})}):i.jsxs("svg",{width:n,height:n,viewBox:"0 0 32 32",children:[i.jsx("circle",{cx:"16",cy:"16",r:"14",fill:t,stroke:"white",strokeWidth:"1.5",strokeOpacity:"0.7"}),i.jsx("circle",{cx:"16",cy:"16",r:"11",fill:t,style:{filter:"brightness(0.85)"}})]})}const Pnt="spoolbuddy-default-core-weight";function Joe(){try{const t=localStorage.getItem(Pnt);if(t){const e=parseInt(t,10);if(e>=0&&e<=500)return e}}catch{}return 250}function Mnt({spool:t,scaleWeight:e,onClose:n,onSyncWeight:r,onAssignToAms:a}){const{t:s}=Dt(),[o,l]=w.useState(!1),[c,u]=w.useState(!1),d=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080",m=t.core_weight&&t.core_weight>0?t.core_weight:Joe(),p=e!==null?Math.round(Math.max(0,e)):null,f=p!==null?Math.round(Math.max(0,p-m)):null,y=Math.round(t.label_weight||1e3),v=f!==null?Math.min(100,Math.round(f/y*100)):null,b=v!==null?v>50?"#22c55e":v>20?"#eab308":"#ef4444":"#808080",_=Math.max(0,(t.label_weight||0)-(t.weight_used||0))+m,N=p!==null?p-_:null,C=N!==null?Math.abs(N)<=50:null,k=async()=>{if(e!==null){l(!0);try{await pa.updateSpoolWeight(t.id,Math.round(e)),u(!0),r?.(),setTimeout(()=>u(!1),3e3)}catch(P){console.error("Failed to sync weight:",P)}finally{l(!1)}}};return i.jsxs("div",{className:"flex flex-col items-center space-y-4 max-w-md",children:[i.jsxs("div",{className:"flex items-start gap-5",children:[i.jsxs("div",{className:"relative shrink-0",children:[i.jsx(E5,{color:d,isEmpty:!1,size:100}),v!==null&&i.jsxs("div",{className:"absolute -bottom-2 -right-2 px-2 py-0.5 rounded-full text-xs font-bold text-white shadow-lg",style:{backgroundColor:b},children:[v,"%"]})]}),i.jsxs("div",{className:"flex-1 min-w-0 pt-1",children:[i.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:t.color_name||"Unknown color"}),i.jsxs("p",{className:"text-sm text-zinc-400",children:[t.brand," • ",t.material,t.subtype&&` ${t.subtype}`]}),f!==null&&i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-baseline gap-2",children:[i.jsxs("span",{className:"text-3xl font-bold font-mono text-zinc-100",children:[f,"g"]}),i.jsxs("span",{className:"text-sm text-zinc-500",children:["/ ",y,"g"]})]}),i.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:s("spoolbuddy.spool.remaining","Remaining")}),i.jsx("div",{className:"mt-2 max-w-xs",children:i.jsx("div",{className:"h-2 bg-zinc-700 rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${v}%`,backgroundColor:b}})})})]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-sm bg-zinc-800 rounded-lg p-4 w-full",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.grossWeight","Gross weight")}),i.jsx("span",{className:"font-mono text-zinc-300",children:p!==null?`${p}g`:"—"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.spool.coreWeight","Core")}),i.jsxs("span",{className:"font-mono text-zinc-300",children:[m,"g"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.spoolSize","Spool size")}),i.jsxs("span",{className:"font-mono text-zinc-300",children:[y,"g"]})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.spool.scaleWeight","Scale")}),p!==null?i.jsxs("span",{className:`flex items-center gap-1 font-mono ${C?"text-green-500":"text-yellow-500"}`,children:[p,"g",C?i.jsx(Zr,{className:"w-3.5 h-3.5"}):i.jsxs(i.Fragment,{children:[i.jsx(jn,{className:"w-3.5 h-3.5"}),i.jsx("button",{onClick:k,className:"p-1 hover:bg-green-500/20 rounded transition-colors text-green-500",title:s("spoolbuddy.dashboard.syncWeight","Sync Weight"),children:i.jsx(Sr,{className:"w-4 h-4"})})]})]}):i.jsx("span",{className:"text-zinc-500",children:"—"})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.tagId","Tag")}),i.jsx("span",{className:"font-mono text-xs text-zinc-400 truncate max-w-[120px]",title:t.tag_uid||"",children:t.tag_uid?t.tag_uid.slice(-8):"—"})]})]}),i.jsxs("div",{className:"flex gap-2 justify-center",children:[a&&i.jsx("button",{onClick:a,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:s("spoolbuddy.modal.assignToAms","Assign to AMS")}),i.jsx("button",{onClick:k,disabled:e===null||o,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${c?"bg-green-600/20 text-green-400":a?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 disabled:cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed"}`,children:o?"...":c?s("spoolbuddy.dashboard.weightSynced","Synced!"):s("spoolbuddy.dashboard.syncWeight","Sync Weight")}),n&&i.jsx("button",{onClick:n,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.close","Close")})]})]})}function Ent({tagUid:t,scaleWeight:e,coreWeight:n,onLinkSpool:r,onAddToInventory:a,onClose:s}){const{t:o}=Dt(),l=n??Joe(),c=e!==null?Math.round(Math.max(0,e)):null,u=c!==null?Math.round(Math.max(0,c-l)):null;return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-5",children:[i.jsx("div",{className:"w-20 h-20 rounded-2xl bg-green-500/15 flex items-center justify-center",children:i.jsx("svg",{className:"w-10 h-10 text-green-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"})})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:o("spoolbuddy.dashboard.newTag","New Tag Detected")}),i.jsx("p",{className:"text-sm text-zinc-500 font-mono mt-1",children:t})]}),c!==null&&i.jsxs("div",{className:"text-sm text-zinc-400",children:[i.jsxs("span",{className:"font-mono font-semibold",children:[c,"g"]})," ",o("spoolbuddy.dashboard.onScale","on scale"),u!==null&&u>0&&i.jsxs("span",{className:"text-zinc-500",children:[" • ~",u,"g filament"]})]}),i.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[a&&i.jsx("button",{onClick:a,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:o("spoolbuddy.modal.addToInventory","Add to Inventory")}),r&&i.jsxs("button",{onClick:r,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:[i.jsx("svg",{className:"w-4 h-4 inline-block mr-1.5 -mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"})}),o("spoolbuddy.dashboard.linkSpool","Link to Spool")]}),s&&i.jsx("button",{onClick:s,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:o("spoolbuddy.dashboard.close","Close")})]})]})}function jnt(t){return t?`#${t.slice(0,6)}`:"#808080"}function ele(t){return!t.tray_type||t.tray_type===""}function Dnt(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function Rnt({className:t}){return i.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:i.jsx("path",{d:"M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z",fill:"#C3C2C1"})})}function Fnt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z",fill:"#C3C2C1"}),i.jsx("path",{d:"M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z",fill:"#1F8FEB"})]})}function Lnt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z",fill:"#1F8FEB"}),i.jsx("path",{d:"M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z",fill:"#C3C2C1"})]})}function Ont({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"}),i.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function Int({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function znt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function tle({humidity:t,goodThreshold:e=40,fairThreshold:n=60}){let r,a;return t<=e?(r="#22a352",a=Rnt):t<=n?(r="#d4a017",a=Fnt):(r="#c62828",a=Lnt),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx(a,{className:"w-3 h-3.5"}),i.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:r},children:[t,"%"]})]})}function nle({temp:t,goodThreshold:e=28,fairThreshold:n=35}){let r,a;return t<=e?(r="#22a352",a=Ont):t<=n?(r="#d4a017",a=Int):(r="#c62828",a=znt),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx(a,{className:"w-3 h-3.5"}),i.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:r},children:[t,"°C"]})]})}function j5({side:t}){return i.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[9px] font-bold rounded",style:{backgroundColor:"#1a4d2e",color:"#00ae42"},children:t})}function Unt({tray:t,slotIndex:e,isActive:n,fillOverride:r,spoolmanFill:a,onClick:s}){const o=ele(t),l=jnt(t.tray_color),c=t.remain!==null&&t.remain!==void 0&&t.remain>=0?t.remain:null,u=r===0&&c!==null&&c>0?null:r,d=a??u??c;return i.jsxs("div",{className:`relative flex flex-col items-center p-2.5 rounded-lg transition-all ${n?"ring-2 ring-bambu-green":""} ${s?"cursor-pointer hover:bg-white/5":""}`,onClick:s,children:[i.jsxs("div",{className:"relative w-16 h-16 mb-1",children:[o?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:i.jsx("div",{className:"w-3 h-3 rounded-full bg-gray-600"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:l}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:l,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),n&&i.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-2.5 h-2.5 bg-bambu-green rounded-full"})]}),i.jsx("span",{className:"text-sm text-white/70 truncate max-w-full",children:o?"Empty":t.tray_type||"Unknown"}),!o&&d!==null&&d>=0&&i.jsx("div",{className:"w-full h-1 bg-bambu-dark-tertiary rounded-full overflow-hidden mt-1",children:i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${d}%`,backgroundColor:ix(d)}})}),i.jsx("span",{className:"absolute top-1 right-1 text-xs text-white/30",children:e+1})]})}function rle({unit:t,activeSlot:e,onConfigureSlot:n,isDualNozzle:r,nozzleSide:a,thresholds:s,fillOverrides:o,spoolmanFillOverrides:l}){const c=t.tray||[],u=t.is_ams_ht,d=u?1:4;return i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("span",{className:"text-white font-medium text-base",children:Dnt(t.id)}),r&&a&&i.jsx(j5,{side:a})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.temp!=null&&i.jsx(nle,{temp:t.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair}),t.humidity!=null&&i.jsx(tle,{humidity:t.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair})]})]}),i.jsx("div",{className:`grid ${u?"grid-cols-1 max-w-[100px] mx-auto":"grid-cols-4"} gap-2`,children:Array.from({length:d}).map((m,p)=>{const f=c[p]||{id:p,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null};return i.jsx(Unt,{tray:f,slotIndex:p,isActive:e===p,fillOverride:o?.[`${t.id}-${p}`]??null,spoolmanFill:l?.[`${t.id}-${p}`]??null,onClick:n?()=>n(t.id,p,ele(f)?null:f):void 0},p)})})]})}function Bnt(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function VY(t){return!t.tray_type||t.tray_type===""}function Hnt(t){return t?`#${t.slice(0,6)}`:"#808080"}function $nt({isOpen:t,onClose:e,spool:n,printerId:r}){const{t:a}=Dt(),s=sn(),[o,l]=w.useState(null),[c,u]=w.useState(null);w.useEffect(()=>{t&&(l(null),u(null))},[t]);const d=w.useCallback(J=>{J.key==="Escape"&&e()},[e]);w.useEffect(()=>(t&&document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)),[t,d]);const{data:m}=et({queryKey:["printerStatus",r],queryFn:()=>ge.getPrinterStatus(r),enabled:t&&r!==null,refetchInterval:5e3}),{data:p}=et({queryKey:["printer",r],queryFn:()=>ge.getPrinter(r),enabled:t&&r!==null}),{data:f}=et({queryKey:["settings"],queryFn:()=>ge.getSettings(),enabled:t,staleTime:300*1e3}),{data:y}=et({queryKey:["spool-assignments",r],queryFn:()=>ge.getAssignments(r),enabled:t&&r!==null,staleTime:30*1e3}),v=w.useMemo(()=>{const J={};if(!y)return J;for(const ae of y){const Y=ae.spool;if(Y&&Y.label_weight>0&&Y.weight_used!=null){const ue=Math.round(Math.max(0,Y.label_weight-Y.weight_used)/Y.label_weight*100);J[`${ae.ams_id}-${ae.tray_id}`]=ue}}return J},[y]),b=f?{humidityGood:Number(f.ams_humidity_good)||40,humidityFair:Number(f.ams_humidity_fair)||60,tempGood:Number(f.ams_temp_good)||28,tempFair:Number(f.ams_temp_fair)||35}:void 0,g=m?.connected??!1,_=w.useMemo(()=>m?.ams??[],[m?.ams]),N=w.useMemo(()=>_.filter(J=>!J.is_ams_ht),[_]),C=w.useMemo(()=>_.filter(J=>J.is_ams_ht),[_]),k=w.useMemo(()=>[...m?.vt_tray??[]].sort((J,ae)=>(J.id??254)-(ae.id??254)),[m?.vt_tray]),P=p?.nozzle_count===2||m?.temperatures?.nozzle_2!==void 0,T=w.useRef({});w.useEffect(()=>{m?.ams_extruder_map&&Object.keys(m.ams_extruder_map).length>0&&(T.current=m.ams_extruder_map)},[m?.ams_extruder_map]);const D=m?.ams_extruder_map&&Object.keys(m.ams_extruder_map).length>0?m.ams_extruder_map:T.current,A=w.useCallback(J=>{if(!P)return null;const ae=D[String(J)],Y=J>=128?J-128:J;return(ae!==void 0?ae:Y)===1?"L":"R"},[P,D]),R=gt({mutationFn:async({amsId:J,trayId:ae})=>{if(!r)throw new Error("No printer selected");await ge.assignSpool({spool_id:n.id,printer_id:r,ams_id:J,tray_id:ae})},onSuccess:()=>{u("success"),l(a("spoolbuddy.modal.assignSuccess","Assigned!")),s.invalidateQueries({queryKey:["slotPresets"]}),setTimeout(()=>e(),1500)},onError:J=>{u("error"),l(J instanceof Error?J.message:a("spoolbuddy.modal.assignError","Failed to assign spool."))}}),G=R.isPending,z=w.useCallback((J,ae)=>{G||(u("info"),l(a("spoolbuddy.modal.assigning","Configuring slot...")),R.mutate({amsId:J,trayId:ae}))},[G,R,a]),Z=w.useMemo(()=>{const J=[];for(const ae of C){const Y=ae.tray?.[0]||{id:0,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},ue=v[`${ae.id}-0`]??null,de=Y.remain!=null&&Y.remain>=0?Y.remain:null,he=ue===0&&de!==null&&de>0?null:ue;J.push({key:`ht-${ae.id}`,label:Bnt(ae.id),amsId:ae.id,trayId:0,tray:Y,isEmpty:VY(Y),nozzleSide:A(ae.id),effectiveFill:he??de})}for(const ae of k){const Y=ae.id??254,ue=Y-254,de=v[`255-${ue}`]??null,he=ae.remain!=null&&ae.remain>=0?ae.remain:null,V=de===0&&he!==null&&he>0?null:de;J.push({key:`ext-${Y}`,label:P?Y===254?a("printers.extL","Ext-L"):a("printers.extR","Ext-R"):a("printers.ext","Ext"),amsId:255,trayId:ue,tray:ae,isEmpty:VY(ae),nozzleSide:P?Y===254?"L":"R":null,effectiveFill:V??he})}return J},[C,k,P,a,A,v]);if(!t)return null;const I=n.rgba?`#${n.rgba.slice(0,6)}`:"#808080";return i.jsxs("div",{className:"fixed inset-0 z-[60] bg-bambu-dark flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-zinc-800 shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx("div",{className:"w-7 h-7 rounded-full shrink-0",style:{backgroundColor:I}}),i.jsx("div",{className:"min-w-0",children:i.jsxs("h2",{className:"text-sm font-semibold text-zinc-100 truncate",children:[a("spoolbuddy.modal.assignToAmsTitle","Assign to AMS"),i.jsxs("span",{className:"font-normal text-zinc-500 ml-2",children:[n.color_name||"Unknown"," • ",n.brand," ",n.material,n.subtype&&` ${n.subtype}`]})]})})]}),i.jsx("button",{onClick:e,disabled:G,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800 transition-colors shrink-0 disabled:opacity-50",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),o&&i.jsxs("div",{className:`mx-5 mt-3 p-3 rounded-lg flex items-center gap-3 border shrink-0 ${c==="info"?"bg-blue-500/10 border-blue-500/40":c==="success"?"bg-green-500/10 border-green-500/40":"bg-red-500/10 border-red-500/40"}`,children:[c==="info"&&i.jsx(ft,{className:"w-4 h-4 text-blue-400 animate-spin shrink-0"}),c==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-400 shrink-0"}),c==="error"&&i.jsx(Vi,{className:"w-4 h-4 text-red-400 shrink-0"}),i.jsx("span",{className:`text-sm ${c==="info"?"text-blue-300":c==="success"?"text-green-300":"text-red-300"}`,children:o})]}),i.jsx("div",{className:"flex-1 flex flex-col gap-3 p-4 min-h-0",children:!g&&r?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsx("div",{className:"text-center text-white/50",children:i.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):_.length===0&&k.length===0?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsxs("div",{className:"text-center text-white/50",children:[i.jsx(Gi,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),i.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.noData","No AMS detected")}),i.jsx("p",{className:"text-sm",children:a("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):i.jsxs(i.Fragment,{children:[N.length>0&&i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 flex-1 min-h-0",children:N.map(J=>i.jsx(rle,{unit:J,activeSlot:null,onConfigureSlot:(ae,Y)=>z(J.id,Y),isDualNozzle:P,nozzleSide:A(J.id),thresholds:b,fillOverrides:v},J.id))}),Z.length>0&&i.jsx("div",{className:"flex gap-2 shrink-0",children:Z.map(({key:J,label:ae,amsId:Y,trayId:ue,tray:de,isEmpty:he,nozzleSide:V,effectiveFill:ne})=>{const se=Hnt(de.tray_color);return i.jsxs("div",{onClick:()=>z(Y,ue),className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-2 ${G?"opacity-50 pointer-events-none":""}`,children:[i.jsx("div",{className:"relative w-10 h-10 shrink-0",children:he?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:i.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:se}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:se,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]})}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"text-xs text-white/50 font-medium",children:ae}),V&&i.jsx(j5,{side:V})]}),i.jsx("div",{className:"text-sm text-white/80 truncate",children:he?"Empty":de.tray_type||"?"})]}),!he&&ne!=null&&ne>=0&&i.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden shrink-0 flex flex-col-reverse",children:i.jsx("div",{className:"w-full rounded-full",style:{height:`${ne}%`,backgroundColor:ix(ne)}})})]},J)})})]})}),i.jsx("div",{className:"flex justify-end gap-3 px-5 py-3 border-t border-zinc-800 shrink-0",children:i.jsx("button",{onClick:e,disabled:G,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-800 text-zinc-300 hover:bg-zinc-700 transition-colors min-h-[44px] disabled:opacity-50",children:c==="success"?a("spoolbuddy.dashboard.close","Close"):a("spoolbuddy.modal.cancel","Cancel")})})]})}function qnt({isOpen:t,onClose:e,tagId:n,untaggedSpools:r,onLink:a}){const{t:s}=Dt(),[o,l]=w.useState(null),c=w.useCallback(()=>{l(null),e()},[e]),u=w.useCallback(m=>{m.key==="Escape"&&c()},[c]);if(w.useEffect(()=>(t&&(document.addEventListener("keydown",u),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",u),document.body.style.overflow=""}),[t,u]),!t)return null;const d=()=>{o&&(a(o),l(null))};return i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:c,children:i.jsxs("div",{className:"bg-zinc-800 rounded-xl shadow-2xl w-full max-w-lg mx-4 animate-slide-up",onClick:m=>m.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-zinc-700",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-base font-semibold text-zinc-100",children:s("spoolbuddy.dashboard.linkTagTitle","Link Tag to Spool")}),i.jsx("p",{className:"text-sm text-zinc-500 font-mono",children:n})]}),i.jsx("button",{onClick:c,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"px-5 py-4 space-y-3 max-h-[400px] overflow-y-auto",children:[i.jsx("p",{className:"text-sm text-zinc-400",children:s("spoolbuddy.dashboard.selectSpool","Select a spool to link this tag to:")}),r.length===0?i.jsx("div",{className:"text-center py-8 text-zinc-500",children:s("spoolbuddy.dashboard.noUntagged","No spools without tags found")}):i.jsx("div",{className:"space-y-2",children:r.map(m=>i.jsxs("button",{type:"button",onClick:()=>l(m),className:`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left ${o?.id===m.id?"border-green-500 bg-green-500/10":"border-zinc-700 hover:border-green-500/50 hover:bg-zinc-700/50"}`,children:[i.jsx(E5,{color:m.rgba?`#${m.rgba.slice(0,6)}`:"#808080",isEmpty:!1,size:40}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"font-medium text-zinc-100 truncate",children:m.color_name||"Unknown color"}),i.jsxs("div",{className:"text-sm text-zinc-400 truncate",children:[m.brand," • ",m.material,m.subtype&&` ${m.subtype}`]})]}),i.jsxs("div",{className:"text-sm font-mono text-zinc-500",children:[Math.max(0,m.label_weight-m.weight_used),"g"]})]},m.id))})]}),i.jsxs("div",{className:"flex justify-end gap-2 px-5 py-4 border-t border-zinc-700",children:[i.jsx("button",{onClick:c,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("common.cancel","Cancel")}),i.jsx("button",{onClick:d,disabled:!o,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.linkTag","Link Tag")})]})]})})}const GY=["#00AE42","#FF6B35","#3B82F6","#EF4444","#A855F7","#FBBF24","#14B8A6","#EC4899","#F97316","#22C55E"];function Vnt(){const{t}=Dt(),[e,n]=w.useState(0);w.useEffect(()=>{const a=setInterval(()=>{n(s=>(s+1)%GY.length)},2e3);return()=>clearInterval(a)},[]);const r=GY[e];return i.jsxs("div",{className:"flex flex-col items-center text-center",children:[i.jsxs("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:[i.jsx("div",{className:"absolute w-24 h-24 rounded-full border-2 border-green-500/30 animate-ping",style:{animationDuration:"2.5s"}}),i.jsx("div",{className:"absolute w-32 h-32 rounded-full border border-green-500/20 animate-ping",style:{animationDuration:"2.5s",animationDelay:"0.4s"}}),i.jsx("div",{className:"absolute w-40 h-40 rounded-full border border-green-500/10 animate-ping",style:{animationDuration:"2.5s",animationDelay:"0.8s"}}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute -inset-4 rounded-full blur-2xl opacity-30 transition-colors duration-1000",style:{backgroundColor:r}}),i.jsx("div",{className:"transition-all duration-1000",children:i.jsx(E5,{color:r,isEmpty:!1,size:100})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xl font-medium text-zinc-300",children:t("spoolbuddy.dashboard.readyToScan","Ready to scan")}),i.jsx("p",{className:"text-sm text-zinc-500",children:t("spoolbuddy.dashboard.idleMessage","Place a spool on the scale to identify it")})]}),i.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-zinc-600",children:[i.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),i.jsx("span",{children:t("spoolbuddy.dashboard.nfcHint","NFC tag will be read automatically")})]})]})}function Gnt(){const{t}=Dt();return i.jsxs("div",{className:"flex flex-col items-center text-center",children:[i.jsx("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:i.jsx("div",{className:"w-24 h-24 rounded-full bg-zinc-800 flex items-center justify-center",children:i.jsx("svg",{className:"w-12 h-12 text-zinc-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"M18.364 5.636a9 9 0 010 12.728m0 0l-12.728-12.728m12.728 12.728L5.636 5.636m12.728 0a9 9 0 00-12.728 0m0 12.728a9 9 0 010-12.728"})})})}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-lg font-medium text-zinc-500",children:t("spoolbuddy.status.deviceOffline","Device Offline")}),i.jsx("p",{className:"text-sm text-zinc-600",children:t("spoolbuddy.status.connectDisplay","Connect the SpoolBuddy display to scan spools")})]}),i.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-zinc-600",children:[i.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.14 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"})}),i.jsx("span",{children:t("spoolbuddy.status.waitingConnection","Waiting for device connection...")})]})]})}function Wnt(){const{sbState:t,selectedPrinterId:e}=fw(),{t:n}=Dt(),{data:r=[],refetch:a}=et({queryKey:["inventory-spools"],queryFn:()=>ge.getSpools(!1)}),{data:s=[]}=et({queryKey:["printers"],queryFn:()=>ge.getPrinters()}),o=tg({queries:s.map(V=>({queryKey:["printerStatus",V.id],queryFn:()=>ge.getPrinterStatus(V.id),refetchInterval:1e4}))}),[l,c]=w.useState(null),[u,d]=w.useState(null),[m,p]=w.useState(null),[f,y]=w.useState(!1),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[N,C]=w.useState(!1),k=t.matchedSpool?.tag_uid??t.unknownTagUid??null,P=t.weight,T=t.weightStable,D=w.useRef(null);P===null?D.current=null:(D.current===null||Math.abs(P-D.current)>=3||T)&&(D.current=P);const R=D.current,G=w.useMemo(()=>l?r.find(V=>V.tag_uid===l)??null:null,[l,r]),z=w.useMemo(()=>r.filter(V=>!V.tag_uid&&!V.archived_at),[r]);w.useEffect(()=>{if(k){const V=m===k;(l!==null&&l!==k||!V&&l!==k)&&(c(k),d(null),p(null)),!V&&P!==null&&T&&d(Math.round(Math.max(0,P)))}else m&&(c(null),p(null),d(null))},[k,P,T,l,m]);const Z=()=>{p(l)},I=async V=>{if(l)try{await ge.linkTagToSpool(V.id,{tag_uid:l,tag_type:"generic",data_origin:"nfc_link"}),y(!1),a()}catch(ne){console.error("Failed to link tag:",ne)}},J=async()=>{if(l){C(!0);try{const V=Y??u;await ge.createSpool({material:"PLA",subtype:null,color_name:null,rgba:null,brand:null,label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,nozzle_temp_min:null,nozzle_temp_max:null,note:null,added_full:null,last_used:null,encode_time:null,tag_uid:l,tray_uuid:null,data_origin:"spoolbuddy",tag_type:"generic",cost_per_kg:null,last_scale_weight:V,last_weighed_at:V!==null?new Date().toISOString():null}),_(!1),a()}catch(V){console.error("Failed to quick-add spool:",V)}finally{C(!1)}}},Y=P!==null&&(k===l||k===null&&l!==null)?P:null,ue=r.length,de=new Set(r.map(V=>V.material)).size,he=new Set(r.filter(V=>V.brand).map(V=>V.brand)).size;return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsxs("div",{className:"flex items-center gap-6 px-4 py-1.5 bg-zinc-800/50 rounded-xl border border-zinc-700/50 mb-3 shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xl font-bold text-zinc-100",children:ue}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.inventory.spools","Spools")})]}),i.jsx("div",{className:"w-px h-5 bg-zinc-700"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xl font-bold text-zinc-100",children:de}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.material","Materials")})]}),i.jsx("div",{className:"w-px h-5 bg-zinc-700"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xl font-bold text-zinc-100",children:he}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.brand","Brands")})]})]}),i.jsxs("div",{className:"flex-1 flex gap-4 min-h-0",children:[i.jsxs("div",{className:"w-5/12 flex flex-col min-h-0",children:[i.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-4",children:[i.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-3",children:n("spoolbuddy.dashboard.device","Device")}),i.jsxs("div",{className:"space-y-2.5",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${t.deviceOnline?"bg-green-500 animate-pulse":"bg-red-500"}`}),i.jsx("span",{className:"text-base text-zinc-400",children:t.deviceOnline?n("spoolbuddy.status.online","Online"):n("spoolbuddy.status.offline","Disconnected")})]}),i.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3"})}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.scaleWeight","Scale")})]}),i.jsx("span",{className:"text-lg font-mono font-semibold text-zinc-100",children:R!==null?`${Math.abs(R)<=20?0:Math.round(Math.max(0,R))}g`:"—"})]}),i.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"})}),i.jsx("span",{className:"text-sm text-zinc-500",children:"NFC"})]}),i.jsx("span",{className:`text-sm font-medium ${k?"text-green-500":"text-zinc-500"}`,children:k?n("spoolbuddy.dashboard.tagDetected","Tag detected"):n("spoolbuddy.dashboard.noTag","No tag")})]})]})]}),s.length>0&&i.jsxs("div",{className:"mt-3 border border-dashed border-zinc-700/50 rounded-xl p-4",children:[i.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-2.5",children:n("spoolbuddy.dashboard.printers","Printers")}),i.jsx("div",{className:"flex flex-wrap gap-2 overflow-hidden",children:s.map((V,ne)=>{const se=o[ne]?.data?.connected??!1;return i.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 bg-zinc-800/50 rounded-lg",title:`${V.name} — ${se?"Online":"Offline"}`,children:[i.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${se?"bg-green-500":"bg-zinc-600"}`}),i.jsx("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:V.name})]},V.id)})})]})]}),i.jsx("div",{className:"w-7/12 min-h-0",children:i.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-6 h-full flex flex-col",children:[i.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-4 shrink-0",children:n("spoolbuddy.dashboard.currentSpool","Current Spool")}),i.jsx("div",{className:"flex-1 flex items-center justify-center min-h-0",children:t.deviceOnline?G&&l&&m!==l?i.jsx(Mnt,{spool:{id:G.id,tag_uid:l,material:G.material,subtype:G.subtype,color_name:G.color_name,rgba:G.rgba,brand:G.brand,label_weight:G.label_weight,core_weight:G.core_weight,weight_used:G.weight_used},scaleWeight:Y??u,onSyncWeight:()=>a(),onAssignToAms:()=>b(!0),onClose:Z}):l&&!G&&m!==l?i.jsx(Ent,{tagUid:l,scaleWeight:Y??u,onLinkSpool:z.length>0?()=>y(!0):void 0,onAddToInventory:()=>_(!0),onClose:Z}):i.jsx(Vnt,{}):i.jsx(Gnt,{})})]})})]}),G&&l&&i.jsx($nt,{isOpen:v,onClose:()=>b(!1),spool:G,printerId:e}),l&&i.jsx(qnt,{isOpen:f,onClose:()=>y(!1),tagId:l,untaggedSpools:z,onLink:I}),g&&l&&i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",children:i.jsxs("div",{className:"bg-zinc-800 rounded-2xl p-6 mx-4 max-w-sm w-full border border-zinc-700",children:[i.jsx("h3",{className:"text-lg font-semibold text-zinc-100 mb-3",children:n("spoolbuddy.modal.addToInventory","Add to Inventory")}),i.jsxs("div",{className:"flex gap-2.5 p-3 bg-amber-500/10 border border-amber-500/20 rounded-lg mb-4",children:[i.jsx("svg",{className:"w-5 h-5 text-amber-500 shrink-0 mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),i.jsx("p",{className:"text-sm text-amber-200/80",children:n("spoolbuddy.modal.quickAddHint",'For best results, add the spool in the Bambuddy web interface first (with material, color, brand), then use "Link to Spool" here to assign the NFC tag.')})]}),i.jsx("p",{className:"text-sm text-zinc-400 mb-1",children:n("spoolbuddy.modal.quickAddDesc","This will create a basic PLA spool entry with this NFC tag. You can edit the details later in Bambuddy.")}),i.jsx("p",{className:"text-xs text-zinc-500 font-mono mb-5",children:l}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx("button",{onClick:()=>_(!1),className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:n("common.cancel","Cancel")}),i.jsx("button",{onClick:J,disabled:N,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-50 transition-colors min-h-[44px]",children:N?n("common.saving","Saving..."):n("spoolbuddy.modal.addAnyway","Add Anyway")})]})]})})]})}function WY(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function Knt(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",P1S:"P1S",P1P:"P1P",P2S:"P2S",A1:"A1","A1 Mini":"A1 Mini",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[t]||t:""}function Pb(t){return!t.tray_type||t.tray_type===""}function Ynt(t){return t?`#${t.slice(0,6)}`:"#808080"}function Xnt(){const{selectedPrinterId:t,setAlert:e}=fw(),{t:n}=Dt(),r=sn(),{data:a}=et({queryKey:["printerStatus",t],queryFn:()=>ge.getPrinterStatus(t),enabled:t!==null,staleTime:30*1e3}),{data:s}=et({queryKey:["printer",t],queryFn:()=>ge.getPrinter(t),enabled:t!==null,staleTime:60*1e3}),{data:o}=et({queryKey:["slotPresets",t],queryFn:()=>ge.getSlotPresets(t),enabled:t!==null,staleTime:120*1e3}),{data:l}=et({queryKey:["settings"],queryFn:()=>ge.getSettings(),staleTime:300*1e3}),{data:c}=et({queryKey:["spoolman-status"],queryFn:ge.getSpoolmanStatus,staleTime:60*1e3}),u=c?.enabled&&c?.connected,{data:d}=et({queryKey:["linked-spools"],queryFn:ge.getLinkedSpools,enabled:!!u,staleTime:30*1e3}),m=d?.linked,{data:p}=et({queryKey:["spool-assignments",t],queryFn:()=>ge.getAssignments(t),enabled:t!==null,staleTime:30*1e3}),f=w.useMemo(()=>{const V={};if(!p)return V;for(const ne of p){const se=ne.spool;if(se&&se.label_weight>0&&se.weight_used!=null){const pe=Math.round(Math.max(0,se.label_weight-se.weight_used)/se.label_weight*100);V[`${ne.ams_id}-${ne.tray_id}`]=pe}}return V},[p]),y=s?.serial_number??"",v=w.useCallback((V,ne,se)=>{if(!m||!y)return null;const pe=(se?.tray_uuid||se?.tag_uid||$p(y,V,ne))?.toUpperCase(),Te=pe?m[pe]:void 0;return yN(Te)},[m,y]),b=a?.connected??!1,g=w.useRef([]);w.useEffect(()=>{a?.ams&&a.ams.length>0&&(g.current=a.ams)},[a?.ams]);const _=w.useMemo(()=>{const V=a?.ams;return V&&V.length>0?V:g.current??[]},[a?.ams]),N=w.useMemo(()=>_.filter(V=>!V.is_ams_ht),[_]),C=w.useMemo(()=>_.filter(V=>V.is_ams_ht),[_]),k=w.useMemo(()=>{const V={};if(!m||!y)return V;for(const ne of N)for(let se=0;se<(ne.tray?.length??0);se++){const pe=ne.tray[se],Te=v(ne.id,se,Pb(pe)?null:pe);Te!==null&&(V[`${ne.id}-${se}`]=Te)}return V},[m,y,N,v]),P=w.useRef(void 0),T=a?.tray_now;T!==void 0&&T!==255?P.current=T:T===255&&(P.current=void 0);const D=T!==void 0&&T!==255?T:P.current,A=s?.nozzle_count===2||a?.temperatures?.nozzle_2!==void 0,R=w.useMemo(()=>[...a?.vt_tray??[]].sort((V,ne)=>(V.id??254)-(ne.id??254)),[a?.vt_tray]),G=l?{humidityGood:Number(l.ams_humidity_good)||40,humidityFair:Number(l.ams_humidity_fair)||60,tempGood:Number(l.ams_temp_good)||28,tempFair:Number(l.ams_temp_fair)||35}:void 0,z=w.useRef({});w.useEffect(()=>{a?.ams_extruder_map&&Object.keys(a.ams_extruder_map).length>0&&(z.current=a.ams_extruder_map)},[a?.ams_extruder_map]);const Z=a?.ams_extruder_map&&Object.keys(a.ams_extruder_map).length>0?a.ams_extruder_map:z.current,I=w.useCallback(V=>{if(!A)return null;const ne=Z[String(V)],se=V>=128?V-128:V;return(ne!==void 0?ne:se)===1?"L":"R"},[A,Z]),[J,ae]=w.useState(null),Y=w.useCallback(V=>D===void 0?null:V<=3&&Math.floor(D/4)===V?D%4:V>=128&&V<=135&&D===Ex(V,0,!1)?0:null,[D]),ue=w.useCallback((V,ne,se)=>{const pe=V>=128?(V-128)*4+ne+64:V*4+ne,Te=o?.[pe],q=Z[String(V)],X=V>=128?V-128:V,j=q!==void 0?q:X;ae({amsId:V,trayId:ne,trayCount:se&&V>=128?1:4,trayType:se?.tray_type||void 0,trayColor:se?.tray_color||void 0,traySubBrands:se?.tray_sub_brands||void 0,trayInfoIdx:se?.tray_info_idx||void 0,extruderId:A?j:void 0,caliIdx:se?.cali_idx,savedPresetId:Te?.preset_id})},[o,Z,A]),de=w.useCallback(V=>{const ne=V.id??254,se=ne-254,pe=o?.[1020+se];ae({amsId:255,trayId:se,trayCount:1,trayType:V.tray_type||void 0,trayColor:V.tray_color||void 0,traySubBrands:V.tray_sub_brands||void 0,trayInfoIdx:V.tray_info_idx||void 0,extruderId:A?ne===254?1:0:void 0,caliIdx:V.cali_idx,savedPresetId:pe?.preset_id})},[o,A]);w.useEffect(()=>{if(!b&&t){e({type:"warning",message:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")});return}for(const V of _)for(const ne of V.tray||[])if(ne.remain!==null&&ne.remain>=0&&ne.remain<15&&ne.tray_type){e({type:"warning",message:`Low Filament: ${ne.tray_type} (${WY(V.id)}) - ${ne.remain}% remaining`});return}e(null)},[_,b,t,e,n]);const he=w.useMemo(()=>{const V=[];for(const ne of C){const se=ne.tray?.[0]||{id:0,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},pe=v(ne.id,0,Pb(se)?null:se),Te=f[`${ne.id}-0`]??null,q=se.remain!=null&&se.remain>=0?se.remain:null,X=Te===0&&q!==null&&q>0?null:Te;V.push({key:`ht-${ne.id}`,label:WY(ne.id),tray:se,isEmpty:Pb(se),isActive:Y(ne.id)===0,temp:ne.temp,humidity:ne.humidity,nozzleSide:I(ne.id),effectiveFill:pe??X??q,onClick:()=>ue(ne.id,0,Pb(se)?null:se)})}for(const ne of R){const se=ne.id??254,pe=A&&D===254?se===254&&a?.active_extruder===1||se===255&&a?.active_extruder===0:D===se,Te=se-254,q=v(255,Te,Pb(ne)?null:ne),X=f[`255-${Te}`]??null,j=ne.remain!=null&&ne.remain>=0?ne.remain:null,E=X===0&&j!==null&&j>0?null:X;V.push({key:`ext-${se}`,label:A?se===254?n("printers.extL","Ext-L"):n("printers.extR","Ext-R"):n("printers.ext","Ext"),tray:ne,isEmpty:Pb(ne),isActive:pe,nozzleSide:null,effectiveFill:q??E??j,onClick:()=>de(ne)})}return V},[C,R,A,D,a?.active_extruder,n,Y,I,ue,de,f,v]);return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("div",{className:"flex-1 min-h-0",children:t?b?_.length===0&&R.length===0?i.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:i.jsxs("div",{className:"text-center text-white/50",children:[i.jsx(Gi,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),i.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noData","No AMS detected")}),i.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):i.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:N.map(V=>i.jsx(rle,{unit:V,activeSlot:Y(V.id),onConfigureSlot:ue,isDualNozzle:A,nozzleSide:I(V.id),thresholds:G,fillOverrides:f,spoolmanFillOverrides:k},V.id))}),he.length>0&&i.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:he.map(({key:V,label:ne,tray:se,isEmpty:pe,isActive:Te,temp:q,humidity:X,nozzleSide:j,effectiveFill:E,onClick:U})=>{const K=Ynt(se.tray_color);return i.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-3 ${Te?"ring-2 ring-bambu-green":""}`,onClick:U,children:[i.jsxs("div",{className:"relative w-10 h-10 flex-shrink-0",children:[pe?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:i.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:K}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:K,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),Te&&i.jsx("div",{className:"absolute -bottom-0.5 left-1/2 -translate-x-1/2 w-1.5 h-1.5 bg-bambu-green rounded-full"})]}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"text-xs text-white/50 font-medium truncate",children:ne}),j&&i.jsx(j5,{side:j})]}),i.jsx("div",{className:"text-sm text-white/80 truncate",children:pe?"Empty":se.tray_type||"?"}),(q!=null||X!=null)&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[q!=null&&i.jsx(nle,{temp:q,goodThreshold:G?.tempGood,fairThreshold:G?.tempFair}),X!=null&&i.jsx(tle,{humidity:X,goodThreshold:G?.humidityGood,fairThreshold:G?.humidityFair})]})]}),!pe&&E!=null&&E>=0&&i.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0 flex flex-col-reverse",children:i.jsx("div",{className:"w-full rounded-full",style:{height:`${E}%`,backgroundColor:ix(E)}})})]},V)})})]}):i.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:i.jsx("div",{className:"text-center text-white/50",children:i.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):i.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:i.jsxs("div",{className:"text-center text-white/50",children:[i.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noPrinter","No printer selected")}),i.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.selectPrinter","Select a printer from the top bar")})]})})}),J&&t&&i.jsx(tie,{isOpen:!!J,onClose:()=>ae(null),printerId:t,slotInfo:J,printerModel:Knt(s?.model??null)||void 0,fullScreen:!0,onSuccess:()=>{r.invalidateQueries({queryKey:["slotPresets",t]}),r.invalidateQueries({queryKey:["printerStatus",t]})}})]})}function Qnt(t){if(t<60)return`${t}s`;if(t<3600)return`${Math.floor(t/60)}m`;const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return`${e}h ${n}m`}function Znt(t){if(!t)return"-";try{const e=new Date(t);return e.toLocaleDateString(void 0,{month:"short",day:"numeric"})+" "+e.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}catch{return"-"}}const Jnt=[{label:"Off",value:0},{label:"1m",value:60},{label:"2m",value:120},{label:"5m",value:300},{label:"10m",value:600},{label:"30m",value:1800}];function ert({device:t}){const{t:e}=Dt();return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsx("div",{className:"flex items-center gap-3 mb-2",children:i.jsx("img",{src:"/img/spoolbuddy_logo_dark_small.png",alt:"SpoolBuddy",className:"h-7 w-auto"})}),i.jsx("p",{className:"text-xs text-zinc-500 mb-1",children:"Part of Bambuddy"}),i.jsx("span",{className:"text-xs text-zinc-500",children:"github.com/maziggy/bambuddy"})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.nfcReader","NFC Reader")}),i.jsxs("div",{className:"space-y-1.5 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.type","Type")}),i.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_reader_type||"N/A"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.connection","Connection")}),i.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_connection||"N/A"})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.status.status","Status")}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${t.nfc_ok?"bg-green-500":t.nfc_reader_type?"bg-red-500":"bg-zinc-600"}`}),i.jsx("span",{className:t.nfc_ok?"text-green-400":t.nfc_reader_type?"text-red-400":"text-zinc-500",children:t.nfc_ok?e("spoolbuddy.status.nfcReady","Ready"):t.nfc_reader_type?e("common.error","Error"):e("spoolbuddy.settings.notConnected","N/A")})]})]})]})]}),i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.deviceInfo","Device Info")}),i.jsxs("div",{className:"space-y-1.5 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.hostname","Host")}),i.jsx("span",{className:"text-zinc-300 truncate ml-2",children:t.hostname})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:"IP"}),i.jsx("span",{className:"text-zinc-300",children:t.ip_address})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.uptime","Uptime")}),i.jsx("span",{className:"text-zinc-300",children:Qnt(t.uptime_s)})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.status.status","Status")}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${t.online?"bg-green-500":"bg-zinc-600"}`}),i.jsx("span",{className:t.online?"text-green-400":"text-zinc-500",children:t.online?e("spoolbuddy.status.online","Online"):e("spoolbuddy.status.offline","Offline")})]})]})]})]})]}),i.jsxs("div",{className:"bg-zinc-800 rounded-lg px-3 py-2 flex justify-between items-center text-xs",children:[i.jsx("span",{className:"text-zinc-500",children:"Device ID"}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.device_id})]})]})}function trt({device:t,onBrightnessChange:e,onBlankTimeoutChange:n}){const{t:r}=Dt(),[a,s]=w.useState(t.display_brightness),[o,l]=w.useState(t.display_blank_timeout),[c,u]=w.useState(!1),d=w.useRef(void 0),m=w.useRef(void 0);w.useEffect(()=>{s(t.display_brightness),l(t.display_blank_timeout)},[t.display_brightness,t.display_blank_timeout]);const p=w.useCallback(()=>{u(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>u(!1),1500)},[]),f=w.useCallback((b,g)=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{pa.updateDisplay(t.device_id,b,g).then(()=>p()).catch(_=>console.error("Failed to update display:",_))},300)},[t.device_id,p]),y=b=>{s(b),e(b),f(b,o)},v=b=>{l(b),n(b),f(a,b)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:r("spoolbuddy.settings.brightness","Brightness")}),c&&i.jsxs("span",{className:"text-xs text-green-400 flex items-center gap-1 animate-pulse",children:[i.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}),r("spoolbuddy.settings.saved","Saved")]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("svg",{className:"w-4 h-4 text-zinc-500 flex-shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"})}),i.jsx("input",{type:"range",min:0,max:100,value:a,onChange:b=>y(parseInt(b.target.value)),className:"flex-1 h-2 bg-zinc-700 rounded-lg appearance-none cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-sm font-mono text-zinc-400 w-10 text-right",children:[a,"%"]})]}),!t.has_backlight&&i.jsx("p",{className:"text-xs text-zinc-600 mt-2",children:r("spoolbuddy.settings.noBacklight","No DSI backlight detected. Brightness control requires a DSI display.")})]}),i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1",children:r("spoolbuddy.settings.screenBlank","Screen Blank Timeout")}),i.jsx("p",{className:"text-xs text-zinc-500 mb-3",children:r("spoolbuddy.settings.screenBlankDesc","Screen turns off after inactivity. Touch to wake.")}),i.jsx("div",{className:"grid grid-cols-3 gap-2",children:Jnt.map(b=>i.jsx("button",{onClick:()=>v(b.value),className:`px-3 py-2 rounded-lg text-sm font-medium transition-colors min-h-[40px] ${o===b.value?"bg-green-600 text-white":"bg-zinc-700 text-zinc-300 hover:bg-zinc-600"}`,children:b.label},b.value))})]}),i.jsx("p",{className:"text-xs text-zinc-600 text-center",children:r("spoolbuddy.settings.displayNote","Brightness is applied as a software filter.")})]})}function nrt({step:t,labels:e}){return i.jsxs("div",{className:"flex flex-col items-center w-16 shrink-0 pt-1",children:[i.jsx("div",{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${t==="tare"?"bg-green-600 text-white":"bg-green-600/20 text-green-400"}`,children:t==="weight"?i.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}):"1"}),i.jsx("span",{className:`text-[10px] mt-0.5 ${t==="tare"?"text-green-400 font-medium":"text-green-400/60"}`,children:e.tare}),i.jsx("div",{className:`w-px h-5 my-1 ${t==="weight"?"bg-green-600/40":"bg-zinc-700"}`}),i.jsx("div",{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${t==="weight"?"bg-green-600 text-white":"bg-zinc-700 text-zinc-500"}`,children:"2"}),i.jsx("span",{className:`text-[10px] mt-0.5 ${t==="weight"?"text-green-400 font-medium":"text-zinc-600"}`,children:e.weight})]})}function rrt({device:t,weight:e,weightStable:n,rawAdc:r}){const{t:a}=Dt(),[s,o]=w.useState("idle"),[l,c]=w.useState("500"),[u,d]=w.useState(null),[m,p]=w.useState(!1),[f,y]=w.useState(null),v=_=>{_==="backspace"?c(N=>N.slice(0,-1)||""):_==="."&&!l.includes(".")?c(N=>N+"."):_>="0"&&_<="9"&&c(N=>N==="0"?_:N+_)},b=async()=>{p(!0),y(null);try{await pa.tare(t.device_id),y({type:"ok",msg:a("spoolbuddy.settings.tareSet","Tare command sent. Waiting for device...")})}catch{y({type:"error",msg:a("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{p(!1)}},g=async()=>{if(s==="tare"){p(!0),y(null);try{d(r),await pa.tare(t.device_id),y({type:"ok",msg:a("spoolbuddy.settings.zeroSet","Zero point set. Place known weight on scale.")}),o("weight")}catch{y({type:"error",msg:a("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{p(!1)}}else if(s==="weight"){const _=parseFloat(l);if(r===null||!_||_<=0)return;p(!0),y(null);try{await pa.setCalibrationFactor(t.device_id,_,r,u??void 0),y({type:"ok",msg:a("spoolbuddy.settings.calibrationDone","Calibration complete!")}),o("idle")}catch{y({type:"error",msg:a("spoolbuddy.settings.calibrationFailed","Calibration failed")})}finally{p(!1)}}};return s==="idle"?i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 mb-3",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),i.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]}),i.jsxs("div",{className:"text-xs text-zinc-500 text-right",children:[i.jsxs("span",{children:[a("spoolbuddy.settings.tareOffset","Tare"),": ",t.tare_offset]}),i.jsx("span",{className:"mx-1.5",children:"·"}),i.jsxs("span",{children:[a("spoolbuddy.settings.calFactor","Factor"),": ",t.calibration_factor.toFixed(2)]})]})]}),t.last_calibrated_at&&i.jsxs("div",{className:"text-xs text-zinc-600 mt-1",children:[a("spoolbuddy.settings.lastCalibrated","Last calibrated"),": ",Znt(t.last_calibrated_at)]})]}),f&&i.jsx("div",{className:`rounded-lg px-3 py-2 mb-3 text-sm ${f.type==="ok"?"bg-green-900/30 text-green-300 border border-green-800":"bg-red-900/30 text-red-300 border border-red-800"}`,children:f.msg}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:b,disabled:m,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px] flex items-center justify-center gap-2",children:[m&&i.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),a("spoolbuddy.weight.tare","Tare")]}),i.jsx("button",{onClick:()=>{o("tare"),y(null)},className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:a("spoolbuddy.weight.calibrate","Calibrate")})]})]}):i.jsxs("div",{className:"flex gap-3",children:[i.jsx(nrt,{step:s,labels:{tare:a("spoolbuddy.weight.tare","Tare"),weight:a("spoolbuddy.settings.knownWeight","Known weight")}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 rounded-lg px-3 py-1.5 mb-1.5",children:[i.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),i.jsx("span",{className:"text-sm font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"}),i.jsx("span",{className:`text-xs ml-auto ${n?"text-green-400":"text-amber-400"}`,children:n?a("spoolbuddy.settings.stable","Stable"):a("spoolbuddy.settings.settling","Settling...")})]}),f&&i.jsx("div",{className:`rounded-lg px-3 py-1.5 mb-1.5 text-xs ${f.type==="ok"?"bg-green-900/30 text-green-300 border border-green-800":"bg-red-900/30 text-red-300 border border-red-800"}`,children:f.msg}),s==="tare"?i.jsx("p",{className:"text-sm text-zinc-300 mb-3",children:a("spoolbuddy.settings.calStep1","Remove all items from the scale and press Set Zero.")}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[i.jsx("span",{className:"text-xs text-zinc-400 shrink-0",children:a("spoolbuddy.settings.knownWeight","Known weight")}),i.jsxs("div",{className:"flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1 text-right text-lg font-mono text-zinc-100",children:[l||"0",i.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),i.jsx("div",{className:"grid grid-cols-4 gap-1 mb-1.5",children:["7","8","9","backspace","4","5","6",".","1","2","3","0"].map(_=>i.jsx("button",{onClick:()=>v(_),className:`rounded text-lg font-medium transition-colors h-[48px] active:scale-95 ${_==="backspace"?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600":"bg-zinc-800 text-zinc-100 hover:bg-zinc-700 border border-zinc-700"}`,children:_==="backspace"?"⌫":_},_))})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>{o("idle"),y(null)},className:"flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors h-[40px]",children:a("common.cancel","Cancel")}),i.jsxs("button",{onClick:g,disabled:m,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors h-[40px] flex items-center justify-center gap-2",children:[m&&i.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),s==="tare"?a("spoolbuddy.settings.setZero","Set Zero"):a("spoolbuddy.settings.calibrateNow","Calibrate")]})]})]})]})}function irt({device:t}){const{t:e}=Dt(),[n,r]=w.useState(null),[a,s]=w.useState(null),[o,l]=w.useState(!1),[c,u]=w.useState(!1),d=t.update_status==="pending"||t.update_status==="updating";w.useEffect(()=>{d&&n==="applying"&&r(null)},[d,n]),w.useEffect(()=>{const N=()=>{d&&setTimeout(()=>window.location.reload(),1e3)};return window.addEventListener("spoolbuddy-online",N),()=>window.removeEventListener("spoolbuddy-online",N)},[d]);const{data:m,refetch:p}=et({queryKey:["spoolbuddy-update-check",t.device_id],queryFn:()=>pa.checkDaemonUpdate(t.device_id),staleTime:0}),{data:f}=et({queryKey:["spoolbuddy-ssh-key"],queryFn:()=>pa.getSSHPublicKey(),enabled:o,staleTime:1/0}),y=async()=>{r("checking"),s(null);try{await p()}finally{r(null)}},v=async()=>{r("applying"),s(null);try{await pa.triggerUpdate(t.device_id)}catch(N){s(N instanceof Error?N.message:"Failed to trigger update"),r(null)}},b=n!=null||d,g=()=>{f?.public_key&&(navigator.clipboard.writeText(f.public_key),u(!0),setTimeout(()=>u(!1),2e3))},_=t.firmware_version||(m?.current_version&&m.current_version!=="0.0.0"?m.current_version:null);return i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 space-y-3",children:[i.jsxs("div",{className:"flex justify-between items-center text-sm",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.currentVersion","Current Version")}),i.jsx("span",{className:"text-zinc-200 font-mono",children:_||i.jsx("span",{className:"text-zinc-500 italic text-xs",children:e("spoolbuddy.settings.versionPending","Waiting for daemon...")})})]}),b?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("svg",{className:"w-4 h-4 animate-spin text-green-400 flex-shrink-0",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),i.jsx("span",{className:"text-green-300 text-xs",children:n==="checking"?e("spoolbuddy.settings.checking","Checking for updates..."):t.update_message||e("spoolbuddy.settings.updateWaiting","Updating...")})]}):t.update_status==="error"?i.jsx("p",{className:"text-xs text-red-300",children:t.update_message||e("spoolbuddy.settings.updateFailed","Update failed")}):a?i.jsx("p",{className:"text-xs text-red-300",children:a}):m?.update_available?i.jsxs("p",{className:"text-xs text-green-300",children:[e("spoolbuddy.settings.updateAvailable","Update available"),": ",_," → ",m.latest_version]}):null,!b&&(m?.update_available?i.jsx("button",{onClick:v,disabled:!t.online,className:"w-full px-3 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors",children:t.online?e("spoolbuddy.settings.applyUpdate","Apply Update"):e("spoolbuddy.settings.deviceOffline","Device Offline")}):i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:y,className:"flex-1 px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors",children:e("spoolbuddy.settings.checkUpdates","Check for Updates")}),i.jsx("button",{onClick:v,disabled:!t.online,className:"px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-400 hover:bg-zinc-600 hover:text-zinc-200 disabled:opacity-40 transition-colors",children:e("spoolbuddy.settings.forceUpdate","Force Update")})]}))]}),i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[i.jsxs("button",{onClick:()=>l(!o),className:"w-full flex justify-between items-center text-xs",children:[i.jsx("span",{className:"font-medium text-zinc-400",children:e("spoolbuddy.settings.sshSetup","SSH Setup")}),i.jsx("svg",{className:`w-3 h-3 text-zinc-500 transition-transform ${o?"rotate-180":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})]}),o&&i.jsxs("div",{className:"mt-2 space-y-2",children:[i.jsx("p",{className:"text-xs text-zinc-500",children:e("spoolbuddy.settings.sshDescription","SSH key is deployed automatically. For manual setup, add this key to ~/.ssh/authorized_keys on the device.")}),f?.public_key?i.jsxs("div",{className:"relative",children:[i.jsx("pre",{className:"bg-zinc-900 rounded p-2 text-[10px] text-zinc-400 font-mono break-all whitespace-pre-wrap",children:f.public_key}),i.jsx("button",{onClick:g,className:"absolute top-1 right-1 px-1.5 py-0.5 rounded text-[10px] bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors",children:c?e("common.copied","Copied!"):e("common.copy","Copy")})]}):i.jsx("span",{className:"text-[10px] text-zinc-500 italic",children:e("spoolbuddy.settings.sshKeyLoading","Loading...")})]})]})]})}function art(){const{sbState:t,setDisplayBrightness:e,setDisplayBlankTimeout:n}=fw(),{t:r}=Dt(),[a,s]=w.useState("device"),{data:o=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>pa.getDevices(),refetchInterval:1e4}),l=t.deviceId?o.find(u=>u.device_id===t.deviceId)??o[0]:o[0],c=[{id:"device",label:r("spoolbuddy.settings.tabDevice","Device")},{id:"display",label:r("spoolbuddy.settings.tabDisplay","Display")},{id:"scale",label:r("spoolbuddy.settings.tabScale","Scale")},{id:"updates",label:r("spoolbuddy.settings.tabUpdates","Updates")}];return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("h1",{className:"text-xl font-semibold text-zinc-100 mb-3",children:r("spoolbuddy.nav.settings","Settings")}),i.jsx("div",{className:"flex gap-1 bg-zinc-800/50 rounded-lg p-1 mb-4",children:c.map(u=>i.jsx("button",{onClick:()=>s(u.id),className:`flex-1 px-2 py-2 rounded-md text-sm font-medium transition-colors min-h-[36px] ${a===u.id?"bg-zinc-700 text-zinc-100":"text-zinc-500 hover:text-zinc-300"}`,children:u.label},u.id))}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:l?i.jsxs(i.Fragment,{children:[a==="device"&&i.jsx(ert,{device:l}),a==="display"&&i.jsx(trt,{device:l,onBrightnessChange:e,onBlankTimeoutChange:n}),a==="scale"&&i.jsx(rrt,{device:l,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}),a==="updates"&&i.jsx(irt,{device:l})]}):i.jsx("div",{className:"flex items-center justify-center h-32",children:i.jsx("div",{className:"text-center text-zinc-500",children:i.jsx("p",{className:"text-sm",children:r("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}function srt({device:t,weight:e,weightStable:n,rawAdc:r}){const{t:a}=Dt(),[s,o]=w.useState(!1),[l,c]=w.useState("idle"),[u,d]=w.useState("500"),[m,p]=w.useState(null),[f,y]=w.useState(!1),v=N=>{N==="backspace"?d(C=>C.slice(0,-1)||""):N==="."&&!u.includes(".")?d(C=>C+"."):N>="0"&&N<="9"&&d(C=>C==="0"?N:C+N)},b=async()=>{y(!0);try{await pa.tare(t.device_id)}catch(N){console.error("Failed to tare:",N)}finally{y(!1)}},g=()=>{c("tare")},_=async()=>{if(l==="tare"){o(!0);try{p(r),await pa.tare(t.device_id),c("weight")}catch(N){console.error("Failed to tare:",N)}finally{o(!1)}}else if(l==="weight"){const N=parseFloat(u);if(r===null||!N||N<=0)return;o(!0);try{await pa.setCalibrationFactor(t.device_id,N,r,m??void 0),c("idle")}catch(C){console.error("Failed to calibrate:",C)}finally{o(!1)}}};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-zinc-400",children:a("spoolbuddy.settings.currentWeight","Current weight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),i.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-3 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.settings.tareOffset","Tare offset")}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.tare_offset})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.settings.calFactor","Cal. factor")}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.calibration_factor.toFixed(2)})]})]})]}),l==="idle"?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:b,disabled:f,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px]",children:f?"...":a("spoolbuddy.weight.tare","Tare")}),i.jsx("button",{onClick:g,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:a("spoolbuddy.weight.calibrate","Calibrate")})]}):i.jsxs("div",{className:"bg-zinc-800 border border-zinc-700 rounded-lg p-3 space-y-2",children:[i.jsx("div",{className:"text-sm font-medium text-zinc-200",children:l==="tare"?a("spoolbuddy.settings.calStep1","Step 1: Remove all items from the scale"):a("spoolbuddy.settings.calStep2","Step 2: Place known weight on scale")}),l==="weight"&&i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-zinc-400",children:a("spoolbuddy.settings.knownWeight","Known weight (g)")}),i.jsxs("div",{className:"flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1.5 text-right text-base font-mono text-zinc-100",children:[u||"0",i.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),i.jsx("div",{className:"grid grid-cols-4 gap-1",children:["7","8","9","backspace","4","5","6",".","1","2","3","0"].map(N=>i.jsx("button",{onClick:()=>v(N),className:`py-2 rounded text-sm font-medium transition-colors min-h-[36px] ${N==="backspace"?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600":"bg-zinc-800 text-zinc-100 hover:bg-zinc-700 border border-zinc-700"}`,children:N==="backspace"?"⌫":N},N))})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>c("idle"),className:"flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[40px]",children:a("common.cancel","Cancel")}),i.jsx("button",{onClick:_,disabled:s,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors min-h-[40px]",children:s?"...":l==="tare"?a("spoolbuddy.settings.setZero","Set Zero"):a("spoolbuddy.settings.calibrateNow","Calibrate")})]})]})]})}function ort(){const{sbState:t}=fw(),{t:e}=Dt(),n=ol(),{data:r=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>pa.getDevices(),refetchInterval:1e4}),a=t.deviceId?r.find(s=>s.device_id===t.deviceId)??r[0]:r[0];return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("button",{onClick:()=>n("/spoolbuddy/settings"),className:"p-1.5 rounded-lg text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800 transition-colors",children:i.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 19l-7-7 7-7"})})}),i.jsx("h1",{className:"text-xl font-semibold text-zinc-100",children:e("spoolbuddy.settings.scaleCalibration","Scale Calibration")})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:a?i.jsx(srt,{device:a,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}):i.jsx("div",{className:"flex items-center justify-center h-32",children:i.jsx("div",{className:"text-center text-zinc-500",children:i.jsx("p",{className:"text-sm",children:e("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}const lrt=["PLA","PETG","ABS","ASA","TPU","PA","PC","PVA","HIPS"];function crt(){const{t}=Dt(),{sbState:e}=fw(),[n,r]=w.useState("existing"),[a,s]=w.useState(null),[o,l]=w.useState(""),[c,u]=w.useState("idle"),[d,m]=w.useState(""),[p,f]=w.useState(!1),[y,v]=w.useState(null),[b,g]=w.useState("PLA"),[_,N]=w.useState(""),[C,k]=w.useState("#00AE42"),[P,T]=w.useState(""),[D,A]=w.useState(1e3),[R,G]=w.useState(!1),{data:z=[],refetch:Z}=et({queryKey:["inventory-spools"],queryFn:()=>ge.getSpools(!1),refetchInterval:1e4}),{data:I=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>pa.getDevices(),refetchInterval:5e3}),J=I[0],ae=e.deviceOnline,Y=w.useMemo(()=>{let X;if(n==="existing")X=z.filter(j=>!j.tag_uid&&!j.archived_at);else if(n==="replace")X=z.filter(j=>j.tag_uid&&!j.archived_at);else return[];if(o){const j=o.toLowerCase();X=X.filter(E=>E.material?.toLowerCase().includes(j)||E.color_name?.toLowerCase().includes(j)||E.brand?.toLowerCase().includes(j)||E.subtype?.toLowerCase().includes(j))}return X},[z,n,o]),ue=w.useCallback(X=>{const j=X.detail;(j.sak??j.data?.sak)===0&&(f(!0),v(j.tag_uid??j.data?.tag_uid??null))},[]),de=w.useCallback(X=>{const j=X.detail;f(!0),v(j.tag_uid??j.data?.tag_uid??null)},[]),he=w.useCallback(()=>{f(!1),v(null)},[]),V=w.useCallback(X=>{const j=X.detail;(j.spool_id===a?.id||j.data?.spool_id===a?.id)&&(u("success"),m(t("spoolbuddy.writeTag.writeSuccess","Tag written successfully!")),Z(),setTimeout(()=>{u("idle"),s(null),m("")},5e3))},[a,t,Z]),ne=w.useCallback(X=>{const j=X.detail;(j.spool_id===a?.id||j.data?.spool_id===a?.id)&&(u("error"),m(j.message??j.data?.message??t("spoolbuddy.writeTag.writeFailed","Write failed")))},[a,t]);w.useEffect(()=>(window.addEventListener("spoolbuddy-unknown-tag",ue),window.addEventListener("spoolbuddy-tag-matched",de),window.addEventListener("spoolbuddy-tag-removed",he),window.addEventListener("spoolbuddy-tag-written",V),window.addEventListener("spoolbuddy-tag-write-failed",ne),()=>{window.removeEventListener("spoolbuddy-unknown-tag",ue),window.removeEventListener("spoolbuddy-tag-matched",de),window.removeEventListener("spoolbuddy-tag-removed",he),window.removeEventListener("spoolbuddy-tag-written",V),window.removeEventListener("spoolbuddy-tag-write-failed",ne)}),[ue,de,he,V,ne]),w.useEffect(()=>{s(null),u("idle"),m(""),l("")},[n]);const se=async()=>{if(!(!a||!J)){u("writing"),m(t("spoolbuddy.writeTag.waiting","Waiting for SpoolBuddy..."));try{await pa.writeTag(J.device_id,a.id)}catch{u("error"),m(t("spoolbuddy.writeTag.queueFailed","Failed to queue write command"))}}},pe=async()=>{if(J){try{await pa.cancelWrite(J.device_id)}catch{}u("idle"),m("")}},Te=async()=>{G(!0);try{const X=C.replace("#","")+"FF",j=await ge.createSpool({material:b,subtype:null,color_name:_||null,rgba:X,brand:P||null,label_weight:D,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,nozzle_temp_min:null,nozzle_temp_max:null,note:null,added_full:!0,last_used:null,encode_time:null,tag_uid:null,tray_uuid:null,data_origin:null,tag_type:null,cost_per_kg:null,last_scale_weight:null,last_weighed_at:null});s(j),Z()}catch{m(t("spoolbuddy.writeTag.createFailed","Failed to create spool")),u("error")}finally{G(!1)}},q=a&&ae&&c!=="writing"&&c!=="success";return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsx("div",{className:"flex border-b border-bambu-dark-tertiary shrink-0",children:[{key:"existing",label:t("spoolbuddy.writeTag.tabExisting","Existing Spool")},{key:"new",label:t("spoolbuddy.writeTag.tabNew","New Spool")},{key:"replace",label:t("spoolbuddy.writeTag.tabReplace","Replace Tag")}].map(X=>i.jsx("button",{onClick:()=>r(X.key),className:`flex-1 py-3 text-sm font-medium transition-colors ${n===X.key?"text-bambu-green border-b-2 border-bambu-green bg-bambu-dark":"text-zinc-400 hover:text-zinc-200 hover:bg-bambu-dark-tertiary"}`,children:X.label},X.key))}),i.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[i.jsx("div",{className:"flex-1 flex flex-col overflow-hidden border-r border-bambu-dark-tertiary",children:n==="new"?i.jsx(drt,{material:b,setMaterial:g,colorName:_,setColorName:N,colorHex:C,setColorHex:k,brand:P,setBrand:T,weight:D,setWeight:A,creating:R,onSubmit:Te,selectedSpool:a,t}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"p-3 shrink-0",children:i.jsx("input",{type:"text",value:o,onChange:X=>l(X.target.value),placeholder:t("spoolbuddy.writeTag.searchPlaceholder","Search by material, color, brand..."),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})}),i.jsx("div",{className:"flex-1 overflow-y-auto px-3 pb-3 space-y-2",children:Y.length===0?i.jsx("div",{className:"text-center text-zinc-500 py-8 text-sm",children:n==="existing"?t("spoolbuddy.writeTag.noUntaggedSpools","No spools without tags"):t("spoolbuddy.writeTag.noTaggedSpools","No spools with tags")}):Y.map(X=>i.jsx(urt,{spool:X,selected:a?.id===X.id,showTag:n==="replace",onClick:()=>{s(X),u("idle"),m("")}},X.id))})]})}),i.jsx("div",{className:"w-[340px] flex flex-col items-center justify-center p-6 shrink-0",children:i.jsx(mrt,{writeStatus:c,writeMessage:d,selectedSpool:a,tagOnReader:p,tagUid:y,deviceOnline:ae,canWrite:!!q,isReplace:n==="replace",onWrite:se,onCancel:pe,onRetry:()=>{u("idle"),m("")},t})})]})]})}function urt({spool:t,selected:e,showTag:n,onClick:r}){const a=t.rgba?`#${t.rgba.slice(0,6)}`:"#666",s=Math.max(0,t.label_weight-t.weight_used),o=t.label_weight>0?Math.round(s/t.label_weight*100):0;return i.jsxs("button",{onClick:r,className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${e?"bg-bambu-green/15 border border-bambu-green/50":"bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary border border-transparent"}`,children:[i.jsx("div",{className:"w-8 h-8 rounded-full shrink-0 border border-white/10",style:{backgroundColor:a}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("span",{className:"text-sm font-medium text-white truncate",children:[t.brand?`${t.brand} `:"",t.material,t.subtype?` ${t.subtype}`:""]})}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-zinc-400",children:[t.color_name&&i.jsx("span",{children:t.color_name}),i.jsxs("span",{children:[s,"g / ",t.label_weight,"g (",o,"%)"]})]}),n&&t.tag_uid&&i.jsx("div",{className:"text-xs text-zinc-500 mt-0.5 font-mono",children:t.tag_uid})]}),e&&i.jsx("svg",{className:"w-5 h-5 text-bambu-green shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})]})}function drt({material:t,setMaterial:e,colorName:n,setColorName:r,colorHex:a,setColorHex:s,brand:o,setBrand:l,weight:c,setWeight:u,creating:d,onSubmit:m,selectedSpool:p,t:f}){return p?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-6 text-center",children:[i.jsx("div",{className:"w-12 h-12 rounded-full mb-4 border border-white/10",style:{backgroundColor:p.rgba?`#${p.rgba.slice(0,6)}`:"#666"}}),i.jsxs("p",{className:"text-white font-medium",children:[p.brand?`${p.brand} `:"",p.material]}),p.color_name&&i.jsx("p",{className:"text-zinc-400 text-sm",children:p.color_name}),i.jsxs("p",{className:"text-zinc-500 text-xs mt-1",children:[p.label_weight,"g"]}),i.jsx("p",{className:"text-bambu-green text-sm mt-4",children:f("spoolbuddy.writeTag.spoolCreated","Spool created! Ready to write.")})]}):i.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:f("spoolbuddy.writeTag.material","Material")}),i.jsx("select",{value:t,onChange:y=>e(y.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",children:lrt.map(y=>i.jsx("option",{value:y,children:y},y))})]}),i.jsxs("div",{className:"flex gap-3",children:[i.jsxs("div",{className:"flex-1",children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:f("spoolbuddy.writeTag.colorName","Color Name")}),i.jsx("input",{type:"text",value:n,onChange:y=>r(y.target.value),placeholder:"Jade White",className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:f("spoolbuddy.writeTag.color","Color")}),i.jsx("input",{type:"color",value:a,onChange:y=>s(y.target.value),className:"w-10 h-9 bg-transparent border border-bambu-dark-tertiary rounded cursor-pointer"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:f("spoolbuddy.writeTag.brand","Brand")}),i.jsx("input",{type:"text",value:o,onChange:y=>l(y.target.value),placeholder:"Polymaker",className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:f("spoolbuddy.writeTag.weight","Weight (g)")}),i.jsx("input",{type:"number",value:c,onChange:y=>u(parseInt(y.target.value)||0),min:0,max:1e4,className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green"})]}),i.jsx("button",{onClick:m,disabled:d||!t,className:"w-full py-2.5 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded transition-colors",children:d?f("spoolbuddy.writeTag.creating","Creating..."):f("spoolbuddy.writeTag.createSpool","Create Spool")})]})}function mrt({writeStatus:t,writeMessage:e,selectedSpool:n,tagOnReader:r,tagUid:a,deviceOnline:s,canWrite:o,isReplace:l,onWrite:c,onCancel:u,onRetry:d,t:m}){if(t==="success")return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[i.jsx("div",{className:"w-16 h-16 rounded-full bg-green-500/20 flex items-center justify-center",children:i.jsx("svg",{className:"w-8 h-8 text-green-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}),i.jsx("p",{className:"text-green-400 font-medium",children:e}),n&&i.jsxs("p",{className:"text-zinc-400 text-sm",children:[n.brand?`${n.brand} `:"",n.material,n.color_name?` - ${n.color_name}`:""]})]});if(t==="error")return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[i.jsx("div",{className:"w-16 h-16 rounded-full bg-red-500/20 flex items-center justify-center",children:i.jsx("svg",{className:"w-8 h-8 text-red-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),i.jsx("p",{className:"text-red-400 font-medium",children:e}),i.jsx("button",{onClick:d,className:"px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-white text-sm rounded transition-colors",children:m("spoolbuddy.writeTag.tryAgain","Try Again")})]});if(t==="writing")return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[i.jsxs("div",{className:"relative w-16 h-16",children:[i.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-bambu-green/30 animate-ping"}),i.jsx("div",{className:"absolute inset-2 rounded-full border-2 border-bambu-green/50 animate-pulse"}),i.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:i.jsx(Ev,{className:"w-8 h-8 text-bambu-green"})})]}),i.jsx("p",{className:"text-bambu-green font-medium",children:m("spoolbuddy.writeTag.writing","Writing tag...")}),i.jsx("p",{className:"text-zinc-500 text-xs",children:e}),i.jsx("button",{onClick:u,className:"px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-zinc-400 text-sm rounded transition-colors",children:m("spoolbuddy.writeTag.cancel","Cancel")})]});if(!s)return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[i.jsx(Ev,{className:"w-12 h-12 text-zinc-600"}),i.jsx("p",{className:"text-zinc-500 text-sm",children:m("spoolbuddy.writeTag.deviceOffline","SpoolBuddy is offline")})]});if(!n)return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[i.jsx(Ev,{className:"w-12 h-12 text-zinc-600"}),i.jsx("p",{className:"text-zinc-400 text-sm",children:m("spoolbuddy.writeTag.selectSpool","Select a spool, then place a blank NTAG on the reader")})]});const p=n.rgba?`#${n.rgba.slice(0,6)}`:"#666";return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-4 w-full",children:[i.jsx("div",{className:"relative w-16 h-16",children:r?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"absolute inset-0 rounded-full bg-bambu-green/10"}),i.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:i.jsx(Ev,{className:"w-8 h-8 text-bambu-green"})})]}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-zinc-600 animate-pulse"}),i.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:i.jsx(Ev,{className:"w-8 h-8 text-zinc-500"})})]})}),r?i.jsxs("div",{className:"space-y-1",children:[i.jsx("p",{className:"text-bambu-green text-sm font-medium",children:m("spoolbuddy.writeTag.tagReady","Tag detected — ready to write")}),a&&i.jsx("p",{className:"text-zinc-500 text-xs font-mono",children:a})]}):i.jsx("p",{className:"text-zinc-400 text-sm",children:m("spoolbuddy.writeTag.placeTag","Place an NTAG on the reader")}),i.jsxs("div",{className:"w-full bg-bambu-dark-secondary rounded-lg p-3 space-y-2",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-8 h-8 rounded-full border border-white/10 shrink-0",style:{backgroundColor:p}}),i.jsxs("div",{className:"text-left min-w-0",children:[i.jsxs("p",{className:"text-white text-sm font-medium truncate",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&i.jsx("p",{className:"text-zinc-400 text-xs",children:n.color_name})]})]}),i.jsxs("div",{className:"text-xs text-zinc-500",children:[n.label_weight,"g"]})]}),l&&n.tag_uid&&i.jsx("p",{className:"text-yellow-500/80 text-xs",children:m("spoolbuddy.writeTag.replaceWarning","Old tag will be unlinked. New tag will replace it.")}),i.jsx("button",{onClick:c,disabled:!o,className:"w-full py-3 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors text-sm",children:l?m("spoolbuddy.writeTag.replaceTag","Replace Tag"):m("spoolbuddy.writeTag.writeTag","Write Tag")})]})}function Ev({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,children:[i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.288 15.038a5.25 5.25 0 017.424 0M5.106 11.856c3.807-3.808 9.98-3.808 13.788 0M1.924 8.674c5.565-5.565 14.587-5.565 20.152 0"}),i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12.53 18.22l-.53.53-.53-.53a.75.75 0 011.06 0z"})]})}const hrt=new Zme({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function KY({children:t}){return pnt(),i.jsx(i.Fragment,{children:t})}function YY({children:t}){const{authEnabled:e,loading:n,user:r}=Ar();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!r?i.jsx(lx,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function i3({children:t}){const{authEnabled:e,loading:n,user:r,isAdmin:a}=Ar();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?r?a?i.jsx(i.Fragment,{children:t}):i.jsx(lx,{to:"/",replace:!0}):i.jsx(lx,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function prt({children:t}){const{authEnabled:e,loading:n}=Ar();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?i.jsx(lx,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function frt(){return i.jsx(Vbe,{children:i.jsx(Jbe,{children:i.jsx(Jme,{client:hrt,children:i.jsx(Qbe,{children:i.jsx(xme,{children:i.jsxs(Wde,{children:[i.jsx(kr,{path:"/setup",element:i.jsx(prt,{children:i.jsx(mnt,{})})}),i.jsx(kr,{path:"/login",element:i.jsx(dnt,{})}),i.jsx(kr,{path:"/camera/:printerId",element:i.jsx(_tt,{})}),i.jsx(kr,{path:"/overlay/:printerId",element:i.jsx(Ttt,{})}),i.jsxs(kr,{element:i.jsx(YY,{children:i.jsx(KY,{children:i.jsx(Ant,{})})}),children:[i.jsx(kr,{path:"spoolbuddy",element:i.jsx(Wnt,{})}),i.jsx(kr,{path:"spoolbuddy/ams",element:i.jsx(Xnt,{})}),i.jsx(kr,{path:"spoolbuddy/write-tag",element:i.jsx(crt,{})}),i.jsx(kr,{path:"spoolbuddy/settings",element:i.jsx(art,{})}),i.jsx(kr,{path:"spoolbuddy/calibration",element:i.jsx(ort,{})})]}),i.jsxs(kr,{element:i.jsx(YY,{children:i.jsx(KY,{children:i.jsx(hxe,{})})}),children:[i.jsx(kr,{index:!0,element:i.jsx(fVe,{})}),i.jsx(kr,{path:"archives",element:i.jsx(oZe,{})}),i.jsx(kr,{path:"queue",element:i.jsx(VJe,{})}),i.jsx(kr,{path:"stats",element:i.jsx(uet,{})}),i.jsx(kr,{path:"profiles",element:i.jsx(ttt,{})}),i.jsx(kr,{path:"maintenance",element:i.jsx(stt,{})}),i.jsx(kr,{path:"projects",element:i.jsx(ltt,{})}),i.jsx(kr,{path:"projects/:id",element:i.jsx(htt,{})}),i.jsx(kr,{path:"inventory",element:i.jsx(rnt,{})}),i.jsx(kr,{path:"files",element:i.jsx(ytt,{})}),i.jsx(kr,{path:"settings",element:i.jsx(i3,{children:i.jsx(Bet,{})})}),i.jsx(kr,{path:"groups/new",element:i.jsx(i3,{children:i.jsx(LY,{})})}),i.jsx(kr,{path:"groups/:id/edit",element:i.jsx(i3,{children:i.jsx(LY,{})})}),i.jsx(kr,{path:"users",element:i.jsx(lx,{to:"/settings?tab=users",replace:!0})}),i.jsx(kr,{path:"groups",element:i.jsx(lx,{to:"/settings?tab=users",replace:!0})}),i.jsx(kr,{path:"system",element:i.jsx(unt,{})}),i.jsx(kr,{path:"notifications",element:i.jsx(hnt,{})}),i.jsx(kr,{path:"external/:id",element:i.jsx(Att,{})})]})]})})})})})})}Hce.createRoot(document.getElementById("root")).render(i.jsx(w.StrictMode,{children:i.jsx(frt,{})})); diff --git a/static/index.html b/static/index.html index efc63279b..ced97fb81 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +