From ae82cde7bc590f099958bebc95895533884b39c0 Mon Sep 17 00:00:00 2001 From: maziggy Date: Tue, 10 Mar 2026 10:31:18 +0100 Subject: [PATCH 01/10] Change license from MIT to AGPL-3.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prevent unauthorized closed-source redistribution of Bambuddy. AGPL-3.0 requires anyone who modifies and distributes or hosts Bambuddy to share their source code. All prior contributions were made under MIT, which is forward-compatible with AGPL-3.0 β€” no contributor rights are affected. Community usage, forking, and contributions continue as before; the only change is that derivative works must remain open source. Files changed: - LICENSE: replaced MIT with AGPL-3.0 (from gnu.org) - README.md: updated license reference - CHANGELOG.md: documented license change under [0.2.3b1] --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- README.md | 2 +- 2 files changed, 658 insertions(+), 18 deletions(-) diff --git a/LICENSE b/LICENSE index 95c737406..be3f7b28e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,661 @@ -MIT License + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 -Copyright (c) 2025 MartinNYHC + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + Preamble -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md index 064793eee..2278febef 100644 --- a/README.md +++ b/README.md @@ -618,7 +618,7 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. ## πŸ“„ License -MIT License β€” see [LICENSE](LICENSE) for details. +AGPL-3.0 License β€” see [LICENSE](LICENSE) for details. --- From fe6c022be67b92c12fce1000c134e37bfc0fc860 Mon Sep 17 00:00:00 2001 From: maziggy Date: Tue, 10 Mar 2026 10:34:45 +0100 Subject: [PATCH 02/10] Updated CHANGELOG --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7456c8929..20dbe25a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ All notable changes to Bambuddy will be documented in this file. - **ETA Variable in Notifications** ([#638](https://github.com/maziggy/bambuddy/issues/638)) β€” Added `{eta}` template variable to print start, print progress, and queue job started notifications. Shows the estimated wall-clock completion time (e.g. "15:53" or "3:53 PM") based on the user's configured time format (12h/24h). Existing `{estimated_time}` still shows duration ("1h 23m"). Requested by @SebSeifert. - **Bulk Delete Spool and Color Catalog Entries** ([#646](https://github.com/maziggy/bambuddy/issues/646)) β€” Added checkbox selection and bulk delete to both the Spool Catalog and Color Catalog in Settings > Filament. Select individual entries with checkboxes, use the header checkbox to select/deselect all visible entries, then click "Delete Selected" to remove them in one operation. Previously, entries could only be deleted one at a time. Requested by @SebSeifert. +### Changes +- **License changed from MIT to AGPL-3.0** β€” To prevent unauthorized redistribution of Bambuddy as a closed-source product. All existing contributions were made under MIT, which is forward-compatible with AGPL-3.0. Community contributions and usage are unaffected. + ### Improved - **Higher FTP Timeout Options for Large Files** ([#660](https://github.com/maziggy/bambuddy/issues/660)) β€” Added 180s and 300s FTP timeout options in Settings. The previous maximum of 120s was insufficient for large 3MF files (e.g. 28 MB Hueforge models) which can't be downloaded from the printer's FTP server within 2 minutes, especially during active printing. Reported by @PasDoe. - **Separate Permission for AMS Spool Assignments** ([#635](https://github.com/maziggy/bambuddy/issues/635)) β€” Added a new `inventory:view_assignments` permission that controls whether spool-to-AMS-slot assignment data is visible on the Printers page. Previously, viewing spool assignments on printer cards required `inventory:read`, which also exposed the full Inventory page in the sidebar. Admins can now grant `inventory:view_assignments` without `inventory:read` so users can see what's loaded in the AMS without accessing the full spool inventory. All default groups (Administrators, Operators, Viewers) include the new permission automatically. Also fixed multi-word permission labels in the group editor (e.g. "Update_Own" β†’ "Update Own"). Reported by @Minebuddy. From 63208cf6f14f42cfa3f6a1d7d8fd102fad3106fd Mon Sep 17 00:00:00 2001 From: maziggy Date: Tue, 10 Mar 2026 10:51:23 +0100 Subject: [PATCH 03/10] Fix debug logging banner showing negative timer duration The debug logging banner displayed a negative elapsed time (e.g. "-60m -59s") equal to the server's UTC offset. datetime.now() stored local time without a timezone indicator, but the frontend's parseUTCDate() interpreted it as UTC. Use datetime.now(tz=timezone.utc) consistently for storing, parsing, and comparing the enabled_at timestamp. --- CHANGELOG.md | 1 + backend/app/api/routes/support.py | 10 ++++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20dbe25a4..8567924b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ All notable changes to Bambuddy will be documented in this file. - **P2S Shows Carbon Rod Maintenance Tasks** ([#640](https://github.com/maziggy/bambuddy/issues/640)) β€” The P2S was incorrectly classified as a carbon rod printer, showing "Lubricate Carbon Rods" and "Clean Carbon Rods" maintenance tasks. The P2S uses hardened steel linear shafts, not carbon fiber rods. Added a new `steel_rod` motion system category and "Lubricate Steel Rods" / "Clean Steel Rods" maintenance tasks specific to the P2S. X1/P1 series continue to show carbon rod tasks; A1/H2 series continue to show linear rail tasks. Reported by @maziggy. - **Dispatch Toast Stuck After Second Print** β€” The print dispatch progress toast ("Starting prints…") stayed visible forever after the second print dispatch in a session. The dedup guard (`lastDispatchSummaryRef`) that prevents duplicate completion toasts was never reset between batches, so every single-printer dispatch produced the same summary key (`"first-complete:1:0"`). The first print completed normally, but subsequent completions matched the stale ref and skipped creating the done toast β€” leaving the progress toast stuck in "Processing" state with no way to dismiss except a page reload. Now resets the dedup guard whenever the dispatch toast is dismissed (auto-dismiss timeout, cleanup events) and when a new batch starts. - **Archive Card Buttons Overlapping at Narrow Widths** ([#641](https://github.com/maziggy/bambuddy/issues/641)) β€” The "Reprint" and "Schedule" buttons at the bottom of archive cards overlapped when the browser window was narrower than the card grid expected (e.g. snapped to half-screen on a 2K monitor). The button text labels used a viewport-based `sm:` breakpoint that didn't account for actual card width. Added `overflow-hidden` to the flex buttons and `truncate` to the text spans so labels clip cleanly with ellipsis instead of bleeding into adjacent buttons. Reported by rsocko@outlook.com, confirmed by @dsmitty166. +- **Debug Logging Banner Timer Shows Negative Time** β€” When enabling debug logging, the banner showed a negative duration (e.g. "-60m -59s") equal to the server's UTC offset. The `enabled_at` timestamp was stored using `datetime.now()` (local time, no timezone indicator), but the frontend interpreted it as UTC. Now stores and compares all debug logging timestamps in UTC. ## [0.2.2b2] - 2026-03-06 diff --git a/backend/app/api/routes/support.py b/backend/app/api/routes/support.py index cd863ea75..9d7682e06 100644 --- a/backend/app/api/routes/support.py +++ b/backend/app/api/routes/support.py @@ -10,7 +10,7 @@ import os import platform import re import zipfile -from datetime import datetime +from datetime import datetime, timezone from pathlib import Path from fastapi import APIRouter, HTTPException, Query @@ -63,6 +63,8 @@ async def _get_debug_setting(db: AsyncSession) -> tuple[bool, datetime | None]: if enabled_at_setting and enabled_at_setting.value: try: enabled_at = datetime.fromisoformat(enabled_at_setting.value) + if enabled_at.tzinfo is None: + enabled_at = enabled_at.replace(tzinfo=timezone.utc) except ValueError: pass # Ignore malformed timestamp; enabled_at stays None @@ -80,7 +82,7 @@ async def _set_debug_setting(db: AsyncSession, enabled: bool) -> datetime | None db.add(Settings(key="debug_logging_enabled", value=str(enabled).lower())) # Update enabled_at timestamp - enabled_at = datetime.now() if enabled else None + enabled_at = datetime.now(tz=timezone.utc) if enabled else None result = await db.execute(select(Settings).where(Settings.key == "debug_logging_enabled_at")) at_setting = result.scalar_one_or_none() if at_setting: @@ -127,7 +129,7 @@ async def get_debug_logging_state( duration = None if enabled and enabled_at: - duration = int((datetime.now() - enabled_at).total_seconds()) + duration = int((datetime.now(tz=timezone.utc) - enabled_at).total_seconds()) return DebugLoggingState( enabled=enabled, @@ -149,7 +151,7 @@ async def toggle_debug_logging( duration = None if toggle.enabled and enabled_at: - duration = int((datetime.now() - enabled_at).total_seconds()) + duration = int((datetime.now(tz=timezone.utc) - enabled_at).total_seconds()) return DebugLoggingState( enabled=toggle.enabled, From 1b32cc26ccf13e1dc69cb887dc8a81549319660b Mon Sep 17 00:00:00 2001 From: maziggy Date: Tue, 10 Mar 2026 11:36:08 +0100 Subject: [PATCH 04/10] Shorten inventory location labels for compact display AMS slots now show "B3" instead of "AMS-B Slot 3" and external spool holders show "Ext" instead of "External", keeping the table readable at narrow widths. --- CHANGELOG.md | 1 + frontend/src/utils/amsHelpers.ts | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8567924b9..dcb380e39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ All notable changes to Bambuddy will be documented in this file. - **License changed from MIT to AGPL-3.0** β€” To prevent unauthorized redistribution of Bambuddy as a closed-source product. All existing contributions were made under MIT, which is forward-compatible with AGPL-3.0. Community contributions and usage are unaffected. ### Improved +- **Shorter Inventory Location Labels** β€” The location column in the Inventory table now shows compact labels like "H2D-1 B3" instead of "H2D-1 AMS-B Slot 3". External spool holders show "Ext" instead of "External". AMS-HT labels remain unchanged ("HT-A"). - **Higher FTP Timeout Options for Large Files** ([#660](https://github.com/maziggy/bambuddy/issues/660)) β€” Added 180s and 300s FTP timeout options in Settings. The previous maximum of 120s was insufficient for large 3MF files (e.g. 28 MB Hueforge models) which can't be downloaded from the printer's FTP server within 2 minutes, especially during active printing. Reported by @PasDoe. - **Separate Permission for AMS Spool Assignments** ([#635](https://github.com/maziggy/bambuddy/issues/635)) β€” Added a new `inventory:view_assignments` permission that controls whether spool-to-AMS-slot assignment data is visible on the Printers page. Previously, viewing spool assignments on printer cards required `inventory:read`, which also exposed the full Inventory page in the sidebar. Admins can now grant `inventory:view_assignments` without `inventory:read` so users can see what's loaded in the AMS without accessing the full spool inventory. All default groups (Administrators, Operators, Viewers) include the new permission automatically. Also fixed multi-word permission labels in the group editor (e.g. "Update_Own" β†’ "Update Own"). Reported by @Minebuddy. diff --git a/frontend/src/utils/amsHelpers.ts b/frontend/src/utils/amsHelpers.ts index 854fde004..d2f8274d7 100644 --- a/frontend/src/utils/amsHelpers.ts +++ b/frontend/src/utils/amsHelpers.ts @@ -68,12 +68,12 @@ export function formatSlotLabel( isHt: boolean, isExternal: boolean ): string { - if (isExternal) return 'External'; + if (isExternal) return 'Ext'; // Convert AMS ID to letter (A, B, C, D) // AMS-HT uses IDs starting at 128 const letter = String.fromCharCode(65 + (amsId >= 128 ? amsId - 128 : amsId)); if (isHt) return `HT-${letter}`; - return `AMS-${letter} Slot ${trayId + 1}`; + return `${letter}${trayId + 1}`; } /** From f5df4c362340399855baf855c8e800782e3f4ec2 Mon Sep 17 00:00:00 2001 From: maziggy Date: Tue, 10 Mar 2026 11:38:52 +0100 Subject: [PATCH 05/10] Housekeeping --- static/assets/{index-BmG2qPP8.js => index-C6MjeXbO.js} | 2 +- static/index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename static/assets/{index-BmG2qPP8.js => index-C6MjeXbO.js} (98%) diff --git a/static/assets/index-BmG2qPP8.js b/static/assets/index-C6MjeXbO.js similarity index 98% rename from static/assets/index-BmG2qPP8.js rename to static/assets/index-C6MjeXbO.js index 53b25dea9..01764b963 100644 --- a/static/assets/index-BmG2qPP8.js +++ b/static/assets/index-C6MjeXbO.js @@ -8503,7 +8503,7 @@ void main() { border-l-[5px] border-l-transparent border-r-[5px] border-r-transparent border-t-[5px] border-t-bambu-dark-tertiary - `})]})]})}function I$e({isOpen:t,onClose:e,tagUid:n,trayUuid:r,printerId:a,amsId:s,trayId:o}){const{t:l}=Mt(),c=en(),{showToast:d}=xn(),[u,m]=w.useState(""),{data:p,isLoading:f}=Je({queryKey:["inventory-spools"],queryFn:()=>be.getSpools(!1),enabled:t}),x=w.useMemo(()=>p?p.filter(g=>{if(g.tag_uid||g.tray_uuid)return!1;if(!u)return!0;const y=u.toLowerCase();return g.material.toLowerCase().includes(y)||g.brand&&g.brand.toLowerCase().includes(y)||g.color_name&&g.color_name.toLowerCase().includes(y)}):[],[p,u]),v=ut({mutationFn:g=>be.linkTagToSpool(g,{tag_uid:n||void 0,tray_uuid:r||void 0,tag_type:r?"bambulab":"generic",data_origin:"nfc_link"}),onSuccess:()=>{c.invalidateQueries({queryKey:["inventory-spools"]}),c.invalidateQueries({queryKey:["inventory-assignments"]}),d(l("inventory.tagLinked"),"success"),e()},onError:g=>{d(g.message||l("inventory.tagLinkFailed"),"error")}});return t?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 bg-bambu-dark-secondary rounded-xl shadow-xl w-full max-w-md mx-4 max-h-[80vh] flex flex-col border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/10",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(dx,{className:"w-5 h-5 text-bambu-green"}),l("inventory.linkToSpool")]}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["AMS ",s," T",o," Β· Printer #",a]})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 border-b border-white/10",children:[i.jsxs("div",{className:"relative",children:[i.jsx(jr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:u,onChange:g=>m(g.target.value),placeholder:l("inventory.searchSpools"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark rounded-lg border border-white/10 text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),(n||r)&&i.jsxs("p",{className:"text-xs text-bambu-gray mt-2 font-mono truncate",title:n||r,children:["Tag: ",n||r]})]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:f?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):x.length===0?i.jsx("p",{className:"text-center text-bambu-gray py-8 text-sm",children:l("inventory.noSpoolsMatch")}):x.map(g=>i.jsxs("button",{onClick:()=>v.mutate(g.id),disabled:v.isPending,className:"w-full flex items-center gap-3 p-3 rounded-lg hover:bg-white/5 transition-colors text-left",children:[i.jsx("span",{className:"w-6 h-6 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:g.rgba?`#${g.rgba.substring(0,6)}`:"#808080"}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"text-sm text-white font-medium truncate",children:[g.brand?`${g.brand} `:"",g.material,g.subtype?` ${g.subtype}`:""]}),i.jsxs("div",{className:"text-xs text-bambu-gray truncate",children:[g.color_name||"No color"," Β· #",g.id]})]}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(g.label_weight-g.weight_used),"g"]})]},g.id))}),i.jsx("div",{className:"p-4 border-t border-white/10 flex justify-end",children:i.jsx(Oe,{variant:"ghost",onClick:e,children:l("inventory.cancel")||"Cancel"})})]})]}):null}function z$e({isOpen:t,onClose:e,printerId:n,amsId:r,trayId:a,trayInfo:s}){const{t:o}=Mt(),l=en(),{showToast:c}=xn(),[d,u]=w.useState(null),[m,p]=w.useState(""),{data:f,isLoading:x}=Je({queryKey:["inventory-spools"],queryFn:()=>be.getSpools(),enabled:t}),{data:v}=Je({queryKey:["spool-assignments"],queryFn:()=>be.getAssignments(),enabled:t}),g=ut({mutationFn:P=>be.assignSpool({spool_id:P,printer_id:n,ams_id:r,tray_id:a}),onSuccess:P=>{l.setQueryData(["spool-assignments"],k=>{const D=(k||[]).filter(A=>!(A.printer_id===n&&A.ams_id===r&&A.tray_id===a));return D.push(P),D}),l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.assignSuccess"),"success"),e()},onError:P=>{c(`${o("inventory.assignFailed")}: ${P.message}`,"error")}});if(!t)return null;const y=new Set((v||[]).filter(P=>!(P.printer_id===n&&P.ams_id===r&&P.tray_id===a)).map(P=>P.spool_id)),_=r===254||r===255,N=f?.filter(P=>!y.has(P.id)&&(_||!P.tag_uid&&!P.tray_uuid)),C=N?.filter(P=>{if(!m)return!0;const k=m.toLowerCase();return P.material.toLowerCase().includes(k)||(P.brand?.toLowerCase().includes(k)??!1)||(P.color_name?.toLowerCase().includes(k)??!1)||(P.subtype?.toLowerCase().includes(k)??!1)}),T=()=>{d&&g.mutate(d)};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-md mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(oa,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("inventory.assignSpool")})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[s&&i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("p",{className:"text-xs text-bambu-gray mb-1",children:[o("inventory.selectSpool"),":"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[s.color&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20",style:{backgroundColor:`#${s.color}`}}),i.jsx("span",{className:"text-white font-medium",children:s.type||o("ams.emptySlot")}),i.jsxs("span",{className:"text-bambu-gray",children:["(",s.location,")"]})]})]}),i.jsxs("div",{className:"relative",children:[i.jsx(jr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:m,onChange:P=>p(P.target.value),placeholder:o("inventory.searchSpools"),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 focus:outline-none focus:border-bambu-green"})]}),i.jsx("div",{children:x?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):C&&C.length>0?i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-2",children:C.map(P=>i.jsx("button",{onClick:()=>u(P.id),className:`w-full p-3 rounded-lg border text-left transition-colors ${d===P.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 gap-2",children:[P.rgba&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:`#${P.rgba.substring(0,6)}`}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("p",{className:"text-white font-medium truncate",children:[P.brand?`${P.brand} `:"",P.material,P.subtype?` ${P.subtype}`:""]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[P.color_name||"",P.label_weight?` - ${P.label_weight}g`:"",P.label_weight?` (${Math.max(0,Math.round(P.label_weight-P.weight_used))}g ${o("ams.remainingUnit")})`:""]})]}),d===P.id&&i.jsx(Vr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]})},P.id))}):N&&N.length===0?i.jsx("div",{className:"text-center py-8 text-bambu-gray",children:i.jsx("p",{children:o("inventory.noManualSpools")})}):i.jsx("div",{className:"text-center py-8 text-bambu-gray",children:i.jsx("p",{children:o("inventory.noSpoolsMatch")})})})]}),i.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Oe,{variant:"secondary",onClick:e,children:o("common.cancel")}),i.jsx(Oe,{onClick:T,disabled:!d||g.isPending,children:g.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ct,{className:"w-4 h-4 animate-spin"}),o("inventory.assigning")]}):i.jsxs(i.Fragment,{children:[i.jsx(oa,{className:"w-4 h-4"}),o("inventory.assignSpool")]})})]}),g.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:g.error.message})]})]})}function bG(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 B_(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 hv=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function xG(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 hv)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 hv){const o=new RegExp(`\\b${s}\\b`,"i");if(o.test(n)){const l=e.split(o),c=l[0]?.trim()||"",d=l[1]?.trim()||"";return{material:s,brand:c,variant:d}}}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 U$e(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const B$e={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"},yG=[{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"}],vG=[{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 wG(t){const e=t.toLowerCase().trim();return B$e[e]||null}function H$e(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 Xne({isOpen:t,onClose:e,printerId:n,slotInfo:r,nozzleDiameter:a="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=Mt(),[d,u]=w.useState(""),[m,p]=w.useState(null),[f,x]=w.useState(""),[v,g]=w.useState(""),[y,_]=w.useState(""),[N,C]=w.useState(!1),[T,P]=w.useState(!1),k=w.useRef(""),{data:D,isLoading:A,isError:R}=Je({queryKey:["cloudSettings"],queryFn:()=>be.getCloudSettings(),enabled:t,retry:!1}),{data:$,isLoading:U}=Je({queryKey:["localPresets"],queryFn:()=>be.getLocalPresets(),enabled:t}),{data:G,isLoading:L}=Je({queryKey:["builtinFilaments"],queryFn:()=>be.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:te,isLoading:re}=Je({queryKey:["kprofiles",n,a],queryFn:()=>be.getKProfiles(n,a),enabled:t&&!!n}),{data:J}=Je({queryKey:["colorCatalog"],queryFn:()=>be.getColorCatalog(),enabled:t,staleTime:1/0}),ue=ut({mutationFn:async()=>{if(!d)throw new Error("No filament preset selected");const E=d.startsWith("local_"),I=d.startsWith("builtin_"),W=E?parseInt(d.replace("local_",""),10):null,B=I?d.replace("builtin_",""):null,ae=E?$?.filament.find(Be=>Be.id===W):null,z=I?G?.find(Be=>Be.filament_id===B):null,V=!E&&!I?D?.filament.find(Be=>Be.setting_id===d):null;if(!E&&!I&&!V)throw new Error("Selected preset not found");if(E&&!ae)throw new Error("Selected local preset not found");if(I&&!z)throw new Error("Selected builtin preset not found");const ee=E?ae.name:I?z.name:V.name,K=xG(ee),ne=m?.slot_id??-1,se=f||r.trayColor?.slice(0,6)||"FFFFFF",ce=ee.replace(/@.+$/,"").trim();let ge,oe;const O=K.material.toUpperCase();if(E){const Be=(hv.includes(O)?O:ae?.filament_type||K.material||"").toUpperCase(),$e={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"};ge=$e[Be]||$e[Be.replace(/[-\s]?CF$/,"")]||$e[Be.replace(/\+$/,"")]||$e[Be.split(/[-\s]/)[0]]||"",oe=""}else if(I)ge=B,oe="";else if(ge=B_(d),oe=d,!d.startsWith("GFS"))try{const Be=await be.getCloudSettingDetail(d);Be.filament_id?ge=Be.filament_id:Be.base_id&&(ge=B_(Be.base_id),console.log(`Derived tray_info_idx from base_id: ${Be.base_id} -> ${ge}`))}catch(Be){console.warn("Failed to fetch preset detail for filament_id:",Be)}let F=E&&ae?.nozzle_temp_min?ae.nozzle_temp_min:190,X=E&&ae?.nozzle_temp_max?ae.nozzle_temp_max:230;if(!E||I||!ae?.nozzle_temp_min&&!ae?.nozzle_temp_max){const Be=(E?hv.includes(O)?O:ae?.filament_type||K.material||"":K.material).toUpperCase();Be.includes("PLA")?(F=190,X=230):Be.includes("PETG")?(F=220,X=260):Be.includes("ABS")||Be.includes("ASA")?(F=240,X=280):Be.includes("TPU")?(F=200,X=240):Be==="PCTG"?(F=220,X=260):Be.includes("PC")?(F=260,X=300):(Be.includes("PA")||Be.includes("NYLON"))&&(F=250,X=290)}const ye=m?.k_value?parseFloat(m.k_value):0,he=E?hv.includes(O)?O:ae?.filament_type||K.material||"PLA":K.material||"PLA",de=await be.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:ge,tray_type:he,tray_sub_brands:ce,tray_color:se+"FF",nozzle_temp_min:F,nozzle_temp_max:X,cali_idx:ne,nozzle_diameter:a,setting_id:oe,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:ye}),Me=E?`local_${W}`:I?`builtin_${B}`:d,_e=E?"local":I?"builtin":"cloud";try{await be.saveSlotPreset(n,r.amsId,r.trayId,Me,ce,_e)}catch(Be){console.warn("Failed to save slot preset mapping:",Be)}return de},onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),me=ut({mutationFn:async()=>be.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),fe=w.useMemo(()=>{const E=y.toLowerCase(),I=[],W=new Set,B=r.savedPresetId,ae=r.trayInfoIdx;if(D?.filament)for(const z of D.filament){W.add(z.setting_id);const V=B===z.setting_id||ae&&(z.setting_id===ae||B_(z.setting_id)===ae);if(!(!V&&E&&!z.name.toLowerCase().includes(E))){if(!V&&s){const ee=H$e(z.name);if(ee&&ee.toUpperCase()!==s.toUpperCase())continue}I.push({id:z.setting_id,name:z.name,source:"cloud",isUser:U$e(z.setting_id)})}}if($?.filament)for(const z of $.filament){const V=`local_${z.id}`,ee=B===V;if(!(!ee&&E&&!z.name.toLowerCase().includes(E))){if(!ee&&s&&z.compatible_printers){const K=z.compatible_printers.split(";").map(ne=>{const se=ne.trim(),ce=se.match(/^BBL\s+(.+)/i);return ce?ce[1].trim().toUpperCase():se.toUpperCase()}).filter(Boolean);if(K.length>0&&!K.includes(s.toUpperCase()))continue}I.push({id:V,name:z.name,source:"local",isUser:!1})}}if(G)for(const z of G){if(W.has(z.filament_id))continue;const V=z.filament_id.startsWith("GF")?"GFS"+z.filament_id.slice(2):z.filament_id;W.has(V)||(!E||z.name.toLowerCase().includes(E))&&I.push({id:`builtin_${z.filament_id}`,name:z.name,source:"builtin",isUser:!1})}return I.sort((z,V)=>{const ee={cloud:0,local:1,builtin:2};return z.source!==V.source?ee[z.source]-ee[V.source]:z.isUser&&!V.isUser?-1:!z.isUser&&V.isUser?1:z.name.localeCompare(V.name)})},[D?.filament,$?.filament,G,y,s,r.savedPresetId,r.trayInfoIdx]),Q=w.useMemo(()=>{if(!d)return null;let E=null;if(d.startsWith("local_")){const B=parseInt(d.replace("local_",""),10);E=$?.filament.find(z=>z.id===B)?.name||null}else if(d.startsWith("builtin_")){const B=d.replace("builtin_","");E=G?.find(z=>z.filament_id===B)?.name||null}else D?.filament&&(E=D.filament.find(ae=>ae.setting_id===d)?.name||null);if(!E)return null;let I=E.replace(/@.+$/,"").trim();I.startsWith("# ")&&(I=I.slice(2).trim());const W=xG(I);return{fullName:I,material:W.material,brand:W.brand}},[d,D?.filament,$?.filament,G]),ie=Q?.fullName||"",le=w.useMemo(()=>{if(!J||!Q)return[];const{fullName:E,brand:I}=Q,W=E.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return J.filter(B=>{const ae=(B.material||"").toUpperCase(),z=B.manufacturer.toUpperCase();if(!(ae===W.toUpperCase()||ae.includes(W.toUpperCase())||W.toUpperCase().includes(ae)))return!1;if(I){const ee=I.toUpperCase();if(!z.includes(ee)&&!ee.includes(z))return!1}return!0})},[J,Q]),pe=w.useMemo(()=>{if(!te?.profiles||!Q)return[];const{fullName:E,material:I,brand:W}=Q,B=E.toUpperCase(),ae=I.toUpperCase(),z=W.toUpperCase();if(!ae||ae.length<2)return[];const V=te.profiles.filter(K=>{const ne=K.name.toUpperCase();if(z)return!(!ne.includes(z)||!ne.includes(ae));if(ne.includes(B)||ne.includes(ae))return!0;const ce={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[ae]||[];for(const ge of ce)if(ne.includes(ge))return!0;return!1}),ee=new Map;for(const K of V){const ne=`${K.name}|${K.k_value}`,se=ee.get(ne);se?r.extruderId!==void 0&&K.extruder_id===r.extruderId&&se.extruder_id!==r.extruderId&&ee.set(ne,K):ee.set(ne,K)}return Array.from(ee.values())},[te?.profiles,Q,r.extruderId]);w.useEffect(()=>{if(t){if(r.savedPresetId)u(r.savedPresetId);else if(r.trayInfoIdx&&D?.filament){let E=D.filament.find(I=>I.setting_id===r.trayInfoIdx);E||(E=D.filament.find(I=>B_(I.setting_id)===r.trayInfoIdx)),E&&u(E.setting_id)}else if(r.trayInfoIdx&&G?.length){const E=r.trayInfoIdx,I=G.find(W=>W.filament_id===E);I&&u(`builtin_${I.filament_id}`)}if(r.trayColor){const E=r.trayColor.slice(0,6);E&&x(E)}}else u(""),p(null),x(""),g(""),_(""),C(!1),k.current=""},[t,r.savedPresetId,r.trayInfoIdx,r.trayColor,D?.filament,G]),w.useEffect(()=>{if(pe.length>0){if(r.caliIdx!=null&&r.caliIdx>0){const E=pe.find(I=>I.slot_id===r.caliIdx);if(E){p(E);return}}p(pe[0])}else p(null)},[d,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||U||L||re;if(w.useEffect(()=>{if(!q&&d&&d!==k.current){const E=requestAnimationFrame(()=>{const W=document.querySelector('[class*="fixed inset-0 z-50"]')?.querySelector(`[data-preset-id="${CSS.escape(d)}"]`);W&&(k.current=d,W.scrollIntoView({block:"nearest"}))});return()=>cancelAnimationFrame(E)}},[d,q]),!t)return null;const Z=d&&!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(du,{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-white/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),i.jsx("span",{className:"text-white/70",children:c("configureAmsSlot.slotLabel",{ams:bG(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(zt,{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(Eb,{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-white/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),i.jsx("span",{className:"text-white font-medium",children:c("configureAmsSlot.slotLabel",{ams:bG(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(ct,{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:y,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:fe.length===0?i.jsx("p",{className:"text-center py-4 text-bambu-gray",children:D?.filament?.length===0&&!$?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):fe.map(E=>i.jsx("button",{"data-preset-id":E.id,onClick:()=>u(E.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${d===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"),ie&&i.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ie})})]}),pe.length>0?i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:m?.name||"",onChange:E=>{const I=pe.find(W=>W.name===E.target.value);p(I||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(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?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")}),le.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:Q?.fullName})}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:le.map(E=>i.jsxs("button",{onClick:()=>{const I=E.hex_color.replace("#","").toUpperCase();x(I),g(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-white/30 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:[yG.map(E=>i.jsx("button",{onClick:()=>{x(E.hex),g(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(!T),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(T?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:T?"βˆ’":"+"})]}),T&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:vG.map(E=>i.jsx("button",{onClick:()=>{x(E.hex),g(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 I=E.target.value;g(I);const W=wG(I);if(W)x(W);else{const B=I.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();B.length===6?x(B):B.length===3&&x(B.split("").map(ae=>ae+ae).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:()=>{x(""),g("")},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:y,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:fe.length===0?i.jsx("p",{className:"text-center py-4 text-bambu-gray",children:D?.filament?.length===0&&!$?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):fe.map(E=>i.jsx("button",{"data-preset-id":E.id,onClick:()=>u(E.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${d===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"),ie&&i.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ie})})]}),pe.length>0?i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:m?.name||"",onChange:E=>{const I=pe.find(W=>W.name===E.target.value);p(I||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(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?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")}),le.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:Q?.fullName})}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:le.map(E=>i.jsxs("button",{onClick:()=>{const I=E.hex_color.replace("#","").toUpperCase();x(I),g(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-white/30 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:[yG.map(E=>i.jsx("button",{onClick:()=>{x(E.hex),g(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(!T),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(T?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:T?"βˆ’":"+"})]}),T&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:vG.map(E=>i.jsx("button",{onClick:()=>{x(E.hex),g(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 I=E.target.value;g(I);const W=wG(I);if(W)x(W);else{const B=I.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();B.length===6?x(B):B.length===3&&x(B.split("").map(ae=>ae+ae).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:()=>{x(""),g("")},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(Oe,{variant:"secondary",onClick:()=>me.mutate(),disabled:me.isPending||ue.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:me.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ct,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):i.jsxs(i.Fragment,{children:[i.jsx(mo,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Oe,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),i.jsx(Oe,{onClick:()=>ue.mutate(),disabled:!Z,children:ue.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ct,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):i.jsxs(i.Fragment,{children:[i.jsx(du,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(ue.isError||me.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||me.error?.message})]})]})}function Qne({folderId:t,onClose:e,onUploadComplete:n,onFileUploaded:r,autoUpload:a,validateFile:s,accept:o}){const{t:l}=Mt(),[c,d]=w.useState([]),[u,m]=w.useState(!1),[p,f]=w.useState(!1),[x,v]=w.useState(!0),[g,y]=w.useState(!1),[_,N]=w.useState(!0),[C,T]=w.useState(null),P=w.useRef(null),k=fe=>{fe.preventDefault(),m(!0)},D=fe=>{fe.preventDefault(),m(!1)},A=fe=>{fe.preventDefault(),m(!1),G(Array.from(fe.dataTransfer.files))},R=fe=>{fe.target.files&&G(Array.from(fe.target.files))},$=(fe,Q)=>{d(ie=>ie.map(le=>le.file===fe?{...le,...Q}:le))},U=async fe=>{f(!0);for(const Q of fe)if(Q.status==="pending"){$(Q.file,{status:"uploading"});try{if(Q.isZip){const ie=await be.extractZipFile(Q.file,t,x,g,_);$(Q.file,{status:ie.errors.length>0&&ie.extracted===0?"error":"success",extractedCount:ie.extracted,error:ie.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:ie.errors.length}):void 0})}else{const ie=await be.uploadLibraryFile(Q.file,t,_);$(Q.file,{status:"success"});const le=r?.(ie);if(le){T(le),d([]),f(!1);return}}}catch(ie){$(Q.file,{status:"error",error:ie instanceof Error?ie.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),n(),e()},G=fe=>{if(T(null),s)for(const ie of fe){const le=s(ie);if(le){T(le);return}}const Q=fe.map(ie=>({file:ie,status:"pending",isZip:ie.name.toLowerCase().endsWith(".zip"),is3mf:ie.name.toLowerCase().endsWith(".3mf")}));d(ie=>[...ie,...Q]),a&&fe.length>0&&U(Q)},L=fe=>{d(Q=>Q.filter((ie,le)=>le!==fe))},te=c.some(fe=>fe.isZip&&fe.status==="pending"),re=c.some(fe=>fe.file.name.toLowerCase().endsWith(".stl")&&fe.status==="pending"),J=c.some(fe=>fe.is3mf&&fe.status==="pending"),ue=c.filter(fe=>fe.status==="pending").length,me=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(zt,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("div",{onDragOver:k,onDragLeave:D,onDrop:A,onClick:()=>P.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${u?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[i.jsx(Si,{className:`w-10 h-10 mx-auto mb-3 ${u?"text-bambu-green":"text-bambu-gray"}`}),i.jsx("p",{className:"text-white font-medium",children:l(u?"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}),te&&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(Os,{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:x,onChange:fe=>v(fe.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:g,onChange:fe=>y(fe.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")})]})]})]})}),J&&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")})]})]})}),(re||te)&&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(cu,{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(te&&!re?"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:fe=>N(fe.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((fe,Q)=>i.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[fe.isZip?i.jsx(Os,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):i.jsx(lC,{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:fe.file.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[(fe.file.size/1024/1024).toFixed(2)," MB",fe.isZip&&fe.status==="pending"&&i.jsxs("span",{className:"text-blue-400 ml-2",children:["β€’ ",l("fileManager.willBeExtracted")]}),fe.extractedCount!==void 0&&i.jsxs("span",{className:"text-green-400 ml-2",children:["β€’ ",l("fileManager.filesExtracted",{count:fe.extractedCount})]})]})]}),fe.status==="pending"&&i.jsx("button",{onClick:()=>L(Q),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(zt,{className:"w-4 h-4 text-bambu-gray"})}),fe.status==="uploading"&&i.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"}),fe.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-500"}),fe.status==="error"&&i.jsx("span",{title:fe.error,children:i.jsx(Vi,{className:"w-4 h-4 text-red-500"})})]},Q))}),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(Oe,{variant:"secondary",onClick:e,children:l("common.cancel")}),!me&&i.jsx(Oe,{onClick:()=>U(c),disabled:ue===0||p,children:p?i.jsxs(i.Fragment,{children:[i.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(Si,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",ue>0?`(${ue})`:""]})})]})]})})}function SG(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Oi(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}function qc(t,e,n=40){const r=Oi(t),a=Oi(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),d=parseInt(a.substring(2,4),16),u=parseInt(a.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-d)<=n&&Math.abs(l-u)<=n}function F4(t,e,n,r){if(r)return"External";const a=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${a}`:`AMS-${a} Slot ${e+1}`}function ok(t,e,n){return n?254+e:t>=128?t:t*4+e}function _G(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(Qn(t)?.getTime()??0)>e}function $$e(t,e,n){const r=Zne(e,t.nozzle_id),a=r.find(l=>!n.has(l.globalTrayId)&&l.type?.toUpperCase()===t.type?.toUpperCase()&&Oi(l.color)===Oi(t.color)),s=a?void 0:r.find(l=>!n.has(l.globalTrayId)&&l.type?.toUpperCase()===t.type?.toUpperCase()&&qc(l.color,t.color)),o=a||s?void 0:r.find(l=>!n.has(l.globalTrayId)&&l.type?.toUpperCase()===t.type?.toUpperCase());return a??s??o}function Zne(t,e){return t.filter(n=>e==null||n.extruderId===e)}function kT(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=SG(o.tray_color);e.push({type:o.tray_type,color:l,colorName:au(l),amsId:a.id,trayId:o.id,isHt:s,isExternal:!1,label:F4(a.id,o.id,s,!1),globalTrayId:ok(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=SG(a.tray_color),o=a.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:a.tray_type,color:s,colorName:au(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 NG(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=kT(e);if(n.length===0)return;const r=new Set,a=t.filaments.map(l=>{const c=l.tray_info_idx||"";let d=n.filter(v=>!r.has(v.globalTrayId));l.nozzle_id!=null&&(d=d.filter(v=>v.extruderId===l.nozzle_id));let u,m,p,f;if(c){const v=d.filter(g=>g.trayInfoIdx===c);v.length===1?u=v[0]:v.length>1&&(m=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&Oi(g.color)===Oi(l.color)),m||(p=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&qc(g.color,l.color))),!m&&!p&&(f=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase())))}!u&&!m&&!p&&!f&&(m=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Oi(v.color)===Oi(l.color)),m||(p=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&qc(v.color,l.color))),!m&&!p&&(f=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase())));const x=u||m||p||f||void 0;return x&&r.add(x.globalTrayId),{slot_id:l.slot_id,globalTrayId:x?.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 q$e(t){return w.useMemo(()=>kT(t),[t])}function Jne(t,e,n){const r=q$e(e),a=w.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const c=new Set(Object.values(n));return t.filaments.map(d=>{const u=d.slot_id||0;if(u>0&&n[u]!==void 0){const P=n[u],k=r.find(D=>D.globalTrayId===P);if(k){const D=k.type?.toUpperCase()===d.type?.toUpperCase(),A=Oi(k.color)===Oi(d.color)||qc(k.color,d.color);let R;return D&&A?R="match":D?R="type_only":R="mismatch",{...d,loaded:k,hasFilament:!0,typeMatch:D,colorMatch:A,status:R,isManual:!0}}}const m=d.tray_info_idx||"";let p=r.filter(P=>!c.has(P.globalTrayId));d.nozzle_id!=null&&(p=p.filter(P=>P.extruderId===d.nozzle_id));let f,x,v,g;if(m){const P=p.filter(k=>k.trayInfoIdx===m);P.length===1?f=P[0]:P.length>1&&(x=P.find(k=>k.type?.toUpperCase()===d.type?.toUpperCase()&&Oi(k.color)===Oi(d.color)),x||(v=P.find(k=>k.type?.toUpperCase()===d.type?.toUpperCase()&&qc(k.color,d.color))),!x&&!v&&(g=P.find(k=>k.type?.toUpperCase()===d.type?.toUpperCase())))}!f&&!x&&!v&&!g&&(x=p.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase()&&Oi(P.color)===Oi(d.color)),x||(v=p.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase()&&qc(P.color,d.color))),!x&&!v&&(g=p.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase())));const y=f||x||v||g||void 0;y&&c.add(y.globalTrayId);const _=!!y,N=_,C=!!f||!!x||!!v;let T;return f||x||v?T="match":g?T="type_only":T="mismatch",{...d,loaded:y,hasFilament:_,typeMatch:N,colorMatch:C,status:T,isManual:!1}})},[t,r,n]),s=w.useMemo(()=>{if(a.length===0)return;const c=Math.max(...a.map(u=>u.slot_id||0));if(c<=0)return;const d=new Array(c).fill(-1);return a.forEach(u=>{u.slot_id&&u.slot_id>0&&(d[u.slot_id-1]=u.loaded?.globalTrayId??-1)}),d},[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 V$e(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 d of t){const u=d.slot_id||0;if(u>0&&n[u]!==void 0){const g=n[u],y=e.find(_=>_.globalTrayId===g);if(y){const _=y.type?.toUpperCase()===d.type?.toUpperCase(),N=Oi(y.color)===Oi(d.color)||qc(y.color,d.color);_&&N?r++:_?a++:s++;continue}}let m=e.filter(g=>!o.has(g.globalTrayId));if(d.nozzle_id!=null){const g=m.filter(y=>y.extruderId===d.nozzle_id);g.length>0&&(m=g)}const p=m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Oi(g.color)===Oi(d.color)),f=p?void 0:m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&qc(g.color,d.color)),x=p||f?void 0:m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()),v=p??f??x;v&&o.add(v.globalTrayId),p||f?r++:x?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 G$e(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=kT(e);if(r.length===0)return;const a=new Set(Object.values(n)),s=[];for(const c of t.filaments){const d=c.slot_id||0;if(d>0&&n[d]!==void 0){s.push({slot_id:d,globalTrayId:n[d]});continue}let u=r.filter(v=>!a.has(v.globalTrayId));if(c.nozzle_id!=null){const v=u.filter(g=>g.extruderId===c.nozzle_id);v.length>0&&(u=v)}const m=u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Oi(v.color)===Oi(c.color)),p=m?void 0:u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&qc(v.color,c.color)),f=m||p?void 0:u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()),x=m??p??f;x&&a.add(x.globalTrayId),s.push({slot_id:d,globalTrayId:x?.globalTrayId??-1})}const o=Math.max(...s.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return s.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}const kG={useDefault:!0,manualMappings:{},autoConfigured:!1};function W$e(t,e,n,r,a,s){const o=bf({queries:t.map(x=>({queryKey:["printer-status",x],queryFn:()=>be.getPrinterStatus(x),enabled:t.length>0,staleTime:5e3}))}),l=w.useMemo(()=>t.map((x,v)=>{const g=o[v],y=g?.data,N=e?.find(R=>R.id===x)?.name||`Printer ${x}`,C=kT(y),T=a[x]||kG,P=NG(n,y),k=T.useDefault?r:T.manualMappings,D=G$e(n,y,k),A=V$e(n?.filaments,C,k);return{printerId:x,printerName:N,status:y,isLoading:g?.isLoading??!1,loadedFilaments:C,autoMapping:P,finalMapping:D,matchStatus:A.status,exactMatches:A.exactMatches,typeOnlyMatches:A.typeOnlyMatches,missingTypes:A.missingTypes,totalSlots:A.totalSlots,config:T}}),[t,o,e,n,a,r]),c=o.some(x=>x.isLoading),d=(x,v)=>{s(g=>({...g,[x]:{...g[x]||kG,...v}}))},u=x=>{const v=l.find(_=>_.printerId===x);if(!v||!v.status||!n?.filaments)return;const g=NG(n,v.status);if(!g)return;const y={};g.forEach((_,N)=>{_!==-1&&(y[N+1]=_)}),d(x,{useDefault:!1,manualMappings:y,autoConfigured:!0})},m=()=>{for(const x of t)u(x)},p=x=>l.find(g=>g.printerId===x)?.finalMapping,f=l.every(x=>x.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:a,updatePrinterConfig:d,autoConfigureAll:m,autoConfigurePrinter:u,getFinalMapping:p,allPrintersReady:f}}const ere={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 ol(t){return ere[t.toUpperCase()]||t}const K$e=Object.entries(ere).map(([t,e])=>({code:t,label:`${t} (${e})`}));function Y$e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,currencySymbol:a,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=Mt(),c=en(),[d,u]=w.useState(!1),[m,p]=w.useState(o),{data:f}=Je({queryKey:["printer-status",t],queryFn:()=>be.getPrinterStatus(t),enabled:!!t}),{data:x}=Je({queryKey:["spool-assignments",t],queryFn:()=>be.getAssignments(t),enabled:!!t}),{loadedFilaments:v,filamentComparison:g,hasTypeMismatch:y,hasColorMismatch:_}=Jne(e,f,n),N=w.useMemo(()=>{const U=new Map;for(const G of x||[]){const L=G.ams_id===255,te=ok(G.ams_id,G.tray_id,L);U.set(te,G.spool?.cost_per_kg??null)}return U},[x]),C=w.useMemo(()=>{const U=new Map;for(const G of x||[]){const L=G.ams_id===255,te=ok(G.ams_id,G.tray_id,L),re=G.spool;if(!re){U.set(te,null);continue}U.set(te,Math.max(0,Math.round((re.label_weight??0)-(re.weight_used??0))))}return U},[x]),T=w.useMemo(()=>{let U=0;for(const G of g){const L=G.loaded?.globalTrayId;if(L==null)continue;const re=N.get(L)??null??s;re>0&&(U+=G.used_grams/1e3*re)}return U},[g,N,s]),P=w.useMemo(()=>Array.from(N.values()).some(U=>U!=null&&U>0),[N]),k=e?.filaments&&e.filaments.length>0,D=e?.filaments?.some(U=>U.nozzle_id!=null)??!1;if(!k||!f)return null;const A=y?"#f97316":_?"#facc15":"#00ae42",R=(U,G)=>{if(U>0)if(G===""){const L={...n};delete L[U],r(L)}else r({...n,[U]:parseInt(G,10)})},$=async()=>{u(!0);try{await be.refreshPrinterStatus(t),await new Promise(U=>setTimeout(U,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{u(!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(U1,{className:"w-4 h-4",fill:A,stroke:"none"}),i.jsx("span",{children:l("printModal.filamentMapping")}),y?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(Sl,{className:"w-4 h-4 ml-auto"}):i.jsx(Fn,{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:$,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:d,children:[i.jsx(Sr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),i.jsx("span",{children:"Re-read"})]})]}),g.map((U,G)=>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} - ${au(U.color)}`,children:i.jsx(U1,{className:"w-3 h-3",fill:U.color,stroke:U.color})}),i.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[D&&U.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:U.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:U.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),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:U.loaded?.globalTrayId??"",onChange:L=>R(U.slot_id||0,L.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 ${U.status==="match"?"border-bambu-green/50 text-bambu-green":U.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${U.isManual?"ring-1 ring-blue-400/50":""}`,title:U.isManual?"Manually selected":"Auto-matched",children:[i.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),v.filter(L=>U.nozzle_id==null||L.extruderId===U.nozzle_id).map(L=>{const te=C.get(L.globalTrayId),re=te!=null?l("printModal.slotRemainingShort",{grams:te,defaultValue:` - ${te}g left`}):"";return i.jsxs("option",{value:L.globalTrayId,className:"bg-bambu-dark text-white",children:[L.label,": ",L.traySubBrands||L.type," (",L.colorName,")",re]},L.globalTrayId)})]}),U.status==="match"?i.jsx(Vr,{className:"w-3 h-3 text-bambu-green"}):U.status==="type_only"?i.jsx("span",{title:"Same type, different color",children:i.jsx(An,{className:"w-3 h-3 text-yellow-400"})}):i.jsx("span",{title:"Filament type not loaded",children:i.jsx(An,{className:"w-3 h-3 text-orange-400"})})]},G)),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",i.jsx("span",{className:"text-white",children:T>0||P?`${a}${T.toFixed(2)}`:"N/A"})]}),y&&i.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function X$e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:r,forceColorMatch:a,onForceColorMatchChange:s}){const{t:o}=Mt(),l=w.useMemo(()=>{const u={};for(const m of e){const p=m.type.toUpperCase();u[p]||(u[p]=[]),u[p].push(m)}return u},[e]),c=t?.filaments;if(!c||c.length===0||e.length===0)return null;const d=(u,m)=>{if(m===""){const p={...n};delete p[u],r(p)}else{const[p,f]=m.split("|");r({...n,[u]:{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(u=>{const m=n[u.slot_id],p=!!m,f=l[u.type.toUpperCase()]||[],x=u.nozzle_id!=null?f.filter(v=>v.extruder_id==null||v.extruder_id===u.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")}: ${u.type} - ${au(u.color)}`,children:i.jsx(U1,{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:p?`${m.type}|${m.color}`:"",onChange:v=>d(u.slot_id,v.target.value),disabled:x.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"),": ",u.type," (",au(u.color),")"]}),x.map((v,g)=>i.jsxs("option",{value:`${v.type}|${v.color}`,className:"bg-bambu-dark text-white",children:[v.tray_sub_brands||v.type," (",au(v.color),")"]},`${v.type}-${v.color}-${v.tray_sub_brands}-${g}`))]}),p?i.jsx("button",{type:"button",onClick:()=>d(u.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:o("printModal.resetToOriginal"),children:i.jsx(mo,{className:"w-3 h-3"})}):i.jsx("span",{className:"w-3"})]}),i.jsxs("label",{className:"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?.[u.slot_id]??!1,onChange:v=>s?.(u.slot_id,v.target.checked),className:"accent-bambu-green w-3 h-3"}),i.jsx(R0,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},u.slot_id)})})]})}function Q$e({plates:t,isMultiPlate:e,selectedPlate:n,onSelect:r,queueAll:a,onQueueAllChange:s}){const{t:o}=Mt();return!e||t.length<=1?null: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.jsx("span",{className:"text-sm text-bambu-gray",children:"Select Plate to Print"}),!n&&!a&&i.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[i.jsx(An,{className:"w-3 h-3"}),"Selection required"]}),s&&i.jsx("button",{type:"button",onClick:()=>s(!a),className:`ml-auto text-xs px-2 py-0.5 rounded-full border transition-colors ${a?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray"}`,children:o("queue.queueAllPlates",{count:t.length})})]}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(l=>i.jsxs("button",{type:"button",onClick:()=>{a&&s&&s(!1),r(l.index)},className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${a||n===l.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[l.has_thumbnail&&l.thumbnail_url!=null?i.jsx("img",{src:l.thumbnail_url,alt:`Plate ${l.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:l.name||`Plate ${l.index}`}),i.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[l.objects.length>0?l.objects.slice(0,3).join(", ")+(l.objects.length>3?"...":""):`${l.filaments.length} filament${l.filaments.length!==1?"s":""}`,l.print_time_seconds!=null?` β€’ ${js(l.print_time_seconds)}`:""]})]}),(a||n===l.index)&&i.jsx(Vr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},l.index))})]})}const Z$e=new Set(["IDLE","FINISH","FAILED"]);function J$e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=en(),[a,s]=w.useState(!1),o=(d,u)=>{if(d<=0)return;const m={...t.config.manualMappings};u===""?delete m[d]:m[d]=parseInt(u,10),n({useDefault:!1,manualMappings:m,autoConfigured:!1})},l=async()=>{s(!0);try{await be.refreshPrinterStatus(t.printerId),await new Promise(d=>setTimeout(d,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(d=>{const u=d.slot_id||0,m=t.config.manualMappings[u];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=$$e(d,t.loadedFilaments,v)}let x="mismatch";if(p){const v=p.type?.toUpperCase()===d.type?.toUpperCase(),g=Oi(p.color)===Oi(d.color)||qc(p.color,d.color);v&&g?x="match":v&&(x="type_only")}return{req:d,loaded:p,status:x,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:d,loaded:u,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: ${d.type} - ${au(d.color)}`,children:i.jsx(U1,{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:u?.globalTrayId??"",onChange:x=>o(d.slot_id||0,x.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${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 --"}),Zne(t.loadedFilaments,d.nozzle_id).map(x=>i.jsxs("option",{value:x.globalTrayId,className:"bg-bambu-dark text-white",children:[x.label,": ",x.traySubBrands||x.type," (",x.colorName,")"]},x.globalTrayId))]}),m==="match"?i.jsx(Vr,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?i.jsx("span",{title:"Same type, different color",children:i.jsx(An,{className:"w-3 h-3 text-yellow-400"})}):i.jsx("span",{title:"Filament type not loaded",children:i.jsx(An,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function eqe({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:a=!1,showInactive:s=!1,disableBusy:o=!1,printerMappingResults:l,filamentReqs:c,onAutoConfigurePrinter:d,onUpdatePrinterConfig:u,assignmentMode:m="printer",onAssignmentModeChange:p,targetModel:f,onTargetModelChange:x,targetLocation:v,onTargetLocationChange:g,slicedForModel:y}){const[_,N]=w.useState(!1),C=s?t:t.filter(ie=>ie.is_active),T=bf({queries:C.map(ie=>({queryKey:["printerStatus",ie.id],queryFn:()=>be.getPrinterStatus(ie.id),staleTime:5e3}))}),P=w.useMemo(()=>{const ie=new Map;return C.forEach((le,pe)=>{const Te=T[pe];Te?.data&&ie.set(le.id,Te.data)}),ie},[C,T]),k=ie=>{const le=P.get(ie);return le?le.connected?!Z$e.has(le.state??""):!0:!1},D=ie=>{const le=P.get(ie);if(!le)return null;if(!le.connected)return"Offline";const pe=le.state;return pe?pe==="RUNNING"?le.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"||!y||_)return C;const ie=C.filter(le=>le.model===y);return ie.length>0?ie:C},[C,m,y,_]),R=C.length-A.length,$=w.useMemo(()=>{const ie=C.map(le=>le.model).filter(le=>!!le);return[...new Set(ie)].sort()},[C]),U=w.useMemo(()=>{if(!f)return[];const ie=C.filter(le=>le.model===f&&le.location).map(le=>le.location).filter(le=>!!le);return[...new Set(ie)].sort()},[C,f]),G=p&&x&&$.length>0,L=a&&e.length>1&&l&&c?.filaments&&c.filaments.length>0&&d&&u;if(r)return i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(ct,{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(zi,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const te=ie=>{o&&k(ie)||(a?e.includes(ie)?n(e.filter(le=>le!==ie)):n([...e,ie]):n([ie]))},re=()=>{const ie=o?A.filter(le=>!k(le.id)):A;n(ie.map(le=>le.id))},J=()=>{n([])},ue=(ie,le,pe)=>{pe.stopPropagation(),!(!d||!u)&&(le?d(ie):u(ie,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},me=ie=>e.includes(ie),fe=e.length,Q=ie=>l?.find(le=>le.printerId===ie);return i.jsxs("div",{className:"space-y-2 mb-6",children:[G&&i.jsxs("div",{className:"flex gap-2 mb-4",children:[i.jsxs("button",{type:"button",onClick:()=>{p("printer"),x(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 ie=y&&$.includes(y)?y:$[0];x(ie)},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(_m,{className:"w-4 h-4"}),i.jsxs("span",{className:"text-sm",children:["Any ",y||"Model"]})]})]}),m==="model"&&G&&i.jsxs("div",{className:"space-y-3 mb-4",children:[!y&&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:ie=>{x(ie.target.value||null),g&&g(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..."}),$.map(ie=>i.jsx("option",{value:ie,children:ie},ie))]})]}),f&&U.length>0&&g&&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:ie=>g(ie.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"}),U.map(ie=>i.jsx("option",{value:ie,children:ie},ie))]})]}),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:fe===0?"Select printers":`${fe} printer${fe!==1?"s":""} selected`}),i.jsxs("div",{className:"flex gap-2",children:[fe0&&i.jsx("button",{type:"button",onClick:J,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&A.map(ie=>{const le=me(ie.id),pe=Q(ie.id),Te=pe&&!pe.config.useDefault,q=k(ie.id),Z=o&&q,j=D(ie.id);return i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>te(ie.id),disabled:Z,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${Z?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":le?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${ie.is_active?"":"opacity-60"}`,children:[i.jsx("div",{className:`p-2 rounded-lg ${Z?"bg-bambu-dark-tertiary":le?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:i.jsx(_r,{className:`w-5 h-5 ${Z?"text-bambu-gray/50":le?"text-bambu-green":"text-bambu-gray"}`})}),i.jsxs("div",{className:"text-left flex-1",children:[i.jsxs("p",{className:`font-medium ${Z?"text-bambu-gray":"text-white"}`,children:[ie.name,!ie.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:[ie.model||"Unknown model"," β€’ ",ie.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 ${Z?"border-bambu-gray/30":le?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:le&&i.jsx(Vr,{className:"w-3 h-3 text-white"})})]}),le&&L&&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(ie.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(),d(ie.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(Bge,{className:"w-3 h-3"}),"Auto"]})]}),Te&&i.jsx(J$e,{printerResult:pe,filamentReqs:c.filaments,onUpdateConfig:E=>u(ie.id,E)})]})]},ie.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(An,{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"&&_&&y&&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 ",y," printers"]})}),m==="printer"&&fe===0&&i.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[i.jsx(zi,{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(zi,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const tqe=[{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 nqe({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(gC,{className:"w-4 h-4"}),i.jsx("span",{children:"Print Options"}),r?i.jsx(Sl,{className:"w-4 h-4 ml-auto"}):i.jsx(Fn,{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:tqe.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 rqe({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system",canControlPrinter:a=!0}){const[s,o]=w.useState(""),[l,c]=w.useState(""),[d,u]=w.useState(!0),[m,p]=w.useState(!0),f=w.useRef(null),x=w.useRef(!1);w.useEffect(()=>{if(t.scheduleType!=="scheduled"){x.current=!1;return}if(!x.current){x.current=!0;let T;t.scheduledTime?(T=new Date(t.scheduledTime),isNaN(T.getTime())&&(T=new Date,T.setHours(T.getHours()+1,0,0,0))):(T=new Date,T.setHours(T.getHours()+1,0,0,0),e({...t,scheduledTime:jD(T)})),o(ED(T,n)),c(l8(T,r)),u(!0),p(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const v=T=>{e({...t,scheduleType:T})},g=(T,P)=>{const k=ube(T,n),D=mbe(P);u(!!k),p(!!D),k&&D&&(k.setHours(D.hours,D.minutes,0,0),k>new Date&&e({...t,scheduledTime:jD(k)}))},y=T=>{o(T),g(T,l)},_=T=>{c(T),g(s,T)},N=T=>{const P=T.target.value;if(P){const k=new Date(P);isNaN(k.getTime())||(o(ED(k,n)),c(l8(k,r)),u(!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(GY,{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 ${d?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:s,onChange:T=>y(T.target.value),placeholder:lbe(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:T=>_(T.target.value),placeholder:cbe(r)})})]}),i.jsx("input",{ref:f,type:"datetime-local",className:"sr-only",value:t.scheduledTime,onChange:N,tabIndex:-1}),(!d||!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:T=>e({...t,requirePreviousSuccess:T.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:T=>e({...t,autoOffAfter:T.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(_u,{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 qg={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},iqe={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function Vc({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:a,initialSelectedPrinterIds:s,onClose:o,onSuccess:l}){const{t:c}=Mt(),d=en(),{showToast:u}=xn(),{hasPermission:m}=Dr(),p=!!n&&!e,[f,x]=w.useState(()=>t==="edit-queue-item"&&a?.printer_id?[a.printer_id]:s?.length?s:[]),[v,g]=w.useState(()=>t==="edit-queue-item"&&a?a.plate_id:null),[y,_]=w.useState(!1),[N,C]=w.useState(()=>t==="edit-queue-item"&&a?{bed_levelling:a.bed_levelling??qg.bed_levelling,flow_cali:a.flow_cali??qg.flow_cali,vibration_cali:a.vibration_cali??qg.vibration_cali,layer_inspect:a.layer_inspect??qg.layer_inspect,timelapse:a.timelapse??qg.timelapse}:qg),[T,P]=w.useState(()=>{if(t==="edit-queue-item"&&a){let lt="asap";a.manual_start?lt="manual":a.scheduled_time&&!_G(a.scheduled_time)&&(lt="scheduled");let ht="";if(a.scheduled_time&&!_G(a.scheduled_time)){const qe=Qn(a.scheduled_time)??new Date;ht=jD(qe)}return{scheduleType:lt,scheduledTime:ht,requirePreviousSuccess:a.require_previous_success,autoOffAfter:a.auto_off_after}}return iqe}),[k,D]=w.useState(()=>{if(t==="edit-queue-item"&&a?.ams_mapping&&Array.isArray(a.ams_mapping)){const lt={};return a.ams_mapping.forEach((ht,qe)=>{ht!==-1&&(lt[qe+1]=ht)}),lt}return{}}),[A,R]=w.useState({}),[$,U]=w.useState(()=>t==="edit-queue-item"&&a?.target_model?"model":"printer"),[G,L]=w.useState(()=>t==="edit-queue-item"&&a?.target_model?a.target_model:null),[te,re]=w.useState(()=>t==="edit-queue-item"&&a?.target_location?a.target_location:null),[J,ue]=w.useState(()=>{if(t==="edit-queue-item"&&a?.filament_overrides){const lt={};for(const ht of a.filament_overrides)lt[ht.slot_id]={type:ht.type,color:ht.color};return lt}return{}}),[me,fe]=w.useState(()=>{if(t==="edit-queue-item"&&a?.filament_overrides){const lt={};for(const ht of a.filament_overrides)lt[ht.slot_id]=ht.force_color_match===!0;return lt}return{}}),[Q]=w.useState(()=>t==="edit-queue-item"&&a?.printer_id?[a.printer_id]:[]),[ie]=w.useState(()=>t==="edit-queue-item"&&a?a.plate_id:null),[le,pe]=w.useState(!1),[Te,q]=w.useState({current:0,total:0}),[Z,j]=w.useState(new Set),E=f.length,I=f.length>0?f[0]:null,{data:W}=Je({queryKey:["settings"],queryFn:be.getSettings}),B=ol(W?.currency||"USD"),ae=W?.default_filament_cost??0,{data:z,isLoading:V}=Je({queryKey:["printers"],queryFn:be.getPrinters}),{data:ee}=Je({queryKey:["archive",e],queryFn:()=>be.getArchive(e),enabled:!!e&&!p}),{data:K}=Je({queryKey:["library-file",n],queryFn:()=>be.getLibraryFile(n),enabled:p&&!!n}),ne=ee?.sliced_for_model||K?.sliced_for_model||null,{data:se,isError:ce}=Je({queryKey:["archive-plates",e],queryFn:()=>be.getArchivePlates(e),enabled:!!e&&!p,retry:!1}),{data:ge}=Je({queryKey:["library-file-plates",n],queryFn:()=>be.getLibraryFilePlates(n),enabled:p&&!!n}),oe=p?ge:se,{data:O,isError:F}=Je({queryKey:["archive-filaments",e,v],queryFn:()=>be.getArchiveFilamentRequirements(e,v??void 0),enabled:!!e&&!p&&(v!==null||!oe?.is_multi_plate),retry:!1}),{data:X}=Je({queryKey:["library-file-filaments",n,v],queryFn:()=>be.getLibraryFileFilamentRequirements(n,v??void 0),enabled:p&&!!n&&(v!==null||!oe?.is_multi_plate)}),ye=!p&&(ce||F),he=p?X:O,de=w.useMemo(()=>{if(!(v===null||!oe?.plates?.length))return oe.plates.find(lt=>lt.index===v)?.name||void 0},[oe,v]),{data:Me}=Je({queryKey:["available-filaments",G,te],queryFn:()=>be.getAvailableFilaments(G,te??void 0),enabled:$==="model"&&!!G}),{data:_e}=Je({queryKey:["printer-status",I],queryFn:()=>be.getPrinterStatus(I),enabled:!!I}),{amsMapping:Be}=Jne(he,_e,k),$e=W$e(f,z,he,k,A,R);w.useEffect(()=>{oe?.plates&&oe.plates.length>=1&&!v&&g(oe.plates[0].index)},[oe,v]),w.useEffect(()=>{if(t==="edit-queue-item")return;const lt=z?.filter(ht=>ht.is_active)||[];lt.length===1&&f.length===0&&x([lt[0].id])},[t,z,f.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(f.sort())!==JSON.stringify(Q.sort())||v!==ie)&&(D({}),R({}),j(new Set)):(D({}),R({}),j(new Set))},[t,f,v,Q,ie]);const[Le,ke]=w.useState(G),[Ee,Ne]=w.useState(v);w.useEffect(()=>{(G!==Le||v!==Ee)&&(ke(G),Ne(v),(t!=="edit-queue-item"||Le!==null)&&(ue({}),fe({})))},[G,v,Le,Ee,t]),w.useEffect(()=>{if(!W?.per_printer_mapping_expanded||f.length<=1)return;const lt=f.filter(ht=>{if(Z.has(ht))return!1;const qe=$e.printerResults.find(pt=>pt.printerId===ht);return qe&&qe.status&&!qe.isLoading});lt.length>0&&(j(ht=>{const qe=new Set(ht);return lt.forEach(pt=>qe.add(pt)),qe}),lt.forEach(ht=>{$e.autoConfigurePrinter(ht)}))},[W?.per_printer_mapping_expanded,f,Z,$e]),w.useEffect(()=>{const lt=ht=>{ht.key==="Escape"&&!le&&o()};return window.addEventListener("keydown",lt),()=>window.removeEventListener("keydown",lt)},[o,le]);const Ae=oe?.is_multi_plate??!1,Ge=oe?.plates??[],xe=ut({mutationFn:lt=>be.addToQueue(lt)}),He=ut({mutationFn:lt=>be.updateQueueItem(a.id,lt),onSuccess:()=>{d.invalidateQueries({queryKey:["queue"]}),u("Queue item updated"),l?.(),o()},onError:lt=>{u(lt.message||"Failed to update queue item","error")}}),Pe=async lt=>{if(lt?.preventDefault(),$==="printer"&&f.length===0){u("Please select at least one printer","error");return}if($==="model"&&!G){u("Please select a target printer model","error");return}pe(!0);const ht=y?Ge:[null],qe=$==="model"?ht.length:f.length*ht.length;q({current:0,total:qe});const pt={success:0,failed:0,errors:[]},xt=Yt=>{if(f.length>1){const Ht=A[Yt];if(Ht&&!Ht.useDefault)return $e.getFinalMapping(Yt)}return Be},nn=(()=>{const Yt=[];if(he?.filaments)for(const Ht of he.filaments){const tn=J[Ht.slot_id],ln=me[Ht.slot_id]??!1,mn=tn?.type??Ht.type,fn=tn?.color??Ht.color;(tn||ln)&&Yt.push({slot_id:Ht.slot_id,type:mn,color:fn,color_name:au(fn),force_color_match:ln})}else for(const[Ht,{type:tn,color:ln}]of Object.entries(J)){const mn=parseInt(Ht,10),fn=me[mn]??!1;Yt.push({slot_id:mn,type:tn,color:ln,color_name:au(ln),force_color_match:fn})}return Yt.length>0?Yt:void 0})(),sn=(Yt,Ht)=>({printer_id:$==="printer"?Yt:null,target_model:$==="model"?G:null,target_location:$==="model"?te:null,filament_overrides:$==="model"?nn:void 0,archive_id:p?void 0:e,library_file_id:p?n:void 0,require_previous_success:T.requirePreviousSuccess,auto_off_after:T.autoOffAfter,manual_start:T.scheduleType==="manual",ams_mapping:Yt?xt(Yt):void 0,plate_id:Ht!==void 0?Ht:v,scheduled_time:T.scheduleType==="scheduled"&&T.scheduledTime?new Date(T.scheduledTime).toISOString():void 0,...N});if($==="model"){if(t==="reprint"){u("Model-based assignment only works with queue mode","error"),pe(!1);return}let Yt=0;for(const Ht of ht){Yt++,q({current:Yt,total:qe});const tn=Ht?Ht.index:v;try{if(t==="edit-queue-item"&&!Ht){const ln={printer_id:null,target_model:G,target_location:te,filament_overrides:nn||null,require_previous_success:T.requirePreviousSuccess,auto_off_after:T.autoOffAfter,manual_start:T.scheduleType==="manual",ams_mapping:void 0,plate_id:tn,scheduled_time:T.scheduleType==="scheduled"&&T.scheduledTime?new Date(T.scheduledTime).toISOString():null,...N};await He.mutateAsync(ln)}else await xe.mutateAsync(sn(null,tn));pt.success++}catch(ln){pt.failed++;const mn=Ht?Ht.name||`Plate ${Ht.index}`:"";pt.errors.push(mn?`${mn}: ${ln.message}`:ln.message)}}}else{let Yt=0;for(const Ht of ht){const tn=Ht?Ht.index:v;for(let ln=0;lntt.id===mn)?.name||`Printer ${mn}`,je=Ht?Ht.name||`Plate ${Ht.index}`:"",Ze=je?`${Ue} (${je})`:Ue;pt.errors.push(`${Ze}: ${fn.message}`)}}}}pe(!1),pt.failed===0?(t!=="reprint"&&(t==="edit-queue-item"?u("Queue item updated"):pt.success===1?u($==="model"?`Queued for any ${G}`:c("queue.printQueued")):u(c("queue.itemsQueued",{count:pt.success}))),d.invalidateQueries({queryKey:["queue"]}),l?.(),o()):pt.success===0?u(`Failed: ${pt.errors[0]}`,"error"):(u(`${pt.success} succeeded, ${pt.failed} failed`,"error"),d.invalidateQueries({queryKey:["queue"]}))},Ve=le||He.isPending,De=w.useMemo(()=>!(Ve||$==="printer"&&f.length===0||$==="model"&&!G||$==="model"&&t==="reprint"||Ae&&!v&&!y),[f.length,$,G,t,Ae,v,y,Ve]),we=(()=>{const lt=f.length;if(t==="reprint")return{title:c(p?"queue.print":"queue.reprint"),icon:_r,submitText:lt>1?c("queue.printToPrinters",{count:lt}):c("queue.print"),submitIcon:_r,loadingText:Te.total>1?c("queue.sendingProgress",{current:Te.current,total:Te.total}):c("queue.sending")};if(t==="add-to-queue"){let ht=c("queue.addToQueue");return y&&Ge.length>1?ht=c("queue.queueAllPlates",{count:Ge.length}):lt>1&&(ht=c("queue.queueToPrinters",{count:lt})),{title:c("queue.schedulePrint"),icon:Xr,submitText:ht,submitIcon:Xr,loadingText:Te.total>1?c("queue.addingProgress",{current:Te.current,total:Te.total}):c("queue.adding")}}return{title:c("queue.editQueueItem"),icon:Ki,submitText:c("common.save"),submitIcon:Ki,loadingText:Te.total>1?c("queue.savingProgress",{current:Te.current,total:Te.total}):c("common.saving")}})(),Ke=we.icon,ot=we.submitIcon,St=I&&!y&&(p||(Ae?v!==null:!0));return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:le?void 0:o,children:i.jsx(Tt,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:lt=>lt.stopPropagation(),children:i.jsxs(Pt,{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(Ke,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:we.title})]}),i.jsx(Oe,{variant:"ghost",size:"sm",onClick:o,disabled:le,children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:Pe,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&&z?i.jsx("span",{className:"text-white",children:z.find(lt=>lt.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(Q$e,{plates:Ge,isMultiPlate:Ae,selectedPlate:v,onSelect:g,queueAll:y,onQueueAllChange:t==="add-to-queue"?_:void 0}),!s?.length&&i.jsx(eqe,{printers:z||[],selectedPrinterIds:f,onMultiSelect:x,isLoading:V,allowMultiple:!0,showInactive:t==="edit-queue-item",disableBusy:t==="reprint",printerMappingResults:$e.printerResults,filamentReqs:he,onAutoConfigurePrinter:$e.autoConfigurePrinter,onUpdatePrinterConfig:$e.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":$,onAssignmentModeChange:t!=="reprint"?U:void 0,targetModel:G,onTargetModelChange:t!=="reprint"?L:void 0,targetLocation:te,onTargetLocationChange:t!=="reprint"?re:void 0,slicedForModel:ne}),$==="model"&&G&&he&&Me&&Me.length>0&&i.jsx(X$e,{filamentReqs:he,availableFilaments:Me,overrides:J,onChange:ue,forceColorMatch:me,onForceColorMatchChange:(lt,ht)=>fe(qe=>({...qe,[lt]:ht}))}),ne&&$==="printer"&&f.length===1&&(()=>{const lt=z?.find(ht=>ht.id===f[0]);return lt&<.model&&ne!==lt.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(An,{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 ",ne,", but printing on ",lt.model]})]}):null})(),ye&&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(zi,{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."})]}),St&&!ye&&f.length===1&&i.jsx(Y$e,{printerId:I,filamentReqs:he,manualMappings:k,onManualMappingChange:D,defaultExpanded:!!s?.length||(W?.per_printer_mapping_expanded??!1),currencySymbol:B,defaultCostPerKg:ae}),(t==="reprint"||E>0||$==="model"&&G)&&i.jsx(nqe,{options:N,onChange:C,defaultExpanded:!!s?.length}),t!=="reprint"&&i.jsx(rqe,{options:T,onChange:P,dateFormat:W?.date_format||"system",timeFormat:W?.time_format||"system",canControlPrinter:m("printers:control")}),He.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:He.error?.message||"Failed to complete operation"}),i.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[i.jsx(Oe,{type:"button",variant:"secondary",onClick:o,className:"flex-1",disabled:le,children:"Cancel"}),i.jsx(Oe,{type:"submit",disabled:!De,className:"flex-1",children:Ve?i.jsxs(i.Fragment,{children:[i.jsx(ct,{className:"w-4 h-4 animate-spin"}),we.loadingText]}):i.jsxs(i.Fragment,{children:[i.jsx(ot,{className:"w-4 h-4"}),we.submitText]})})]})]})]})})})}function CG({value:t}){const{t:e}=Mt(),[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(Vr,{className:"w-3.5 h-3.5 text-bambu-green"}):i.jsx(_l,{className:"w-3.5 h-3.5"})})}function aqe({printer:t,status:e,totalPrintHours:n,onClose:r}){const{t:a}=Mt();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(CG,{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(CG,{value:t.serial_number})]})}),e?.wifi_signal!=null){const o=RQ(e.wifi_signal);s.push({label:a("printers.wifiSignalLabel"),value:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(QY,{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:Wp(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(Tt,{className:"w-full max-w-md",onClick:o=>o.stopPropagation(),children:i.jsxs(Pt,{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(zt,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsx("div",{className:"flex justify-center mb-4",children:i.jsx("img",{src:DQ(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 sqe(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 sj({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&&sqe(t)?"#000":"#fff"},children:r})})}const TG={"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"},oqe={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 oj(t){if(!t)return null;if(TG[t])return TG[t];const e=t.split("-");if(e.length<2)return null;const n=e[1];return oqe[n]||null}function lj(t){return(t??.02).toFixed(3)}function PG({side:t}){const{mode:e}=xf(),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 tre(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 nre(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function rre({slot:t,index:e,activeStatus:n,filamentName:r,children:a}){const{t:s}=Mt(),[o,l]=w.useState(!1),[c,d]=w.useState("top"),u=w.useRef(null),m=w.useRef(null),p=w.useRef(null),f=!t.nozzle_diameter&&!t.nozzle_type,x=t.stat===1;w.useEffect(()=>{if(o&&u.current&&m.current){const C=u.current.getBoundingClientRect(),T=m.current.offsetHeight,k=C.top-56,D=window.innerHeight-C.bottom;kk?d("bottom"):d("top")}},[o]);const v=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},g=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const y=R4(t.filament_color),_=tre(t.nozzle_type,s),N=nre(t.nozzle_type,s);return i.jsxs("div",{ref:u,className:"relative",onMouseEnter:v,onMouseLeave:g,children:[a,o&&i.jsxs("div",{ref:m,className:` + `})]})]})}function I$e({isOpen:t,onClose:e,tagUid:n,trayUuid:r,printerId:a,amsId:s,trayId:o}){const{t:l}=Mt(),c=en(),{showToast:d}=xn(),[u,m]=w.useState(""),{data:p,isLoading:f}=Je({queryKey:["inventory-spools"],queryFn:()=>be.getSpools(!1),enabled:t}),x=w.useMemo(()=>p?p.filter(g=>{if(g.tag_uid||g.tray_uuid)return!1;if(!u)return!0;const y=u.toLowerCase();return g.material.toLowerCase().includes(y)||g.brand&&g.brand.toLowerCase().includes(y)||g.color_name&&g.color_name.toLowerCase().includes(y)}):[],[p,u]),v=ut({mutationFn:g=>be.linkTagToSpool(g,{tag_uid:n||void 0,tray_uuid:r||void 0,tag_type:r?"bambulab":"generic",data_origin:"nfc_link"}),onSuccess:()=>{c.invalidateQueries({queryKey:["inventory-spools"]}),c.invalidateQueries({queryKey:["inventory-assignments"]}),d(l("inventory.tagLinked"),"success"),e()},onError:g=>{d(g.message||l("inventory.tagLinkFailed"),"error")}});return t?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 bg-bambu-dark-secondary rounded-xl shadow-xl w-full max-w-md mx-4 max-h-[80vh] flex flex-col border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/10",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(dx,{className:"w-5 h-5 text-bambu-green"}),l("inventory.linkToSpool")]}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["AMS ",s," T",o," Β· Printer #",a]})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 border-b border-white/10",children:[i.jsxs("div",{className:"relative",children:[i.jsx(jr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:u,onChange:g=>m(g.target.value),placeholder:l("inventory.searchSpools"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark rounded-lg border border-white/10 text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),(n||r)&&i.jsxs("p",{className:"text-xs text-bambu-gray mt-2 font-mono truncate",title:n||r,children:["Tag: ",n||r]})]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:f?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):x.length===0?i.jsx("p",{className:"text-center text-bambu-gray py-8 text-sm",children:l("inventory.noSpoolsMatch")}):x.map(g=>i.jsxs("button",{onClick:()=>v.mutate(g.id),disabled:v.isPending,className:"w-full flex items-center gap-3 p-3 rounded-lg hover:bg-white/5 transition-colors text-left",children:[i.jsx("span",{className:"w-6 h-6 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:g.rgba?`#${g.rgba.substring(0,6)}`:"#808080"}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"text-sm text-white font-medium truncate",children:[g.brand?`${g.brand} `:"",g.material,g.subtype?` ${g.subtype}`:""]}),i.jsxs("div",{className:"text-xs text-bambu-gray truncate",children:[g.color_name||"No color"," Β· #",g.id]})]}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(g.label_weight-g.weight_used),"g"]})]},g.id))}),i.jsx("div",{className:"p-4 border-t border-white/10 flex justify-end",children:i.jsx(Oe,{variant:"ghost",onClick:e,children:l("inventory.cancel")||"Cancel"})})]})]}):null}function z$e({isOpen:t,onClose:e,printerId:n,amsId:r,trayId:a,trayInfo:s}){const{t:o}=Mt(),l=en(),{showToast:c}=xn(),[d,u]=w.useState(null),[m,p]=w.useState(""),{data:f,isLoading:x}=Je({queryKey:["inventory-spools"],queryFn:()=>be.getSpools(),enabled:t}),{data:v}=Je({queryKey:["spool-assignments"],queryFn:()=>be.getAssignments(),enabled:t}),g=ut({mutationFn:P=>be.assignSpool({spool_id:P,printer_id:n,ams_id:r,tray_id:a}),onSuccess:P=>{l.setQueryData(["spool-assignments"],k=>{const D=(k||[]).filter(A=>!(A.printer_id===n&&A.ams_id===r&&A.tray_id===a));return D.push(P),D}),l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.assignSuccess"),"success"),e()},onError:P=>{c(`${o("inventory.assignFailed")}: ${P.message}`,"error")}});if(!t)return null;const y=new Set((v||[]).filter(P=>!(P.printer_id===n&&P.ams_id===r&&P.tray_id===a)).map(P=>P.spool_id)),_=r===254||r===255,N=f?.filter(P=>!y.has(P.id)&&(_||!P.tag_uid&&!P.tray_uuid)),C=N?.filter(P=>{if(!m)return!0;const k=m.toLowerCase();return P.material.toLowerCase().includes(k)||(P.brand?.toLowerCase().includes(k)??!1)||(P.color_name?.toLowerCase().includes(k)??!1)||(P.subtype?.toLowerCase().includes(k)??!1)}),T=()=>{d&&g.mutate(d)};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-md mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(oa,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("inventory.assignSpool")})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[s&&i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("p",{className:"text-xs text-bambu-gray mb-1",children:[o("inventory.selectSpool"),":"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[s.color&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20",style:{backgroundColor:`#${s.color}`}}),i.jsx("span",{className:"text-white font-medium",children:s.type||o("ams.emptySlot")}),i.jsxs("span",{className:"text-bambu-gray",children:["(",s.location,")"]})]})]}),i.jsxs("div",{className:"relative",children:[i.jsx(jr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:m,onChange:P=>p(P.target.value),placeholder:o("inventory.searchSpools"),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 focus:outline-none focus:border-bambu-green"})]}),i.jsx("div",{children:x?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):C&&C.length>0?i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-2",children:C.map(P=>i.jsx("button",{onClick:()=>u(P.id),className:`w-full p-3 rounded-lg border text-left transition-colors ${d===P.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 gap-2",children:[P.rgba&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:`#${P.rgba.substring(0,6)}`}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("p",{className:"text-white font-medium truncate",children:[P.brand?`${P.brand} `:"",P.material,P.subtype?` ${P.subtype}`:""]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[P.color_name||"",P.label_weight?` - ${P.label_weight}g`:"",P.label_weight?` (${Math.max(0,Math.round(P.label_weight-P.weight_used))}g ${o("ams.remainingUnit")})`:""]})]}),d===P.id&&i.jsx(Vr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]})},P.id))}):N&&N.length===0?i.jsx("div",{className:"text-center py-8 text-bambu-gray",children:i.jsx("p",{children:o("inventory.noManualSpools")})}):i.jsx("div",{className:"text-center py-8 text-bambu-gray",children:i.jsx("p",{children:o("inventory.noSpoolsMatch")})})})]}),i.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Oe,{variant:"secondary",onClick:e,children:o("common.cancel")}),i.jsx(Oe,{onClick:T,disabled:!d||g.isPending,children:g.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ct,{className:"w-4 h-4 animate-spin"}),o("inventory.assigning")]}):i.jsxs(i.Fragment,{children:[i.jsx(oa,{className:"w-4 h-4"}),o("inventory.assignSpool")]})})]}),g.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:g.error.message})]})]})}function bG(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 B_(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 hv=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function xG(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 hv)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 hv){const o=new RegExp(`\\b${s}\\b`,"i");if(o.test(n)){const l=e.split(o),c=l[0]?.trim()||"",d=l[1]?.trim()||"";return{material:s,brand:c,variant:d}}}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 U$e(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const B$e={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"},yG=[{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"}],vG=[{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 wG(t){const e=t.toLowerCase().trim();return B$e[e]||null}function H$e(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 Xne({isOpen:t,onClose:e,printerId:n,slotInfo:r,nozzleDiameter:a="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=Mt(),[d,u]=w.useState(""),[m,p]=w.useState(null),[f,x]=w.useState(""),[v,g]=w.useState(""),[y,_]=w.useState(""),[N,C]=w.useState(!1),[T,P]=w.useState(!1),k=w.useRef(""),{data:D,isLoading:A,isError:R}=Je({queryKey:["cloudSettings"],queryFn:()=>be.getCloudSettings(),enabled:t,retry:!1}),{data:$,isLoading:U}=Je({queryKey:["localPresets"],queryFn:()=>be.getLocalPresets(),enabled:t}),{data:G,isLoading:L}=Je({queryKey:["builtinFilaments"],queryFn:()=>be.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:te,isLoading:re}=Je({queryKey:["kprofiles",n,a],queryFn:()=>be.getKProfiles(n,a),enabled:t&&!!n}),{data:J}=Je({queryKey:["colorCatalog"],queryFn:()=>be.getColorCatalog(),enabled:t,staleTime:1/0}),ue=ut({mutationFn:async()=>{if(!d)throw new Error("No filament preset selected");const E=d.startsWith("local_"),I=d.startsWith("builtin_"),W=E?parseInt(d.replace("local_",""),10):null,B=I?d.replace("builtin_",""):null,ae=E?$?.filament.find(Be=>Be.id===W):null,z=I?G?.find(Be=>Be.filament_id===B):null,V=!E&&!I?D?.filament.find(Be=>Be.setting_id===d):null;if(!E&&!I&&!V)throw new Error("Selected preset not found");if(E&&!ae)throw new Error("Selected local preset not found");if(I&&!z)throw new Error("Selected builtin preset not found");const ee=E?ae.name:I?z.name:V.name,K=xG(ee),ne=m?.slot_id??-1,se=f||r.trayColor?.slice(0,6)||"FFFFFF",ce=ee.replace(/@.+$/,"").trim();let ge,oe;const O=K.material.toUpperCase();if(E){const Be=(hv.includes(O)?O:ae?.filament_type||K.material||"").toUpperCase(),$e={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"};ge=$e[Be]||$e[Be.replace(/[-\s]?CF$/,"")]||$e[Be.replace(/\+$/,"")]||$e[Be.split(/[-\s]/)[0]]||"",oe=""}else if(I)ge=B,oe="";else if(ge=B_(d),oe=d,!d.startsWith("GFS"))try{const Be=await be.getCloudSettingDetail(d);Be.filament_id?ge=Be.filament_id:Be.base_id&&(ge=B_(Be.base_id),console.log(`Derived tray_info_idx from base_id: ${Be.base_id} -> ${ge}`))}catch(Be){console.warn("Failed to fetch preset detail for filament_id:",Be)}let F=E&&ae?.nozzle_temp_min?ae.nozzle_temp_min:190,X=E&&ae?.nozzle_temp_max?ae.nozzle_temp_max:230;if(!E||I||!ae?.nozzle_temp_min&&!ae?.nozzle_temp_max){const Be=(E?hv.includes(O)?O:ae?.filament_type||K.material||"":K.material).toUpperCase();Be.includes("PLA")?(F=190,X=230):Be.includes("PETG")?(F=220,X=260):Be.includes("ABS")||Be.includes("ASA")?(F=240,X=280):Be.includes("TPU")?(F=200,X=240):Be==="PCTG"?(F=220,X=260):Be.includes("PC")?(F=260,X=300):(Be.includes("PA")||Be.includes("NYLON"))&&(F=250,X=290)}const ye=m?.k_value?parseFloat(m.k_value):0,he=E?hv.includes(O)?O:ae?.filament_type||K.material||"PLA":K.material||"PLA",de=await be.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:ge,tray_type:he,tray_sub_brands:ce,tray_color:se+"FF",nozzle_temp_min:F,nozzle_temp_max:X,cali_idx:ne,nozzle_diameter:a,setting_id:oe,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:ye}),Me=E?`local_${W}`:I?`builtin_${B}`:d,_e=E?"local":I?"builtin":"cloud";try{await be.saveSlotPreset(n,r.amsId,r.trayId,Me,ce,_e)}catch(Be){console.warn("Failed to save slot preset mapping:",Be)}return de},onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),me=ut({mutationFn:async()=>be.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),fe=w.useMemo(()=>{const E=y.toLowerCase(),I=[],W=new Set,B=r.savedPresetId,ae=r.trayInfoIdx;if(D?.filament)for(const z of D.filament){W.add(z.setting_id);const V=B===z.setting_id||ae&&(z.setting_id===ae||B_(z.setting_id)===ae);if(!(!V&&E&&!z.name.toLowerCase().includes(E))){if(!V&&s){const ee=H$e(z.name);if(ee&&ee.toUpperCase()!==s.toUpperCase())continue}I.push({id:z.setting_id,name:z.name,source:"cloud",isUser:U$e(z.setting_id)})}}if($?.filament)for(const z of $.filament){const V=`local_${z.id}`,ee=B===V;if(!(!ee&&E&&!z.name.toLowerCase().includes(E))){if(!ee&&s&&z.compatible_printers){const K=z.compatible_printers.split(";").map(ne=>{const se=ne.trim(),ce=se.match(/^BBL\s+(.+)/i);return ce?ce[1].trim().toUpperCase():se.toUpperCase()}).filter(Boolean);if(K.length>0&&!K.includes(s.toUpperCase()))continue}I.push({id:V,name:z.name,source:"local",isUser:!1})}}if(G)for(const z of G){if(W.has(z.filament_id))continue;const V=z.filament_id.startsWith("GF")?"GFS"+z.filament_id.slice(2):z.filament_id;W.has(V)||(!E||z.name.toLowerCase().includes(E))&&I.push({id:`builtin_${z.filament_id}`,name:z.name,source:"builtin",isUser:!1})}return I.sort((z,V)=>{const ee={cloud:0,local:1,builtin:2};return z.source!==V.source?ee[z.source]-ee[V.source]:z.isUser&&!V.isUser?-1:!z.isUser&&V.isUser?1:z.name.localeCompare(V.name)})},[D?.filament,$?.filament,G,y,s,r.savedPresetId,r.trayInfoIdx]),Q=w.useMemo(()=>{if(!d)return null;let E=null;if(d.startsWith("local_")){const B=parseInt(d.replace("local_",""),10);E=$?.filament.find(z=>z.id===B)?.name||null}else if(d.startsWith("builtin_")){const B=d.replace("builtin_","");E=G?.find(z=>z.filament_id===B)?.name||null}else D?.filament&&(E=D.filament.find(ae=>ae.setting_id===d)?.name||null);if(!E)return null;let I=E.replace(/@.+$/,"").trim();I.startsWith("# ")&&(I=I.slice(2).trim());const W=xG(I);return{fullName:I,material:W.material,brand:W.brand}},[d,D?.filament,$?.filament,G]),ie=Q?.fullName||"",le=w.useMemo(()=>{if(!J||!Q)return[];const{fullName:E,brand:I}=Q,W=E.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return J.filter(B=>{const ae=(B.material||"").toUpperCase(),z=B.manufacturer.toUpperCase();if(!(ae===W.toUpperCase()||ae.includes(W.toUpperCase())||W.toUpperCase().includes(ae)))return!1;if(I){const ee=I.toUpperCase();if(!z.includes(ee)&&!ee.includes(z))return!1}return!0})},[J,Q]),pe=w.useMemo(()=>{if(!te?.profiles||!Q)return[];const{fullName:E,material:I,brand:W}=Q,B=E.toUpperCase(),ae=I.toUpperCase(),z=W.toUpperCase();if(!ae||ae.length<2)return[];const V=te.profiles.filter(K=>{const ne=K.name.toUpperCase();if(z)return!(!ne.includes(z)||!ne.includes(ae));if(ne.includes(B)||ne.includes(ae))return!0;const ce={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[ae]||[];for(const ge of ce)if(ne.includes(ge))return!0;return!1}),ee=new Map;for(const K of V){const ne=`${K.name}|${K.k_value}`,se=ee.get(ne);se?r.extruderId!==void 0&&K.extruder_id===r.extruderId&&se.extruder_id!==r.extruderId&&ee.set(ne,K):ee.set(ne,K)}return Array.from(ee.values())},[te?.profiles,Q,r.extruderId]);w.useEffect(()=>{if(t){if(r.savedPresetId)u(r.savedPresetId);else if(r.trayInfoIdx&&D?.filament){let E=D.filament.find(I=>I.setting_id===r.trayInfoIdx);E||(E=D.filament.find(I=>B_(I.setting_id)===r.trayInfoIdx)),E&&u(E.setting_id)}else if(r.trayInfoIdx&&G?.length){const E=r.trayInfoIdx,I=G.find(W=>W.filament_id===E);I&&u(`builtin_${I.filament_id}`)}if(r.trayColor){const E=r.trayColor.slice(0,6);E&&x(E)}}else u(""),p(null),x(""),g(""),_(""),C(!1),k.current=""},[t,r.savedPresetId,r.trayInfoIdx,r.trayColor,D?.filament,G]),w.useEffect(()=>{if(pe.length>0){if(r.caliIdx!=null&&r.caliIdx>0){const E=pe.find(I=>I.slot_id===r.caliIdx);if(E){p(E);return}}p(pe[0])}else p(null)},[d,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||U||L||re;if(w.useEffect(()=>{if(!q&&d&&d!==k.current){const E=requestAnimationFrame(()=>{const W=document.querySelector('[class*="fixed inset-0 z-50"]')?.querySelector(`[data-preset-id="${CSS.escape(d)}"]`);W&&(k.current=d,W.scrollIntoView({block:"nearest"}))});return()=>cancelAnimationFrame(E)}},[d,q]),!t)return null;const Z=d&&!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(du,{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-white/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),i.jsx("span",{className:"text-white/70",children:c("configureAmsSlot.slotLabel",{ams:bG(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(zt,{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(Eb,{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-white/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),i.jsx("span",{className:"text-white font-medium",children:c("configureAmsSlot.slotLabel",{ams:bG(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(ct,{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:y,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:fe.length===0?i.jsx("p",{className:"text-center py-4 text-bambu-gray",children:D?.filament?.length===0&&!$?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):fe.map(E=>i.jsx("button",{"data-preset-id":E.id,onClick:()=>u(E.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${d===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"),ie&&i.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ie})})]}),pe.length>0?i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:m?.name||"",onChange:E=>{const I=pe.find(W=>W.name===E.target.value);p(I||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(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?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")}),le.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:Q?.fullName})}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:le.map(E=>i.jsxs("button",{onClick:()=>{const I=E.hex_color.replace("#","").toUpperCase();x(I),g(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-white/30 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:[yG.map(E=>i.jsx("button",{onClick:()=>{x(E.hex),g(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(!T),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(T?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:T?"βˆ’":"+"})]}),T&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:vG.map(E=>i.jsx("button",{onClick:()=>{x(E.hex),g(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 I=E.target.value;g(I);const W=wG(I);if(W)x(W);else{const B=I.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();B.length===6?x(B):B.length===3&&x(B.split("").map(ae=>ae+ae).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:()=>{x(""),g("")},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:y,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:fe.length===0?i.jsx("p",{className:"text-center py-4 text-bambu-gray",children:D?.filament?.length===0&&!$?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):fe.map(E=>i.jsx("button",{"data-preset-id":E.id,onClick:()=>u(E.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${d===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"),ie&&i.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ie})})]}),pe.length>0?i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:m?.name||"",onChange:E=>{const I=pe.find(W=>W.name===E.target.value);p(I||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(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?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")}),le.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:Q?.fullName})}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:le.map(E=>i.jsxs("button",{onClick:()=>{const I=E.hex_color.replace("#","").toUpperCase();x(I),g(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-white/30 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:[yG.map(E=>i.jsx("button",{onClick:()=>{x(E.hex),g(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(!T),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(T?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:T?"βˆ’":"+"})]}),T&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:vG.map(E=>i.jsx("button",{onClick:()=>{x(E.hex),g(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 I=E.target.value;g(I);const W=wG(I);if(W)x(W);else{const B=I.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();B.length===6?x(B):B.length===3&&x(B.split("").map(ae=>ae+ae).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:()=>{x(""),g("")},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(Oe,{variant:"secondary",onClick:()=>me.mutate(),disabled:me.isPending||ue.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:me.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ct,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):i.jsxs(i.Fragment,{children:[i.jsx(mo,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Oe,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),i.jsx(Oe,{onClick:()=>ue.mutate(),disabled:!Z,children:ue.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ct,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):i.jsxs(i.Fragment,{children:[i.jsx(du,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(ue.isError||me.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||me.error?.message})]})]})}function Qne({folderId:t,onClose:e,onUploadComplete:n,onFileUploaded:r,autoUpload:a,validateFile:s,accept:o}){const{t:l}=Mt(),[c,d]=w.useState([]),[u,m]=w.useState(!1),[p,f]=w.useState(!1),[x,v]=w.useState(!0),[g,y]=w.useState(!1),[_,N]=w.useState(!0),[C,T]=w.useState(null),P=w.useRef(null),k=fe=>{fe.preventDefault(),m(!0)},D=fe=>{fe.preventDefault(),m(!1)},A=fe=>{fe.preventDefault(),m(!1),G(Array.from(fe.dataTransfer.files))},R=fe=>{fe.target.files&&G(Array.from(fe.target.files))},$=(fe,Q)=>{d(ie=>ie.map(le=>le.file===fe?{...le,...Q}:le))},U=async fe=>{f(!0);for(const Q of fe)if(Q.status==="pending"){$(Q.file,{status:"uploading"});try{if(Q.isZip){const ie=await be.extractZipFile(Q.file,t,x,g,_);$(Q.file,{status:ie.errors.length>0&&ie.extracted===0?"error":"success",extractedCount:ie.extracted,error:ie.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:ie.errors.length}):void 0})}else{const ie=await be.uploadLibraryFile(Q.file,t,_);$(Q.file,{status:"success"});const le=r?.(ie);if(le){T(le),d([]),f(!1);return}}}catch(ie){$(Q.file,{status:"error",error:ie instanceof Error?ie.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),n(),e()},G=fe=>{if(T(null),s)for(const ie of fe){const le=s(ie);if(le){T(le);return}}const Q=fe.map(ie=>({file:ie,status:"pending",isZip:ie.name.toLowerCase().endsWith(".zip"),is3mf:ie.name.toLowerCase().endsWith(".3mf")}));d(ie=>[...ie,...Q]),a&&fe.length>0&&U(Q)},L=fe=>{d(Q=>Q.filter((ie,le)=>le!==fe))},te=c.some(fe=>fe.isZip&&fe.status==="pending"),re=c.some(fe=>fe.file.name.toLowerCase().endsWith(".stl")&&fe.status==="pending"),J=c.some(fe=>fe.is3mf&&fe.status==="pending"),ue=c.filter(fe=>fe.status==="pending").length,me=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(zt,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("div",{onDragOver:k,onDragLeave:D,onDrop:A,onClick:()=>P.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${u?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[i.jsx(Si,{className:`w-10 h-10 mx-auto mb-3 ${u?"text-bambu-green":"text-bambu-gray"}`}),i.jsx("p",{className:"text-white font-medium",children:l(u?"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}),te&&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(Os,{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:x,onChange:fe=>v(fe.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:g,onChange:fe=>y(fe.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")})]})]})]})}),J&&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")})]})]})}),(re||te)&&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(cu,{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(te&&!re?"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:fe=>N(fe.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((fe,Q)=>i.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[fe.isZip?i.jsx(Os,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):i.jsx(lC,{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:fe.file.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[(fe.file.size/1024/1024).toFixed(2)," MB",fe.isZip&&fe.status==="pending"&&i.jsxs("span",{className:"text-blue-400 ml-2",children:["β€’ ",l("fileManager.willBeExtracted")]}),fe.extractedCount!==void 0&&i.jsxs("span",{className:"text-green-400 ml-2",children:["β€’ ",l("fileManager.filesExtracted",{count:fe.extractedCount})]})]})]}),fe.status==="pending"&&i.jsx("button",{onClick:()=>L(Q),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(zt,{className:"w-4 h-4 text-bambu-gray"})}),fe.status==="uploading"&&i.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"}),fe.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-500"}),fe.status==="error"&&i.jsx("span",{title:fe.error,children:i.jsx(Vi,{className:"w-4 h-4 text-red-500"})})]},Q))}),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(Oe,{variant:"secondary",onClick:e,children:l("common.cancel")}),!me&&i.jsx(Oe,{onClick:()=>U(c),disabled:ue===0||p,children:p?i.jsxs(i.Fragment,{children:[i.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(Si,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",ue>0?`(${ue})`:""]})})]})]})})}function SG(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Oi(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}function qc(t,e,n=40){const r=Oi(t),a=Oi(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),d=parseInt(a.substring(2,4),16),u=parseInt(a.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-d)<=n&&Math.abs(l-u)<=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 ok(t,e,n){return n?254+e:t>=128?t:t*4+e}function _G(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(Qn(t)?.getTime()??0)>e}function $$e(t,e,n){const r=Zne(e,t.nozzle_id),a=r.find(l=>!n.has(l.globalTrayId)&&l.type?.toUpperCase()===t.type?.toUpperCase()&&Oi(l.color)===Oi(t.color)),s=a?void 0:r.find(l=>!n.has(l.globalTrayId)&&l.type?.toUpperCase()===t.type?.toUpperCase()&&qc(l.color,t.color)),o=a||s?void 0:r.find(l=>!n.has(l.globalTrayId)&&l.type?.toUpperCase()===t.type?.toUpperCase());return a??s??o}function Zne(t,e){return t.filter(n=>e==null||n.extruderId===e)}function kT(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=SG(o.tray_color);e.push({type:o.tray_type,color:l,colorName:au(l),amsId:a.id,trayId:o.id,isHt:s,isExternal:!1,label:F4(a.id,o.id,s,!1),globalTrayId:ok(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=SG(a.tray_color),o=a.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:a.tray_type,color:s,colorName:au(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 NG(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=kT(e);if(n.length===0)return;const r=new Set,a=t.filaments.map(l=>{const c=l.tray_info_idx||"";let d=n.filter(v=>!r.has(v.globalTrayId));l.nozzle_id!=null&&(d=d.filter(v=>v.extruderId===l.nozzle_id));let u,m,p,f;if(c){const v=d.filter(g=>g.trayInfoIdx===c);v.length===1?u=v[0]:v.length>1&&(m=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&Oi(g.color)===Oi(l.color)),m||(p=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&qc(g.color,l.color))),!m&&!p&&(f=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase())))}!u&&!m&&!p&&!f&&(m=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Oi(v.color)===Oi(l.color)),m||(p=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&qc(v.color,l.color))),!m&&!p&&(f=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase())));const x=u||m||p||f||void 0;return x&&r.add(x.globalTrayId),{slot_id:l.slot_id,globalTrayId:x?.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 q$e(t){return w.useMemo(()=>kT(t),[t])}function Jne(t,e,n){const r=q$e(e),a=w.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const c=new Set(Object.values(n));return t.filaments.map(d=>{const u=d.slot_id||0;if(u>0&&n[u]!==void 0){const P=n[u],k=r.find(D=>D.globalTrayId===P);if(k){const D=k.type?.toUpperCase()===d.type?.toUpperCase(),A=Oi(k.color)===Oi(d.color)||qc(k.color,d.color);let R;return D&&A?R="match":D?R="type_only":R="mismatch",{...d,loaded:k,hasFilament:!0,typeMatch:D,colorMatch:A,status:R,isManual:!0}}}const m=d.tray_info_idx||"";let p=r.filter(P=>!c.has(P.globalTrayId));d.nozzle_id!=null&&(p=p.filter(P=>P.extruderId===d.nozzle_id));let f,x,v,g;if(m){const P=p.filter(k=>k.trayInfoIdx===m);P.length===1?f=P[0]:P.length>1&&(x=P.find(k=>k.type?.toUpperCase()===d.type?.toUpperCase()&&Oi(k.color)===Oi(d.color)),x||(v=P.find(k=>k.type?.toUpperCase()===d.type?.toUpperCase()&&qc(k.color,d.color))),!x&&!v&&(g=P.find(k=>k.type?.toUpperCase()===d.type?.toUpperCase())))}!f&&!x&&!v&&!g&&(x=p.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase()&&Oi(P.color)===Oi(d.color)),x||(v=p.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase()&&qc(P.color,d.color))),!x&&!v&&(g=p.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase())));const y=f||x||v||g||void 0;y&&c.add(y.globalTrayId);const _=!!y,N=_,C=!!f||!!x||!!v;let T;return f||x||v?T="match":g?T="type_only":T="mismatch",{...d,loaded:y,hasFilament:_,typeMatch:N,colorMatch:C,status:T,isManual:!1}})},[t,r,n]),s=w.useMemo(()=>{if(a.length===0)return;const c=Math.max(...a.map(u=>u.slot_id||0));if(c<=0)return;const d=new Array(c).fill(-1);return a.forEach(u=>{u.slot_id&&u.slot_id>0&&(d[u.slot_id-1]=u.loaded?.globalTrayId??-1)}),d},[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 V$e(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 d of t){const u=d.slot_id||0;if(u>0&&n[u]!==void 0){const g=n[u],y=e.find(_=>_.globalTrayId===g);if(y){const _=y.type?.toUpperCase()===d.type?.toUpperCase(),N=Oi(y.color)===Oi(d.color)||qc(y.color,d.color);_&&N?r++:_?a++:s++;continue}}let m=e.filter(g=>!o.has(g.globalTrayId));if(d.nozzle_id!=null){const g=m.filter(y=>y.extruderId===d.nozzle_id);g.length>0&&(m=g)}const p=m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Oi(g.color)===Oi(d.color)),f=p?void 0:m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&qc(g.color,d.color)),x=p||f?void 0:m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()),v=p??f??x;v&&o.add(v.globalTrayId),p||f?r++:x?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 G$e(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=kT(e);if(r.length===0)return;const a=new Set(Object.values(n)),s=[];for(const c of t.filaments){const d=c.slot_id||0;if(d>0&&n[d]!==void 0){s.push({slot_id:d,globalTrayId:n[d]});continue}let u=r.filter(v=>!a.has(v.globalTrayId));if(c.nozzle_id!=null){const v=u.filter(g=>g.extruderId===c.nozzle_id);v.length>0&&(u=v)}const m=u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Oi(v.color)===Oi(c.color)),p=m?void 0:u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&qc(v.color,c.color)),f=m||p?void 0:u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()),x=m??p??f;x&&a.add(x.globalTrayId),s.push({slot_id:d,globalTrayId:x?.globalTrayId??-1})}const o=Math.max(...s.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return s.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}const kG={useDefault:!0,manualMappings:{},autoConfigured:!1};function W$e(t,e,n,r,a,s){const o=bf({queries:t.map(x=>({queryKey:["printer-status",x],queryFn:()=>be.getPrinterStatus(x),enabled:t.length>0,staleTime:5e3}))}),l=w.useMemo(()=>t.map((x,v)=>{const g=o[v],y=g?.data,N=e?.find(R=>R.id===x)?.name||`Printer ${x}`,C=kT(y),T=a[x]||kG,P=NG(n,y),k=T.useDefault?r:T.manualMappings,D=G$e(n,y,k),A=V$e(n?.filaments,C,k);return{printerId:x,printerName:N,status:y,isLoading:g?.isLoading??!1,loadedFilaments:C,autoMapping:P,finalMapping:D,matchStatus:A.status,exactMatches:A.exactMatches,typeOnlyMatches:A.typeOnlyMatches,missingTypes:A.missingTypes,totalSlots:A.totalSlots,config:T}}),[t,o,e,n,a,r]),c=o.some(x=>x.isLoading),d=(x,v)=>{s(g=>({...g,[x]:{...g[x]||kG,...v}}))},u=x=>{const v=l.find(_=>_.printerId===x);if(!v||!v.status||!n?.filaments)return;const g=NG(n,v.status);if(!g)return;const y={};g.forEach((_,N)=>{_!==-1&&(y[N+1]=_)}),d(x,{useDefault:!1,manualMappings:y,autoConfigured:!0})},m=()=>{for(const x of t)u(x)},p=x=>l.find(g=>g.printerId===x)?.finalMapping,f=l.every(x=>x.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:a,updatePrinterConfig:d,autoConfigureAll:m,autoConfigurePrinter:u,getFinalMapping:p,allPrintersReady:f}}const ere={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 ol(t){return ere[t.toUpperCase()]||t}const K$e=Object.entries(ere).map(([t,e])=>({code:t,label:`${t} (${e})`}));function Y$e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,currencySymbol:a,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=Mt(),c=en(),[d,u]=w.useState(!1),[m,p]=w.useState(o),{data:f}=Je({queryKey:["printer-status",t],queryFn:()=>be.getPrinterStatus(t),enabled:!!t}),{data:x}=Je({queryKey:["spool-assignments",t],queryFn:()=>be.getAssignments(t),enabled:!!t}),{loadedFilaments:v,filamentComparison:g,hasTypeMismatch:y,hasColorMismatch:_}=Jne(e,f,n),N=w.useMemo(()=>{const U=new Map;for(const G of x||[]){const L=G.ams_id===255,te=ok(G.ams_id,G.tray_id,L);U.set(te,G.spool?.cost_per_kg??null)}return U},[x]),C=w.useMemo(()=>{const U=new Map;for(const G of x||[]){const L=G.ams_id===255,te=ok(G.ams_id,G.tray_id,L),re=G.spool;if(!re){U.set(te,null);continue}U.set(te,Math.max(0,Math.round((re.label_weight??0)-(re.weight_used??0))))}return U},[x]),T=w.useMemo(()=>{let U=0;for(const G of g){const L=G.loaded?.globalTrayId;if(L==null)continue;const re=N.get(L)??null??s;re>0&&(U+=G.used_grams/1e3*re)}return U},[g,N,s]),P=w.useMemo(()=>Array.from(N.values()).some(U=>U!=null&&U>0),[N]),k=e?.filaments&&e.filaments.length>0,D=e?.filaments?.some(U=>U.nozzle_id!=null)??!1;if(!k||!f)return null;const A=y?"#f97316":_?"#facc15":"#00ae42",R=(U,G)=>{if(U>0)if(G===""){const L={...n};delete L[U],r(L)}else r({...n,[U]:parseInt(G,10)})},$=async()=>{u(!0);try{await be.refreshPrinterStatus(t),await new Promise(U=>setTimeout(U,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{u(!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(U1,{className:"w-4 h-4",fill:A,stroke:"none"}),i.jsx("span",{children:l("printModal.filamentMapping")}),y?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(Sl,{className:"w-4 h-4 ml-auto"}):i.jsx(Fn,{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:$,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:d,children:[i.jsx(Sr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),i.jsx("span",{children:"Re-read"})]})]}),g.map((U,G)=>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} - ${au(U.color)}`,children:i.jsx(U1,{className:"w-3 h-3",fill:U.color,stroke:U.color})}),i.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[D&&U.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:U.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:U.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),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:U.loaded?.globalTrayId??"",onChange:L=>R(U.slot_id||0,L.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 ${U.status==="match"?"border-bambu-green/50 text-bambu-green":U.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${U.isManual?"ring-1 ring-blue-400/50":""}`,title:U.isManual?"Manually selected":"Auto-matched",children:[i.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),v.filter(L=>U.nozzle_id==null||L.extruderId===U.nozzle_id).map(L=>{const te=C.get(L.globalTrayId),re=te!=null?l("printModal.slotRemainingShort",{grams:te,defaultValue:` - ${te}g left`}):"";return i.jsxs("option",{value:L.globalTrayId,className:"bg-bambu-dark text-white",children:[L.label,": ",L.traySubBrands||L.type," (",L.colorName,")",re]},L.globalTrayId)})]}),U.status==="match"?i.jsx(Vr,{className:"w-3 h-3 text-bambu-green"}):U.status==="type_only"?i.jsx("span",{title:"Same type, different color",children:i.jsx(An,{className:"w-3 h-3 text-yellow-400"})}):i.jsx("span",{title:"Filament type not loaded",children:i.jsx(An,{className:"w-3 h-3 text-orange-400"})})]},G)),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",i.jsx("span",{className:"text-white",children:T>0||P?`${a}${T.toFixed(2)}`:"N/A"})]}),y&&i.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function X$e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:r,forceColorMatch:a,onForceColorMatchChange:s}){const{t:o}=Mt(),l=w.useMemo(()=>{const u={};for(const m of e){const p=m.type.toUpperCase();u[p]||(u[p]=[]),u[p].push(m)}return u},[e]),c=t?.filaments;if(!c||c.length===0||e.length===0)return null;const d=(u,m)=>{if(m===""){const p={...n};delete p[u],r(p)}else{const[p,f]=m.split("|");r({...n,[u]:{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(u=>{const m=n[u.slot_id],p=!!m,f=l[u.type.toUpperCase()]||[],x=u.nozzle_id!=null?f.filter(v=>v.extruder_id==null||v.extruder_id===u.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")}: ${u.type} - ${au(u.color)}`,children:i.jsx(U1,{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:p?`${m.type}|${m.color}`:"",onChange:v=>d(u.slot_id,v.target.value),disabled:x.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"),": ",u.type," (",au(u.color),")"]}),x.map((v,g)=>i.jsxs("option",{value:`${v.type}|${v.color}`,className:"bg-bambu-dark text-white",children:[v.tray_sub_brands||v.type," (",au(v.color),")"]},`${v.type}-${v.color}-${v.tray_sub_brands}-${g}`))]}),p?i.jsx("button",{type:"button",onClick:()=>d(u.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:o("printModal.resetToOriginal"),children:i.jsx(mo,{className:"w-3 h-3"})}):i.jsx("span",{className:"w-3"})]}),i.jsxs("label",{className:"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?.[u.slot_id]??!1,onChange:v=>s?.(u.slot_id,v.target.checked),className:"accent-bambu-green w-3 h-3"}),i.jsx(R0,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},u.slot_id)})})]})}function Q$e({plates:t,isMultiPlate:e,selectedPlate:n,onSelect:r,queueAll:a,onQueueAllChange:s}){const{t:o}=Mt();return!e||t.length<=1?null: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.jsx("span",{className:"text-sm text-bambu-gray",children:"Select Plate to Print"}),!n&&!a&&i.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[i.jsx(An,{className:"w-3 h-3"}),"Selection required"]}),s&&i.jsx("button",{type:"button",onClick:()=>s(!a),className:`ml-auto text-xs px-2 py-0.5 rounded-full border transition-colors ${a?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray"}`,children:o("queue.queueAllPlates",{count:t.length})})]}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(l=>i.jsxs("button",{type:"button",onClick:()=>{a&&s&&s(!1),r(l.index)},className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${a||n===l.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[l.has_thumbnail&&l.thumbnail_url!=null?i.jsx("img",{src:l.thumbnail_url,alt:`Plate ${l.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:l.name||`Plate ${l.index}`}),i.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[l.objects.length>0?l.objects.slice(0,3).join(", ")+(l.objects.length>3?"...":""):`${l.filaments.length} filament${l.filaments.length!==1?"s":""}`,l.print_time_seconds!=null?` β€’ ${js(l.print_time_seconds)}`:""]})]}),(a||n===l.index)&&i.jsx(Vr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},l.index))})]})}const Z$e=new Set(["IDLE","FINISH","FAILED"]);function J$e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=en(),[a,s]=w.useState(!1),o=(d,u)=>{if(d<=0)return;const m={...t.config.manualMappings};u===""?delete m[d]:m[d]=parseInt(u,10),n({useDefault:!1,manualMappings:m,autoConfigured:!1})},l=async()=>{s(!0);try{await be.refreshPrinterStatus(t.printerId),await new Promise(d=>setTimeout(d,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(d=>{const u=d.slot_id||0,m=t.config.manualMappings[u];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=$$e(d,t.loadedFilaments,v)}let x="mismatch";if(p){const v=p.type?.toUpperCase()===d.type?.toUpperCase(),g=Oi(p.color)===Oi(d.color)||qc(p.color,d.color);v&&g?x="match":v&&(x="type_only")}return{req:d,loaded:p,status:x,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:d,loaded:u,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: ${d.type} - ${au(d.color)}`,children:i.jsx(U1,{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:u?.globalTrayId??"",onChange:x=>o(d.slot_id||0,x.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${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 --"}),Zne(t.loadedFilaments,d.nozzle_id).map(x=>i.jsxs("option",{value:x.globalTrayId,className:"bg-bambu-dark text-white",children:[x.label,": ",x.traySubBrands||x.type," (",x.colorName,")"]},x.globalTrayId))]}),m==="match"?i.jsx(Vr,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?i.jsx("span",{title:"Same type, different color",children:i.jsx(An,{className:"w-3 h-3 text-yellow-400"})}):i.jsx("span",{title:"Filament type not loaded",children:i.jsx(An,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function eqe({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:a=!1,showInactive:s=!1,disableBusy:o=!1,printerMappingResults:l,filamentReqs:c,onAutoConfigurePrinter:d,onUpdatePrinterConfig:u,assignmentMode:m="printer",onAssignmentModeChange:p,targetModel:f,onTargetModelChange:x,targetLocation:v,onTargetLocationChange:g,slicedForModel:y}){const[_,N]=w.useState(!1),C=s?t:t.filter(ie=>ie.is_active),T=bf({queries:C.map(ie=>({queryKey:["printerStatus",ie.id],queryFn:()=>be.getPrinterStatus(ie.id),staleTime:5e3}))}),P=w.useMemo(()=>{const ie=new Map;return C.forEach((le,pe)=>{const Te=T[pe];Te?.data&&ie.set(le.id,Te.data)}),ie},[C,T]),k=ie=>{const le=P.get(ie);return le?le.connected?!Z$e.has(le.state??""):!0:!1},D=ie=>{const le=P.get(ie);if(!le)return null;if(!le.connected)return"Offline";const pe=le.state;return pe?pe==="RUNNING"?le.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"||!y||_)return C;const ie=C.filter(le=>le.model===y);return ie.length>0?ie:C},[C,m,y,_]),R=C.length-A.length,$=w.useMemo(()=>{const ie=C.map(le=>le.model).filter(le=>!!le);return[...new Set(ie)].sort()},[C]),U=w.useMemo(()=>{if(!f)return[];const ie=C.filter(le=>le.model===f&&le.location).map(le=>le.location).filter(le=>!!le);return[...new Set(ie)].sort()},[C,f]),G=p&&x&&$.length>0,L=a&&e.length>1&&l&&c?.filaments&&c.filaments.length>0&&d&&u;if(r)return i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(ct,{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(zi,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const te=ie=>{o&&k(ie)||(a?e.includes(ie)?n(e.filter(le=>le!==ie)):n([...e,ie]):n([ie]))},re=()=>{const ie=o?A.filter(le=>!k(le.id)):A;n(ie.map(le=>le.id))},J=()=>{n([])},ue=(ie,le,pe)=>{pe.stopPropagation(),!(!d||!u)&&(le?d(ie):u(ie,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},me=ie=>e.includes(ie),fe=e.length,Q=ie=>l?.find(le=>le.printerId===ie);return i.jsxs("div",{className:"space-y-2 mb-6",children:[G&&i.jsxs("div",{className:"flex gap-2 mb-4",children:[i.jsxs("button",{type:"button",onClick:()=>{p("printer"),x(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 ie=y&&$.includes(y)?y:$[0];x(ie)},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(_m,{className:"w-4 h-4"}),i.jsxs("span",{className:"text-sm",children:["Any ",y||"Model"]})]})]}),m==="model"&&G&&i.jsxs("div",{className:"space-y-3 mb-4",children:[!y&&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:ie=>{x(ie.target.value||null),g&&g(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..."}),$.map(ie=>i.jsx("option",{value:ie,children:ie},ie))]})]}),f&&U.length>0&&g&&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:ie=>g(ie.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"}),U.map(ie=>i.jsx("option",{value:ie,children:ie},ie))]})]}),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:fe===0?"Select printers":`${fe} printer${fe!==1?"s":""} selected`}),i.jsxs("div",{className:"flex gap-2",children:[fe0&&i.jsx("button",{type:"button",onClick:J,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&A.map(ie=>{const le=me(ie.id),pe=Q(ie.id),Te=pe&&!pe.config.useDefault,q=k(ie.id),Z=o&&q,j=D(ie.id);return i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>te(ie.id),disabled:Z,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${Z?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":le?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${ie.is_active?"":"opacity-60"}`,children:[i.jsx("div",{className:`p-2 rounded-lg ${Z?"bg-bambu-dark-tertiary":le?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:i.jsx(_r,{className:`w-5 h-5 ${Z?"text-bambu-gray/50":le?"text-bambu-green":"text-bambu-gray"}`})}),i.jsxs("div",{className:"text-left flex-1",children:[i.jsxs("p",{className:`font-medium ${Z?"text-bambu-gray":"text-white"}`,children:[ie.name,!ie.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:[ie.model||"Unknown model"," β€’ ",ie.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 ${Z?"border-bambu-gray/30":le?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:le&&i.jsx(Vr,{className:"w-3 h-3 text-white"})})]}),le&&L&&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(ie.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(),d(ie.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(Bge,{className:"w-3 h-3"}),"Auto"]})]}),Te&&i.jsx(J$e,{printerResult:pe,filamentReqs:c.filaments,onUpdateConfig:E=>u(ie.id,E)})]})]},ie.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(An,{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"&&_&&y&&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 ",y," printers"]})}),m==="printer"&&fe===0&&i.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[i.jsx(zi,{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(zi,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const tqe=[{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 nqe({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(gC,{className:"w-4 h-4"}),i.jsx("span",{children:"Print Options"}),r?i.jsx(Sl,{className:"w-4 h-4 ml-auto"}):i.jsx(Fn,{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:tqe.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 rqe({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system",canControlPrinter:a=!0}){const[s,o]=w.useState(""),[l,c]=w.useState(""),[d,u]=w.useState(!0),[m,p]=w.useState(!0),f=w.useRef(null),x=w.useRef(!1);w.useEffect(()=>{if(t.scheduleType!=="scheduled"){x.current=!1;return}if(!x.current){x.current=!0;let T;t.scheduledTime?(T=new Date(t.scheduledTime),isNaN(T.getTime())&&(T=new Date,T.setHours(T.getHours()+1,0,0,0))):(T=new Date,T.setHours(T.getHours()+1,0,0,0),e({...t,scheduledTime:jD(T)})),o(ED(T,n)),c(l8(T,r)),u(!0),p(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const v=T=>{e({...t,scheduleType:T})},g=(T,P)=>{const k=ube(T,n),D=mbe(P);u(!!k),p(!!D),k&&D&&(k.setHours(D.hours,D.minutes,0,0),k>new Date&&e({...t,scheduledTime:jD(k)}))},y=T=>{o(T),g(T,l)},_=T=>{c(T),g(s,T)},N=T=>{const P=T.target.value;if(P){const k=new Date(P);isNaN(k.getTime())||(o(ED(k,n)),c(l8(k,r)),u(!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(GY,{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 ${d?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:s,onChange:T=>y(T.target.value),placeholder:lbe(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:T=>_(T.target.value),placeholder:cbe(r)})})]}),i.jsx("input",{ref:f,type:"datetime-local",className:"sr-only",value:t.scheduledTime,onChange:N,tabIndex:-1}),(!d||!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:T=>e({...t,requirePreviousSuccess:T.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:T=>e({...t,autoOffAfter:T.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(_u,{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 qg={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},iqe={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function Vc({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:a,initialSelectedPrinterIds:s,onClose:o,onSuccess:l}){const{t:c}=Mt(),d=en(),{showToast:u}=xn(),{hasPermission:m}=Dr(),p=!!n&&!e,[f,x]=w.useState(()=>t==="edit-queue-item"&&a?.printer_id?[a.printer_id]:s?.length?s:[]),[v,g]=w.useState(()=>t==="edit-queue-item"&&a?a.plate_id:null),[y,_]=w.useState(!1),[N,C]=w.useState(()=>t==="edit-queue-item"&&a?{bed_levelling:a.bed_levelling??qg.bed_levelling,flow_cali:a.flow_cali??qg.flow_cali,vibration_cali:a.vibration_cali??qg.vibration_cali,layer_inspect:a.layer_inspect??qg.layer_inspect,timelapse:a.timelapse??qg.timelapse}:qg),[T,P]=w.useState(()=>{if(t==="edit-queue-item"&&a){let lt="asap";a.manual_start?lt="manual":a.scheduled_time&&!_G(a.scheduled_time)&&(lt="scheduled");let ht="";if(a.scheduled_time&&!_G(a.scheduled_time)){const qe=Qn(a.scheduled_time)??new Date;ht=jD(qe)}return{scheduleType:lt,scheduledTime:ht,requirePreviousSuccess:a.require_previous_success,autoOffAfter:a.auto_off_after}}return iqe}),[k,D]=w.useState(()=>{if(t==="edit-queue-item"&&a?.ams_mapping&&Array.isArray(a.ams_mapping)){const lt={};return a.ams_mapping.forEach((ht,qe)=>{ht!==-1&&(lt[qe+1]=ht)}),lt}return{}}),[A,R]=w.useState({}),[$,U]=w.useState(()=>t==="edit-queue-item"&&a?.target_model?"model":"printer"),[G,L]=w.useState(()=>t==="edit-queue-item"&&a?.target_model?a.target_model:null),[te,re]=w.useState(()=>t==="edit-queue-item"&&a?.target_location?a.target_location:null),[J,ue]=w.useState(()=>{if(t==="edit-queue-item"&&a?.filament_overrides){const lt={};for(const ht of a.filament_overrides)lt[ht.slot_id]={type:ht.type,color:ht.color};return lt}return{}}),[me,fe]=w.useState(()=>{if(t==="edit-queue-item"&&a?.filament_overrides){const lt={};for(const ht of a.filament_overrides)lt[ht.slot_id]=ht.force_color_match===!0;return lt}return{}}),[Q]=w.useState(()=>t==="edit-queue-item"&&a?.printer_id?[a.printer_id]:[]),[ie]=w.useState(()=>t==="edit-queue-item"&&a?a.plate_id:null),[le,pe]=w.useState(!1),[Te,q]=w.useState({current:0,total:0}),[Z,j]=w.useState(new Set),E=f.length,I=f.length>0?f[0]:null,{data:W}=Je({queryKey:["settings"],queryFn:be.getSettings}),B=ol(W?.currency||"USD"),ae=W?.default_filament_cost??0,{data:z,isLoading:V}=Je({queryKey:["printers"],queryFn:be.getPrinters}),{data:ee}=Je({queryKey:["archive",e],queryFn:()=>be.getArchive(e),enabled:!!e&&!p}),{data:K}=Je({queryKey:["library-file",n],queryFn:()=>be.getLibraryFile(n),enabled:p&&!!n}),ne=ee?.sliced_for_model||K?.sliced_for_model||null,{data:se,isError:ce}=Je({queryKey:["archive-plates",e],queryFn:()=>be.getArchivePlates(e),enabled:!!e&&!p,retry:!1}),{data:ge}=Je({queryKey:["library-file-plates",n],queryFn:()=>be.getLibraryFilePlates(n),enabled:p&&!!n}),oe=p?ge:se,{data:O,isError:F}=Je({queryKey:["archive-filaments",e,v],queryFn:()=>be.getArchiveFilamentRequirements(e,v??void 0),enabled:!!e&&!p&&(v!==null||!oe?.is_multi_plate),retry:!1}),{data:X}=Je({queryKey:["library-file-filaments",n,v],queryFn:()=>be.getLibraryFileFilamentRequirements(n,v??void 0),enabled:p&&!!n&&(v!==null||!oe?.is_multi_plate)}),ye=!p&&(ce||F),he=p?X:O,de=w.useMemo(()=>{if(!(v===null||!oe?.plates?.length))return oe.plates.find(lt=>lt.index===v)?.name||void 0},[oe,v]),{data:Me}=Je({queryKey:["available-filaments",G,te],queryFn:()=>be.getAvailableFilaments(G,te??void 0),enabled:$==="model"&&!!G}),{data:_e}=Je({queryKey:["printer-status",I],queryFn:()=>be.getPrinterStatus(I),enabled:!!I}),{amsMapping:Be}=Jne(he,_e,k),$e=W$e(f,z,he,k,A,R);w.useEffect(()=>{oe?.plates&&oe.plates.length>=1&&!v&&g(oe.plates[0].index)},[oe,v]),w.useEffect(()=>{if(t==="edit-queue-item")return;const lt=z?.filter(ht=>ht.is_active)||[];lt.length===1&&f.length===0&&x([lt[0].id])},[t,z,f.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(f.sort())!==JSON.stringify(Q.sort())||v!==ie)&&(D({}),R({}),j(new Set)):(D({}),R({}),j(new Set))},[t,f,v,Q,ie]);const[Le,ke]=w.useState(G),[Ee,Ne]=w.useState(v);w.useEffect(()=>{(G!==Le||v!==Ee)&&(ke(G),Ne(v),(t!=="edit-queue-item"||Le!==null)&&(ue({}),fe({})))},[G,v,Le,Ee,t]),w.useEffect(()=>{if(!W?.per_printer_mapping_expanded||f.length<=1)return;const lt=f.filter(ht=>{if(Z.has(ht))return!1;const qe=$e.printerResults.find(pt=>pt.printerId===ht);return qe&&qe.status&&!qe.isLoading});lt.length>0&&(j(ht=>{const qe=new Set(ht);return lt.forEach(pt=>qe.add(pt)),qe}),lt.forEach(ht=>{$e.autoConfigurePrinter(ht)}))},[W?.per_printer_mapping_expanded,f,Z,$e]),w.useEffect(()=>{const lt=ht=>{ht.key==="Escape"&&!le&&o()};return window.addEventListener("keydown",lt),()=>window.removeEventListener("keydown",lt)},[o,le]);const Ae=oe?.is_multi_plate??!1,Ge=oe?.plates??[],xe=ut({mutationFn:lt=>be.addToQueue(lt)}),He=ut({mutationFn:lt=>be.updateQueueItem(a.id,lt),onSuccess:()=>{d.invalidateQueries({queryKey:["queue"]}),u("Queue item updated"),l?.(),o()},onError:lt=>{u(lt.message||"Failed to update queue item","error")}}),Pe=async lt=>{if(lt?.preventDefault(),$==="printer"&&f.length===0){u("Please select at least one printer","error");return}if($==="model"&&!G){u("Please select a target printer model","error");return}pe(!0);const ht=y?Ge:[null],qe=$==="model"?ht.length:f.length*ht.length;q({current:0,total:qe});const pt={success:0,failed:0,errors:[]},xt=Yt=>{if(f.length>1){const Ht=A[Yt];if(Ht&&!Ht.useDefault)return $e.getFinalMapping(Yt)}return Be},nn=(()=>{const Yt=[];if(he?.filaments)for(const Ht of he.filaments){const tn=J[Ht.slot_id],ln=me[Ht.slot_id]??!1,mn=tn?.type??Ht.type,fn=tn?.color??Ht.color;(tn||ln)&&Yt.push({slot_id:Ht.slot_id,type:mn,color:fn,color_name:au(fn),force_color_match:ln})}else for(const[Ht,{type:tn,color:ln}]of Object.entries(J)){const mn=parseInt(Ht,10),fn=me[mn]??!1;Yt.push({slot_id:mn,type:tn,color:ln,color_name:au(ln),force_color_match:fn})}return Yt.length>0?Yt:void 0})(),sn=(Yt,Ht)=>({printer_id:$==="printer"?Yt:null,target_model:$==="model"?G:null,target_location:$==="model"?te:null,filament_overrides:$==="model"?nn:void 0,archive_id:p?void 0:e,library_file_id:p?n:void 0,require_previous_success:T.requirePreviousSuccess,auto_off_after:T.autoOffAfter,manual_start:T.scheduleType==="manual",ams_mapping:Yt?xt(Yt):void 0,plate_id:Ht!==void 0?Ht:v,scheduled_time:T.scheduleType==="scheduled"&&T.scheduledTime?new Date(T.scheduledTime).toISOString():void 0,...N});if($==="model"){if(t==="reprint"){u("Model-based assignment only works with queue mode","error"),pe(!1);return}let Yt=0;for(const Ht of ht){Yt++,q({current:Yt,total:qe});const tn=Ht?Ht.index:v;try{if(t==="edit-queue-item"&&!Ht){const ln={printer_id:null,target_model:G,target_location:te,filament_overrides:nn||null,require_previous_success:T.requirePreviousSuccess,auto_off_after:T.autoOffAfter,manual_start:T.scheduleType==="manual",ams_mapping:void 0,plate_id:tn,scheduled_time:T.scheduleType==="scheduled"&&T.scheduledTime?new Date(T.scheduledTime).toISOString():null,...N};await He.mutateAsync(ln)}else await xe.mutateAsync(sn(null,tn));pt.success++}catch(ln){pt.failed++;const mn=Ht?Ht.name||`Plate ${Ht.index}`:"";pt.errors.push(mn?`${mn}: ${ln.message}`:ln.message)}}}else{let Yt=0;for(const Ht of ht){const tn=Ht?Ht.index:v;for(let ln=0;lntt.id===mn)?.name||`Printer ${mn}`,je=Ht?Ht.name||`Plate ${Ht.index}`:"",Ze=je?`${Ue} (${je})`:Ue;pt.errors.push(`${Ze}: ${fn.message}`)}}}}pe(!1),pt.failed===0?(t!=="reprint"&&(t==="edit-queue-item"?u("Queue item updated"):pt.success===1?u($==="model"?`Queued for any ${G}`:c("queue.printQueued")):u(c("queue.itemsQueued",{count:pt.success}))),d.invalidateQueries({queryKey:["queue"]}),l?.(),o()):pt.success===0?u(`Failed: ${pt.errors[0]}`,"error"):(u(`${pt.success} succeeded, ${pt.failed} failed`,"error"),d.invalidateQueries({queryKey:["queue"]}))},Ve=le||He.isPending,De=w.useMemo(()=>!(Ve||$==="printer"&&f.length===0||$==="model"&&!G||$==="model"&&t==="reprint"||Ae&&!v&&!y),[f.length,$,G,t,Ae,v,y,Ve]),we=(()=>{const lt=f.length;if(t==="reprint")return{title:c(p?"queue.print":"queue.reprint"),icon:_r,submitText:lt>1?c("queue.printToPrinters",{count:lt}):c("queue.print"),submitIcon:_r,loadingText:Te.total>1?c("queue.sendingProgress",{current:Te.current,total:Te.total}):c("queue.sending")};if(t==="add-to-queue"){let ht=c("queue.addToQueue");return y&&Ge.length>1?ht=c("queue.queueAllPlates",{count:Ge.length}):lt>1&&(ht=c("queue.queueToPrinters",{count:lt})),{title:c("queue.schedulePrint"),icon:Xr,submitText:ht,submitIcon:Xr,loadingText:Te.total>1?c("queue.addingProgress",{current:Te.current,total:Te.total}):c("queue.adding")}}return{title:c("queue.editQueueItem"),icon:Ki,submitText:c("common.save"),submitIcon:Ki,loadingText:Te.total>1?c("queue.savingProgress",{current:Te.current,total:Te.total}):c("common.saving")}})(),Ke=we.icon,ot=we.submitIcon,St=I&&!y&&(p||(Ae?v!==null:!0));return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:le?void 0:o,children:i.jsx(Tt,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:lt=>lt.stopPropagation(),children:i.jsxs(Pt,{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(Ke,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:we.title})]}),i.jsx(Oe,{variant:"ghost",size:"sm",onClick:o,disabled:le,children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:Pe,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&&z?i.jsx("span",{className:"text-white",children:z.find(lt=>lt.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(Q$e,{plates:Ge,isMultiPlate:Ae,selectedPlate:v,onSelect:g,queueAll:y,onQueueAllChange:t==="add-to-queue"?_:void 0}),!s?.length&&i.jsx(eqe,{printers:z||[],selectedPrinterIds:f,onMultiSelect:x,isLoading:V,allowMultiple:!0,showInactive:t==="edit-queue-item",disableBusy:t==="reprint",printerMappingResults:$e.printerResults,filamentReqs:he,onAutoConfigurePrinter:$e.autoConfigurePrinter,onUpdatePrinterConfig:$e.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":$,onAssignmentModeChange:t!=="reprint"?U:void 0,targetModel:G,onTargetModelChange:t!=="reprint"?L:void 0,targetLocation:te,onTargetLocationChange:t!=="reprint"?re:void 0,slicedForModel:ne}),$==="model"&&G&&he&&Me&&Me.length>0&&i.jsx(X$e,{filamentReqs:he,availableFilaments:Me,overrides:J,onChange:ue,forceColorMatch:me,onForceColorMatchChange:(lt,ht)=>fe(qe=>({...qe,[lt]:ht}))}),ne&&$==="printer"&&f.length===1&&(()=>{const lt=z?.find(ht=>ht.id===f[0]);return lt&<.model&&ne!==lt.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(An,{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 ",ne,", but printing on ",lt.model]})]}):null})(),ye&&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(zi,{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."})]}),St&&!ye&&f.length===1&&i.jsx(Y$e,{printerId:I,filamentReqs:he,manualMappings:k,onManualMappingChange:D,defaultExpanded:!!s?.length||(W?.per_printer_mapping_expanded??!1),currencySymbol:B,defaultCostPerKg:ae}),(t==="reprint"||E>0||$==="model"&&G)&&i.jsx(nqe,{options:N,onChange:C,defaultExpanded:!!s?.length}),t!=="reprint"&&i.jsx(rqe,{options:T,onChange:P,dateFormat:W?.date_format||"system",timeFormat:W?.time_format||"system",canControlPrinter:m("printers:control")}),He.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:He.error?.message||"Failed to complete operation"}),i.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[i.jsx(Oe,{type:"button",variant:"secondary",onClick:o,className:"flex-1",disabled:le,children:"Cancel"}),i.jsx(Oe,{type:"submit",disabled:!De,className:"flex-1",children:Ve?i.jsxs(i.Fragment,{children:[i.jsx(ct,{className:"w-4 h-4 animate-spin"}),we.loadingText]}):i.jsxs(i.Fragment,{children:[i.jsx(ot,{className:"w-4 h-4"}),we.submitText]})})]})]})]})})})}function CG({value:t}){const{t:e}=Mt(),[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(Vr,{className:"w-3.5 h-3.5 text-bambu-green"}):i.jsx(_l,{className:"w-3.5 h-3.5"})})}function aqe({printer:t,status:e,totalPrintHours:n,onClose:r}){const{t:a}=Mt();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(CG,{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(CG,{value:t.serial_number})]})}),e?.wifi_signal!=null){const o=RQ(e.wifi_signal);s.push({label:a("printers.wifiSignalLabel"),value:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(QY,{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:Wp(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(Tt,{className:"w-full max-w-md",onClick:o=>o.stopPropagation(),children:i.jsxs(Pt,{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(zt,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsx("div",{className:"flex justify-center mb-4",children:i.jsx("img",{src:DQ(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 sqe(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 sj({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&&sqe(t)?"#000":"#fff"},children:r})})}const TG={"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"},oqe={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 oj(t){if(!t)return null;if(TG[t])return TG[t];const e=t.split("-");if(e.length<2)return null;const n=e[1];return oqe[n]||null}function lj(t){return(t??.02).toFixed(3)}function PG({side:t}){const{mode:e}=xf(),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 tre(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 nre(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function rre({slot:t,index:e,activeStatus:n,filamentName:r,children:a}){const{t:s}=Mt(),[o,l]=w.useState(!1),[c,d]=w.useState("top"),u=w.useRef(null),m=w.useRef(null),p=w.useRef(null),f=!t.nozzle_diameter&&!t.nozzle_type,x=t.stat===1;w.useEffect(()=>{if(o&&u.current&&m.current){const C=u.current.getBoundingClientRect(),T=m.current.offsetHeight,k=C.top-56,D=window.innerHeight-C.bottom;kk?d("bottom"):d("top")}},[o]);const v=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},g=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const y=R4(t.filament_color),_=tre(t.nozzle_type,s),N=nre(t.nozzle_type,s);return i.jsxs("div",{ref:u,className:"relative",onMouseEnter:v,onMouseLeave:g,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 diff --git a/static/index.html b/static/index.html index e1141a8fd..52ff022f3 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - + From 987e18bab95b2d475bb7d2cc29e1d13e00821ea0 Mon Sep 17 00:00:00 2001 From: maziggy Date: Tue, 10 Mar 2026 12:53:48 +0100 Subject: [PATCH 06/10] Updated README --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2278febef..552a53388 100644 --- a/README.md +++ b/README.md @@ -624,6 +624,7 @@ AGPL-3.0 License β€” see [LICENSE](LICENSE) for details. ## πŸ™ Acknowledgments +- [SpoolEase](https://github.com/yanshay/SpoolEase) by yanshay β€” early inspiration for NFC-based spool tracking and AMS inventory concepts - [Bambu Lab](https://bambulab.com/) for amazing printers - The reverse engineering community for protocol documentation - All testers and contributors From 19d056bbc82048c44df70512d6df5e8fc022d61d Mon Sep 17 00:00:00 2001 From: maziggy Date: Tue, 10 Mar 2026 12:57:18 +0100 Subject: [PATCH 07/10] Revert "Updated README" This reverts commit 987e18bab95b2d475bb7d2cc29e1d13e00821ea0. --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 552a53388..2278febef 100644 --- a/README.md +++ b/README.md @@ -624,7 +624,6 @@ AGPL-3.0 License β€” see [LICENSE](LICENSE) for details. ## πŸ™ Acknowledgments -- [SpoolEase](https://github.com/yanshay/SpoolEase) by yanshay β€” early inspiration for NFC-based spool tracking and AMS inventory concepts - [Bambu Lab](https://bambulab.com/) for amazing printers - The reverse engineering community for protocol documentation - All testers and contributors From 4989f5cd42b0ec6cff80916f9bffba58b9afcf07 Mon Sep 17 00:00:00 2001 From: maziggy Date: Wed, 11 Mar 2026 08:32:15 +0100 Subject: [PATCH 08/10] Updated README --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2278febef..552a53388 100644 --- a/README.md +++ b/README.md @@ -624,6 +624,7 @@ AGPL-3.0 License β€” see [LICENSE](LICENSE) for details. ## πŸ™ Acknowledgments +- [SpoolEase](https://github.com/yanshay/SpoolEase) by yanshay β€” early inspiration for NFC-based spool tracking and AMS inventory concepts - [Bambu Lab](https://bambulab.com/) for amazing printers - The reverse engineering community for protocol documentation - All testers and contributors From 283eaed2dec1880c759bf9c0b648de94776e2ee7 Mon Sep 17 00:00:00 2001 From: maziggy Date: Wed, 11 Mar 2026 08:55:03 +0100 Subject: [PATCH 09/10] Fix bed cooled notification never firing (#497) Two bugs prevented bed cooldown notifications from working: 1. Stale temperature data: After print completion, the printer sends partial MQTT updates without bed_temper, leaving the cached value frozen at the end-of-print temperature. The monitor polled for 30 minutes seeing the stale value above threshold, then timed out. Fix: send periodic pushall commands to force fresh temperature data. 2. Missing fields in provider create endpoint: on_bed_cooled and all 7 queue event toggles were omitted from the NotificationProvider constructor, silently discarding user selections on create (update worked fine via dynamic setattr). Also added debug logging to the bed cooldown polling loop. --- CHANGELOG.md | 2 ++ backend/app/api/routes/notifications.py | 10 ++++++++++ backend/app/main.py | 19 ++++++++++++++++++- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dcb380e39..d41ed0ad4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ All notable changes to Bambuddy will be documented in this file. - **Separate Permission for AMS Spool Assignments** ([#635](https://github.com/maziggy/bambuddy/issues/635)) β€” Added a new `inventory:view_assignments` permission that controls whether spool-to-AMS-slot assignment data is visible on the Printers page. Previously, viewing spool assignments on printer cards required `inventory:read`, which also exposed the full Inventory page in the sidebar. Admins can now grant `inventory:view_assignments` without `inventory:read` so users can see what's loaded in the AMS without accessing the full spool inventory. All default groups (Administrators, Operators, Viewers) include the new permission automatically. Also fixed multi-word permission labels in the group editor (e.g. "Update_Own" β†’ "Update Own"). Reported by @Minebuddy. ### Fixed +- **Bed Cooled Notification Never Fires** ([#497](https://github.com/maziggy/bambuddy/issues/497)) β€” The bed cooldown monitor always timed out after 30 minutes without sending a notification. After print completion, P1S (and likely other models) sends partial MQTT status updates that don't include `bed_temper`, so the cached bed temperature stayed frozen at the end-of-print value and never dropped below the threshold. The monitor now sends periodic `pushall` commands to the printer to force fresh temperature data. Also added debug logging to the polling loop for future diagnostics. +- **Notification Provider Missing Event Toggles on Create** ([#497](https://github.com/maziggy/bambuddy/issues/497)) β€” When creating a new notification provider, the `on_bed_cooled` toggle and all 7 queue event toggles (`on_queue_job_added`, `on_queue_job_assigned`, `on_queue_job_started`, `on_queue_job_waiting`, `on_queue_job_skipped`, `on_queue_job_failed`, `on_queue_completed`) were silently discarded. The create endpoint manually listed each field but omitted these 8 toggles, so they always defaulted to `false` regardless of user selection. Editing an existing provider worked correctly. - **Clear Plate Prompt Shown for Staged Queue Items** β€” The "Clear Plate & Start Next" button on the printer card appeared when all pending queue items were staged (`manual_start`/Queue Only), even though the scheduler won't auto-start them. The clear plate prompt now only appears when there are auto-dispatchable items that the scheduler will actually start after the plate is cleared. - **Ethernet Badge Always Shown on Printer Cards** β€” The printer card network badge always showed "Ethernet" instead of the WiFi signal indicator, even on printers without an ethernet port. The `home_flag` bit 18 was incorrectly interpreted as indicating a wired connection. Removed the faulty ethernet detection; the WiFi signal badge now displays correctly when the printer reports signal strength. - **GitHub Backup Required Cloud Login** ([#655](https://github.com/maziggy/bambuddy/issues/655)) β€” The GitHub backup settings card was completely blocked behind Bambu Cloud authentication, showing "Bambu Cloud login required" even though the backup feature works without it (K-profiles and app settings don't need cloud). Removed the cloud auth gate so GitHub backup can be configured and used without Bambu Cloud. The "Cloud Profiles" checkbox is disabled with a hint when not logged in. Reported by @TravisWilder. diff --git a/backend/app/api/routes/notifications.py b/backend/app/api/routes/notifications.py index 426ddd002..f40ff0205 100644 --- a/backend/app/api/routes/notifications.py +++ b/backend/app/api/routes/notifications.py @@ -133,6 +133,16 @@ async def create_notification_provider( on_ams_ht_temperature_high=provider_data.on_ams_ht_temperature_high, # Build plate detection on_plate_not_empty=provider_data.on_plate_not_empty, + # Bed cooled + on_bed_cooled=provider_data.on_bed_cooled, + # Print queue events + on_queue_job_added=provider_data.on_queue_job_added, + on_queue_job_assigned=provider_data.on_queue_job_assigned, + on_queue_job_started=provider_data.on_queue_job_started, + on_queue_job_waiting=provider_data.on_queue_job_waiting, + on_queue_job_skipped=provider_data.on_queue_job_skipped, + on_queue_job_failed=provider_data.on_queue_job_failed, + on_queue_completed=provider_data.on_queue_completed, # Quiet hours quiet_hours_enabled=provider_data.quiet_hours_enabled, quiet_hours_start=provider_data.quiet_hours_start, diff --git a/backend/app/main.py b/backend/app/main.py index c2fdf33a2..80947b8bb 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -2306,10 +2306,19 @@ async def on_print_complete(printer_id: int, data: dict): logger.info("[BED-COOL] Monitoring bed temp for printer %s (threshold: %.0fΒ°C)", printer_id, threshold) + # Request a fresh full status so we get current bed_temper + printer_manager.request_status_update(printer_id) + max_polls = 120 # 120 * 15s = 30 min timeout - for _ in range(max_polls): + for poll_num in range(max_polls): await asyncio.sleep(15) + # Request fresh temperature data every 60s β€” after print completion, + # the printer may send partial MQTT updates without bed_temper, + # leaving the cached value stale at the end-of-print temperature. + if poll_num % 4 == 0: + printer_manager.request_status_update(printer_id) + # Check if printer is still connected status = printer_manager.get_status(printer_id) if status is None: @@ -2327,8 +2336,16 @@ async def on_print_complete(printer_id: int, data: dict): bed_temp = status.temperatures.get("bed") if bed_temp is None: + logger.debug( + "[BED-COOL] Printer %s: bed temp is None (keys: %s, state: %s)", + printer_id, + list(status.temperatures.keys()) if isinstance(status.temperatures, dict) else "N/A", + status.state if hasattr(status, "state") else "N/A", + ) continue + logger.debug("[BED-COOL] Printer %s: bed=%.1fΒ°C, threshold=%.0fΒ°C", printer_id, bed_temp, threshold) + if bed_temp <= threshold: logger.info( "[BED-COOL] Bed cooled to %.1fΒ°C on printer %s (threshold: %.0fΒ°C)", From 53b8cbc16919883bd131310d0feec67d73a31af1 Mon Sep 17 00:00:00 2001 From: maziggy Date: Wed, 11 Mar 2026 09:29:03 +0100 Subject: [PATCH 10/10] Added debug logging for ffmpeg process --- backend/app/api/routes/camera.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/backend/app/api/routes/camera.py b/backend/app/api/routes/camera.py index 12c0f12ef..1748f3a66 100644 --- a/backend/app/api/routes/camera.py +++ b/backend/app/api/routes/camera.py @@ -275,6 +275,14 @@ async def generate_rtsp_mjpeg_stream( if not chunk: logger.warning("Camera stream ended (no more data)") + # Log ffmpeg stderr for diagnostics + if process and process.stderr: + try: + stderr_data = await asyncio.wait_for(process.stderr.read(), timeout=2.0) + if stderr_data: + logger.warning("ffmpeg stderr: %s", stderr_data.decode(errors="replace")) + except (TimeoutError, Exception): + pass break buffer += chunk @@ -317,6 +325,14 @@ async def generate_rtsp_mjpeg_stream( except TimeoutError: logger.warning("Camera stream read timeout") + # Log ffmpeg stderr for diagnostics + if process and process.stderr: + try: + stderr_data = await asyncio.wait_for(process.stderr.read(), timeout=2.0) + if stderr_data: + logger.warning("ffmpeg stderr on timeout: %s", stderr_data.decode(errors="replace")) + except (TimeoutError, Exception): + pass break except asyncio.CancelledError: logger.info("Camera stream cancelled (stream_id=%s)", stream_id)