From 0b2b81a34df198dc1dd706023c3828de9e074c13 Mon Sep 17 00:00:00 2001 From: maziggy Date: Thu, 19 Mar 2026 11:03:10 +0100 Subject: [PATCH] [Fix] Virtual Printer proxy mode fails on isolated networks (#757) When the slicer and printer are on different VLANs, Bambu Studio could not send prints through the proxy because the printer's real IP leaked through MQTT payloads, the bind protocol forwarded the real printer's identity, the port 6000 file transfer tunnel was not proxied, and FTP data connections raced the TLS handshake on zero-byte uploads. - Rewrite IP addresses in MQTT PUBLISH payloads (string + integer) with proper packet framing and cross-chunk buffering - Respond to bind/detect with VP identity via BindServer - Add TLS proxy for port 6000 (file transfer tunnel) - Buffer slicer FTP data during printer connection setup - Advertise configured VP name in SSDP proxy - Add cross-subnet SSDP wildcard listener for VPN setups - Register UserEmailPreference model in models/__init__.py - Add 11 unit tests for MQTT rewrite, IP conversion, SSDP name --- CHANGELOG.md | 2 + backend/app/models/__init__.py | 2 + .../app/services/virtual_printer/manager.py | 7 + .../services/virtual_printer/ssdp_server.py | 125 ++++-- .../app/services/virtual_printer/tcp_proxy.py | 390 ++++++++++++++++-- .../unit/services/test_virtual_printer.py | 215 ++++++++++ .../{index-DTIUjlhj.js => index-HM8c6qA1.js} | 2 +- static/index.html | 2 +- 8 files changed, 670 insertions(+), 75 deletions(-) rename static/assets/{index-DTIUjlhj.js => index-HM8c6qA1.js} (95%) diff --git a/CHANGELOG.md b/CHANGELOG.md index d113ae1ed..720093433 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ All notable changes to Bambuddy will be documented in this file. - **User Notification Ruff/Lint Fixes** ([#693](https://github.com/maziggy/bambuddy/pull/693)) — Fixed missing `timezone` import in email timestamp, unused lambda argument, PEP 8 blank line spacing for `mark_printer_stopped_by_user`, and SQLAlchemy forward reference in `UserEmailPreference` model. - **Carbon Rod Lubrication Maintenance Task Incorrect** ([#755](https://github.com/maziggy/bambuddy/issues/755)) — X1/P1 series printers showed a "Lubricate Carbon Rods" maintenance task, but carbon rods use plain bearings and should never be lubricated — doing so degrades print quality. Removed the lubrication task; only "Clean Carbon Rods" remains. Existing "Lubricate Carbon Rods" entries are automatically removed on next startup. Reported by @RosdasHH. - **Ntfy Notifications Fail With Non-ASCII Characters** ([#742](https://github.com/maziggy/bambuddy/issues/742)) — Ntfy notifications with camera snapshots failed when the printer name or filename contained non-ASCII characters (e.g. accented letters, CJK). The `Title` and `Message` HTTP headers were passed as Python strings, causing httpx to reject them with `UnicodeEncodeError`. Fixed by encoding header values as UTF-8 bytes, which ntfy handles correctly. Test notifications were unaffected because they use a hardcoded ASCII title and no image attachment. Reported by @user. +- **Virtual Printer Proxy Mode Printing Fails on Isolated Networks** ([#757](https://github.com/maziggy/bambuddy/issues/757)) — When the slicer and printer are on different VLANs/subnets, Bambu Studio could not send prints through the virtual printer proxy because: (1) the printer's real IP leaked through MQTT payloads (`rtsp_url`, `net.info[].ip`), causing BS to bypass the proxy; (2) the bind/detect protocol (port 3000/3002) was forwarded to the real printer, leaking its identity and name; (3) the file transfer tunnel (port 6000) used by BS for verify_job and uploads was not proxied; (4) FTP data connections for zero-byte uploads (verify_job) failed due to a TLS handshake race condition. Fixed by: rewriting IP addresses in MQTT PUBLISH payloads (both string and integer formats) with proper MQTT framing preservation, responding to bind/detect with the VP's own identity via BindServer, adding a TLS proxy for port 6000, buffering slicer data during FTP data proxy connection setup, and advertising the configured VP name in SSDP. Also added cross-subnet SSDP support via a wildcard listener for VPN/multi-subnet setups. Reported by @Utility9298. +- **UserEmailPreference Model Not Registered** — The `UserEmailPreference` SQLAlchemy model was not imported in `models/__init__.py`, causing mapper initialization failures when the `User` model's relationship resolved the string reference before the model class was registered with Base metadata. ### Added - **Quick Print Speed Control** ([#256](https://github.com/maziggy/bambuddy/issues/256)) — Added a print speed control badge to the printer card controls row, next to the fan status badges. Click to choose between Silent (50%), Standard (100%), Sport (124%), and Ludicrous (166%) speed presets. The badge shows the current speed percentage with a gauge icon, always visible but disabled when no print is active. Includes optimistic UI updates for instant feedback. Requested by @Sllepper. diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index b3bbbbb12..350121cdc 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -25,6 +25,7 @@ from backend.app.models.spool_k_profile import SpoolKProfile from backend.app.models.spool_usage_history import SpoolUsageHistory from backend.app.models.spoolbuddy_device import SpoolBuddyDevice from backend.app.models.user import User +from backend.app.models.user_email_pref import UserEmailPreference __all__ = [ "Printer", @@ -59,4 +60,5 @@ __all__ = [ "SpoolUsageHistory", "ColorCatalogEntry", "SpoolBuddyDevice", + "UserEmailPreference", ] diff --git a/backend/app/services/virtual_printer/manager.py b/backend/app/services/virtual_printer/manager.py index 95633486f..aadd31f22 100644 --- a/backend/app/services/virtual_printer/manager.py +++ b/backend/app/services/virtual_printer/manager.py @@ -473,6 +473,12 @@ class VirtualPrinterInstance: key_path=key_path, on_activity=lambda n, m: logger.info("[VP %s] Proxy %s: %s", self.name, n, m), bind_address=self.bind_ip or "0.0.0.0", # nosec B104 + bind_identity={ + "serial": self.target_printer_serial or self.serial, + "model": self.model or DEFAULT_VIRTUAL_PRINTER_MODEL, + "name": self.name, + "version": "01.00.00.00", + }, ) async def run_with_logging(coro, svc_name): @@ -494,6 +500,7 @@ class VirtualPrinterInstance: local_interface_ip=local_iface["ip"], remote_interface_ip=self.remote_interface_ip, target_printer_ip=self.target_printer_ip, + name=self.name, ) self._tasks.append( asyncio.create_task( diff --git a/backend/app/services/virtual_printer/ssdp_server.py b/backend/app/services/virtual_printer/ssdp_server.py index 4fd1a735c..eb0a17fac 100644 --- a/backend/app/services/virtual_printer/ssdp_server.py +++ b/backend/app/services/virtual_printer/ssdp_server.py @@ -35,6 +35,7 @@ class VirtualPrinterSSDPServer: model: str = "BL-P001", # X1C model code for best compatibility advertise_ip: str = "", bind_ip: str = "", + extra_interfaces: list[str] | None = None, ): """Initialize the SSDP server. @@ -44,6 +45,10 @@ class VirtualPrinterSSDPServer: model: Model code advertise_ip: Override IP to advertise instead of auto-detecting bind_ip: IP address to bind the SSDP socket to + extra_interfaces: Additional interface IPs to broadcast on (e.g. VPN). + NOTIFY and M-SEARCH responses are sent on these interfaces too, + but Location always points to the bind IP so the slicer connects + to the correct address for MQTT/FTP. """ self.name = name self.serial = serial @@ -51,6 +56,8 @@ class VirtualPrinterSSDPServer: self._bind_ip = bind_ip self._running = False self._socket: socket.socket | None = None + self._extra_sockets: list[socket.socket] = [] + self._extra_interfaces = extra_interfaces or [] self._local_ip: str | None = advertise_ip or bind_ip or None def _get_local_ip(self) -> str: @@ -163,6 +170,30 @@ class VirtualPrinterSSDPServer: logger.info("SSDP server listening on port %s, advertising IP: %s", SSDP_PORT, local_ip) logger.info("Virtual printer: %s (%s) model=%s", self.name, self.serial, self.model) + # Create extra sockets for additional interfaces (VPN, etc.) + # If no explicit extra interfaces given and we're bound to a + # specific IP, add a wildcard socket to catch M-SEARCH from + # other subnets (VPN tunnels, secondary NICs, etc.) + extra_ips = list(self._extra_interfaces) + if not extra_ips and self._bind_ip: + extra_ips.append("0.0.0.0") # nosec B104 + + for iface_ip in extra_ips: + try: + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + except (AttributeError, OSError): + pass + sock.setblocking(False) + sock.bind((iface_ip, SSDP_PORT)) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) + self._extra_sockets.append(sock) + logger.info("SSDP server also listening on %s:%s", iface_ip, SSDP_PORT) + except OSError as e: + logger.warning("SSDP server: failed to bind extra interface %s: %s", iface_ip, e) + # Send initial NOTIFY await self._send_notify() logger.info("Sent initial SSDP NOTIFY announcement") @@ -172,7 +203,7 @@ class VirtualPrinterSSDPServer: notify_interval = 30.0 # Send NOTIFY every 30 seconds while self._running: - # Try to receive M-SEARCH requests + # Try to receive M-SEARCH requests on primary socket try: data, addr = self._socket.recvfrom(4096) message = data.decode("utf-8", errors="ignore") @@ -183,6 +214,17 @@ class VirtualPrinterSSDPServer: if self._running: logger.debug("SSDP receive error: %s", e) + # Try to receive M-SEARCH requests on extra sockets + for sock in self._extra_sockets: + try: + data, addr = sock.recvfrom(4096) + message = data.decode("utf-8", errors="ignore") + await self._handle_message(message, addr, sock) + except BlockingIOError: + pass + except OSError: + pass + # Send periodic NOTIFY now = asyncio.get_event_loop().time() if now - last_notify >= notify_interval: @@ -224,23 +266,35 @@ class VirtualPrinterSSDPServer: pass # Best-effort socket close; may already be released self._socket = None - async def _send_notify(self) -> None: - """Send SSDP NOTIFY message via broadcast.""" - if not self._socket: - return + for sock in self._extra_sockets: + try: + sock.close() + except OSError: + pass + self._extra_sockets = [] - try: - msg = self._build_notify_message() - self._socket.sendto(msg, (SSDP_BROADCAST_ADDR, SSDP_PORT)) - logger.debug( - "Sent SSDP NOTIFY for %s (Location=%s, USN=%s, bind=%s)", - self.name, - self._get_local_ip(), - self.serial, - self._bind_ip, - ) - except OSError as e: - logger.debug("Failed to send NOTIFY for %s: %s", self.name, e) + async def _send_notify(self) -> None: + """Send SSDP NOTIFY message via broadcast on all sockets.""" + msg = self._build_notify_message() + + if self._socket: + try: + self._socket.sendto(msg, (SSDP_BROADCAST_ADDR, SSDP_PORT)) + logger.debug( + "Sent SSDP NOTIFY for %s (Location=%s, USN=%s, bind=%s)", + self.name, + self._get_local_ip(), + self.serial, + self._bind_ip, + ) + except OSError as e: + logger.debug("Failed to send NOTIFY for %s: %s", self.name, e) + + for sock in self._extra_sockets: + try: + sock.sendto(msg, (SSDP_BROADCAST_ADDR, SSDP_PORT)) + except OSError: + pass # Best-effort broadcast on extra interfaces async def _send_byebye(self) -> None: """Send SSDP byebye message when shutting down.""" @@ -262,12 +316,15 @@ class VirtualPrinterSSDPServer: except OSError: pass # Best-effort byebye send; network may be unavailable during shutdown - async def _handle_message(self, message: str, addr: tuple[str, int]) -> None: + async def _handle_message( + self, message: str, addr: tuple[str, int], reply_socket: socket.socket | None = None + ) -> None: """Handle incoming SSDP message. Args: message: The SSDP message content addr: Tuple of (ip_address, port) of sender + reply_socket: Socket to send the response on (defaults to primary) """ # Check if this is an M-SEARCH request for Bambu printers if "M-SEARCH" not in message: @@ -279,11 +336,12 @@ class VirtualPrinterSSDPServer: logger.debug("Received M-SEARCH from %s", addr[0]) - # Send response - if self._socket: + # Send response on the socket that received the request + sock = reply_socket or self._socket + if sock: try: response = self._build_response_message() - self._socket.sendto(response, addr) + sock.sendto(response, addr) logger.info( "Sent SSDP response to %s for '%s' (Location=%s, USN=%s)", addr[0], @@ -310,6 +368,7 @@ class SSDPProxy: local_interface_ip: str, remote_interface_ip: str, target_printer_ip: str, + name: str | None = None, ): """Initialize the SSDP proxy. @@ -317,10 +376,12 @@ class SSDPProxy: local_interface_ip: IP of interface on printer's network (LAN A) remote_interface_ip: IP of interface on slicer's network (LAN B) target_printer_ip: IP of the real printer to proxy SSDP for + name: Optional VP name to advertise (replaces printer's real name) """ self.local_interface_ip = local_interface_ip self.remote_interface_ip = remote_interface_ip self.target_printer_ip = target_printer_ip + self.proxy_name = name self._running = False self._local_socket: socket.socket | None = None self._remote_socket: socket.socket | None = None @@ -365,13 +426,21 @@ class SSDPProxy: text, flags=re.IGNORECASE, ) - # Append " - Proxy" to printer name so it's distinguishable - text = re.sub( - r"(DevName\.bambu\.com:\s*)(.+)", - r"\g<1>\g<2> - Proxy", - text, - flags=re.IGNORECASE, - ) + # Replace printer name with configured VP name, or append " - Proxy" + if self.proxy_name: + text = re.sub( + r"(DevName\.bambu\.com:\s*)[^\r\n]+", + rf"\g<1>{self.proxy_name}", + text, + flags=re.IGNORECASE, + ) + else: + text = re.sub( + r"(DevName\.bambu\.com:\s*)([^\r\n]+)", + r"\g<1>\g<2> - Proxy", + text, + flags=re.IGNORECASE, + ) if text != original: logger.debug("Rewrote SSDP for proxy:\n%s", text) else: diff --git a/backend/app/services/virtual_printer/tcp_proxy.py b/backend/app/services/virtual_printer/tcp_proxy.py index cb7a37689..1c28380e5 100644 --- a/backend/app/services/virtual_printer/tcp_proxy.py +++ b/backend/app/services/virtual_printer/tcp_proxy.py @@ -82,6 +82,7 @@ class TLSProxy: on_connect: Callable[[str], None] | None = None, on_disconnect: Callable[[str], None] | None = None, bind_address: str = "0.0.0.0", # nosec B104 + rewrite_ip: tuple[str, str] | None = None, ): """Initialize the TLS proxy. @@ -95,6 +96,10 @@ class TLSProxy: on_connect: Optional callback when client connects (receives client_id) on_disconnect: Optional callback when client disconnects (receives client_id) bind_address: IP address to bind to (default: all interfaces) + rewrite_ip: Optional (old_ip, new_ip) tuple — replaces occurrences of + the printer's real IP with the proxy's bind IP in printer→client data. + This prevents the slicer from discovering the printer's real IP + in MQTT payloads (ip_addr, rtsp_url, etc.) and bypassing the proxy. """ self.name = name self.listen_port = listen_port @@ -106,12 +111,41 @@ class TLSProxy: self.on_disconnect = on_disconnect self.bind_address = bind_address + # IP rewriting for printer→client direction + if rewrite_ip: + self._rewrite_old = rewrite_ip[0].encode("utf-8") + self._rewrite_new = rewrite_ip[1].encode("utf-8") + # Also rewrite the integer IP in net.info[].ip fields. + # Bambu printers encode their IP as a little-endian uint32 integer + # in the JSON payload. BambuStudio reads this to set dev_ip. + self._rewrite_old_int = self._ip_to_le_int_bytes(rewrite_ip[0]) + self._rewrite_new_int = self._ip_to_le_int_bytes(rewrite_ip[1]) + else: + self._rewrite_old = None + self._rewrite_new = None + self._rewrite_old_int = None + self._rewrite_new_int = None + self._server: asyncio.Server | None = None self._running = False self._active_connections: dict[str, tuple[asyncio.Task, asyncio.Task]] = {} self._server_ssl_context: ssl.SSLContext | None = None self._client_ssl_context: ssl.SSLContext | None = None + @staticmethod + def _ip_to_le_int_bytes(ip: str) -> bytes: + """Convert an IP address to its little-endian integer JSON representation. + + E.g. "192.168.255.16" → b"285190336" (the integer as a decimal string, + as it appears in Bambu MQTT JSON payloads in the net.info[].ip field). + """ + import struct as _struct + + parts = ip.split(".") + packed = bytes(int(p) for p in parts) + le_int = _struct.unpack(" ssl.SSLContext: """Create SSL context for accepting client (slicer) connections.""" ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) @@ -263,7 +297,7 @@ class TLSProxy: name=f"{self.name}_c2p_{client_id}", ) printer_to_client = asyncio.create_task( - self._forward(printer_reader, client_writer, f"printer→{client_id}"), + self._forward(printer_reader, client_writer, f"printer→{client_id}", rewrite_ip=True), name=f"{self.name}_p2c_{client_id}", ) @@ -305,11 +339,157 @@ class TLSProxy: except Exception: pass # Ignore disconnect callback errors; cleanup continues + @staticmethod + def _rewrite_mqtt_ip( + data: bytes, + old_ip: bytes, + new_ip: bytes, + buffer: bytearray, + extra_replacements: list[tuple[bytes, bytes]] | None = None, + ) -> tuple[bytes, bytearray]: + """Rewrite IP addresses inside MQTT packets, preserving packet framing. + + MQTT packets have a variable-length header encoding the remaining + packet length. A naive bytes.replace() would corrupt this framing + when old_ip and new_ip differ in length. + + This method parses individual MQTT packets out of the data stream, + performs the replacement only on PUBLISH payloads, and re-encodes + the remaining-length field to match the new size. + + Incomplete packets are buffered and returned for the next call. + + Args: + extra_replacements: Additional (old, new) byte pairs to replace + (e.g. the integer IP representation in net.info[].ip). + + Returns (output_data, remaining_buffer). + """ + buffer.extend(data) + + # Check if any replacement target exists in the buffer + has_target = old_ip in buffer + if not has_target and extra_replacements: + has_target = any(old in buffer for old, _new in extra_replacements) + + if not has_target: + # Fast path: no IP in buffer, but we still need to check for + # incomplete packets at the end that might contain a partial IP. + # For safety, try to parse and emit only complete packets. + result = bytearray() + pos = 0 + length = len(buffer) + + while pos < length: + packet_start = pos + if pos + 1 >= length: + break + pos += 1 # header byte + + # Parse remaining length + remaining_length = 0 + multiplier = 1 + length_bytes = 0 + while pos < length: + encoded_byte = buffer[pos] + pos += 1 + remaining_length += (encoded_byte & 0x7F) * multiplier + multiplier *= 128 + length_bytes += 1 + if (encoded_byte & 0x80) == 0: + break + if length_bytes >= 4: + break + + if pos + remaining_length > length: + # Incomplete — keep in buffer + new_buffer = bytearray(buffer[packet_start:]) + return bytes(result), new_buffer + + pos += remaining_length + result.extend(buffer[packet_start:pos]) + + # All complete + buffer.clear() + return bytes(result) if result else bytes(data), buffer + + # Buffer contains old_ip — parse packets and rewrite + result = bytearray() + pos = 0 + length = len(buffer) + + while pos < length: + packet_start = pos + + if pos >= length: + break + header_byte = buffer[pos] + pos += 1 + + # Remaining length: variable-length encoding (1-4 bytes) + remaining_length = 0 + multiplier = 1 + length_bytes = 0 + while pos < length: + encoded_byte = buffer[pos] + pos += 1 + remaining_length += (encoded_byte & 0x7F) * multiplier + multiplier *= 128 + length_bytes += 1 + if (encoded_byte & 0x80) == 0: + break + if length_bytes >= 4: + break + + # Check if we have enough data for the full packet + if pos + remaining_length > length: + # Incomplete packet — keep in buffer for next call + new_buffer = bytearray(buffer[packet_start:]) + return bytes(result), new_buffer + + packet_type = (header_byte >> 4) & 0x0F + packet_body = buffer[pos : pos + remaining_length] + pos += remaining_length + + # Only rewrite PUBLISH packets (type 3) + needs_rewrite = packet_type == 3 and ( + old_ip in packet_body + or (extra_replacements and any(old in packet_body for old, _new in extra_replacements)) + ) + if needs_rewrite: + new_body = bytes(packet_body).replace(old_ip, new_ip) + if extra_replacements: + for old_val, new_val in extra_replacements: + new_body = new_body.replace(old_val, new_val) + + # Re-encode: header byte + new remaining length + new body + result.append(header_byte) + + # Encode remaining length (MQTT variable-length encoding) + new_remaining = len(new_body) + while True: + encoded_byte = new_remaining % 128 + new_remaining //= 128 + if new_remaining > 0: + encoded_byte |= 0x80 + result.append(encoded_byte) + if new_remaining == 0: + break + + result.extend(new_body) + else: + # Pass through unchanged + result.extend(buffer[packet_start:pos]) + + buffer.clear() + return bytes(result), buffer + async def _forward( self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, direction: str, + rewrite_ip: bool = False, ) -> None: """Forward data from reader to writer. @@ -317,7 +497,12 @@ class TLSProxy: reader: Source stream (already TLS-decrypted) writer: Destination stream (will be TLS-encrypted by the stream) direction: Description for logging (e.g., "client→printer") + rewrite_ip: If True and rewrite_ip was configured, replace the + printer's real IP with the proxy's bind IP in the data. """ + do_rewrite = rewrite_ip and self._rewrite_old is not None + rewrite_buffer = bytearray() if do_rewrite else None + rewrite_logged = False total_bytes = 0 try: while self._running: @@ -327,6 +512,29 @@ class TLSProxy: # Connection closed break + # Rewrite printer IP → proxy IP in MQTT PUBLISH payloads + # to prevent the slicer from bypassing the proxy. + if do_rewrite: + original_len = len(data) + extra = [(self._rewrite_old_int, self._rewrite_new_int)] if self._rewrite_old_int else None + data, rewrite_buffer = self._rewrite_mqtt_ip( + data, + self._rewrite_old, + self._rewrite_new, + rewrite_buffer, + extra_replacements=extra, + ) + if not rewrite_logged and data and len(data) != original_len: + logger.info( + "%s proxy IP rewrite active: %s → %s", + self.name, + self._rewrite_old.decode(), + self._rewrite_new.decode(), + ) + rewrite_logged = True + if not data: + continue # All data buffered, waiting for more + # Forward to destination writer.write(data) await writer.drain() @@ -923,6 +1131,11 @@ class FTPTLSProxy(TLSProxy): async def _start_data_proxy_server(self, port: int, printer_ip: str, printer_port: int, use_tls: bool) -> None: """Start a one-shot server for one FTP data connection. + When the slicer connects, immediately connects to the printer's data + port and buffers any slicer data until the printer connection is ready. + This handles zero-byte uploads (verify_job) where the slicer closes + the data channel before a naive proxy would finish its TLS handshake. + The slicer-side listener is ALWAYS cleartext. Even when the slicer sends PROT P on the control channel, Bambu Studio does not perform a TLS handshake on the data connection — it relies on the implicit @@ -967,13 +1180,26 @@ class FTPTLSProxy(TLSProxy): printer_writer = None try: + # Buffer any slicer data while connecting to printer. + # This handles the race where the slicer sends data (or closes + # for zero-byte files) before the TLS handshake completes. + slicer_buffer = bytearray() + slicer_eof = False + + async def buffer_slicer(): + nonlocal slicer_eof + while True: + chunk = await client_reader.read(65536) + if not chunk: + slicer_eof = True + return + slicer_buffer.extend(chunk) + + buffer_task = asyncio.create_task(buffer_slicer()) + # Connect to printer's data port printer_reader, printer_writer = await asyncio.wait_for( - asyncio.open_connection( - printer_ip, - printer_port, - ssl=client_ssl, - ), + asyncio.open_connection(printer_ip, printer_port, ssl=client_ssl), timeout=10.0, ) logger.info( @@ -984,21 +1210,35 @@ class FTPTLSProxy(TLSProxy): printer_port, ) - # Bidirectional data forwarding - c2p = asyncio.create_task(self._forward(client_reader, printer_writer, "data_c2p")) - p2c = asyncio.create_task(self._forward(printer_reader, client_writer, "data_p2c")) + # Stop buffering + buffer_task.cancel() + try: + await buffer_task + except asyncio.CancelledError: + pass - done, pending = await asyncio.wait([c2p, p2c], return_when=asyncio.FIRST_COMPLETED) - for task in pending: - task.cancel() - try: - await task - except asyncio.CancelledError: - pass # Expected when other data direction closes - except TimeoutError: - logger.error("FTP data proxy port %s: timeout connecting to printer", port) - except ssl.SSLError as e: - logger.error("FTP data proxy port %s: SSL error to printer: %s", port, e) + # Flush buffered slicer data to printer + if slicer_buffer: + printer_writer.write(bytes(slicer_buffer)) + await printer_writer.drain() + + if slicer_eof: + # Slicer already closed (zero-byte upload like verify_job). + # Close the printer write side to signal upload complete. + if printer_writer.can_write_eof(): + printer_writer.write_eof() + else: + # Continue bidirectional forwarding + c2p = asyncio.create_task(self._forward(client_reader, printer_writer, "data_c2p")) + p2c = asyncio.create_task(self._forward(printer_reader, client_writer, "data_p2c")) + + done, pending = await asyncio.wait([c2p, p2c], return_when=asyncio.FIRST_COMPLETED) + for task in pending: + task.cancel() + try: + await task + except asyncio.CancelledError: + pass # Expected when other data direction closes except Exception as e: logger.error("FTP data proxy port %s: error: %s", port, e) finally: @@ -1048,6 +1288,7 @@ class SlicerProxyManager: # Bambu printer ports PRINTER_FTP_PORT = 990 PRINTER_MQTT_PORT = 8883 + PRINTER_FILE_TRANSFER_PORT = 6000 PRINTER_BIND_PORTS = [3000, 3002] # Local listen ports - must match what Bambu Studio expects @@ -1062,6 +1303,7 @@ class SlicerProxyManager: key_path: Path, on_activity: Callable[[str, str], None] | None = None, bind_address: str = "0.0.0.0", # nosec B104 + bind_identity: dict[str, str] | None = None, ): """Initialize the slicer proxy manager. @@ -1071,16 +1313,23 @@ class SlicerProxyManager: key_path: Path to server private key on_activity: Optional callback for activity logging (name, message) bind_address: IP address to bind proxy listeners to + bind_identity: Optional dict with keys (serial, model, name, version) + for the bind/detect response. When provided, the proxy responds + to detect requests itself instead of forwarding to the printer. + This ensures the slicer sees the VP identity, not the real printer. """ self.target_host = target_host self.cert_path = cert_path self.key_path = key_path self.on_activity = on_activity self.bind_address = bind_address + self.bind_identity = bind_identity self._ftp_proxy: TLSProxy | None = None self._mqtt_proxy: TLSProxy | None = None + self._file_transfer_proxy: TLSProxy | None = None self._bind_proxies: list[TCPProxy] = [] + self._bind_server = None self._tasks: list[asyncio.Task] = [] async def start(self) -> None: @@ -1124,33 +1373,65 @@ class SlicerProxyManager: on_connect=lambda cid: self._log_activity("MQTT", f"connected: {cid}"), on_disconnect=lambda cid: self._log_activity("MQTT", f"disconnected: {cid}"), bind_address=self.bind_address, + rewrite_ip=(self.target_host, self.bind_address) if self.bind_address != "0.0.0.0" else None, ) - # Bind/auth proxy — port 3000 plain TCP, port 3002 TLS - for bind_port in self.PRINTER_BIND_PORTS: - if bind_port == 3002: - proxy = TLSProxy( - name="Bind-TLS", - listen_port=bind_port, - target_host=self.target_host, - target_port=bind_port, - server_cert_path=self.cert_path, - server_key_path=self.key_path, - on_connect=lambda cid: self._log_activity("Bind", f"connected: {cid}"), - on_disconnect=lambda cid: self._log_activity("Bind", f"disconnected: {cid}"), - bind_address=self.bind_address, - ) - else: - proxy = TCPProxy( - name="Bind", - listen_port=bind_port, - target_host=self.target_host, - target_port=bind_port, - on_connect=lambda cid: self._log_activity("Bind", f"connected: {cid}"), - on_disconnect=lambda cid: self._log_activity("Bind", f"disconnected: {cid}"), - bind_address=self.bind_address, - ) - self._bind_proxies.append(proxy) + # File transfer proxy — port 6000 (TLS) + # BambuStudio connects here for verify_job and actual file uploads. + self._file_transfer_proxy = TLSProxy( + name="FileTransfer", + listen_port=self.PRINTER_FILE_TRANSFER_PORT, + target_host=self.target_host, + target_port=self.PRINTER_FILE_TRANSFER_PORT, + server_cert_path=self.cert_path, + server_key_path=self.key_path, + on_connect=lambda cid: self._log_activity("FileTransfer", f"connected: {cid}"), + on_disconnect=lambda cid: self._log_activity("FileTransfer", f"disconnected: {cid}"), + bind_address=self.bind_address, + ) + + # Bind/auth — respond with VP identity instead of proxying to printer. + # The detect response contains the printer name, serial, model, and + # bind status. Proxying it would leak the real printer's identity and + # cause the slicer to treat it as a different device. + if self.bind_identity: + from backend.app.services.virtual_printer.bind_server import BindServer + + self._bind_server = BindServer( + serial=self.bind_identity["serial"], + model=self.bind_identity["model"], + name=self.bind_identity["name"], + version=self.bind_identity.get("version", "01.00.00.00"), + bind_address=self.bind_address, + cert_path=self.cert_path, + key_path=self.key_path, + ) + else: + # Fallback: proxy bind requests to the real printer + for bind_port in self.PRINTER_BIND_PORTS: + if bind_port == 3002: + proxy = TLSProxy( + name="Bind-TLS", + listen_port=bind_port, + target_host=self.target_host, + target_port=bind_port, + server_cert_path=self.cert_path, + server_key_path=self.key_path, + on_connect=lambda cid: self._log_activity("Bind", f"connected: {cid}"), + on_disconnect=lambda cid: self._log_activity("Bind", f"disconnected: {cid}"), + bind_address=self.bind_address, + ) + else: + proxy = TCPProxy( + name="Bind", + listen_port=bind_port, + target_host=self.target_host, + target_port=bind_port, + on_connect=lambda cid: self._log_activity("Bind", f"connected: {cid}"), + on_disconnect=lambda cid: self._log_activity("Bind", f"disconnected: {cid}"), + bind_address=self.bind_address, + ) + self._bind_proxies.append(proxy) # Start as background tasks async def run_with_logging(proxy: TLSProxy) -> None: @@ -1168,7 +1449,18 @@ class SlicerProxyManager: run_with_logging(self._mqtt_proxy), name="slicer_proxy_mqtt", ), + asyncio.create_task( + run_with_logging(self._file_transfer_proxy), + name="slicer_proxy_file_transfer", + ), ] + if self._bind_server: + self._tasks.append( + asyncio.create_task( + run_with_logging(self._bind_server), + name="slicer_proxy_bind_server", + ) + ) for bp in self._bind_proxies: self._tasks.append( asyncio.create_task( @@ -1199,6 +1491,14 @@ class SlicerProxyManager: await self._mqtt_proxy.stop() self._mqtt_proxy = None + if self._file_transfer_proxy: + await self._file_transfer_proxy.stop() + self._file_transfer_proxy = None + + if self._bind_server: + await self._bind_server.stop() + self._bind_server = None + for bp in self._bind_proxies: await bp.stop() self._bind_proxies = [] diff --git a/backend/tests/unit/services/test_virtual_printer.py b/backend/tests/unit/services/test_virtual_printer.py index 6b35387fe..8cc8353cd 100644 --- a/backend/tests/unit/services/test_virtual_printer.py +++ b/backend/tests/unit/services/test_virtual_printer.py @@ -1567,3 +1567,218 @@ class TestResolveModelCodes: assert _resolve_printer_model(None) is None assert _resolve_printer_model("UnknownModel") is None + + +class TestMqttIpRewrite: + """Tests for TLSProxy._rewrite_mqtt_ip() MQTT packet IP rewriting.""" + + @staticmethod + def _build_mqtt_publish(topic: str, payload: bytes) -> bytes: + """Build a minimal MQTT PUBLISH packet.""" + # PUBLISH fixed header: type 3, no flags + topic_bytes = topic.encode("utf-8") + # Variable header: topic length (2 bytes) + topic + var_header = len(topic_bytes).to_bytes(2, "big") + topic_bytes + body = var_header + payload + + # Encode remaining length + remaining = len(body) + header = bytearray([0x30]) # PUBLISH, QoS 0 + while True: + encoded_byte = remaining % 128 + remaining //= 128 + if remaining > 0: + encoded_byte |= 0x80 + header.append(encoded_byte) + if remaining == 0: + break + + return bytes(header) + body + + @staticmethod + def _build_mqtt_pingreq() -> bytes: + """Build an MQTT PINGREQ packet (2 bytes, no payload).""" + return b"\xc0\x00" + + def test_rewrite_ip_in_publish(self): + """IP string in PUBLISH payload is rewritten.""" + from backend.app.services.virtual_printer.tcp_proxy import TLSProxy + + payload = b'{"rtsp_url":"rtsps://192.168.1.100:322/live"}' + packet = self._build_mqtt_publish("device/status", payload) + + result, buf = TLSProxy._rewrite_mqtt_ip(packet, b"192.168.1.100", b"10.0.0.1", bytearray()) + + assert b"10.0.0.1" in result + assert b"192.168.1.100" not in result + + def test_no_rewrite_when_ip_absent(self): + """Packets without the target IP are passed through unchanged.""" + from backend.app.services.virtual_printer.tcp_proxy import TLSProxy + + payload = b'{"status":"idle"}' + packet = self._build_mqtt_publish("device/status", payload) + + result, buf = TLSProxy._rewrite_mqtt_ip(packet, b"192.168.1.100", b"10.0.0.1", bytearray()) + + assert result == packet + + def test_non_publish_packets_unchanged(self): + """Non-PUBLISH packets (e.g. PINGREQ) are never rewritten.""" + from backend.app.services.virtual_printer.tcp_proxy import TLSProxy + + pingreq = self._build_mqtt_pingreq() + result, buf = TLSProxy._rewrite_mqtt_ip(pingreq, b"192.168.1.100", b"10.0.0.1", bytearray()) + + assert result == pingreq + + def test_rewrite_preserves_packet_framing(self): + """Rewritten packet has valid MQTT remaining length.""" + from backend.app.services.virtual_printer.tcp_proxy import TLSProxy + + # Use IPs of different lengths to test length re-encoding + old_ip = b"192.168.255.133" # 15 bytes + new_ip = b"10.0.0.1" # 8 bytes + + payload = b'{"ip":"192.168.255.133"}' + packet = self._build_mqtt_publish("device/status", payload) + + result, buf = TLSProxy._rewrite_mqtt_ip(packet, old_ip, new_ip, bytearray()) + + # Parse the result to verify framing + assert result[0] == 0x30 # PUBLISH header byte + # Decode remaining length + pos = 1 + remaining = 0 + multiplier = 1 + while True: + b = result[pos] + pos += 1 + remaining += (b & 0x7F) * multiplier + multiplier *= 128 + if (b & 0x80) == 0: + break + + # Remaining length should match actual data + assert pos + remaining == len(result) + assert new_ip in result + + def test_incomplete_packet_buffered(self): + """Incomplete packet at end of chunk is buffered for next call.""" + from backend.app.services.virtual_printer.tcp_proxy import TLSProxy + + payload = b'{"ip":"192.168.1.100"}' + packet = self._build_mqtt_publish("device/status", payload) + + # Split packet in the middle + half = len(packet) // 2 + chunk1 = packet[:half] + chunk2 = packet[half:] + + result1, buf = TLSProxy._rewrite_mqtt_ip(chunk1, b"192.168.1.100", b"10.0.0.1", bytearray()) + # First chunk should be buffered (incomplete packet) + assert len(buf) > 0 + + result2, buf = TLSProxy._rewrite_mqtt_ip(chunk2, b"192.168.1.100", b"10.0.0.1", buf) + # Second chunk completes the packet, IP should be rewritten + combined = result1 + result2 + assert b"10.0.0.1" in combined + assert b"192.168.1.100" not in combined + + def test_multiple_packets_in_one_chunk(self): + """Multiple MQTT packets in a single chunk are all processed.""" + from backend.app.services.virtual_printer.tcp_proxy import TLSProxy + + payload1 = b'{"ip":"192.168.1.100"}' + payload2 = b'{"other":"data"}' + packet1 = self._build_mqtt_publish("topic1", payload1) + packet2 = self._build_mqtt_publish("topic2", payload2) + + combined = packet1 + packet2 + result, buf = TLSProxy._rewrite_mqtt_ip(combined, b"192.168.1.100", b"10.0.0.1", bytearray()) + + assert b"10.0.0.1" in result + assert b"192.168.1.100" not in result + # Second packet should still be present + assert b"other" in result + + def test_extra_replacements(self): + """Extra replacement pairs (e.g. integer IP) are also applied.""" + from backend.app.services.virtual_printer.tcp_proxy import TLSProxy + + payload = b'{"net":{"info":[{"ip":2248124608}]}}' + packet = self._build_mqtt_publish("device/status", payload) + + result, buf = TLSProxy._rewrite_mqtt_ip( + packet, + b"NOMATCH", + b"NOREPLACE", + bytearray(), + extra_replacements=[(b"2248124608", b"285190336")], + ) + + assert b"285190336" in result + assert b"2248124608" not in result + + +class TestIpToLeIntBytes: + """Tests for TLSProxy._ip_to_le_int_bytes() integer IP conversion.""" + + def test_converts_ip_to_le_int(self): + from backend.app.services.virtual_printer.tcp_proxy import TLSProxy + + assert TLSProxy._ip_to_le_int_bytes("192.168.255.133") == b"2248124608" + assert TLSProxy._ip_to_le_int_bytes("192.168.255.16") == b"285190336" + assert TLSProxy._ip_to_le_int_bytes("10.0.0.1") == b"16777226" + + def test_roundtrip(self): + """Verify the integer converts back to the correct IP.""" + import struct + + from backend.app.services.virtual_printer.tcp_proxy import TLSProxy + + for ip in ["192.168.1.1", "10.0.0.1", "172.16.0.100", "192.168.255.133"]: + le_int = int(TLSProxy._ip_to_le_int_bytes(ip)) + parts = ip.split(".") + expected = struct.unpack("n+" "+JSON.stringify(s)+": "+vL(o,e+1)).join(`, `)+` -`+n+"}"}return String(t)}function Xet({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:a,hasPermission:s,t:o}){const{showToast:l}=fn(),c=sn(),[u,d]=w.useState(!1),{data:m,isLoading:p}=tt({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>fe.getCloudSettingDetail(t.setting_id)}),f=ft({mutationFn:()=>fe.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),y=uw(t.setting_id),v=C5(t.name,m?.setting?.inherits);return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:i.jsxs(Et,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),y&&i.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),i.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[i.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&i.jsxs(i.Fragment,{children:[i.jsx("span",{children:"•"}),i.jsx("span",{children:v.printer})]})]})]}),i.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?i.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:vL(m)}):i.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),u?i.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[i.jsx(Mn,{className:"w-5 h-5"}),i.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ie,{variant:"secondary",onClick:()=>d(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),i.jsxs(Ie,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):i.jsx(en,{className:"w-4 h-4"}),o("common.delete")]})]})]}):i.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ie,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),i.jsxs(Ie,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[i.jsx(vo,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),y&&i.jsxs(i.Fragment,{children:[i.jsxs(Ie,{variant:"secondary",onClick:a,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[i.jsx(Ki,{className:"w-4 h-4"}),o("common.edit")]}),i.jsx(Ie,{variant:"danger",onClick:()=>d(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:i.jsx(en,{className:"w-4 h-4"})})]})]})})]})})})}function zoe(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Uoe(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Qet({onClose:t,onApply:e,t:n}){const{showToast:r}=fn(),[a,s]=w.useState(zoe),[o,l]=w.useState("all"),[c,u]=w.useState(null),[d,m]=w.useState(""),[p,f]=w.useState(""),[y,v]=w.useState("{}"),[b,g]=w.useState(null),[_,N]=w.useState(null),T=o==="all"?a:a.filter(W=>W.type===o),C=W=>{s(W),Uoe(W)},P=W=>{const I=a.filter(J=>J.id!==W);C(I),N(null),r(n("profiles.templates.toast.deleted"))},k=W=>{u(W.id),m(W.name),f(W.description),v(JSON.stringify(W.settings,null,2)),g(null)},R=()=>{if(!(!c||!d.trim()))try{const W=JSON.parse(y),I=a.map(J=>J.id===c?{...J,name:d.trim(),description:p.trim(),settings:W}:J);C(I),u(null),r(n("profiles.templates.toast.updated"))}catch(W){g(W.message)}},A=()=>{u(null),m(""),f(""),v("{}"),g(null)},D=W=>{const I=a.map(J=>J.id===W?{...J,showInModal:!J.showInModal}:J);C(I)},B={filament:{label:n("profiles.presets.types.filament"),icon:QC,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:Od,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:_r,color:"text-purple-400"}},z=_?a.find(W=>W.id===_):null;return w.useEffect(()=>{const W=I=>{I.key==="Escape"&&(_?N(null):c?A():t())};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[_,c,t]),i.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[z&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:i.jsx(Pt,{className:"w-full max-w-md",children:i.jsxs(Et,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:i.jsx(Mn,{className:"w-6 h-6 text-red-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),i.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:z.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ie,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),i.jsxs(Ie,{onClick:()=>P(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[i.jsx(en,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),i.jsx(Pt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:i.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(ox,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(W=>i.jsx("button",{onClick:()=>l(W),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===W?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:W==="all"?n("common.all"):B[W].label},W))]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:T.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(ox,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:n("profiles.templates.noTemplates")}),i.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):i.jsx("div",{className:"space-y-2",children:T.map(W=>{const I=B[W.type],J=I.icon;return c===W.id?i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[i.jsx("input",{type:"text",value:d,onChange:ie=>m(ie.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx("input",{type:"text",value:p,onChange:ie=>f(ie.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),i.jsx("textarea",{value:y,onChange:ie=>{v(ie.target.value),g(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${b?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),b&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ie,{size:"sm",onClick:R,disabled:!d.trim(),children:[i.jsx(ss,{className:"w-4 h-4"}),"Save"]}),i.jsx(Ie,{size:"sm",variant:"secondary",onClick:A,children:"Cancel"})]})]},W.id):i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[i.jsx(J,{className:`w-5 h-5 ${I.color} flex-shrink-0`}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:W.name}),i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:W.description})]}),i.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(W.settings).length})}),i.jsx("button",{onClick:()=>D(W.id),className:`p-1 transition-colors ${W.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:W.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:W.showInModal?i.jsx(Ac,{className:"w-4 h-4"}):i.jsx(fw,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>e(W),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),i.jsx("button",{onClick:()=>k(W),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:i.jsx(Ki,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>N(W.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:i.jsx(en,{className:"w-4 h-4"})})]},W.id)})})})]})})]})}function Boe({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:a,t:s}){const[o,l]=w.useState("changes"),[c,u]=w.useState(""),d=w.useMemo(()=>{const y=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const b of y){if(b==="inherits"||b==="version")continue;const g=e[b],_=n[b],N=b in e,T=b in n;let C;!N&&T?C="added":N&&!T?C="removed":JSON.stringify(g)!==JSON.stringify(_)?C="changed":C="same",v.push({key:b,left:g,right:_,status:C})}return v.sort((b,g)=>{const _={changed:0,added:1,removed:2,same:3};return _[b.status]!==_[g.status]?_[b.status]-_[g.status]:b.key.localeCompare(g.key)})},[e,n]),m=w.useMemo(()=>{let y=[...d];if(o==="changes"&&(y=y.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();y=y.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return y},[d,o,c]),p=w.useMemo(()=>({added:d.filter(y=>y.status==="added").length,removed:d.filter(y=>y.status==="removed").length,changed:d.filter(y=>y.status==="changed").length,same:d.filter(y=>y.status==="same").length}),[d]),f=y=>{if(y===void 0)return"—";if(y===null)return"null";if(Array.isArray(y))return y.length===0?"[]":y.length===1?String(y[0]):y.join(", ");if(typeof y=="object")return JSON.stringify(y);const v=String(y);if(v.includes("\\n")||v.length>100){const b=v.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const y=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:i.jsxs(Et,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Bb,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),i.jsx("p",{className:"text-white font-medium truncate",children:r})]}),i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),i.jsx("p",{className:"text-white font-medium truncate",children:a})]})]}),i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[i.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[i.jsx(ar,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(RN,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[i.jsx(g3,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[i.jsx($M,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:c,onChange:y=>u(y.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),p.same>0&&i.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),i.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx($M,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:i.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[i.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),i.jsx("th",{className:"text-left p-3 w-1/3",children:r}),i.jsx("th",{className:"text-left p-3 w-1/3",children:a})]})}),i.jsx("tbody",{children:m.map(y=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[y.status],b={added:i.jsx(ar,{className:"w-3.5 h-3.5 text-green-400"}),removed:i.jsx(RN,{className:"w-3.5 h-3.5 text-red-400"}),changed:i.jsx(g3,{className:"w-3.5 h-3.5 text-amber-400"}),same:i.jsx($M,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[y.status];return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[i.jsx("td",{className:"p-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[b,i.jsx("span",{className:"text-sm text-white font-mono",children:y.key})]})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${y.status==="removed"?"text-red-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.left)})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${y.status==="added"?"text-green-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.right)})})]},y.key)})})]})})]})})})}function Zet({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:a}=fn(),s=sn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[u,d]=w.useState(e?.type||"filament"),[m,p]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,y]=w.useState(e?.base_id||""),[v,b]=w.useState(""),[g,_]=w.useState(e?.setting||{inherits:""}),[N,T]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[C,P]=w.useState(null),[k,R]=w.useState(""),[A,D]=w.useState(!1),[B,z]=w.useState(""),[W,I]=w.useState(!1),[J,ie]=w.useState(zoe),[Q,ue]=w.useState(!1),[me,pe]=w.useState(""),[Y,se]=w.useState(""),[oe,be]=w.useState(!0),[Me,q]=w.useState(null),[Z,j]=w.useState(!1),E=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),U=w.useMemo(()=>E.filter(Pe=>uw(Pe.setting_id)),[E]),{data:K}=tt({queryKey:["cloudFields",u],queryFn:()=>fe.getCloudFields(u==="print"?"process":u),staleTime:1e3*60*60}),{data:$}=tt({queryKey:["allPresetDetails",u,U.map(Pe=>Pe.setting_id).join(",")],queryFn:async()=>{const Pe={};for(let je=0;je{try{const Ee=await fe.getCloudSettingDetail(Ge.setting_id);return{id:Ge.setting_id,detail:Ee}}catch{return null}}))).forEach(Ge=>{Ge&&(Pe[Ge.id]=Ge.detail)})}return Pe},enabled:U.length>0,staleTime:1e3*60*10}),{data:ne,isLoading:O}=tt({queryKey:["cloudSettingDetail",f],queryFn:()=>fe.getCloudSettingDetail(f),enabled:!!f});w.useEffect(()=>{l!=="json"&&T(JSON.stringify(g,null,2))},[g,l]);const V=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(Ue=>!uw(Ue.setting_id)).sort((Ue,je)=>Ue.name.localeCompare(je.name)),[n,u]);w.useEffect(()=>{if(!f)return;const Pe=V.find(Ue=>Ue.setting_id===f);Pe&&(b(Pe.name),o||(_({inherits:Pe.name}),T(JSON.stringify({inherits:Pe.name},null,2))))},[f,V,o]);const ee=w.useMemo(()=>{const Pe=K?.fields||[],Ue=new Set(Pe.map(Ge=>Ge.key)),je=new Set,Xe=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);$&&Object.values($).forEach(Ge=>{Ge?.setting&&Object.keys(Ge.setting).forEach(Ee=>{!Ue.has(Ee)&&!Xe.has(Ee)&&je.add(Ee)})}),Object.keys(g).forEach(Ge=>{!Ue.has(Ge)&&!Xe.has(Ge)&&je.add(Ge)});const ye=Array.from(je).sort().map(Ge=>({key:Ge,label:Ge.replace(/_/g," ").replace(/\b\w/g,Ee=>Ee.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Pe,...ye]},[K,$,g,r]),G=ee.filter(Pe=>Pe.label.toLowerCase().includes(k.toLowerCase())||Pe.key.toLowerCase().includes(k.toLowerCase())),re=()=>{if(B.trim()){const Pe=B.trim().toLowerCase().replace(/\s+/g,"_");ce(Pe,""),z(""),I(!1),a(r("profiles.presets.toast.fieldAdded",{key:Pe}))}},ce=(Pe,Ue)=>{_(je=>{const Xe={...je};return Ue===""||Ue===void 0?delete Xe[Pe]:Xe[Pe]=Ue,Xe})},ge=Pe=>{_(Ue=>({...Ue,...Pe.settings})),q(Pe.name),a(r("profiles.templates.toast.applied"))},xe=()=>{if(!me.trim())return;const Pe={...g};if(delete Pe.inherits,Object.keys(Pe).length===0){a(r("profiles.presets.noOverridesToSave"),"error");return}const Ue={id:Date.now().toString(),name:me.trim(),description:Y.trim()||r("profiles.presets.customTemplate"),type:u,settings:Pe,showInModal:oe},je=[...J,Ue];ie(je),Uoe(je),ue(!1),pe(""),se(""),be(!0),a(r("profiles.templates.toast.created"))},ae=w.useMemo(()=>J.filter(Pe=>Pe.type===u&&Pe.showInModal),[u,J]),L=Pe=>{T(Pe);try{const Ue=JSON.parse(Pe);_(Ue),P(null)}catch(Ue){P(Ue.message)}},F=Pe=>{Pe.preventDefault(),D(!1);const Ue=Pe.dataTransfer.files[0];if(Ue&&Ue.name.endsWith(".json")){const je=new FileReader;je.onload=Xe=>{try{const ye=Xe.target?.result,Ge=JSON.parse(ye),Ee=Ge.setting||Ge;_(Ke=>({...Ke,...Ee})),T(JSON.stringify({...g,...Ee},null,2)),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJsonFile"),"error")}},je.readAsText(Ue)}},te=ft({mutationFn:()=>{const Pe={...g},Ue=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";Pe[Ue]=`"${m}"`;const je={type:u,name:m,base_id:f,setting:Pe};return fe.createCloudSetting(je)},onSuccess:async()=>{a(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Pe=>a(Pe.message,"error")}),ve=ft({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return fe.updateCloudSetting(e.setting_id,{name:m,setting:g})},onSuccess:async()=>{a(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Pe=>a(Pe.message,"error")}),he=o?ve:te,de=ne?.setting?.inherits,ke=de?V.find(Pe=>Pe.name===de):void 0,{data:_e}=tt({queryKey:["cloudSettingDetail",ke?.setting_id],queryFn:()=>fe.getCloudSettingDetail(ke.setting_id),enabled:!!ke?.setting_id}),Le=w.useMemo(()=>{const Pe=_e?.setting||{},Ue=ne?.setting||{},je=f&&$?.[f]?.setting?$[f].setting:{};return{...Pe,...Ue,...je}},[f,ne,_e,$]),$e=Pe=>{if(Pe==null)return"";if(Array.isArray(Pe)){const Ue=[...new Set(Pe.map(je=>String(je)))];return Ue.length===1?Ue[0]:Pe.join(", ")}return String(Pe)},Re=Pe=>{const Ue=g[Pe.key],je=Le[Pe.key],Xe=$e(je),ye=O?r("common.loading"):Xe||"",Ge="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(Pe.type==="boolean"){const Ee=Ue==="1"||Ue===void 0&&je==="1";return i.jsx("button",{type:"button",onClick:()=>ce(Pe.key,Ue==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Ee?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Ee?"translate-x-3.5":"translate-x-0.5"}`})})}return Pe.type==="select"?i.jsxs("select",{value:Ue||"",onChange:Ee=>ce(Pe.key,Ee.target.value),className:Ge,children:[i.jsx("option",{value:"",children:ye}),Pe.options?.map(Ee=>i.jsx("option",{value:Ee.value,children:Ee.label},Ee.value))]}):i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:Pe.type==="number"?"number":"text",value:Ue!==void 0?String(Ue):"",onChange:Ee=>ce(Pe.key,Ee.target.value),step:Pe.step,min:Pe.min,max:Pe.max,placeholder:ye,className:Ge}),Pe.unit&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Pe.unit})]})},Ae=w.useMemo(()=>ne?.setting?ne.setting:{},[ne]);return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Pe=>{Pe.preventDefault(),D(!0)},onDragLeave:()=>D(!1),onDrop:F,children:[Z&&f&&i.jsx(Boe,{onClose:()=>j(!1),leftPreset:Ae,rightPreset:g,leftLabel:r("profiles.presets.baseLabel",{name:v||f}),rightLabel:r("profiles.presets.currentLabel",{name:m||r("profiles.presets.newPreset")}),t:r}),i.jsx(Pt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:i.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[f&&i.jsxs("button",{onClick:()=>j(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:r("profiles.presets.compareWithBase"),children:[i.jsx(Bb,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),i.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]})]}),A&&i.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(vi,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),i.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),i.jsxs("select",{value:u,onChange:Pe=>{d(Pe.target.value),y("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),i.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),i.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),i.jsxs("select",{value:f,onChange:Pe=>y(Pe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),V.map(Pe=>i.jsx("option",{value:Pe.setting_id,children:Pe.name},Pe.setting_id))]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),i.jsx("input",{type:"text",value:m,onChange:Pe=>p(Pe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("profiles.presets.myCustomPreset")})]})]}),v&&i.jsx("div",{className:"text-xs text-bambu-gray",children:i.jsxs("p",{className:"flex items-center gap-1",children:[i.jsx(Qr,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",i.jsx("span",{className:"text-white",children:v}),O&&i.jsx(pt,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[i.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(G8,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),i.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(eT,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),i.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(HX,{className:"w-4 h-4"}),"JSON",C&&i.jsx(Li,{className:"w-3 h-3 text-red-400"})]}),i.jsx("div",{className:"flex-1 max-[640px]:hidden"}),i.jsxs("button",{onClick:()=>{const Pe={name:m,type:u,base_id:f,setting:g},Ue=new Blob([JSON.stringify(Pe,null,2)],{type:"application/json"}),je=URL.createObjectURL(Ue),Xe=document.createElement("a");Xe.href=je,Xe.download=`${m||"preset"}.json`,document.body.appendChild(Xe),Xe.click(),document.body.removeChild(Xe),URL.revokeObjectURL(je),a(r("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.exportToJson"),children:[i.jsx(bi,{className:"w-4 h-4"}),r("common.download")]}),i.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.importFromJson"),children:[i.jsx(vi,{className:"w-4 h-4"}),r("common.upload")]}),i.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Pe=>{const Ue=Pe.target.files?.[0];if(Ue){const je=new FileReader;je.onload=Xe=>{try{const ye=JSON.parse(Xe.target?.result),Ge=ye.setting||ye;_(Ee=>({...Ee,...Ge})),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJson"),"error")}},je.readAsText(Ue)}}})]}),i.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(ox,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(g).filter(Pe=>Pe!=="inherits").length>0&&i.jsxs("button",{onClick:()=>ue(!Q),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[i.jsx(ss,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),Q&&i.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[i.jsx("input",{type:"text",value:me,onChange:Pe=>pe(Pe.target.value),placeholder:r("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx("input",{type:"text",value:Y,onChange:Pe=>se(Pe.target.value),placeholder:r("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ie,{size:"sm",onClick:xe,disabled:!me.trim(),children:[i.jsx(ss,{className:"w-3 h-3"}),r("common.save")]}),i.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>ue(!1),children:r("common.cancel")})]}),i.jsxs("button",{onClick:()=>be(!oe),className:`flex items-center gap-1.5 text-xs transition-colors ${oe?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[oe?i.jsx(Ac,{className:"w-3.5 h-3.5"}):i.jsx(fw,{className:"w-3.5 h-3.5"}),r(oe?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Me&&i.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[i.jsx(Qr,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",i.jsx("span",{className:"font-medium",children:Me})]}),i.jsx("button",{onClick:()=>q(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[ae.map(Pe=>i.jsxs("button",{onClick:()=>ge(Pe),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:Pe.name}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Pe.description})]},Pe.id)),ae.length===0&&i.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),i.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),i.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:ee.slice(0,10).map(Pe=>i.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[i.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Pe.label}),i.jsx("div",{className:"w-48 max-[640px]:w-full",children:Re(Pe)})]},Pe.key))})]}),Object.keys(g).length>1&&i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(g).filter(([Pe])=>Pe!=="inherits").map(([Pe,Ue])=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Pe,": ",String(Ue).slice(0,20),i.jsx("button",{onClick:()=>ce(Pe,void 0),className:"hover:text-white",children:i.jsx(Ht,{className:"w-3 h-3"})})]},Pe))})]})]}),l==="fields"&&i.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:$?r("profiles.templates.fieldsCount",{count:ee.length}):r("common.loading")})]}),i.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:k,onChange:Pe=>R(Pe.target.value),placeholder:r("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[G.filter(Pe=>!(Pe.key in g)).map(Pe=>{const Ue=Le[Pe.key],je=$e(Ue);return i.jsxs("div",{onClick:()=>{_(Xe=>({...Xe,[Pe.key]:je||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white truncate",children:Pe.label}),i.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Pe.key})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[je&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:je,children:[je.slice(0,20),je.length>20?"...":""]}),i.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:i.jsx(ar,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Pe.key)}),G.filter(Pe=>!(Pe.key in g)).length===0&&i.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(k?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:W?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:B,onChange:Pe=>z(Pe.target.value),onKeyDown:Pe=>Pe.key==="Enter"&&re(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx(Ie,{size:"sm",onClick:re,disabled:!B.trim(),children:i.jsx(ar,{className:"w-4 h-4"})}),i.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>{I(!1),z("")},children:i.jsx(Ht,{className:"w-4 h-4"})})]}):i.jsxs("button",{onClick:()=>I(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[i.jsx(ar,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(g).filter(Pe=>Pe!=="inherits").length})})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(g).filter(([Pe])=>Pe!=="inherits").map(([Pe,Ue])=>{const je=ee.find(Xe=>Xe.key===Pe);return i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium text-white",children:je?.label||Pe}),i.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Pe})]}),i.jsx("button",{onClick:()=>ce(Pe,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),je?Re(je):i.jsx("input",{type:"text",value:String(Ue),onChange:Xe=>ce(Pe,Xe.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},Pe)}),Object.keys(g).filter(Pe=>Pe!=="inherits").length===0&&i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(G8,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),i.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),i.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(g).filter(Pe=>Pe!=="inherits").length>0&&i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:i.jsxs("button",{onClick:()=>{ue(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[i.jsx(ss,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&i.jsxs("div",{className:"space-y-2",children:[C&&i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(Li,{className:"w-4 h-4"}),C]}),i.jsx("textarea",{value:N,onChange:Pe=>L(Pe.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${C?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[i.jsx(Ie,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsxs(Ie,{onClick:()=>he.mutate(),disabled:he.isPending||!m.trim()||!o&&!f||!!C,className:"flex-1",children:[he.isPending?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):o?i.jsx(ss,{className:"w-4 h-4"}):i.jsx(ar,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function Jet({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:a,hasPermission:s,t:o}){const[l,c]=w.useState(""),[u,d]=w.useState("all"),[m,p]=w.useState("all"),[f,y]=w.useState("all"),[v,b]=w.useState("all"),[g,_]=w.useState("all"),[N,T]=w.useState("all"),[C,P]=w.useState(null),[k,R]=w.useState(!1),[A,D]=w.useState(!1),[B,z]=w.useState(null),[W,I]=w.useState(null),[J,ie]=w.useState(null),[Q,ue]=w.useState(!1),[me,pe]=w.useState([null,null]),[Y,se]=w.useState(!1),[oe,be]=w.useState(null),Me=sn(),q=w.useMemo(()=>[...t.filament.map(re=>({...re,type:"filament"})),...t.printer.map(re=>({...re,type:"printer"})),...t.process.map(re=>({...re,type:"process"}))].map(re=>({...re,meta:C5(re.name)})),[t]),Z=w.useMemo(()=>{const G=new Set,re=new Set,ce=new Set;return q.forEach(ge=>{ge.meta.nozzle&&G.add(ge.meta.nozzle),ge.meta.filamentType&&re.add(ge.meta.filamentType),ge.meta.layerHeight&&ce.add(ge.meta.layerHeight)}),{printers:a.map(ge=>({id:ge.id.toString(),name:ge.name})),nozzles:Array.from(G).sort((ge,xe)=>parseFloat(ge)-parseFloat(xe)),filaments:Array.from(re).sort(),layerHeights:Array.from(ce).sort((ge,xe)=>parseFloat(ge)-parseFloat(xe))}},[q,a]),j=w.useMemo(()=>f==="all"?null:a.find(re=>re.id.toString()===f)?.model||null,[f,a]),E=w.useMemo(()=>q.filter(G=>u==="all"||G.type===u).filter(G=>{if(m==="all")return!0;const re=uw(G.setting_id);return m==="custom"?re:!re}).filter(G=>{if(f==="all"||!j)return!0;const re=G.meta.printer?.toLowerCase()||"",ce=j.toLowerCase();return re.includes(ce)||ce.includes(re)}).filter(G=>v==="all"||G.meta.nozzle===v).filter(G=>g==="all"||G.meta.filamentType===g).filter(G=>N==="all"||G.meta.layerHeight===N).filter(G=>l===""||G.name.toLowerCase().includes(l.toLowerCase())).sort((G,re)=>G.name.localeCompare(re.name)),[q,u,m,f,j,v,g,N,l]),U=G=>{if(Q){const re=me[0]?.setting_id===G.setting_id,ce=me[1]?.setting_id===G.setting_id;if(re)pe([me[1],null]);else if(ce)pe([me[0],null]);else if(!me[0])pe([G,null]);else if(me[1]){if(me[0].type!==G.type)return;pe([me[0],G])}else{if(me[0].type!==G.type)return;pe([me[0],G])}}else P(G)},K=G=>{if(me[0]?.setting_id===G.setting_id)return 0;if(me[1]?.setting_id===G.setting_id)return 1},$=async G=>{try{const re=await fe.getCloudSettingDetail(G.setting_id),ce=G.type==="process"?"print":G.type;z({type:ce,name:G.name,base_id:re.base_id||"GFSA00",setting:re.setting||{}}),P(null)}catch(re){console.error("Failed to fetch preset details for duplication:",re)}},ne=async G=>{try{Me.removeQueries({queryKey:["cloudSettingDetail",G.setting_id]});const re=await fe.getCloudSettingDetail(G.setting_id),ce=G.type==="process"?"print":G.type;I({type:ce,name:G.name,base_id:re.base_id||"GFSA00",setting:re.setting||{},setting_id:G.setting_id}),P(null)}catch(re){console.error("Failed to fetch preset details for editing:",re)}},O=()=>{d("all"),p("all"),y("all"),b("all"),_("all"),T("all"),c("")},V=u!=="all"||m!=="all"||f!=="all"||v!=="all"||g!=="all"||N!=="all"||l!=="",ee=t.filament.length+t.printer.length+t.process.length;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-4 mb-6",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:l,onChange:G=>c(G.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[i.jsxs(Ie,{variant:Q?"primary":"secondary",onClick:()=>{Q?(ue(!1),pe([null,null])):ue(!0)},children:[i.jsx(Bb,{className:"w-4 h-4"}),o(Q?"common.cancel":"profiles.presets.compare")]}),i.jsxs(Ie,{variant:"secondary",onClick:()=>D(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[i.jsx(ox,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),i.jsxs(Ie,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[i.jsx(Sr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),i.jsxs(Ie,{onClick:()=>R(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[i.jsx(ar,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(JC,{className:"w-4 h-4 text-bambu-gray"}),i.jsx(_b,{label:o("profiles.cloudView.filters.type"),value:u,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:ee},{value:"filament",label:o("profiles.cloudView.filters.filament"),count:t.filament.length},{value:"printer",label:o("profiles.cloudView.filters.printer"),count:t.printer.length},{value:"process",label:o("profiles.cloudView.filters.process"),count:t.process.length}],onChange:G=>d(G)}),i.jsx(_b,{label:o("profiles.cloudView.filters.owner"),value:m,options:[{value:"all",label:o("profiles.cloudView.filters.all")},{value:"custom",label:o("profiles.cloudView.filters.myPresets")},{value:"builtin",label:o("profiles.cloudView.filters.builtIn")}],onChange:G=>p(G)}),Z.printers.length>0&&i.jsx(_b,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Z.printers.map(G=>({value:G.id,label:G.name}))],onChange:y}),Z.nozzles.length>0&&i.jsx(_b,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Z.nozzles.map(G=>({value:G,label:G}))],onChange:b}),Z.filaments.length>0&&(u==="all"||u==="filament")&&i.jsx(_b,{label:o("profiles.cloudView.filters.filament"),value:g,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Z.filaments.map(G=>({value:G,label:G}))],onChange:_}),Z.layerHeights.length>0&&(u==="all"||u==="process")&&i.jsx(_b,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Z.layerHeights.map(G=>({value:G,label:G}))],onChange:T}),V&&i.jsx("button",{onClick:O,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),Q&&i.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(Bb,{className:"w-5 h-5 text-blue-400"}),i.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),i.jsx("span",{className:"text-bambu-gray",children:me[0]?o("profiles.cloudView.selectAnotherPreset",{type:me[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${me[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:me[0]?me[0].name:o("profiles.cloudView.selectFirst")}),i.jsx(g3,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${me[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:me[1]?me[1].name:o("profiles.cloudView.selectSecond")})]}),me[0]&&me[1]&&i.jsxs(Ie,{size:"sm",onClick:async()=>{try{const[G,re]=await Promise.all([fe.getCloudSettingDetail(me[0].setting_id),fe.getCloudSettingDetail(me[1].setting_id)]);be([G.setting||{},re.setting||{}]),se(!0)}catch{}},children:[i.jsx(Bb,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),i.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(Jn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",w0(e.toISOString(),"system",o)]}),i.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:E.length,total:ee})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),i.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),E.length===0?i.jsxs("div",{className:"text-center py-16",children:[i.jsx(Vi,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),i.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),V&&i.jsx("button",{onClick:O,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(QC,{className:"w-4 h-4 text-amber-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(G=>G.type==="filament").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(G=>G.type==="filament").map(G=>i.jsx(qD,{setting:G,onClick:()=>U(G),onDuplicate:()=>$(G),compareMode:Q,isCompareSelected:K(G)!==void 0,compareIndex:K(G),compareDisabled:Q&&!!me[0]&&me[0].type!==G.type,t:o},G.setting_id)),E.filter(G=>G.type==="filament").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(Od,{className:"w-4 h-4 text-blue-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(G=>G.type==="process").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(G=>G.type==="process").map(G=>i.jsx(qD,{setting:G,onClick:()=>U(G),onDuplicate:()=>$(G),compareMode:Q,isCompareSelected:K(G)!==void 0,compareIndex:K(G),compareDisabled:Q&&!!me[0]&&me[0].type!==G.type,t:o},G.setting_id)),E.filter(G=>G.type==="process").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(_r,{className:"w-4 h-4 text-purple-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(G=>G.type==="printer").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(G=>G.type==="printer").map(G=>i.jsx(qD,{setting:G,onClick:()=>U(G),onDuplicate:()=>$(G),compareMode:Q,isCompareSelected:K(G)!==void 0,compareIndex:K(G),compareDisabled:Q&&!!me[0]&&me[0].type!==G.type,t:o},G.setting_id)),E.filter(G=>G.type==="printer").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),C&&i.jsx(Xet,{setting:C,onClose:()=>P(null),onDeleted:()=>P(null),onDuplicate:()=>$(C),onEdit:()=>ne(C),hasPermission:s,t:o}),(k||B||W||J)&&i.jsx(Zet,{onClose:()=>{R(!1),z(null),I(null),ie(null)},initialData:W||B||(J?{type:J.type,name:"",base_id:"",setting:J.setting}:void 0),allPresets:t,t:o}),A&&i.jsx(Qet,{onClose:()=>D(!1),onApply:G=>{ie({type:G.type,setting:G.settings}),D(!1)},t:o}),Y&&oe&&me[0]&&me[1]&&i.jsx(Boe,{onClose:()=>{se(!1),be(null)},leftPreset:oe[0],rightPreset:oe[1],leftLabel:me[0].name,rightLabel:me[1].name,t:o})]})}function ett(){const{t}=Rt(),e=sn(),{showToast:n}=fn(),{hasPermission:r}=Nr(),[a,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:u}=tt({queryKey:["cloudStatus"],queryFn:fe.getCloudStatus}),{data:d=[]}=tt({queryKey:["printers"],queryFn:fe.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:y}=tt({queryKey:["cloudSettings"],queryFn:()=>fe.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{y&&l(new Date(y))},[y]);const v=ft({mutationFn:fe.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return u?i.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:i.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"p-6 lg:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),i.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[i.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(Ox,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),i.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(Ix,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),i.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(gw,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),a==="cloud"&&i.jsxs(i.Fragment,{children:[c?.is_authenticated&&i.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",i.jsx("span",{className:"text-white",children:c.email})]})]}),i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[i.jsx(v3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?i.jsx(Jet,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:d,hasPermission:r,t}):i.jsxs("div",{className:"text-center py-16",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),i.jsx(Ie,{onClick:()=>f(),children:t("profiles.retry")})]}):i.jsx(Ket,{onSuccess:b,t})]}),a==="local"&&i.jsx(Wet,{}),a==="kprofiles"&&i.jsx($et,{}),i.jsx(Yet,{})]})}const Bv={Droplet:QC,Flame:Ip,Ruler:Tge,Sparkles:ox,Square:ql,Cable:BL,Wrench:kf,Calendar:Yr,Timer:yd,Cog:gpe,Fan:$X,Zap:Mc,Wind:nQ,Thermometer:sT,Layers:Vi,Box:na,Target:JX,RefreshCw:Sr,Settings:aT,Filter:JC,CircleDot:Qhe};function m0(t){return t&&Bv[t]||kf}function Nb(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const a=Math.round(t);return n?n("maintenance.days",{count:a}):`${a} days`}if(t<180){const a=Math.round(t/7);return a===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:a}):`${a} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const a=r/7;return a<12?`${a<2?a.toFixed(1):Math.round(a)}w`:`${Math.round(a/4)}mo`}}function VD(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function ttt(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),a=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),u=n.includes("H2S"),d=l||c||u,m=n.includes("P2S");switch(t){case"Lubricate Carbon Rods":return r?"https://wiki.bambulab.com/en/x1/maintenance/basic-maintenance":a?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":null;case"Lubricate Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||a?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":d?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":m?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return r?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":a?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":u?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":m?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||a?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return r||a?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":u?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return d?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}function ntt({item:t,onPerform:e,onToggle:n,hasPermission:r,t:a}){const s=m0(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const f=t.days_since_maintenance??0;return Math.max(0,Math.min(100,f/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),u=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",d=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",m=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",p=()=>{if(!t.enabled)return a("common.disabled");if(o==="days"){const f=t.days_until_due??0;return t.is_due?a("maintenance.overdueBy",{duration:Nb(Math.abs(f),"days",a)}):t.is_warning?a("maintenance.dueIn",{duration:Nb(f,"days",a)}):a("maintenance.timeLeft",{duration:Nb(f,"days",a)})}else return t.is_due?a("maintenance.overdueBy",{duration:Nb(Math.abs(t.hours_until_due),"hours",a)}):t.is_warning?a("maintenance.dueIn",{duration:Nb(t.hours_until_due,"hours",a)}):a("maintenance.timeLeft",{duration:Nb(t.hours_until_due,"hours",a)})};return i.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:i.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[i.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[i.jsx(s,{className:`w-5 h-5 ${u()}`}),t.enabled&&(t.is_due||t.is_warning)&&i.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&i.jsx("span",{title:a("maintenance.timeBasedInterval"),children:i.jsx(Yr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||ttt(t.maintenance_type_name,t.printer_model);return f?i.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:a("maintenance.viewDocumentation"),onClick:y=>y.stopPropagation(),children:i.jsx(ti,{className:"w-3.5 h-3.5"})}):null})()]}),i.jsx("div",{className:"mt-2 mb-1.5",children:i.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${d()}`,style:{width:`${c}%`}})})}),i.jsxs("div",{className:`text-xs flex items-center gap-1 ${u()}`,children:[t.is_due&&i.jsx(Mn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&i.jsx(Jn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&i.jsx(Qr,{className:"w-3 h-3"}),p()]})]}),i.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[i.jsx("span",{title:r("maintenance:update")?void 0:a("maintenance.noPermissionUpdate"),children:i.jsx(Bn,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!r("maintenance:update")})}),i.jsxs(Ie,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:a("maintenance.noPermissionPerform"),className:"!px-3",children:[i.jsx(So,{className:"w-3.5 h-3.5"}),a("common.reset")]})]})]})})}function rtt({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:a,t:s}){const[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,m]=w.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((v,b)=>v.is_due&&!b.is_due?-1:!v.is_due&&b.is_due?1:v.is_warning&&!b.is_warning?-1:!v.is_warning&&b.is_warning?1:v.maintenance_type_id-b.maintenance_type_id),f=p.find(v=>v.enabled&&(v.is_due||v.is_warning)),y=()=>{const v=parseFloat(d);!isNaN(v)&&v>=0&&(r(t.printer_id,v),u(!1))};return i.jsxs(Pt,{className:"overflow-hidden",children:[i.jsxs("div",{className:"p-5",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&i.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(Mn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&i.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(Jn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&i.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(Qr,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),i.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?i.jsx($l,{className:"w-4 h-4"}):i.jsx(On,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),i.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:i.jsx(yd,{className:"w-4 h-4 text-bambu-gray"})}),c?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",value:d,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&y(),v.key==="Escape"&&u(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),i.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),i.jsx(Ie,{size:"sm",onClick:y,children:s("common.save")}),i.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>u(!1),children:s("common.cancel")})]}):i.jsxs("button",{onClick:()=>{a("maintenance:update")&&(m(Math.round(t.total_print_hours).toString()),u(!0))},className:`group ${a("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:a("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[i.jsxs("div",{className:`text-sm font-medium text-white ${a("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),i.jsx(_f,{className:`w-3 h-3 text-bambu-gray ${a("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),i.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),i.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=m0(f.maintenance_type_icon);return i.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),i.jsxs("div",{children:[i.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),i.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&i.jsx(Et,{className:"pt-0 border-t border-bambu-dark-tertiary",children:i.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>i.jsx(ntt,{item:v,onPerform:e,onToggle:n,hasPermission:a,t:s},v.id))})})]})}function itt({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:a,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:u,hasPermission:d,t:m}){const[p,f]=w.useState(null),[y,v]=w.useState(""),[b,g]=w.useState("hours"),[_,N]=w.useState(!1),[T,C]=w.useState(""),[P,k]=w.useState("100"),[R,A]=w.useState("hours"),[D,B]=w.useState("Wrench"),[z,W]=w.useState(""),[I,J]=w.useState(new Set),[ie,Q]=w.useState(null),[ue,me]=w.useState(null),pe=w.useMemo(()=>t?t.map(L=>({id:L.printer_id,name:L.printer_name})):[],[t]),Y=L=>t?t.filter(F=>F.maintenance_items.some(te=>te.maintenance_type_id===L)).map(F=>({printerId:F.printer_id,printerName:F.printer_name,itemId:F.maintenance_items.find(te=>te.maintenance_type_id===L)?.id})):[],se=L=>{if(!t)return[];const F=new Set(Y(L).map(te=>te.printerId));return pe.filter(te=>!F.has(te.id))},[oe,be]=w.useState(null),[Me,q]=w.useState(""),[Z,j]=w.useState(""),[E,U]=w.useState("hours"),[K,$]=w.useState("Wrench"),[ne,O]=w.useState(""),V=L=>{be(L),q(L.name),j(L.default_interval_hours.toString()),U(L.interval_type||"hours"),$(L.icon||"Wrench"),O(L.wiki_url||"")},ee=()=>{oe&&Me.trim()&&parseFloat(Z)>0&&(a(oe.id,{name:Me.trim(),default_interval_hours:parseFloat(Z),interval_type:E,icon:K,wiki_url:ne.trim()||null}),be(null))},G=(L,F,te)=>{const ve=parseFloat(y);if(!isNaN(ve)&&ve>0){const he=Math.abs(ve-F)<.01?null:ve;n(L,{custom_interval_hours:he,custom_interval_type:b!==te?b:null})}f(null)},re=L=>{L.preventDefault(),T.trim()&&parseFloat(P)>0&&I.size>0&&(r({name:T.trim(),default_interval_hours:parseFloat(P),interval_type:R,icon:D,wiki_url:z.trim()||null},Array.from(I)),C(""),k("100"),A("hours"),W(""),J(new Set),N(!1))},ce=L=>{J(F=>{const te=new Set(F);return te.has(L)?te.delete(L):te.add(L),te})},ge=t?.map(L=>({printerId:L.printer_id,printerName:L.printer_name,items:L.maintenance_items.sort((F,te)=>F.maintenance_type_id-te.maintenance_type_id)})).sort((L,F)=>L.printerName.localeCompare(F.printerName))||[],xe=e.filter(L=>L.is_system),ae=e.filter(L=>!L.is_system);return i.jsxs("div",{className:"space-y-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ie,{variant:"secondary",onClick:o,disabled:!d("maintenance:delete")||l,title:d("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),i.jsxs(Ie,{onClick:()=>N(!_),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[i.jsx(ar,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),_&&i.jsx(Pt,{className:"mb-6",children:i.jsx(Et,{className:"py-4",children:i.jsxs("form",{onSubmit:re,children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"lg:col-span-2",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),i.jsx("input",{type:"text",value:T,onChange:L=>C(L.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.exampleName"),autoFocus:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),i.jsxs("select",{value:R,onChange:L=>{A(L.target.value),L.target.value==="days"?k("30"):k("100")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"hours",children:m("maintenance.printHours")}),i.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:R==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),i.jsx("input",{type:"number",value:P,onChange:L=>k(L.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),i.jsx("div",{className:"mt-4 flex items-end justify-between",children:i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),i.jsx("div",{className:"flex gap-1",children:Object.keys(Bv).map(L=>{const F=Bv[L];return i.jsx("button",{type:"button",onClick:()=>B(L),className:`p-2 rounded-lg transition-colors ${D===L?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:i.jsx(F,{className:"w-4 h-4"})},L)})})]})}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),i.jsx("input",{type:"url",value:z,onChange:L=>W(L.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:pe.map(L=>i.jsx("button",{type:"button",onClick:()=>ce(L.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${I.has(L.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:L.name},L.id))}),I.size===0&&i.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),i.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",onClick:()=>{N(!1),J(new Set)},children:m("common.cancel")}),i.jsx(Ie,{type:"submit",disabled:!T.trim()||I.size===0,children:m("maintenance.addType")})]})]})})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[xe.map(L=>{const F=m0(L.icon),te=L.interval_type||"hours";return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:i.jsx(F,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[te==="days"?i.jsx(Yr,{className:"w-3 h-3"}):i.jsx(yd,{className:"w-3 h-3"}),VD(L.default_interval_hours,te,m)]})]}),i.jsx("button",{onClick:()=>{d("maintenance:delete")&&me(L)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(en,{className:"w-4 h-4"})})]})},L.id)}),ae.map(L=>{const F=m0(L.icon),te=L.interval_type||"hours";if(oe?.id===L.id)return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx("input",{type:"text",value:Me,onChange:_e=>q(_e.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("common.name"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("select",{value:E,onChange:_e=>U(_e.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"hours",children:m("maintenance.printHours")}),i.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:Z,onChange:_e=>j(_e.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),i.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(Bv).map(_e=>{const Le=Bv[_e];return i.jsx("button",{type:"button",onClick:()=>$(_e),className:`p-1.5 rounded transition-colors ${K===_e?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:i.jsx(Le,{className:"w-3.5 h-3.5"})},_e)})}),i.jsx("input",{type:"url",value:ne,onChange:_e=>O(_e.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.documentationLink")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ie,{size:"sm",onClick:ee,disabled:!Me.trim(),children:m("common.save")}),i.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>be(null),children:m("common.cancel")})]})]})},L.id);const he=Y(L.id),de=se(L.id),ke=ie===L.id;return i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:i.jsx(F,{className:"w-5 h-5 text-bambu-green"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:m("maintenance.custom")})]}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[te==="days"?i.jsx(Yr,{className:"w-3 h-3"}):i.jsx(yd,{className:"w-3 h-3"}),VD(L.default_interval_hours,te,m)]})]}),i.jsxs("button",{onClick:()=>Q(ke?null:L.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${he.length>0?"border-bambu-green/50 bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20":"border-orange-400/50 bg-orange-400/10 text-orange-400 hover:bg-orange-400/20"}`,title:m("maintenance.printersAssignedClick",{count:he.length}),children:[i.jsx(_r,{className:"w-3 h-3"}),i.jsx("span",{className:"text-xs font-medium",children:he.length}),i.jsx(On,{className:`w-3 h-3 transition-transform ${ke?"rotate-180":""}`})]}),i.jsx("button",{onClick:()=>V(L),disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:m("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${d("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(_f,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:L.name}))&&s(L.id)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(en,{className:"w-4 h-4"})})]}),ke&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),he.length===0?i.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):i.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:he.map(_e=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[_e.printerName,i.jsx("button",{onClick:()=>_e.itemId&&u(_e.itemId),disabled:!d("maintenance:delete"),title:d("maintenance:delete")?m("maintenance.removeFromPrinter"):m("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${d("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},_e.printerId))}),de.length>0&&i.jsxs("div",{className:"flex flex-wrap gap-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),de.map(_e=>i.jsxs("button",{onClick:()=>c(_e.id,L.id),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:m("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${d("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",_e.name]},_e.id))]})]})]},L.id)})]})]}),ge.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"mb-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),i.jsx("div",{className:"space-y-4",children:ge.map(L=>i.jsx(Pt,{children:i.jsxs(Et,{className:"py-4",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:L.printerName}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:L.items.map(F=>{const te=m0(F.maintenance_type_icon),ve=e.find(Le=>Le.id===F.maintenance_type_id),he=ve?.default_interval_hours||F.interval_hours,de=ve?.interval_type||"hours",ke=F.interval_type||"hours",_e=p===F.id;return i.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[i.jsx(te,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:F.maintenance_type_name}),_e?i.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?i.jsx(Yr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):i.jsx(yd,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),i.jsxs("select",{value:b,onChange:Le=>g(Le.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[i.jsx("option",{value:"hours",children:m("maintenance.printHours")}),i.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:y,onChange:Le=>v(Le.target.value),onKeyDown:Le=>{Le.key==="Enter"&&G(F.id,he,de),Le.key==="Escape"&&f(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),i.jsx(Ie,{size:"sm",onClick:()=>G(F.id,he,de),children:"OK"})]}):i.jsxs("button",{onClick:()=>{d("maintenance:update")&&(f(F.id),v(F.interval_hours.toString()),g(ke))},disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:m("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${d("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[ke==="days"?i.jsx(Yr,{className:"w-3 h-3"}):i.jsx(yd,{className:"w-3 h-3"}),VD(F.interval_hours,ke,m),i.jsx(_f,{className:"w-3 h-3 text-bambu-gray"})]})]},F.id)})})]})},L.printerId))})]}),ge.length===0&&i.jsx(Pt,{children:i.jsxs(Et,{className:"text-center py-12",children:[i.jsx(Jn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),ue&&i.jsx(_n,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:ue.name}),confirmText:m("common.delete"),cancelText:m("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(ue.id),me(null)},onCancel:()=>me(null)})]})}function att(){const{t}=Rt(),e=sn(),{showToast:n}=fn(),{hasPermission:r}=Nr(),[a,s]=w.useState("status"),{data:o,isLoading:l}=tt({queryKey:["maintenanceOverview"],queryFn:fe.getMaintenanceOverview}),{data:c}=tt({queryKey:["maintenanceTypes"],queryFn:fe.getMaintenanceTypes}),u=ft({mutationFn:({id:P,notes:k})=>fe.performMaintenance(P,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:P=>{n(P.message,"error")}}),d=ft({mutationFn:({id:P,data:k})=>fe.updateMaintenanceItem(P,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:P=>{n(P.message,"error")}}),m=ft({mutationFn:({id:P,data:k})=>fe.updateMaintenanceType(P,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:P=>{n(P.message,"error")}}),p=ft({mutationFn:fe.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:P=>{n(P.message,"error")}}),f=ft({mutationFn:fe.restoreDefaultMaintenanceTypes,onSuccess:P=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:P.restored}))},onError:P=>{n(P.message,"error")}}),y=ft({mutationFn:({printerId:P,hours:k})=>fe.setPrinterHours(P,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:P=>{n(P.message,"error")}}),v=ft({mutationFn:({printerId:P,typeId:k})=>fe.assignMaintenanceType(P,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:P=>{n(P.message,"error")}}),b=ft({mutationFn:fe.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:P=>{n(P.message,"error")}}),g=P=>{u.mutate({id:P})},_=(P,k)=>{d.mutate({id:P,data:{enabled:k}})},N=(P,k)=>{y.mutate({printerId:P,hours:k})};if(l)return i.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:i.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})});const T=o?.reduce((P,k)=>P+k.due_count,0)||0,C=o?.reduce((P,k)=>P+k.warning_count,0)||0;return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),i.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:a==="status"?i.jsxs(i.Fragment,{children:[T>0&&i.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:T})}),T>0&&C>0&&" · ",C>0&&i.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:C})}),T===0&&C===0&&i.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),i.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),i.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),a==="status"?i.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((P,k)=>{const R=P.due_count*10+P.warning_count,A=k.due_count*10+k.warning_count;return R!==A?A-R:P.printer_name.localeCompare(k.printer_name)}).map(P=>i.jsx(rtt,{overview:P,onPerform:g,onToggle:_,onSetHours:N,hasPermission:r,t},P.printer_id)):i.jsx(Pt,{children:i.jsxs(Et,{className:"text-center py-16",children:[i.jsx(kf,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),i.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):i.jsx(itt,{overview:o,types:c||[],onUpdateInterval:(P,k)=>d.mutate({id:P,data:k}),onAddType:async(P,k)=>{const R=await fe.createMaintenanceType(P);for(const A of k)await fe.assignMaintenanceType(A,R.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(P,k)=>m.mutate({id:P,data:k}),onDeleteType:P=>p.mutate(P),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(P,k)=>v.mutate({printerId:P,typeId:k}),onRemoveItem:P=>b.mutate(P),hasPermission:r,t})]})}const PY=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Hoe({project:t,onClose:e,onSave:n,isLoading:r,currencySymbol:a,t:s}){const[o,l]=w.useState(t?.name||""),[c,u]=w.useState(t?.description||""),[d,m]=w.useState(t?.color||PY[0]),[p,f]=w.useState(t?.target_count?.toString()||""),[y,v]=w.useState(t?.target_parts_count?.toString()||""),[b,g]=w.useState(t?.status||"active"),[_,N]=w.useState(t?.tags||""),[T,C]=w.useState(t?.due_date?.split("T")[0]||""),[P,k]=w.useState(t?.priority||"normal"),[R,A]=w.useState(t?.budget?.toString()||""),D=B=>{B.preventDefault(),n({name:o.trim(),description:c.trim()||void 0,color:d,target_count:p?parseInt(p,10):void 0,target_parts_count:y?parseInt(y,10):void 0,tags:_.trim()||void 0,due_date:T||void 0,priority:P,budget:R.trim()?parseFloat(R):null,...t&&{status:b}})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),i.jsxs("form",{onSubmit:D,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),i.jsx("input",{type:"text",value:o,onChange:B=>l(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.namePlaceholder"),required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),i.jsx("textarea",{value:c,onChange:B=>u(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:s("projects.descriptionPlaceholder"),rows:2})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),i.jsx("div",{className:"flex gap-2 flex-wrap",children:PY.map(B=>i.jsx("button",{type:"button",onClick:()=>m(B),className:`w-8 h-8 rounded-full transition-transform ${d===B?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:B}},B))})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),i.jsx("input",{type:"number",value:p,onChange:B=>f(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPlatesPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),i.jsx("input",{type:"number",value:y,onChange:B=>v(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPartsPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),i.jsx("input",{type:"text",value:_,onChange:B=>N(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.tagsPlaceholder")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),i.jsx("input",{type:"date",value:T,onChange:B=>C(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),i.jsxs("select",{value:P,onChange:B=>k(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"low",children:s("projects.priorityLow")}),i.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),i.jsx("option",{value:"high",children:s("projects.priorityHigh")}),i.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),i.jsxs("div",{className:"relative",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:a}),i.jsx("input",{type:"number",step:"0.01",min:"0",value:R,onChange:B=>A(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded pl-8 pr-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"0.00"})]})]}),t&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),i.jsxs("select",{value:b,onChange:B=>g(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"active",children:s("projects.statusActive")}),i.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),i.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(Ie,{type:"submit",disabled:!o.trim()||r,children:r?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function stt({project:t,onClick:e,onEdit:n,onDelete:r,hasPermission:a,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",u=t.status==="archived",[d,m]=w.useState(!1),f=c?{icon:su,color:"text-bambu-green",bg:"bg-bambu-green/10"}:u?{icon:$s,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Jn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:Ss,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return i.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[i.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),i.jsxs("div",{className:"p-5 pl-6",children:[i.jsxs("div",{className:"flex items-start justify-between mb-4",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:i.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?i.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?i.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?i.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&i.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),u&&i.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const y=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(Boolean),v=[...new Set(y)],b=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),g=[...new Set(b)];return v.length===0&&g.length===0?null:i.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>i.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),g.length>0&&i.jsxs("div",{className:"flex items-center gap-0.5",children:[g.slice(0,5).map(_=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),g.length>5&&i.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",g.length-5]})]})]})})()]})]}),i.jsxs("div",{className:"relative",onClick:y=>y.stopPropagation(),children:[i.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>m(!d),children:i.jsx(yh,{className:"w-4 h-4"})}),d&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),i.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:update")&&(n(),m(!1))},disabled:!a("projects:update"),title:a("projects:update")?void 0:s("projects.noEditPermission"),children:[i.jsx(_f,{className:"w-4 h-4"}),s("common.edit")]}),i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:delete")&&(r(),m(!1))},disabled:!a("projects:delete"),title:a("projects:delete")?void 0:s("projects.noDeletePermission"),children:[i.jsx(en,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),i.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?i.jsxs("div",{className:"space-y-3",children:[t.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),i.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),i.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&i.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?i.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx($s,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[i.jsx(Mn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[i.jsx(Jn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):i.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&i.jsxs("div",{className:"mb-4",children:[i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(y=>i.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:y.print_name||"Unknown",children:[y.thumbnail_path?i.jsx("img",{src:fe.getArchiveThumbnail(y.id),alt:y.print_name||"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:i.jsx(Gi,{className:"w-6 h-6"})}),y.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:i.jsx(Mn,{className:"w-4 h-4 text-white"})})]},y.id))}),t.archive_count>4&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),i.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[i.jsx(Vi,{className:"w-3.5 h-3.5 text-blue-400"}),i.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[i.jsx(Gi,{className:"w-3.5 h-3.5 text-bambu-green"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[i.jsx(Mn,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[i.jsx(y3,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.queue_count})]})]}),i.jsx(fa,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function ott(){const{t}=Rt(),e=al(),n=sn(),{showToast:r}=fn(),{hasPermission:a}=Nr(),[s,o]=w.useState(!1),[l,c]=w.useState(),[u,d]=w.useState("active"),[m,p]=w.useState(null),{data:f}=tt({queryKey:["settings"],queryFn:fe.getSettings}),y=Go(f?.currency||"USD"),{data:v,isLoading:b}=tt({queryKey:["projects",u==="all"?void 0:u],queryFn:()=>fe.getProjects(u==="all"?void 0:u)}),g=ft({mutationFn:J=>fe.createProject(J),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:J=>{r(J.message,"error")}}),_=ft({mutationFn:({id:J,data:ie})=>fe.updateProject(J,ie),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:J=>{r(J.message,"error")}}),N=ft({mutationFn:J=>fe.deleteProject(J),onSuccess:()=>{p(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:J=>{p(null),r(J.message,"error")}}),T=ft({mutationFn:J=>fe.importProject(J),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:J=>{r(J.message,"error")}}),C=w.useRef(null),P=async()=>{try{const J=await fe.getProjects(),ie=await Promise.all(J.map(async pe=>await fe.exportProjectJson(pe.id))),Q=new Blob([JSON.stringify(ie,null,2)],{type:"application/json"}),ue=URL.createObjectURL(Q),me=document.createElement("a");me.href=ue,me.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,me.click(),URL.revokeObjectURL(ue),r(t("projects.toast.exported"),"success")}catch(J){r(J.message,"error")}},k=()=>{C.current?.click()},R=async J=>{const ie=J.target.files?.[0];if(ie){try{if(ie.name.toLowerCase().endsWith(".zip"))await fe.importProjectFile(ie),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const ue=await ie.text(),me=JSON.parse(ue),pe=Array.isArray(me)?me:[me];for(const Y of pe)await T.mutateAsync(Y);pe.length>1&&r(t("projects.toast.multipleImported",{count:pe.length}),"success")}}catch(Q){r(`${t("projects.toast.importFailed")}: ${Q.message}`,"error")}J.target.value=""}},A=J=>{l?_.mutate({id:l.id,data:J}):g.mutate(J)},D=J=>{c(J),o(!0)},B=J=>{e(`/projects/${J.id}`)},z=J=>{p(J)},W=()=>{m!==null&&N.mutate(m)},I=v?.reduce((J,ie)=>(J[ie.status]=(J[ie.status]||0)+1,J.all=(J.all||0)+1,J),{})||{};return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsx("input",{ref:C,type:"file",accept:".json,.zip",onChange:R,className:"hidden"}),i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(Ss,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ie,{variant:"secondary",onClick:k,disabled:!a("projects:create"),title:a("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[i.jsx(vi,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),i.jsxs(Ie,{variant:"secondary",onClick:P,disabled:!a("projects:read"),title:a("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[i.jsx(bi,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),i.jsxs(Ie,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(ar,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),i.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Jn},{key:"completed",label:t("projects.statusCompleted"),icon:su},{key:"archived",label:t("projects.statusArchived"),icon:$s},{key:"all",label:t("common.all"),icon:Ss}].map(({key:J,label:ie,icon:Q})=>i.jsxs("button",{onClick:()=>d(J),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===J?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Q,{className:"w-4 h-4"}),i.jsx("span",{children:ie}),I[J]>0&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===J?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:I[J]})]},J))}),b?i.jsx("div",{className:"flex items-center justify-center py-20",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(Ss,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:u==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:u})}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:u==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:u})}),u==="all"&&i.jsxs(Ie,{onClick:()=>o(!0),disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(ar,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(J=>i.jsx(stt,{project:J,onClick:()=>B(J),onEdit:()=>D(J),onDelete:()=>z(J.id),hasPermission:a,t},J.id))}),m!==null&&i.jsx(_n,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:W,onCancel:()=>p(null)}),s&&i.jsx(Hoe,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:A,isLoading:g.isPending||_.isPending,currencySymbol:y,t})]})}function ltt(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function ctt({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,a={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return i.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:a[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function MY({icon:t,label:e,value:n,subValue:r,hint:a,color:s="text-bambu-gray"}){return i.jsx(Pt,{children:i.jsx(Et,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",title:a,children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function utt({archives:t,t:e}){return t.length===0?i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(Gi,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),i.jsx("p",{children:e("projectDetail.noPrints")})]}):i.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(n=>i.jsxs(co,{to:`/archives?search=${encodeURIComponent(n.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[n.thumbnail_path?i.jsx("img",{src:fe.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:i.jsx(Gi,{className:"w-8 h-8"})}),n.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:i.jsx(qi,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&i.jsx("div",{className:"absolute top-1 right-1",children:i.jsx(fr,{className:"w-4 h-4 text-bambu-green"})}),i.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function dtt({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:r,label:a}=n[t]||n.normal;return i.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&i.jsx(Mn,{className:"w-3 h-3"}),a]})}function GD(t,e){if(!t)return null;const n=Zn(t);if(!n)return null;const r=new Date,a=Math.ceil((n.getTime()-r.getTime())/(1e3*60*60*24));return a<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:a===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:a<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:a})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:a})}}function mtt(){const{id:t}=hw(),e=al(),{t:n}=Rt(),r=sn(),{showToast:a}=fn(),{hasPermission:s}=Nr(),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,m]=w.useState(""),p=parseInt(t||"0",10),{data:f,isLoading:y,error:v}=tt({queryKey:["project",p],queryFn:()=>fe.getProject(p),enabled:p>0}),{data:b,isLoading:g}=tt({queryKey:["project-archives",p],queryFn:()=>fe.getProjectArchives(p),enabled:p>0}),{data:_,isLoading:N}=tt({queryKey:["project-bom",p],queryFn:()=>fe.getProjectBOM(p),enabled:p>0}),{data:T,isLoading:C}=tt({queryKey:["project-timeline",p],queryFn:()=>fe.getProjectTimeline(p,20),enabled:p>0}),{data:P}=tt({queryKey:["settings"],queryFn:fe.getSettings}),{data:k}=tt({queryKey:["project-folders",p],queryFn:()=>fe.getLibraryFoldersByProject(p),enabled:p>0}),R=Go(P?.currency||"USD"),A=P?.time_format||"system",D=ft({mutationFn:je=>fe.updateProject(p,je),onSuccess:()=>{r.invalidateQueries({queryKey:["project",p]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),a(n("projectDetail.toast.projectUpdated"),"success")},onError:je=>{a(je.message,"error")}}),B=()=>{m(f?.notes||""),u(!0)},z=()=>{D.mutate({notes:d})},W=()=>{u(!1),m("")},[I,J]=w.useState(""),[ie,Q]=w.useState(1),[ue,me]=w.useState(""),[pe,Y]=w.useState(""),[se,oe]=w.useState(""),[be,Me]=w.useState(!1),[q,Z]=w.useState(!1),[j,E]=w.useState(null),[U,K]=w.useState(""),[$,ne]=w.useState(1),[O,V]=w.useState(""),[ee,G]=w.useState(""),[re,ce]=w.useState(""),[ge,xe]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),ae=ft({mutationFn:je=>fe.createBOMItem(p,je),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),J(""),Q(1),me(""),Y(""),oe(""),Me(!1),a(n("projectDetail.toast.partAdded"),"success")},onError:je=>a(je.message,"error")}),L=ft({mutationFn:({itemId:je,data:Xe})=>fe.updateBOMItem(p,je,Xe),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),E(null)},onError:je=>a(je.message,"error")}),F=ft({mutationFn:je=>fe.deleteBOMItem(p,je),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),a(n("projectDetail.toast.partRemoved"),"success")},onError:je=>a(je.message,"error")}),te=je=>{je.preventDefault(),I.trim()&&ae.mutate({name:I.trim(),quantity_needed:ie,unit_price:ue?parseFloat(ue):void 0,sourcing_url:pe.trim()||void 0,remarks:se.trim()||void 0})},ve=je=>{const Xe=je.is_complete?0:je.quantity_needed;L.mutate({itemId:je.id,data:{quantity_acquired:Xe}})},he=(je,Xe)=>{xe({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Xe}),onConfirm:()=>{xe(ye=>({...ye,isOpen:!1})),F.mutate(je)}})},de=je=>{E(je),K(je.name),ne(je.quantity_needed),V(je.unit_price?.toString()||""),G(je.sourcing_url||""),ce(je.remarks||"")},ke=je=>{je.preventDefault(),!(!j||!U.trim())&&L.mutate({itemId:j.id,data:{name:U.trim(),quantity_needed:$,unit_price:O?parseFloat(O):void 0,sourcing_url:ee.trim()||void 0,remarks:re.trim()||void 0}})},_e=()=>{E(null)},Le=async()=>{try{const{blob:je,filename:Xe}=await fe.exportProjectZip(Number(p)),ye=URL.createObjectURL(je),Ge=document.createElement("a");Ge.href=ye,Ge.download=Xe||`${f?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,Ge.click(),URL.revokeObjectURL(ye),a(n("projectDetail.toast.projectExported"),"success")}catch(je){a(je.message,"error")}},$e=ft({mutationFn:()=>fe.createTemplateFromProject(p),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),a(n("projectDetail.toast.templateCreated"),"success")},onError:je=>a(je.message,"error")}),Re=je=>Tf(je,A,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(y)return i.jsx("div",{className:"flex items-center justify-center py-24",children:i.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!f)return i.jsxs("div",{className:"text-center py-24",children:[i.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),i.jsx(Ie,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const Ae=f.stats,Pe=Ae?.progress_percent??0,Ue=Ae?.parts_progress_percent??0;return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(co,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),i.jsx(fa,{className:"w-4 h-4"}),i.jsx("span",{className:"text-white",children:f.name})]}),i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:i.jsx(IX,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:f.color||"#6b7280"}}),i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:f.name}),f.description&&i.jsx("p",{className:"text-bambu-gray mt-1",children:f.description})]})]}),i.jsx(ctt,{status:f.status,t:n})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ie,{variant:"secondary",onClick:Le,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[i.jsx(bi,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),i.jsxs(Ie,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[i.jsx(_f,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(f.target_count||f.target_parts_count)&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4 space-y-4",children:[f.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[Ae?.total_archives||0," / ",f.target_count," ",n("projectDetail.progress.printJobs")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Pe,100)}%`,backgroundColor:Pe>=100?"#22c55e":f.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Pe.toFixed(0)})}),Ae?.remaining_prints!=null&&Ae.remaining_prints>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Ae.remaining_prints})})]})]}),f.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[Ae?.completed_prints||0," / ",f.target_parts_count," ",n("projectDetail.progress.parts")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ue,100)}%`,backgroundColor:Ue>=100?"#22c55e":f.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Ue.toFixed(0)})}),Ae?.remaining_parts!=null&&Ae.remaining_parts>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Ae.remaining_parts})})]})]})]})}),Ae&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(Pt,{children:i.jsx(Et,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:i.jsx(Gi,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),i.jsxs("p",{className:"text-xl font-semibold text-white",children:[Ae.total_archives," ",i.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),Ae.failed_prints>0&&i.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:Ae.failed_prints})}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:Ae.completed_prints})})]})]})})}),i.jsx(MY,{icon:Jn,label:n("projectDetail.stats.printTime"),value:rxe(Ae.total_print_time_hours),color:"text-yellow-400"}),i.jsx(MY,{icon:_r,label:n("projectDetail.stats.filamentUsed"),value:ltt(Ae.total_filament_grams),color:"text-purple-400"})]}),Ae&&(()=>{const je=Ae.estimated_cost+Ae.total_energy_cost+Ae.bom_cost;return Ae.estimated_cost>0||je>0||f.budget!==null})()&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[R,Ae.estimated_cost.toFixed(2)]})]}),Ae.total_energy_kwh>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[Ae.total_energy_kwh.toFixed(3)," kWh",Ae.total_energy_cost>0&&i.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",R,Ae.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const je=Ae.estimated_cost+Ae.total_energy_cost+Ae.bom_cost;return je<=0?null:i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),i.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[R,je.toFixed(2)]}),Ae.bom_cost>0&&i.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),f.budget!==null&&(()=>{const je=Ae.estimated_cost+Ae.total_energy_cost+Ae.bom_cost,Xe=f.budget-je;return i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",i.jsxs("span",{className:"text-white font-semibold",children:[R,f.budget.toFixed(2)]})]}),i.jsxs("p",{className:`text-sm ${Xe>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",i.jsxs("span",{className:"font-semibold",children:[R,Xe.toFixed(2)]})]})]})})()]})]})}),f.children&&f.children.length>0&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[i.jsx(Zpe,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:f.children.length})]}),i.jsx("div",{className:"space-y-2",children:f.children.map(je=>i.jsxs(co,{to:`/projects/${je.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:je.color||"#6b7280"}}),i.jsx("span",{className:"text-white",children:je.name}),i.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${je.status==="completed"?"bg-status-ok/20 text-status-ok":je.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:je.status})]}),je.progress_percent!==null&&i.jsxs("span",{className:"text-sm text-bambu-gray",children:[je.progress_percent.toFixed(0),"%"]})]},je.id))})]})}),f.parent_id&&f.parent_name&&i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Vi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),i.jsx(co,{to:`/projects/${f.parent_id}`,className:"text-bambu-green hover:underline",children:f.parent_name})]}),(f.tags||f.due_date||f.priority!=="normal")&&i.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[f.priority&&f.priority!=="normal"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),i.jsx(dtt,{priority:f.priority,t:n})]}),f.due_date&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Yr,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-sm text-white",children:Cf(f.due_date,{year:"numeric",month:"short",day:"numeric"})}),GD(f.due_date,n)&&i.jsxs("span",{className:`text-xs ${GD(f.due_date,n).color}`,children:["(",GD(f.due_date,n).label,")"]})]}),f.tags&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Id,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:f.tags.split(",").map((je,Xe)=>i.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:je.trim()},Xe))})]})]}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(zs,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:W,disabled:D.isPending,children:[i.jsx(Ht,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),i.jsxs(Ie,{size:"sm",onClick:z,disabled:D.isPending,children:[D.isPending?i.jsx(pt,{className:"w-4 h-4 animate-spin mr-1"}):i.jsx(ss,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:B,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[i.jsx(_f,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?i.jsx(hL,{content:d,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):f.notes?i.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:pie.sanitize(f.notes)}}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Pc,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),i.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[i.jsx(co,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),k&&k.length>0?i.jsx("div",{className:"space-y-2",children:k.map(je=>i.jsxs(co,{to:`/files?folder=${je.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx(Pc,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:je.name}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:je.file_count})})]})]}),i.jsx(fa,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},je.id))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(XX,{className:"w-5 h-5"}),n("projectDetail.bom.title"),Ae&&Ae.bom_total_items>0&&i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:Ae.bom_completed_items,total:Ae.bom_total_items}),")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[_&&_.some(je=>je.is_complete)&&i.jsx("button",{onClick:()=>Z(!q),className:`text-xs px-2 py-1 rounded transition-colors ${q?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(q?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!be&&i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>Me(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[i.jsx(ar,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),be&&i.jsxs("form",{onSubmit:te,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:I,onChange:je=>J(je.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:ie,onChange:je=>Q(parseInt(je.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),i.jsx("input",{type:"number",step:"0.01",value:ue,onChange:je=>me(je.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:R})})]})]}),i.jsx("input",{type:"url",value:pe,onChange:je=>Y(je.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),i.jsx("input",{type:"text",value:se,onChange:je=>oe(je.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",size:"sm",onClick:()=>Me(!1),children:n("common.cancel")}),i.jsx(Ie,{type:"submit",size:"sm",disabled:!I.trim()||ae.isPending,children:ae.isPending?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),N?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):_&&_.length>0?i.jsxs("div",{className:"space-y-2",children:[_.filter(je=>!q||!je.is_complete).map(je=>i.jsx("div",{className:`p-3 rounded-lg transition-colors ${je.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:j?.id===je.id?i.jsxs("form",{onSubmit:ke,className:"space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:U,onChange:Xe=>K(Xe.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partName"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:$,onChange:Xe=>ne(parseInt(Xe.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),i.jsx("input",{type:"number",step:"0.01",value:O,onChange:Xe=>V(Xe.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:R})})]})]}),i.jsx("input",{type:"url",value:ee,onChange:Xe=>G(Xe.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),i.jsx("input",{type:"text",value:re,onChange:Xe=>ce(Xe.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",size:"sm",onClick:_e,children:n("common.cancel")}),i.jsx(Ie,{type:"submit",size:"sm",disabled:!U.trim()||L.isPending,children:L.isPending?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("button",{onClick:()=>s("projects:update")&&ve(je),disabled:L.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors flex-shrink-0 ${je.is_complete?"bg-status-ok border-status-ok text-white":s("projects:update")?"border-bambu-gray hover:border-bambu-green":"border-bambu-gray/50 cursor-not-allowed"}`,children:je.is_complete&&i.jsx(fr,{className:"w-3 h-3"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsxs("p",{className:`text-sm font-medium ${je.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[je.name,i.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",je.quantity_needed]})]}),je.unit_price!==null&&i.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[R,(je.unit_price*je.quantity_needed).toFixed(2)]})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>s("projects:update")&&de(je),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:i.jsx(Ki,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("projects:update")&&he(je.id,je.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:i.jsx(en,{className:"w-4 h-4"})})]})]}),je.sourcing_url&&i.jsxs("a",{href:je.sourcing_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 mt-1 text-xs text-blue-400 hover:text-blue-300 transition-colors",onClick:Xe=>Xe.stopPropagation(),children:[i.jsx(ti,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"truncate",children:(()=>{try{return new URL(je.sourcing_url).hostname.replace("www.","")}catch{return je.sourcing_url}})()})]}),je.remarks&&i.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:je.remarks})]})]})},je.id)),Ae&&Ae.bom_cost>0&&i.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),i.jsxs("span",{className:"text-white font-medium",children:[R,Ae.bom_cost.toFixed(2)]})]})]}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(x0,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),C?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):T&&T.length>0?i.jsx("div",{className:"space-y-3",children:T.slice(0,10).map((je,Xe)=>i.jsxs("div",{className:"flex gap-3",children:[i.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${je.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":je.event_type==="print_failed"?"bg-status-error/20 text-status-error":je.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[je.event_type==="print_completed"&&i.jsx(fr,{className:"w-4 h-4"}),je.event_type==="print_failed"&&i.jsx(qi,{className:"w-4 h-4"}),je.event_type==="print_started"&&i.jsx(_r,{className:"w-4 h-4"}),je.event_type==="queued"&&i.jsx(y3,{className:"w-4 h-4"}),je.event_type==="project_created"&&i.jsx(ar,{className:"w-4 h-4"})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white",children:je.title}),je.description&&i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:je.description}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:Re(je.timestamp)})]})]},Xe))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!f.is_template&&i.jsx("div",{className:"flex justify-end",children:i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>$e.mutate(),disabled:$e.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[$e.isPending?i.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(vo,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),Ae&&(Ae.queued_prints>0||Ae.in_progress_prints>0)&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(y3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),i.jsx(co,{to:`/queue?project=${p}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[Ae.in_progress_prints>0&&i.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:Ae.in_progress_prints})}),Ae.queued_prints>0&&i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:Ae.queued_prints})})]})]})}),i.jsxs("div",{children:[i.jsx("div",{className:"flex items-center justify-between mb-4",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Gi,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:b?.length||0})]})}),g?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):i.jsx(utt,{archives:b||[],t:n})]}),o&&i.jsx(Hoe,{t:n,currencySymbol:R,project:{...f,archive_count:Ae?.total_archives||0,total_items:Ae?.total_items||0,completed_count:Ae?.completed_prints||0,failed_count:Ae?.failed_prints||0,queue_count:Ae?.queued_prints||0,progress_percent:Ae?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:je=>D.mutate(je),isLoading:D.isPending}),ge.isOpen&&i.jsx(_n,{title:ge.title,message:ge.message,confirmText:n("common.delete"),variant:"danger",onConfirm:ge.onConfirm,onCancel:()=>xe(je=>({...je,isOpen:!1}))})]})}function htt({parentId:t,onClose:e,onSave:n,isLoading:r,t:a}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("fileManager.newFolder")})}),i.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.folderName")}),i.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ie,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):a("common.create")})]})]})]})})}function ptt({type:t,currentName:e,onClose:n,onSave:r,isLoading:a,t:s}){const[o,l]=w.useState(e),c=u=>{u.preventDefault(),o.trim()&&o.trim()!==e&&r(o.trim())};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),i.jsxs("form",{onSubmit:c,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),i.jsx("input",{type:"text",value:o,onChange:u=>l(u.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),i.jsx(Ie,{type:"submit",disabled:!o.trim()||o.trim()===e||a,children:a?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function ftt({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:a,isLoading:s,t:o}){const[l,c]=w.useState(null),u=(m,p=0)=>{const f=[];for(const y of m)f.push({id:y.id,name:y.name,depth:p}),y.children.length>0&&f.push(...u(y.children,p+1));return f},d=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...u(t)];return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:d.map(m=>i.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[i.jsx(Pc,{className:"w-4 h-4"}),m.name,m.id===n&&i.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),i.jsx(Ie,{onClick:()=>a(l),disabled:s,children:s?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function gtt({folder:t,onClose:e,onLink:n,isLoading:r,t:a}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:u}=tt({queryKey:["projects"],queryFn:()=>fe.getProjects()}),{data:d}=tt({queryKey:["archives-for-link"],queryFn:()=>fe.getArchives(void 0,void 0,100)}),m=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(_h,{className:"w-5 h-5 text-bambu-green"}),a("fileManager.linkFolder")]}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("fileManager.linkFolderDescription",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[i.jsx(zX,{className:"w-4 h-4"}),a("fileManager.project")]}),i.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[i.jsx($s,{className:"w-4 h-4"}),a("fileManager.archive")]})]}),i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?u&&u.length>0?u.map(y=>i.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:y.color||"#00ae42"}}),i.jsx("span",{className:"truncate",children:y.name})]},y.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noProjectsFound")}):d&&d.length>0?d.map(y=>i.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx(sf,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"truncate",children:y.print_name||y.filename})]},y.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noArchivesFound")})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&i.jsxs(Ie,{variant:"danger",onClick:p,disabled:r,children:[i.jsx(y0,{className:"w-4 h-4 mr-2"}),a("fileManager.unlink")]}),i.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[i.jsx(Ie,{variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ie,{onClick:m,disabled:!l||r,children:r?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):a("fileManager.link")})]})]})]})})}function $oe({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:u}){const[d,m]=w.useState(!0),[p,f]=w.useState(!1),y=t.children.length>0,v=t.project_id||t.archive_id;return i.jsxs("div",{children:[i.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>n(t.id),children:[y?i.jsx("button",{onClick:b=>{b.stopPropagation(),m(!d)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(fa,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-90":""}`})}):i.jsx("div",{className:"w-4.5"}),i.jsx(Pc,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),i.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&i.jsxs("button",{onClick:b=>{b.stopPropagation(),a(t)},className:"flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors",title:`${t.project_name?`Project: ${t.project_name}`:`Archive: ${t.archive_name}`} (click to change)`,children:[i.jsx(_h,{className:"w-3 h-3"}),t.project_name?i.jsx(zX,{className:"w-3 h-3"}):i.jsx($s,{className:"w-3 h-3"})]}),t.file_count>0&&i.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&i.jsx("button",{onClick:b=>{b.stopPropagation(),a(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:i.jsx(_h,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),i.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:b=>b.stopPropagation(),children:i.jsxs("div",{className:"relative",children:[i.jsx("button",{onClick:()=>f(!p),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:i.jsx(yh,{className:"w-3.5 h-3.5 text-bambu-gray"})}),p&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>f(!1)}),i.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(s(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[i.jsx(Ki,{className:"w-3.5 h-3.5"}),u("common.rename")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(a(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[i.jsx(_h,{className:"w-3.5 h-3.5"}),u(v?"fileManager.changeLink":"fileManager.linkTo")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:delete_all")&&(r(t.id),f(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[i.jsx(en,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),y&&d&&i.jsx("div",{children:t.children.map(b=>i.jsx($oe,{folder:b,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},b.id))})]})}function wL(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function btt({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:a,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:u,onGenerateThumbnail:d,thumbnailVersion:m,hasPermission:p,canModify:f,authEnabled:y,t:v}){const[b,g]=w.useState(!1);return i.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>r(t.id),children:[i.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?i.jsx("img",{src:`${fe.getLibraryFileThumbnailUrl(t.id)}${m?`?v=${m}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):i.jsx(sf,{className:"w-12 h-12 text-bambu-gray/30"}),i.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),i.jsxs("div",{className:"p-3",children:[i.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),i.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[i.jsx("span",{children:ho(t.file_size)}),t.print_time_seconds&&i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Jn,{className:"w-3 h-3"}),Is(t.print_time_seconds)]})]}),t.sliced_for_model&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(_r,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&i.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),y&&t.created_by_username&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(zd,{className:"w-3 h-3"}),t.created_by_username]})]}),i.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[i.jsx("button",{onClick:()=>g(!b),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:i.jsx(yh,{className:"w-4 h-4 text-bambu-gray"})}),b&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),i.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&wL(t.filename)&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("printers:control")&&(l(t),g(!1))},disabled:!p("printers:control"),title:p("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[i.jsx(_r,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&wL(t.filename)&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("queue:create")&&(o(t.id),g(!1))},disabled:!p("queue:create"),title:p("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[i.jsx(Jn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(c(t),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:"You do not have permission to preview files",children:[i.jsx(na,{className:"w-3.5 h-3.5"}),"3D Preview"]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(s(t.id),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[i.jsx(bi,{className:"w-3.5 h-3.5"}),v("common.download")]}),u&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(u(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[i.jsx(Ki,{className:"w-3.5 h-3.5"}),v("common.rename")]}),d&&t.file_type==="stl"&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(d(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[i.jsx(Ld,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","delete",t.created_by_id)&&(a(t.id),g(!1))},disabled:!f("library","delete",t.created_by_id),title:f("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[i.jsx(en,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),i.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function xtt(){const{t}=Rt(),e=sn(),{showToast:n}=fn(),{hasPermission:r,hasAnyPermission:a,canModify:s,authEnabled:o}=Nr(),[l]=jL(),c=l.get("folder"),u=c?parseInt(c,10):null,[d,m]=w.useState(u),[p,f]=w.useState([]),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,N]=w.useState(!1),[T,C]=w.useState(null),[P,k]=w.useState(null),[R,A]=w.useState(null),[D,B]=w.useState(null),[z,W]=w.useState(null),[I,J]=w.useState(null),[ie,Q]=w.useState({}),[ue,me]=w.useState(null),[pe,Y]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[se,oe]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[be,Me]=w.useState(()=>{const qe=localStorage.getItem("library-sidebar-width");return qe?parseInt(qe,10):256}),[q,Z]=w.useState(!1),j=w.useRef(null);w.useEffect(()=>{if(!q)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const qe=Nt=>{if(!j.current)return;const mt=j.current.parentElement?.getBoundingClientRect();if(!mt)return;const jt=Nt.clientX-mt.left,qt=Math.min(500,Math.max(200,jt));Me(qt)},_t=()=>{Z(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(be))};return document.addEventListener("mousemove",qe),document.addEventListener("mouseup",_t),()=>{document.removeEventListener("mousemove",qe),document.removeEventListener("mouseup",_t),document.body.style.userSelect="",document.body.style.cursor=""}},[q,be]);const[E,U]=w.useState(""),[K,$]=w.useState("all"),[ne,O]=w.useState(""),[V,ee]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[G,re]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),ce=aie();w.useEffect(()=>{const qe=l.get("folder");if(qe){const _t=parseInt(qe,10);m(_t)}},[l]);const{data:ge}=tt({queryKey:["settings"],queryFn:()=>fe.getSettings()}),{data:xe,isLoading:ae}=tt({queryKey:["library-folders"],queryFn:()=>fe.getLibraryFolders()}),{data:L,isLoading:F}=tt({queryKey:["library-files",d],queryFn:()=>fe.getLibraryFiles(d,d===null)}),{data:te}=tt({queryKey:["library-stats"],queryFn:()=>fe.getLibraryStats()}),{data:ve}=tt({queryKey:["users"],queryFn:()=>fe.getUsers()}),he=w.useMemo(()=>{if(!L)return[];const qe=new Set(L.map(_t=>_t.file_type));return Array.from(qe).sort()},[L]),de=w.useMemo(()=>{if(!L)return[];let qe=[...L];if(E.trim()){const _t=E.toLowerCase();qe=qe.filter(Nt=>Nt.filename.toLowerCase().includes(_t)||Nt.print_name&&Nt.print_name.toLowerCase().includes(_t))}if(K!=="all"&&(qe=qe.filter(_t=>_t.file_type===K)),ne.trim()){const _t=ne.toLowerCase();qe=qe.filter(Nt=>Nt.created_by_username&&Nt.created_by_username.toLowerCase().includes(_t))}return qe.sort((_t,Nt)=>{let mt=0;switch(V){case"name":mt=(_t.print_name||_t.filename).localeCompare(Nt.print_name||Nt.filename);break;case"date":mt=(Zn(_t.created_at)?.getTime()??0)-(Zn(Nt.created_at)?.getTime()??0);break;case"size":mt=_t.file_size-Nt.file_size;break;case"type":mt=_t.file_type.localeCompare(Nt.file_type);break;case"prints":mt=_t.print_count-Nt.print_count;break}return G==="asc"?mt:-mt}),qe},[L,E,K,ne,V,G]),ke=w.useMemo(()=>{if(!te||!ge)return!1;const qe=(ge.library_disk_warning_gb||5)*1024*1024*1024;return te.disk_free_bytesfe.createLibraryFolder(qe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:qe=>n(qe.message,"error")}),Le=ft({mutationFn:qe=>fe.deleteLibraryFolder(qe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===P?.id&&m(null),k(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:qe=>{k(null),n(qe.message,"error")}}),$e=ft({mutationFn:qe=>fe.deleteLibraryFile(qe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),f(qe=>qe.filter(_t=>_t!==P?.id)),k(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:qe=>{k(null),n(qe.message,"error")}}),Re=ft({mutationFn:qe=>fe.bulkDeleteLibrary(qe,[]),onSuccess:(qe,_t)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:_t.length}),"success"),f([]),k(null)},onError:qe=>{k(null),n(qe.message,"error")}}),Ae=ft({mutationFn:({fileIds:qe,folderId:_t})=>fe.moveLibraryFiles(qe,_t),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),f([]),g(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:qe=>n(qe.message,"error")}),Pe=ft({mutationFn:({id:qe,data:_t})=>fe.updateLibraryFolder(qe,_t),onSuccess:(qe,_t)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),C(null);const Nt=_t.data.project_id===0&&_t.data.archive_id===0;n(t(Nt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:qe=>n(qe.message,"error")}),Ue=ft({mutationFn:({id:qe,filename:_t})=>fe.updateLibraryFile(qe,{filename:_t}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),J(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:qe=>{J(null),n(qe.message,"error")}}),je=ft({mutationFn:({id:qe,name:_t})=>fe.updateLibraryFolder(qe,{name:_t}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),J(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:qe=>{J(null),n(qe.message,"error")}}),Xe=ft({mutationFn:()=>fe.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:qe=>{if(e.invalidateQueries({queryKey:["library-files"]}),qe.succeeded>0){const _t=Date.now(),Nt={};qe.results.forEach(mt=>{mt.success&&(Nt[mt.file_id]=_t)}),Q(mt=>({...mt,...Nt}))}qe.succeeded>0&&qe.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:qe.succeeded}),"success"):qe.succeeded>0&&qe.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:qe.succeeded,failed:qe.failed}),"success"):qe.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:qe.results[0]?.error||"Unknown error"}),"error")},onError:qe=>n(qe.message,"error")}),ye=ft({mutationFn:qe=>fe.batchGenerateStlThumbnails({file_ids:[qe]}),onSuccess:qe=>{if(e.invalidateQueries({queryKey:["library-files"]}),qe.succeeded>0){const _t=qe.results[0]?.file_id;_t&&Q(Nt=>({...Nt,[_t]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:qe.results[0]?.error||"Unknown error"}),"error")},onError:qe=>n(qe.message,"error")}),Ge=w.useCallback(qe=>{const _t=qe.toLowerCase();return _t.endsWith(".gcode")||_t.includes(".gcode.")},[]),Ee=w.useMemo(()=>L?L.filter(qe=>p.includes(qe.id)&&Ge(qe.filename)):[],[L,p,Ge]),Ke=w.useCallback(qe=>{f(_t=>_t.includes(qe)?_t.filter(Nt=>Nt!==qe):[..._t,qe])},[]),Ve=w.useCallback(()=>{de.length>0&&f(de.map(qe=>qe.id))},[de]),Ne=w.useCallback(()=>{f([])},[]),Ce=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},He=qe=>{fe.downloadLibraryFile(qe).catch(_t=>{console.error("Library file download failed:",_t)})},et=()=>{P&&(P.type==="file"?$e.mutate(P.id):P.type==="folder"?Le.mutate(P.id):P.type==="bulk"&&Re.mutate(p))},it=Le.isPending||$e.isPending||Re.isPending,xt=qe=>{Y(qe),localStorage.setItem("library-view-mode",qe)},vt=ae||F;return i.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(Pc,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[i.jsx("button",{onClick:()=>xt("grid"),className:`p-1.5 rounded transition-colors ${pe==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:i.jsx(xw,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>xt("list"),className:`p-1.5 rounded transition-colors ${pe==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:i.jsx(eT,{className:"w-4 h-4"})})]}),i.jsxs(Ie,{variant:"secondary",onClick:()=>Xe.mutate(),disabled:Xe.isPending||!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[Xe.isPending?i.jsx(pt,{className:"w-4 h-4 mr-2 animate-spin"}):i.jsx(Ld,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),i.jsxs(Ie,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[i.jsx(Xpe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),i.jsxs(Ie,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(vi,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),ke&&te&&ge&&i.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[i.jsx(Mn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),i.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:ho(te.disk_free_bytes),total:ho(te.disk_total_bytes),threshold:ge.library_disk_warning_gb})})]})]}),te&&i.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(ZC,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),i.jsx("span",{className:"text-white font-medium",children:te.total_files})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Pc,{className:"w-4 h-4 text-blue-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),i.jsx("span",{className:"text-white font-medium",children:te.total_folders})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Ix,{className:"w-4 h-4 text-amber-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),i.jsx("span",{className:"text-white font-medium",children:ho(te.total_size_bytes)})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),i.jsx("span",{className:`font-medium ${ke?"text-amber-500":"text-white"}`,children:ho(te.disk_free_bytes)})]})]}),i.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[i.jsx("div",{className:"lg:hidden",children:i.jsxs("select",{value:d??"",onChange:qe=>m(qe.target.value?parseInt(qe.target.value,10):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[i.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),xe&&(()=>{const qe=(_t,Nt=0)=>{const mt=[];for(const jt of _t)mt.push({id:jt.id,name:jt.name,fileCount:jt.file_count,depth:Nt}),jt.children.length>0&&mt.push(...qe(jt.children,Nt+1));return mt};return qe(xe).map(_t=>i.jsxs("option",{value:_t.id,children:["│ ".repeat(_t.depth),"📂 ",_t.name," ",_t.fileCount>0?`(${_t.fileCount})`:""]},_t.id))})()]})}),i.jsxs("div",{ref:j,className:"hidden lg:flex flex-shrink-0 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden flex-col relative",style:{width:`${be}px`},children:[i.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${q?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:qe=>{qe.preventDefault(),Z(!0)},onDoubleClick:()=>{Me(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:i.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${q?"opacity-100":""}`,children:[i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),i.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),i.jsx("button",{onClick:()=>{const qe=!se;oe(qe),localStorage.setItem("library-wrap-folders",String(qe))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${se?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(se?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[i.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${d===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>m(null),children:[i.jsx(sf,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),xe?.map(qe=>i.jsx($oe,{folder:qe,selectedFolderId:d,onSelect:m,onDelete:_t=>k({type:"folder",id:_t}),onLink:C,onRename:_t=>J({type:"folder",id:_t.id,name:_t.name}),wrapNames:se,hasPermission:r,t},qe.id))]})]}),i.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[L&&L.length>0&&i.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[i.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:E,onChange:qe=>U(qe.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(JC,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),i.jsxs("select",{value:K,onChange:qe=>$(qe.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"all",children:t("fileManager.allTypes")}),he.map(qe=>i.jsx("option",{value:qe,children:qe.toUpperCase()},qe))]})]}),o&&i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:ne,onChange:qe=>O(qe.target.value),list:"usernames-list",className:`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${ne?"pr-7":""}`,style:ne?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),ne&&i.jsx("button",{onClick:()=>O(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:i.jsx(Ht,{className:"w-3 h-3"})}),i.jsx("datalist",{id:"usernames-list",children:ve?.map(qe=>i.jsx("option",{value:qe.username},qe.id))})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("select",{value:V,onChange:qe=>{const _t=qe.target.value;ee(_t),localStorage.setItem("library-sort-field",_t)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"name",children:t("common.name")}),i.jsx("option",{value:"date",children:t("common.date")}),i.jsx("option",{value:"size",children:t("fileManager.size")}),i.jsx("option",{value:"type",children:t("common.type")}),i.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),i.jsx("button",{onClick:()=>re(qe=>{const _t=qe==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",_t),_t}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(G==="asc"?"fileManager.ascending":"fileManager.descending"),children:G==="asc"?i.jsx(ghe,{className:"w-4 h-4 text-white"}):i.jsx(che,{className:"w-4 h-4 text-white"})})]}),(E||K!=="all"||ne)&&i.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:de.length,total:L.length})})]}),de.length>0&&i.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[p.length===de.length&&p.length>0?i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:Ne,children:[i.jsx(ql,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:Ve,children:[i.jsx(_o,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),p.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:p.length})}),i.jsx("div",{className:"hidden sm:block flex-1"}),i.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Ee.length===1&&i.jsxs(Ie,{variant:"primary",size:"sm",onClick:()=>B(Ee[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[i.jsx(wo,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Ee.length===1&&i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>W(Ee[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[i.jsx(Jn,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>g(!0),disabled:!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[i.jsx(sge,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),i.jsxs(Ie,{variant:"danger",size:"sm",onClick:()=>{p.length===1?k({type:"file",id:p[0]}):k({type:"bulk",id:0,count:p.length})},disabled:!a("library:delete_own","library:delete_all"),title:a("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[i.jsx(en,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:Ne,children:[i.jsx(Ht,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),vt?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):L?.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(sf,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(d!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(d!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),i.jsxs(Ie,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(ar,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):de.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(Rr,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),i.jsx(Ie,{variant:"secondary",onClick:()=>{U(""),$("all")},children:t("fileManager.clearFilters")})]}):pe==="grid"?i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:de.map(qe=>i.jsx(btt,{file:qe,isSelected:p.includes(qe.id),isMobile:ce,t,onSelect:Ke,onDelete:_t=>k({type:"file",id:_t}),onDownload:He,onAddToQueue:_t=>{const Nt=L?.find(mt=>mt.id===_t);Nt&&W(Nt)},onPrint:A,onPreview3d:me,onRename:_t=>J({type:"file",id:_t.id,name:_t.filename}),onGenerateThumbnail:_t=>ye.mutate(_t.id),thumbnailVersion:ie[qe.id],hasPermission:r,canModify:s,authEnabled:o},qe.id))})}):i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[i.jsx("div",{className:"w-6"}),i.jsx("div",{children:t("common.name")}),o&&i.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),i.jsx("div",{children:t("common.type")}),i.jsx("div",{children:t("fileManager.size")}),i.jsx("div",{children:t("fileManager.prints")}),i.jsx("div",{})]}),de.map(qe=>i.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${p.includes(qe.id)?"bg-bambu-green/10":""}`,onClick:()=>Ke(qe.id),children:[i.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${p.includes(qe.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:p.includes(qe.id)&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsxs("div",{className:"relative group/thumb",children:[i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:qe.thumbnail_path?i.jsx("img",{src:`${fe.getLibraryFileThumbnailUrl(qe.id)}${ie[qe.id]?`?v=${ie[qe.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(sf,{className:"w-5 h-5 text-bambu-gray/50"})})}),qe.thumbnail_path&&i.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:i.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:i.jsx("img",{src:`${fe.getLibraryFileThumbnailUrl(qe.id)}${ie[qe.id]?`?v=${ie[qe.id]}`:""}`,alt:qe.filename,className:"w-full h-full object-contain"})})})]}),i.jsx("div",{className:"min-w-0",children:i.jsx("div",{className:"text-sm text-white truncate",children:qe.print_name||qe.filename})})]}),o&&i.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:qe.created_by_username?i.jsxs(i.Fragment,{children:[i.jsx(zd,{className:"w-3 h-3"}),i.jsx("span",{className:"truncate",children:qe.created_by_username})]}):"-"}),i.jsx("div",{children:i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${qe.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":qe.file_type==="gcode"?"bg-blue-500/20 text-blue-400":qe.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:qe.file_type.toUpperCase()})}),i.jsx("div",{className:"text-sm text-bambu-gray",children:ho(qe.file_size)}),i.jsx("div",{className:"text-sm text-bambu-gray",children:qe.print_count>0?`${qe.print_count}x`:"-"}),i.jsxs("div",{className:"flex items-center gap-1",onClick:_t=>_t.stopPropagation(),children:[wL(qe.filename)&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>r("printers:control")&&A(qe),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:i.jsx(_r,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{r("queue:create")&&W(qe)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:i.jsx(Jn,{className:"w-4 h-4"})})]}),(qe.file_type==="3mf"||qe.file_type==="gcode"||qe.file_type==="stl")&&i.jsx("button",{onClick:()=>r("library:read")&&me(qe),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:i.jsx(na,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>r("library:read")&&He(qe.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:i.jsx(bi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","update",qe.created_by_id)&&J({type:"file",id:qe.id,name:qe.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",qe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",qe.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",qe.created_by_id),children:i.jsx(Ki,{className:"w-4 h-4"})}),qe.file_type==="stl"&&i.jsx("button",{onClick:()=>s("library","update",qe.created_by_id)&&ye.mutate(qe.id),className:`p-1.5 rounded transition-colors ${s("library","update",qe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",qe.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:ye.isPending||!s("library","update",qe.created_by_id),children:i.jsx(Ld,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","delete",qe.created_by_id)&&k({type:"file",id:qe.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",qe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","delete",qe.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",qe.created_by_id),children:i.jsx(en,{className:"w-4 h-4"})})]})]},qe.id))]})})]})]}),y&&i.jsx(htt,{parentId:d,onClose:()=>v(!1),onSave:qe=>_e.mutate(qe),isLoading:_e.isPending,t}),b&&xe&&i.jsx(ftt,{folders:xe,selectedFiles:p,currentFolderId:d,onClose:()=>g(!1),onMove:qe=>Ae.mutate({fileIds:p,folderId:qe}),isLoading:Ae.isPending,t}),_&&i.jsx(Qre,{folderId:d,onClose:()=>N(!1),onUploadComplete:Ce}),T&&i.jsx(gtt,{folder:T,onClose:()=>C(null),onLink:qe=>Pe.mutate({id:T.id,data:qe}),isLoading:Pe.isPending,t}),P&&i.jsx(_n,{title:P.type==="folder"?t("fileManager.deleteFolder"):P.type==="bulk"?t("fileManager.deleteFilesCount",{count:P.count}):t("fileManager.deleteFile"),message:P.type==="folder"?t("fileManager.deleteFolderConfirm"):P.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:P.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:it,loadingText:t("fileManager.deleting"),onConfirm:et,onCancel:()=>k(null)}),R&&i.jsx(bu,{mode:"reprint",libraryFileId:R.id,archiveName:R.print_name||R.filename,onClose:()=>A(null),onSuccess:()=>{A(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),D&&i.jsx(bu,{mode:"reprint",libraryFileId:D.id,archiveName:D.print_name||D.filename,onClose:()=>B(null),onSuccess:()=>{B(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),z&&i.jsx(bu,{mode:"add-to-queue",libraryFileId:z.id,archiveName:z.print_name||z.filename,onClose:()=>W(null),onSuccess:()=>{W(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),ue&&i.jsx(jI,{libraryFileId:ue.id,title:ue.print_name||ue.filename,fileType:ue.file_type,onClose:()=>me(null)}),I&&i.jsx(ptt,{type:I.type,currentName:I.name,onClose:()=>J(null),onSave:qe=>{I.type==="file"?Ue.mutate({id:I.id,filename:qe}):je.mutate({id:I.id,name:qe})},isLoading:Ue.isPending||je.isPending,t})]})}const WD=5,ytt=2e3,vtt=3e4,wtt=5e3;function Stt(){const{t}=Rt(),e=sn(),{showToast:n}=fn(),{hasPermission:r}=Nr(),{printerId:a}=hw(),s=parseInt(a||"0",10),[o,l]=w.useState("stream"),[c,u]=w.useState(!1),[d,m]=w.useState(!1),[p,f]=w.useState(!0),[y,v]=w.useState(Date.now()),[b,g]=w.useState(!1),[_,N]=w.useState(!1),[T,C]=w.useState(0),[P,k]=w.useState(!1),[R,A]=w.useState(0),[D,B]=w.useState(1),[z,W]=w.useState({x:0,y:0}),[I,J]=w.useState(!1),[ie,Q]=w.useState({x:0,y:0}),[ue,me]=w.useState(null),[pe,Y]=w.useState(null),se=w.useRef(null),oe=w.useRef(null),be=w.useRef(null),Me=w.useRef(null),q=w.useRef(null),{data:Z}=tt({queryKey:["printer",s],queryFn:()=>fe.getPrinter(s),enabled:s>0}),{data:j}=tt({queryKey:["printerStatus",s],queryFn:()=>fe.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),E=ft({mutationFn:Ae=>fe.setChamberLight(s,Ae),onMutate:async Ae=>{await e.cancelQueries({queryKey:["printerStatus",s]});const Pe=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],Ue=>({...Ue,chamber_light:Ae})),{previousStatus:Pe}},onSuccess:(Ae,Pe)=>{n(`Chamber light ${Pe?"on":"off"}`)},onError:(Ae,Pe,Ue)=>{Ue?.previousStatus&&e.setQueryData(["printerStatus",s],Ue.previousStatus),n(Ae.message||t("printers.toast.failedToControlChamberLight"),"error")}}),U=(j?.state==="RUNNING"||j?.state==="PAUSE")&&(j?.printable_objects_count??0)>=2;w.useEffect(()=>(Z&&(document.title=`${Z.name} - Camera`),()=>{document.title="Bambuddy"}),[Z]);const K=w.useRef(!1);w.useEffect(()=>{const Ae=`/api/v1/printers/${s}/camera/stop`;K.current=!1;const Pe=()=>{if(s>0&&!K.current){K.current=!0;const Xe={},ye=Ud();ye&&(Xe.Authorization=`Bearer ${ye}`),fetch(Ae,{method:"POST",keepalive:!0,headers:Xe}).catch(()=>{})}},Ue=()=>{Pe()};window.addEventListener("beforeunload",Ue);const je=se.current;return()=>{window.removeEventListener("beforeunload",Ue),je&&(je.src=""),Pe()}},[s]),w.useEffect(()=>{if(p&&!b){const Pe=setTimeout(()=>{f(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(Pe)}},[o,p,y,b]),w.useEffect(()=>{const Ae=()=>{const Pe=!!document.fullscreenElement;N(Pe),B(1),W({x:0,y:0}),o==="stream"&&!b&&(se.current&&(se.current.src=""),setTimeout(()=>{f(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",Ae),()=>document.removeEventListener("fullscreenchange",Ae)},[o,b]),w.useEffect(()=>{let Ae;const Pe=()=>{clearTimeout(Ae),Ae=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Pe),()=>{clearTimeout(Ae),window.removeEventListener("resize",Pe)}},[]),w.useEffect(()=>()=>{be.current&&clearTimeout(be.current),Me.current&&clearInterval(Me.current),q.current&&clearInterval(q.current)},[]);const $=w.useCallback(()=>{if(T>=WD){k(!1),m(!0);return}const Ae=Math.min(ytt*Math.pow(2,T),vtt);k(!0),A(Math.ceil(Ae/1e3)),Me.current=setInterval(()=>{A(Pe=>Pe<=1?(Me.current&&clearInterval(Me.current),0):Pe-1)},1e3),be.current=setTimeout(()=>{C(Pe=>Pe+1),k(!1),f(!0),m(!1),se.current&&(se.current.src=""),v(Date.now())},Ae)},[T]);w.useEffect(()=>{if(o!=="stream"||p||P||b){q.current&&(clearInterval(q.current),q.current=null);return}return q.current=setInterval(async()=>{try{const Ae=await fe.getCameraStatus(s);(Ae.stalled||!Ae.active&&!d)&&(console.log(`Stream issue detected: stalled=${Ae.stalled}, active=${Ae.active}, reconnecting...`),q.current&&(clearInterval(q.current),q.current=null),f(!1),$())}catch{}},wtt),()=>{q.current&&(clearInterval(q.current),q.current=null)}},[o,p,d,P,b,s,$]);const ne=()=>{f(!1),o==="stream"&&T{if(f(!1),m(!1),C(0),k(!1),be.current&&clearTimeout(be.current),Me.current&&clearInterval(Me.current),se.current&&!localStorage.getItem("cameraWindowState")){const Ae=se.current,Pe=Ae.naturalWidth,Ue=Ae.naturalHeight;if(Pe>0&&Ue>0){const ye=window.outerWidth-window.innerWidth,Ge=window.outerHeight-window.innerHeight,Ee=Pe+16+ye,Ke=Ue+45+16+Ge;try{window.resizeTo(Ee,Ke)}catch{}}}},V=()=>{if(s>0){const Ae={},Pe=Ud();Pe&&(Ae.Authorization=`Bearer ${Pe}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:Ae}).catch(()=>{})}},ee=Ae=>{o===Ae||b||(g(!0),f(!0),m(!1),C(0),k(!1),B(1),W({x:0,y:0}),be.current&&clearTimeout(be.current),Me.current&&clearInterval(Me.current),se.current&&(se.current.src=""),o==="stream"&&V(),setTimeout(()=>{l(Ae),v(Date.now()),g(!1)},100))},G=()=>{b||(g(!0),f(!0),m(!1),C(0),k(!1),be.current&&clearTimeout(be.current),Me.current&&clearInterval(Me.current),se.current&&(se.current.src=""),o==="stream"&&V(),setTimeout(()=>{v(Date.now()),g(!1)},100))},re=()=>{oe.current&&(document.fullscreenElement?document.exitFullscreen():oe.current.requestFullscreen())},ce=()=>{B(Ae=>Math.min(Ae+.5,4))},ge=()=>{B(Ae=>{const Pe=Math.max(Ae-.5,1);return Pe===1&&W({x:0,y:0}),Pe})},xe=Ae=>{Ae.preventDefault(),Ae.deltaY<0?ce():ge()},ae=Ae=>{D>1&&(Ae.preventDefault(),J(!0),Q({x:Ae.clientX-z.x,y:Ae.clientY-z.y}))},L=w.useCallback(()=>{if(!oe.current)return{x:300,y:200};const Ae=oe.current.getBoundingClientRect(),Pe=Ae.width*(D-1)/2,Ue=Ae.height*(D-1)/2;return{x:Math.max(50,Pe),y:Math.max(50,Ue)}},[D]),F=Ae=>{if(I&&D>1){const Pe=Ae.clientX-ie.x,Ue=Ae.clientY-ie.y,je=L();W({x:Math.max(-je.x,Math.min(je.x,Pe)),y:Math.max(-je.y,Math.min(je.y,Ue))})}},te=()=>{J(!1)},ve=Ae=>{if(Ae.length<2)return 0;const Pe=Ae[0].clientX-Ae[1].clientX,Ue=Ae[0].clientY-Ae[1].clientY;return Math.sqrt(Pe*Pe+Ue*Ue)},he=Ae=>Ae.length<2?{x:Ae[0].clientX,y:Ae[0].clientY}:{x:(Ae[0].clientX+Ae[1].clientX)/2,y:(Ae[0].clientY+Ae[1].clientY)/2},de=Ae=>{Ae.touches.length===2?(Ae.preventDefault(),me(ve(Ae.touches)),Y(he(Ae.touches))):Ae.touches.length===1&&D>1&&(Ae.preventDefault(),J(!0),Q({x:Ae.touches[0].clientX-z.x,y:Ae.touches[0].clientY-z.y}))},ke=Ae=>{if(Ae.touches.length===2&&ue!==null){Ae.preventDefault();const Pe=ve(Ae.touches),Ue=Pe/ue;B(Xe=>{const ye=Math.max(1,Math.min(4,Xe*Ue));return ye===1&&W({x:0,y:0}),ye}),me(Pe);const je=he(Ae.touches);if(pe){const Xe=L();W(ye=>({x:Math.max(-Xe.x,Math.min(Xe.x,ye.x+(je.x-pe.x))),y:Math.max(-Xe.y,Math.min(Xe.y,ye.y+(je.y-pe.y)))}))}Y(je)}else if(Ae.touches.length===1&&I&&D>1){Ae.preventDefault();const Pe=Ae.touches[0].clientX-ie.x,Ue=Ae.touches[0].clientY-ie.y,je=L();W({x:Math.max(-je.x,Math.min(je.x,Pe)),y:Math.max(-je.y,Math.min(je.y,Ue))})}},_e=Ae=>{Ae.touches.length<2&&(me(null),Y(null)),Ae.touches.length===0&&J(!1)},Le=()=>{B(1),W({x:0,y:0})},$e=b?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${y}`:`/api/v1/printers/${s}/camera/snapshot?t=${y}`,Re=p||b||P;return s?i.jsxs("div",{ref:oe,className:"min-h-screen bg-black flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[i.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(ax,{className:"w-4 h-4"}),Z?.name||`Printer ${s}`]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[i.jsx("button",{onClick:()=>ee("stream"),disabled:Re,className:`px-3 py-1 text-xs rounded transition-colors ${o==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),i.jsx("button",{onClick:()=>ee("snapshot"),disabled:Re,className:`px-3 py-1 text-xs rounded transition-colors ${o==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),i.jsx("button",{onClick:()=>E.mutate(!j?.chamber_light),disabled:!j?.connected||E.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${j?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:i.jsx(kO,{on:j?.chamber_light??!1,className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>u(!0),disabled:!U||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${U&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(U?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:i.jsx(xT,{className:"w-4 h-4 text-bambu-gray"})}),i.jsx("button",{onClick:G,disabled:Re,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:i.jsx(Sr,{className:`w-4 h-4 text-bambu-gray ${Re?"animate-spin":""}`})}),i.jsx("button",{onClick:re,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?i.jsx(KX,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(Kfe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),i.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:xe,onMouseMove:F,onMouseUp:te,onMouseLeave:te,onTouchStart:de,onTouchMove:ke,onTouchEnd:_e,style:{touchAction:"none"},children:i.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(p||b)&&!P&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(Sr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),P&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(Rh,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:R,attempt:T+1,max:WD})}),i.jsx("button",{onClick:G,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),d&&!P&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(Mn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),i.jsx("button",{onClick:G,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),i.jsx("img",{ref:se,src:$e,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${D}) translate(${z.x/D}px, ${z.y/D}px) rotate(${Z?.camera_rotation||0}deg)`,...Z?.camera_rotation===90||Z?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:D>1?I?"grabbing":"grab":"default"},onError:$e?ne:void 0,onLoad:$e?O:void 0,onMouseDown:ae,draggable:!1},y),i.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[i.jsx("button",{onClick:ge,disabled:D<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:i.jsx(YL,{className:"w-4 h-4 text-white"})}),i.jsxs("button",{onClick:Le,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(D*100),"%"]}),i.jsx("button",{onClick:ce,disabled:D>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:i.jsx(KL,{className:"w-4 h-4 text-white"})})]})]})}),i.jsx(CO,{printerId:s,isOpen:c,onClose:()=>u(!1)})]}):i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function _tt(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),a=t.get("camera"),s=a!=="false"&&a!=="0";return{size:t.get("size")||"medium",fps:r,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function Ntt(t,e){if(t.stg_cur_name)return t.stg_cur_name;switch(t.state){case"RUNNING":return e("streamOverlay.status.printing");case"PAUSE":return e("streamOverlay.status.paused");case"FINISH":return e("streamOverlay.status.finished");case"FAILED":return e("streamOverlay.status.failed");case"IDLE":return e("streamOverlay.status.idle");default:return t.state||e("streamOverlay.status.unknown")}}function ktt(t){switch(t){case"small":return{container:"p-3",text:"text-sm",textLarge:"text-lg",progressHeight:"h-2",icon:"w-3 h-3",gap:"gap-2",logoHeight:"h-12"};case"large":return{container:"p-6",text:"text-xl",textLarge:"text-3xl",progressHeight:"h-4",icon:"w-6 h-6",gap:"gap-4",logoHeight:"h-24"};default:return{container:"p-4",text:"text-base",textLarge:"text-xl",progressHeight:"h-3",icon:"w-4 h-4",gap:"gap-3",logoHeight:"h-16"}}}function Ctt(){const{printerId:t}=hw(),[e]=jL(),{t:n}=Rt(),r=sn(),a=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>_tt(e),[e]),c=ktt(l.size),{data:u}=tt({queryKey:["printer",a],queryFn:()=>fe.getPrinter(a),enabled:a>0}),{data:d}=tt({queryKey:["printerStatus",a],queryFn:()=>fe.getPrinterStatus(a),enabled:a>0,refetchInterval:2e3}),{data:m}=tt({queryKey:["settings"],queryFn:fe.getSettings}),p=m?.time_format||"system";w.useEffect(()=>{if(!a)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,N=new WebSocket(_);return N.onmessage=T=>{try{const C=JSON.parse(T.data);C.type==="printer_status"&&C.printer_id===a&&r.setQueryData(["printerStatus",a],C.status)}catch{}},N.onerror=()=>{},()=>{N.close()}},[a,r]),w.useEffect(()=>(document.title=u?`${u.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[u,n]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!a)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!d)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const y=d.state==="RUNNING"||d.state==="PAUSE",v=d.progress||0,b=`/api/v1/printers/${a}/camera/stream?fps=${l.fps}&t=${s}`;return i.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&i.jsx("img",{src:b,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",style:u?.camera_rotation?{transform:`rotate(${u.camera_rotation}deg)`}:void 0,onError:f},s),i.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:i.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),i.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:i.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&u&&i.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[i.jsx(_r,{className:`${c.icon} text-white/70`}),i.jsx("span",{className:`${c.text} text-white font-medium`,children:u.name})]}),l.showFilename&&d.current_print&&i.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:d.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,"")}),l.showStatus&&i.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:Ntt(d,n)}),l.showProgress&&y&&i.jsxs("div",{className:"mb-3",children:[i.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[i.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),i.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),i.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:i.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),y&&(l.showLayers||l.showEta)&&i.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&d.layer_num!=null&&d.total_layers!=null&&d.total_layers>0&&i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Vi,{className:c.icon}),i.jsxs("span",{className:c.text,children:[i.jsx("span",{className:"text-white",children:d.layer_num}),i.jsx("span",{className:"mx-1",children:"/"}),i.jsx("span",{children:d.total_layers})]})]}),l.showEta&&d.remaining_time!=null&&d.remaining_time>0&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(yd,{className:c.icon}),i.jsx("span",{className:`${c.text} text-white`,children:Is(d.remaining_time*60)})]}),i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Jn,{className:c.icon}),i.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",XL(d.remaining_time,p,n)]})]})]})]}),!y&&i.jsx("div",{className:`${c.text} text-white/70 py-2`,children:d.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function Ttt(){const{t}=Rt(),{id:e}=hw(),{mode:n}=Xf(),{data:r,isLoading:a,error:s}=tt({queryKey:["external-link",e],queryFn:()=>fe.getExternalLink(Number(e)),enabled:!!e});return a?i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[i.jsx(Mn,{className:"w-12 h-12"}),i.jsx("p",{children:t("common.linkNotFound")})]}):i.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function EY(){const{id:t}=hw(),e=al(),n=sn(),{t:r}=Rt(),{showToast:a}=fn(),s=!!t,[o,l]=w.useState(""),[c,u]=w.useState(""),[d,m]=w.useState([]),[p,f]=w.useState(""),[y,v]=w.useState(!1),{data:b,isLoading:g}=tt({queryKey:["group",t],queryFn:()=>fe.getGroup(Number(t)),enabled:s}),{data:_,isLoading:N}=tt({queryKey:["permissions"],queryFn:()=>fe.getPermissions()});s&&b&&!y&&(l(b.name),u(b.description||""),m(b.permissions),v(!0));const T=ft({mutationFn:Q=>fe.createGroup(Q),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.created")),e("/settings?tab=users")},onError:Q=>{a(Q.message,"error")}}),C=ft({mutationFn:Q=>fe.updateGroup(Number(t),Q),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.updated")),e("/settings?tab=users")},onError:Q=>{a(Q.message,"error")}}),P=T.isPending||C.isPending,k=()=>{if(!o.trim()){a(r("groups.toast.enterGroupName"),"error");return}s?C.mutate({name:o!==b?.name?o:void 0,description:c,permissions:d}):T.mutate({name:o,description:c||void 0,permissions:d})},R=Q=>{m(ue=>ue.includes(Q)?ue.filter(me=>me!==Q):[...ue,Q])},A=(Q,ue)=>{const me=Q.permissions.map(pe=>pe.value);m(pe=>{const Y=pe.filter(se=>!me.includes(se));return ue?[...Y,...me]:Y})},D=Q=>Q.permissions.every(ue=>d.includes(ue.value)),B=Q=>{const ue=Q.permissions.filter(me=>d.includes(me.value)).length;return ue>0&&ue{_&&m(_.all_permissions)},W=()=>{m([])},I=p.toLowerCase(),J=w.useMemo(()=>_?I?_.categories.map(Q=>({...Q,permissions:Q.permissions.filter(ue=>ue.label.toLowerCase().includes(I))})).filter(Q=>Q.permissions.length>0):_.categories:[],[_,I]),ie=_?.all_permissions.length??0;return g||N?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:i.jsx(IX,{className:"w-5 h-5"})}),i.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&i.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[i.jsx(Mn,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),i.jsx("input",{type:"text",value:o,onChange:Q=>l(Q.target.value),disabled:s&&b?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:r("groups.form.groupNamePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),i.jsx("input",{type:"text",value:c,onChange:Q=>u(Q.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:r("groups.form.descriptionPlaceholder")})]})]}),i.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:d.length})," / ",ie]}),i.jsx(Ie,{size:"sm",variant:"ghost",onClick:z,children:r("groups.editor.selectAll")}),i.jsx(Ie,{size:"sm",variant:"ghost",onClick:W,children:r("groups.editor.clearAll")})]}),i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),i.jsx("input",{type:"text",value:p,onChange:Q=>f(Q.target.value),placeholder:r("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"})]})]}),J.length===0?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:J.map(Q=>{const ue=_.categories.find(oe=>oe.name===Q.name),me=ue.permissions.filter(oe=>d.includes(oe.value)).length,pe=ue.permissions.length,Y=D(ue),se=B(ue);return i.jsxs(Pt,{children:[i.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>A(ue,!Y),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${Y?"bg-bambu-green border-bambu-green":se?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[Y&&i.jsx(Qr,{className:"w-3 h-3 text-white"}),se&&!Y&&i.jsx(RN,{className:"w-3 h-3 text-white"})]}),i.jsx(S3,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-white font-medium text-sm",children:Q.name})]}),i.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[me,"/",pe]})]}),i.jsx("div",{className:"p-3 space-y-1",children:Q.permissions.map(oe=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d.includes(oe.value),onChange:()=>R(oe.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:oe.label})]},oe.value))})]},Q.name)})}),i.jsx("div",{className:"h-16"}),i.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[i.jsx(Ie,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),i.jsx(Ie,{onClick:k,disabled:P||!o.trim(),children:P?i.jsxs(i.Fragment,{children:[i.jsx(pt,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(ss,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const jY={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function Att(t,e=!1){const n={};return e?(t.material||(n.material="Material is required"),{isValid:Object.keys(n).length===0,errors:n}):(t.slicer_filament||(n.slicer_filament="Slicer preset is required"),t.material||(n.material="Material is required"),t.brand||(n.brand="Brand is required"),t.subtype||(n.subtype="Subtype is required"),{isValid:Object.keys(n).length===0,errors:n})}const Ptt=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Mtt=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],h0=["Basic","Matte","Silk","Tough","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],qoe=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"}],Ett=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],DY=[...qoe,...Ett],Voe="bambuddy-recent-colors",jtt=8,Dtt=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function Dx(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let r="",a=-1;for(const c of n){const u=e.toUpperCase().indexOf(c.toUpperCase());if(u!==-1){r=c,a=u;break}}let s="";a>0&&(s=e.substring(0,a).trim(),s=s.replace(/[-_\s]+$/,""));let o="";a!==-1&&r&&(o=e.substring(a+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of h0)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of h0){const u=new RegExp(`\\s+${c}$`,"i");if(u.test(s)){l=c,s=s.replace(u,"").trim();break}}return{brand:s,material:r,variant:l}}function Rtt(t,e){const n=new Set(Mtt);for(const r of t){const{brand:a}=Dx(r.name);a&&a.length>1&&n.add(a)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:a}=Dx(r.name);a&&a.length>1&&n.add(a)}return Array.from(n).sort((r,a)=>r.localeCompare(a))}function Ftt(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const a=r.name.replace(/@.*$/,"").trim(),s=n.get(a);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(a,{code:o,name:a,displayName:a,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,a)=>r.displayName.localeCompare(a.displayName))}function Ltt(t,e,n){if(t.length>0){const r=[],a=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=a.get(o);l?l.allCodes.push(s.setting_id):a.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(a.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=Ftt(n);if(r.length>0)return r}return Dtt}function Ott(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(a=>a.code.toLowerCase()===r||a.allCodes.some(s=>s.toLowerCase()===r))}return n}function Itt(){try{const t=localStorage.getItem(Voe);if(t)return JSON.parse(t)}catch{}return[]}function ztt(t,e){const n=e.filter(a=>a.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,jtt);try{localStorage.setItem(Voe,JSON.stringify(r))}catch{}return r}function KD(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),a=Dx(r);return!(!(a.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(a.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(a.brand.toLowerCase()))||e.subtype&&!(a.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(a.variant.toLowerCase())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function Utt({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:a,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:u,quickAdd:d,quantity:m,onQuantityChange:p,errors:f}){const{t:y}=Rt(),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[N,T]=w.useState(!1),[C,P]=w.useState(!1),[k,R]=w.useState(""),[A,D]=w.useState(""),[B,z]=w.useState(""),[W,I]=w.useState(String(t.label_weight)),[J,ie]=w.useState(!1),Q=w.useRef(null),ue=w.useRef(null),me=w.useRef(null),pe=w.useRef(null);w.useEffect(()=>{const q=Z=>{Q.current&&!Q.current.contains(Z.target)&&b(!1),pe.current&&!pe.current.contains(Z.target)&&P(!1),ue.current&&!ue.current.contains(Z.target)&&_(!1),me.current&&!me.current.contains(Z.target)&&T(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[]);const Y=w.useMemo(()=>{if(!a)return l;const q=a.toLowerCase();return l.filter(Z=>Z.displayName.toLowerCase().includes(q)||Z.code.toLowerCase().includes(q))},[l,a]),se=w.useMemo(()=>{if(!k)return c;const q=k.toLowerCase();return c.filter(j=>j.toLowerCase().includes(q)).sort((j,E)=>{const U=j.toLowerCase()===q,K=E.toLowerCase()===q;return U&&!K?-1:!U&&K?1:j.localeCompare(E)})},[c,k]),oe=w.useMemo(()=>{if(!A)return h0;const q=A.toLowerCase();return h0.filter(Z=>Z.toLowerCase().includes(q))},[A]),be=w.useMemo(()=>{if(!B)return u;const q=B.toLowerCase();return u.filter(j=>j.toLowerCase().includes(q)).sort((j,E)=>{const U=j.toLowerCase()===q,K=E.toLowerCase()===q;return U&&!K?-1:!U&&K?1:j.localeCompare(E)})},[B,u]);w.useEffect(()=>{J||I(String(t.label_weight))},[t.label_weight,J]);const Me=q=>{e("slicer_filament",q.code),s(q.displayName),b(!1);const Z=Dx(q.name);Z.material&&e("material",Z.material),Z.brand&&e("brand",Z.brand),Z.variant&&e("subtype",Z.variant)};return i.jsxs("div",{className:"space-y-4",children:[!d&&i.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?i.jsxs(i.Fragment,{children:[i.jsx(pt,{className:"w-3 h-3 animate-spin"})," ",y("inventory.loadingPresets")]}):n?i.jsxs(i.Fragment,{children:[i.jsx(Ox,{className:"w-3 h-3 text-bambu-green"})," ",y("inventory.cloudConnected")]}):i.jsxs(i.Fragment,{children:[i.jsx(spe,{className:"w-3 h-3"})," ",y("inventory.cloudNotConnected")]})}),!d&&i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.slicerPreset")," *"]}),i.jsxs("div",{className:"relative",ref:Q,children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.searchPresets"),value:a,onChange:q=>{s(q.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),v&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:Y.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noPresetsFound")}):Y.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===q.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Me(q),children:q.displayName},q.code))})]}),o&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[y("inventory.selectedPreset"),": ",i.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.material")," *"]}),i.jsxs("div",{className:"relative",ref:pe,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.selectMaterial"),value:C?B:t.material,onChange:q=>{z(q.target.value),P(!0)},onFocus:()=>{P(!0),z("")}}),i.jsx(On,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),C&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[be.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):be.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",q),P(!1),z("")},children:q},q)),B&&!be.includes(B)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",B),P(!1),z("")},children:y("inventory.useCustomMaterial",{material:B})})]})]}),f?.material&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.brand"),!d&&" *"]}),i.jsxs("div",{className:"relative",ref:ue,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.searchBrand"),value:g?k:t.brand,onChange:q=>{R(q.target.value),_(!0)},onFocus:()=>{_(!0),R("")}}),i.jsx(On,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),g&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[se.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):se.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",q),_(!1),R("")},children:q},q)),k&&!se.includes(k)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",k),_(!1),R("")},children:y("inventory.useCustomBrand",{brand:k})})]})]}),f?.brand&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.subtype"),!d&&" *"]}),i.jsxs("div",{className:"relative",ref:me,children:[i.jsx("input",{type:"text",value:N?A:t.subtype,onChange:q=>{D(q.target.value),T(!0)},onFocus:()=>{T(!0),D("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),i.jsx(On,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[oe.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):oe.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",q),T(!1),D("")},children:q},q)),A&&!h0.some(q=>q.toLowerCase()===A.toLowerCase().trim())&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",A),T(!1),D("")},children:y("inventory.useCustomBrand",{brand:A})})]})]}),f?.subtype&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.labelWeight")}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:W,min:0,onFocus:()=>ie(!0),onChange:q=>I(q.target.value),onBlur:()=>{ie(!1);const q=W.trim(),Z=Number(q);if(!q||!Number.isFinite(Z)||Z<0){I(String(t.label_weight));return}const j=Math.round(Z);e("label_weight",j),I(String(j))}}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),d&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.quantity")}),i.jsx("input",{type:"number",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:m,min:1,max:100,onChange:q=>{const Z=Math.max(1,Math.min(100,parseInt(q.target.value)||1));p(Z)}})]})]})}function Btt({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:a}){const{t:s}=Rt(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=t.rgba.replace("#","").substring(0,6),m=g=>d.toUpperCase()===g.toUpperCase(),p=(g,_)=>{e("rgba",g.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:g})},f=w.useMemo(()=>{if(a.length===0)return[];const g=t.brand?.trim(),_=t.material?.toLowerCase().trim(),N=t.subtype?.toLowerCase().trim();if(!g&&!_)return[];const T=g?g.toLowerCase().split(/[\s\-_]+/).filter(k=>k.length>=2):[],C=k=>{if(T.length===0)return!0;const R=k.toLowerCase();return T.some(A=>R.includes(A))};if(g&&!_){const k=a.filter(R=>C(R.manufacturer));if(k.length>0)return k.map(R=>({name:R.color_name,hex:R.hex_color.replace("#","").substring(0,6),manufacturer:R.manufacturer,material:typeof R.material=="string"?R.material:void 0}))}const P=_&&N?`${_} ${N}`:"";if(P){const k=a.filter(A=>C(A.manufacturer)&&A.material?.toLowerCase()===P);if(k.length>0)return k.map(A=>({name:A.color_name,hex:A.hex_color.replace("#","").substring(0,6),manufacturer:A.manufacturer,material:typeof A.material=="string"?A.material:void 0}));const R=P.replace(/\+$/,"");if(R!==P){const A=a.filter(D=>C(D.manufacturer)&&D.material?.toLowerCase()===R);if(A.length>0)return A.map(D=>({name:D.color_name,hex:D.hex_color.replace("#","").substring(0,6),manufacturer:D.manufacturer,material:typeof D.material=="string"?D.material:void 0}))}}if(_){const k=a.filter(R=>C(R.manufacturer)&&(!R.material||R.material.toLowerCase().startsWith(_)));if(k.length>0)return k.map(R=>({name:R.color_name,hex:R.hex_color.replace("#","").substring(0,6),manufacturer:R.manufacturer,material:typeof R.material=="string"?R.material:void 0}))}return[]},[a,t.brand,t.material,t.subtype]),y=w.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const g=c.toLowerCase();return f.filter(N=>N.name.toLowerCase().includes(g)||(N.manufacturer?.toLowerCase().includes(g)??!1)||(N.material?.toLowerCase().includes(g)??!1))},[c,f]),v=f.length>0,b=w.useMemo(()=>c?DY.filter(g=>g.name.toLowerCase().includes(c.toLowerCase())):o?DY:qoe,[c,o]);return i.jsxs("div",{className:"space-y-3",children:[i.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${d}`}}),n.length>0&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[i.jsx(Jn,{className:"w-3 h-3"}),i.jsx("span",{children:s("inventory.recentColors")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(g=>i.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name},g.hex))})]}),i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:g=>u(g.target.value)})]}),v?i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.map(g=>i.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name})},`${g.hex}-${g.name}-${g.manufacturer??""}`)),y.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[i.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&i.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?i.jsxs(i.Fragment,{children:[s("inventory.showLess")," ",i.jsx($l,{className:"w-3 h-3"})]}):i.jsxs(i.Fragment,{children:[s("inventory.showAll")," ",i.jsx(On,{className:"w-3 h-3"})]})})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(g=>i.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:g.name})},g.hex)),b.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:g=>e("color_name",g.target.value)})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),i.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:d.toUpperCase(),onChange:g=>{const _=g.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),i.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${d}`,onChange:g=>{const _=g.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function Htt({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:a}){const{t:s}=Rt(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{const v=b=>{d.current&&!d.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(b=>b.weight===e);if(r){const b=t.find(g=>g.id===r);if(b&&b.weight===e)return}v.length===1?a(v[0].id):v.length===0&&r!==null&&a(null)},[e,t,r,a]);const p=w.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(v)||b.weight.toString().includes(v))},[t,c]),f=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),y=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(b=>b.id===r);if(v)return v.name}return f.length>0?f[0].name:""},[o,c,r,t,f]);return i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(Mge,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsxs("div",{className:"flex-1 min-w-0 relative",ref:d,children:[i.jsx("input",{ref:m,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:y,onFocus:()=>{l(!0),u("")},onChange:v=>{u(v.target.value),l(!0)}}),o&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:p.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>i.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{a(v.id),n(v.weight),l(!1),u("")},children:[i.jsx("span",{className:"truncate",children:v.name}),i.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),i.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[i.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:v=>{const b=parseInt(v.target.value);!isNaN(b)&&b>=0&&n(b)}}),i.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function $tt({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:a}=Rt(),{showToast:s}=fn(),[o,l]=w.useState(""),[c,u]=w.useState(!1),[d,m]=w.useState(""),[p,f]=w.useState(!1),y=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+y;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{p||m(String(y))},[p,y]),i.jsxs("div",{className:"space-y-4",children:[i.jsx(Htt,{catalog:n,value:t.core_weight,onChange:b=>e("core_weight",b),catalogId:t.core_weight_catalog_id,onCatalogIdChange:b=>e("core_weight_catalog_id",b)}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.currentWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:d,min:0,max:t.label_weight,onFocus:()=>f(!0),onChange:b=>{m(b.target.value)},onBlur:()=>{f(!1);const b=d.trim(),g=Number(b);if(!b||!Number.isFinite(g)||g<0||g>t.label_weight){m(String(y));return}const _=Math.round(g);e("weight_used",Math.max(0,t.label_weight-_)),m(String(_))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.measuredWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:o,min:0,onFocus:()=>u(!0),onChange:b=>{l(b.target.value)},onBlur:()=>{u(!1);const b=o.trim(),g=Number(b),_=t.core_weight,N=t.core_weight+t.label_weight;if(!b||!Number.isFinite(g)||g<_||g>N){s(a("inventory.measuredWeightError",{min:_,max:N}),"error"),l(String(v));return}const T=Math.round(g),C=Math.max(0,Math.min(t.label_weight,T-t.core_weight));e("weight_used",Math.max(0,t.label_weight-C)),l(String(T))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.costPerKg","Cost per kg")}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),i.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:b=>{const g=b.target.value===""?null:parseFloat(b.target.value);e("cost_per_kg",g)},style:{paddingLeft:`${Math.max(2,r.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.note")}),i.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:a("inventory.notePlaceholder"),value:t.note,onChange:b=>e("note",b.target.value)})]})]})}function qtt({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:a,setExpandedPrinters:s}){const{t:o}=Rt(),l=p=>{s(f=>{const y=new Set(f);return y.has(p)?y.delete(p):y.add(p),y})},c=(p,f,y)=>{const v=`${p}:${f}:${y??"null"}`,b=`${p}:${y??"null"}`;r(g=>{const _=new Set(g);if(_.has(v))_.delete(v);else{for(const N of Array.from(_)){const T=N.split(":");`${T[0]}:${T[2]}`===b&&_.delete(N)}_.add(v)}return _})},u=()=>{const p=new Set;for(const{printer:f,calibrations:y}of e){if(!f.connected)continue;const v=y.filter(g=>KD(g,t)),b=new Map;for(const g of v){const _=`${g.extruder_id??"null"}`;b.has(_)||b.set(_,[]),b.get(_).push(g)}for(const[g,_]of b)if(_.length>0){const T=[..._].sort((C,P)=>P.k_value-C.k_value)[0];p.add(`${f.id}:${T.cali_idx}:${g}`)}}r(p)};if(!t.material)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const d=e.reduce((p,{printer:f,calibrations:y})=>f.connected?p+y.filter(v=>KD(v,t)).length:p,0),m=(p,f)=>{const y=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=n.has(y);return i.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[i.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),i.jsx("div",{className:"flex items-center gap-2 shrink-0",children:i.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),d>0&&i.jsxs("button",{type:"button",onClick:u,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[i.jsx(ox,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",d,")"]})]}),i.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const y=a.has(String(p.id)),v=f.filter(T=>KD(T,t)),b=v.length,g=v.some(T=>T.extruder_id!==void 0&&T.extruder_id!==null&&T.extruder_id>0),_=v.filter(T=>T.extruder_id===1),N=v.filter(T=>T.extruder_id===0||T.extruder_id===void 0||T.extruder_id===null);return i.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{type:"button",onClick:()=>l(String(p.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[y?i.jsx(On,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(fa,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?i.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[b," ",o(b!==1?"inventory.matches":"inventory.match")]}):i.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),i.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),y&&i.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):g?i.jsxs(i.Fragment,{children:[_.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),i.jsx("div",{className:"space-y-2",children:_.map(T=>m(p,T))})]}),N.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),i.jsx("div",{className:"space-y-2",children:N.map(T=>m(p,T))})]})]}):i.jsx("div",{className:"space-y-2",children:v.map(T=>m(p,T))}):i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function Vtt(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const Gtt={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function Wtt({spoolId:t}){const{t:e}=Rt(),n=sn(),{showToast:r}=fn(),{data:a,isLoading:s}=tt({queryKey:["spool-usage",t],queryFn:()=>fe.getSpoolUsageHistory(t)}),o=ft({mutationFn:()=>fe.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?i.jsx("div",{className:"flex justify-center py-4",children:i.jsx(pt,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!a||a.length===0?i.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[i.jsx(Jn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),i.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[i.jsx(en,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:a.map(l=>i.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("span",{className:"text-bambu-gray",children:Vtt(l.created_at)}),l.print_name&&i.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[i.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),i.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),i.jsx("span",{className:Gtt[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function Ktt({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:a}){const{t:s}=Rt(),o=sn(),{showToast:l}=fn(),c=!!n,[u,d]=w.useState(jY),[m,p]=w.useState({}),[f,y]=w.useState("filament"),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[N,T]=w.useState(1),[C,P]=w.useState(!1),[k,R]=w.useState(!1),[A,D]=w.useState([]),[B,z]=w.useState(""),[W,I]=w.useState([]),[J,ie]=w.useState([]),[Q,ue]=w.useState([]),[me,pe]=w.useState([]),[Y,se]=w.useState([]),[oe,be]=w.useState(new Set),[Me,q]=w.useState(new Set),Z=r.length>0?r:Y,j=w.useMemo(()=>oe.size,[oe]);w.useEffect(()=>{pe(Itt())},[]),w.useEffect(()=>{t&&((async()=>{R(!0);try{const de=await fe.getCloudStatus();if(P(de.is_authenticated),de.is_authenticated){const ke=await fe.getFilamentPresets();D(ke)}}catch(de){console.error("Failed to fetch cloud presets:",de),P(!1)}finally{R(!1)}})(),fe.getSpoolCatalog().then(I).catch(console.error),fe.getColorCatalog().then(ue).catch(console.error),fe.getLocalPresets().then(de=>ie(de.filament)).catch(console.error),r.length===0&&(async()=>{try{const de=await fe.getPrinters(),ke=await Promise.all(de.map(Le=>fe.getPrinterStatus(Le.id).catch(()=>null))),_e=[];for(let Le=0;Le({cali_idx:je.slot_id,filament_id:je.filament_id,setting_id:je.setting_id||"",name:je.name,k_value:parseFloat(je.k_value)||0,n_coef:parseFloat(je.n_coef)||0,extruder_id:je.extruder_id,nozzle_diameter:je.nozzle_diameter}))}catch{}_e.push({printer:{...$e,connected:Ae},calibrations:Pe})}se(_e)}catch(de){console.error("Failed to fetch printer calibrations:",de)}})())},[t,r.length]);const E=w.useMemo(()=>Ltt(A,new Set,J),[A,J]),U=w.useMemo(()=>{const he=Rtt(A,J),de=Q.map(_e=>_e.manufacturer?.trim()).filter(_e=>!!_e),ke=new Set([...he,...de]);return Array.from(ke).sort((_e,Le)=>_e.localeCompare(Le))},[A,J,Q]),K=w.useMemo(()=>{const he=Q.map(ke=>ke.material?.trim()).filter(ke=>!!ke),de=new Set([...Ptt,...he]);return Array.from(de).sort((ke,_e)=>ke.localeCompare(_e))},[Q]),$=w.useMemo(()=>{const he=[];for(const de of Q){const ke=de.manufacturer?.trim(),_e=de.material?.trim();ke&&_e&&he.push({brand:ke,material:_e})}for(const de of A){const ke=Dx(de.name);ke.brand&&ke.material&&he.push({brand:ke.brand,material:ke.material})}for(const de of J){const ke=Dx(de.name),_e=de.filament_vendor?.trim()||ke.brand,Le=ke.material;_e&&Le&&he.push({brand:_e,material:Le})}return he},[A,Q,J]),ne=w.useMemo(()=>{const he=new Map;for(const de of $){const ke=de.brand.toLowerCase(),_e=de.material.toLowerCase();he.has(ke)||he.set(ke,new Set),he.get(ke).add(_e)}return he},[$]),O=w.useMemo(()=>{const he=new Map;for(const de of $){const ke=de.brand.toLowerCase(),_e=de.material.toLowerCase();he.has(_e)||he.set(_e,new Set),he.get(_e).add(ke)}return he},[$]),V=w.useMemo(()=>{if(!u.material)return U;const he=u.material.toLowerCase(),de=O.get(he);return!de||de.size===0?U:U.filter(ke=>de.has(ke.toLowerCase()))},[U,u.material,O]),ee=w.useMemo(()=>{if(!u.brand)return K;const he=u.brand.toLowerCase(),de=ne.get(he);return!de||de.size===0?K:K.filter(ke=>de.has(ke.toLowerCase()))},[K,u.brand,ne]),G=w.useMemo(()=>Ott(u.slicer_filament,E),[u.slicer_filament,E]);w.useEffect(()=>{if(t){if(n)if(d({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),z(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const he=new Set;for(const de of n.k_profiles)de.cali_idx!==null&&de.cali_idx!==void 0&&he.add(`${de.printer_id}:${de.cali_idx}:${de.extruder??"null"}`);be(he)}else be(new Set);else d(jY),z(""),be(new Set),_(!1),T(1);p({}),y("filament"),b(!1)}},[t,n]),w.useEffect(()=>{t&&Z.length>0&&q(new Set(Z.map(he=>String(he.printer.id))))},[t,Z]);const re=(he,de)=>{d(ke=>({...ke,[he]:de})),he==="weight_used"&&b(!0),m[he]&&p(ke=>({...ke,[he]:void 0}))},ce=he=>{pe(de=>ztt(he,de))},ge=ft({mutationFn:he=>fe.createSpool(he),onSuccess:async he=>{oe.size>0&&he?.id&&await F(he.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolCreated"),"success"),e()},onError:he=>{l(he.message,"error")}}),xe=ft({mutationFn:({data:he,qty:de})=>fe.bulkCreateSpools(he,de),onSuccess:async he=>{if(oe.size>0)for(const de of he)await F(de.id);await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolsCreated",{count:he.length}),"success"),e()},onError:he=>{l(he.message,"error")}}),ae=ft({mutationFn:he=>fe.updateSpool(n.id,he),onSuccess:async()=>{n?.id&&await F(n.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolUpdated"),"success"),e()},onError:he=>{l(he.message,"error")}}),L=ft({mutationFn:()=>fe.updateSpool(n.id,{tag_uid:null}),onSuccess:async()=>{await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.tagDeleted","Tag removed"),"success"),e()},onError:he=>{l(he.message,"error")}}),F=async he=>{if(oe.size===0){try{await fe.saveSpoolKProfiles(he,[])}catch{}return}const de=[];for(const ke of oe){const[_e,Le,$e]=ke.split(":"),Re=parseInt(_e),Ae=parseInt(Le),Pe=$e==="null"?0:parseInt($e),Ue=Z.find(je=>je.printer.id===Re);if(Ue){const je=Ue.calibrations.find(Xe=>Xe.cali_idx===Ae);je&&de.push({printer_id:Re,extruder:Pe,nozzle_diameter:je.nozzle_diameter||"0.4",k_value:je.k_value,name:je.name||null,cali_idx:je.cali_idx,setting_id:je.setting_id||null})}}if(de.length>0)try{await fe.saveSpoolKProfiles(he,de)}catch(ke){console.error("Failed to save K-profiles:",ke)}};if(w.useEffect(()=>{if(!t)return;const he=de=>{de.key==="Escape"&&e()};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[t,e]),!t)return null;const te=()=>{const he=Att(u,g);if(!he.isValid){p(he.errors),(he.errors.slicer_filament||he.errors.material||he.errors.brand||he.errors.subtype)&&y("filament");return}const de=G?.displayName||B||null,ke={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:de,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!c||v)&&(ke.weight_used=u.weight_used),c?ae.mutate(ke):N>1?xe.mutate({data:ke,qty:N}):ge.mutate(ke)},ve=ge.isPending||xe.isPending||ae.isPending||L.isPending;return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(c?"inventory.editSpool":"inventory.addSpool")}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),!c&&i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Mc,{className:"w-4 h-4 text-amber-400"}),i.jsx("span",{className:"text-sm text-white",children:s("inventory.quickAdd")})]}),i.jsx("button",{type:"button",onClick:()=>{_(!g),g||y("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${g?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${g?"translate-x-4":"translate-x-0.5"}`})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("button",{onClick:()=>y("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${f==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(yw,{className:"w-4 h-4"}),s("inventory.filamentInfoTab")]}),!g&&i.jsxs("button",{onClick:()=>y("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${f==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(yhe,{className:"w-4 h-4"}),s("inventory.paProfileTab"),j>0&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:j})]})]}),i.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:f==="filament"?i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.filamentInfo")}),i.jsx(Utt,{formData:u,updateField:re,cloudAuthenticated:C,loadingCloudPresets:k,presetInputValue:B,setPresetInputValue:z,selectedPresetOption:G,filamentOptions:E,availableBrands:V,availableMaterials:ee,quickAdd:g,quantity:N,onQuantityChange:T,errors:m})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.color")}),i.jsx(Btt,{formData:u,updateField:re,recentColors:me,onColorUsed:ce,catalogColors:Q})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.additional")}),i.jsx($tt,{formData:u,updateField:re,spoolCatalog:W,currencySymbol:a})]}),c&&n&&i.jsx("div",{children:i.jsx(Wtt,{spoolId:n.id})})]}):i.jsx(qtt,{formData:u,updateField:re,printersWithCalibrations:Z,selectedProfiles:oe,setSelectedProfiles:be,expandedPrinters:Me,setExpandedPrinters:q})}),i.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[c&&i.jsxs(Ie,{variant:"secondary",onClick:()=>L.mutate(),disabled:ve||!n?.tag_uid,className:"mr-auto",children:[i.jsx(Id,{className:"w-4 h-4"}),s("inventory.deleteTag","Delete Tag")]}),i.jsxs("div",{className:"flex gap-2 ml-auto",children:[i.jsx(Ie,{variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(Ie,{onClick:te,disabled:ve,children:ve?i.jsxs(i.Fragment,{children:[i.jsx(pt,{className:"w-4 h-4 animate-spin"}),s("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(ss,{className:"w-4 h-4"}),s(c?"common.save":"inventory.addSpool")]})})]})]})]})]})}function Ytt({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:a}){const{t:s}=Rt(),[o,l]=w.useState(n),[c,u]=w.useState(null),d=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(T=>({...T})))},[t,n]),w.useEffect(()=>{if(!t)return;const T=C=>{C.key==="Escape"&&e()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[t,e]),!t)return null;const m=T=>{l(C=>C.map((P,k)=>k===T?{...P,visible:!P.visible}:P))},p=(T,C)=>{C<0||C>=o.length||l(P=>{const k=[...P],[R]=k.splice(T,1);return k.splice(C,0,R),k})},f=(T,C)=>{d.current=C,u(C),T.dataTransfer.effectAllowed="move"},y=(T,C)=>{T.preventDefault(),T.dataTransfer.dropEffect="move";const P=d.current;P!==null&&P!==C&&(p(P,C),d.current=C,u(C))},v=T=>{T.preventDefault()},b=()=>{d.current=null,u(null)},g=()=>{l(r.map(T=>({...T})))},_=()=>{a(o),e()},N=o.filter(T=>T.visible).length;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsx(Pt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:T=>T.stopPropagation(),children:i.jsxs(Et,{className:"p-6 flex flex-col min-h-0",children:[i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),i.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),i.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),i.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((T,C)=>i.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===C?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${T.visible?"":"opacity-50"}`,draggable:!0,onDragStart:P=>f(P,C),onDragOver:P=>y(P,C),onDrop:v,onDragEnd:b,children:[i.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:i.jsx(Sh,{className:"w-4 h-4"})}),i.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:T.label}),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{onClick:()=>p(C,C-1),disabled:C===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:i.jsx($l,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>p(C,C+1),disabled:C===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:i.jsx(On,{className:"w-4 h-4"})})]}),i.jsx("button",{onClick:()=>m(C),className:`p-1.5 rounded transition-colors ${T.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:T.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:T.visible?i.jsx(Ac,{className:"w-4 h-4"}):i.jsx(fw,{className:"w-4 h-4"})})]},T.id))}),i.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs(Ie,{variant:"secondary",onClick:g,className:"mr-auto",children:[i.jsx(So,{className:"w-4 h-4"}),s("inventory.reset")]}),i.jsx(Ie,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),i.jsx(Ie,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}function RY(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.label_weight}`}const Goe="bambuddy-inventory-columns",SN=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function Xtt(){try{const t=localStorage.getItem(Goe);if(t){const e=JSON.parse(t),n=new Set(SN.map(o=>o.id)),r=new Set(e.map(o=>o.id)),a=e.filter(o=>n.has(o.id)),s=SN.filter(o=>!r.has(o.id));return[...a,...s]}}catch{}return SN.map(t=>({...t}))}function Qtt(t){try{localStorage.setItem(Goe,JSON.stringify(t))}catch{}}function du(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const Ztt={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function YD(t,e="system"){if(!t)return"-";const n=Zn(t);return n?N3(n,e):"-"}const Jtt={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},SL={id:({spool:t})=>i.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:YD(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:YD(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?YD(t.last_used,e):"Never"}),rgba:({spool:t})=>i.jsx("div",{className:"flex items-center justify-center",children:i.jsx("span",{className:"w-5 h-5 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:PI(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,a=n.ams_id===254||n.ams_id===255,s=!a&&n.ams_id>=128,o=EI(n.ams_id,n.tray_id,s,a);return i.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[r," ",o,n.ams_label?` (${n.ams_label})`:""]})},label_weight:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:du(t.label_weight)}),net:({remaining:t})=>i.jsx("span",{className:"text-sm text-white",children:du(t)}),gross:({spool:t,remaining:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:du(e+t.core_weight)}),added_full:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?du(t.weight_used):"-"}),printed_total:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?i.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return i.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const n=t.last_scale_weight;if(n==null)return i.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const r=t.core_weight||0,a=Math.max(0,t.label_weight-t.weight_used)+r;let s,o;n0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g +`+n+"}"}return String(t)}function Xet({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:a,hasPermission:s,t:o}){const{showToast:l}=fn(),c=sn(),[u,d]=w.useState(!1),{data:m,isLoading:p}=tt({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>fe.getCloudSettingDetail(t.setting_id)}),f=ft({mutationFn:()=>fe.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),y=uw(t.setting_id),v=C5(t.name,m?.setting?.inherits);return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:i.jsxs(Et,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),y&&i.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),i.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[i.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&i.jsxs(i.Fragment,{children:[i.jsx("span",{children:"•"}),i.jsx("span",{children:v.printer})]})]})]}),i.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?i.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:vL(m)}):i.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),u?i.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[i.jsx(Mn,{className:"w-5 h-5"}),i.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ie,{variant:"secondary",onClick:()=>d(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),i.jsxs(Ie,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):i.jsx(en,{className:"w-4 h-4"}),o("common.delete")]})]})]}):i.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ie,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),i.jsxs(Ie,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[i.jsx(vo,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),y&&i.jsxs(i.Fragment,{children:[i.jsxs(Ie,{variant:"secondary",onClick:a,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[i.jsx(Ki,{className:"w-4 h-4"}),o("common.edit")]}),i.jsx(Ie,{variant:"danger",onClick:()=>d(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:i.jsx(en,{className:"w-4 h-4"})})]})]})})]})})})}function zoe(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Uoe(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Qet({onClose:t,onApply:e,t:n}){const{showToast:r}=fn(),[a,s]=w.useState(zoe),[o,l]=w.useState("all"),[c,u]=w.useState(null),[d,m]=w.useState(""),[p,f]=w.useState(""),[y,v]=w.useState("{}"),[b,g]=w.useState(null),[_,N]=w.useState(null),T=o==="all"?a:a.filter(W=>W.type===o),C=W=>{s(W),Uoe(W)},P=W=>{const I=a.filter(J=>J.id!==W);C(I),N(null),r(n("profiles.templates.toast.deleted"))},k=W=>{u(W.id),m(W.name),f(W.description),v(JSON.stringify(W.settings,null,2)),g(null)},R=()=>{if(!(!c||!d.trim()))try{const W=JSON.parse(y),I=a.map(J=>J.id===c?{...J,name:d.trim(),description:p.trim(),settings:W}:J);C(I),u(null),r(n("profiles.templates.toast.updated"))}catch(W){g(W.message)}},A=()=>{u(null),m(""),f(""),v("{}"),g(null)},D=W=>{const I=a.map(J=>J.id===W?{...J,showInModal:!J.showInModal}:J);C(I)},B={filament:{label:n("profiles.presets.types.filament"),icon:QC,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:Od,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:_r,color:"text-purple-400"}},z=_?a.find(W=>W.id===_):null;return w.useEffect(()=>{const W=I=>{I.key==="Escape"&&(_?N(null):c?A():t())};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[_,c,t]),i.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[z&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:i.jsx(Pt,{className:"w-full max-w-md",children:i.jsxs(Et,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:i.jsx(Mn,{className:"w-6 h-6 text-red-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),i.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:z.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ie,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),i.jsxs(Ie,{onClick:()=>P(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[i.jsx(en,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),i.jsx(Pt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:i.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(ox,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(W=>i.jsx("button",{onClick:()=>l(W),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===W?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:W==="all"?n("common.all"):B[W].label},W))]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:T.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(ox,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:n("profiles.templates.noTemplates")}),i.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):i.jsx("div",{className:"space-y-2",children:T.map(W=>{const I=B[W.type],J=I.icon;return c===W.id?i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[i.jsx("input",{type:"text",value:d,onChange:ie=>m(ie.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx("input",{type:"text",value:p,onChange:ie=>f(ie.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),i.jsx("textarea",{value:y,onChange:ie=>{v(ie.target.value),g(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${b?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),b&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ie,{size:"sm",onClick:R,disabled:!d.trim(),children:[i.jsx(ss,{className:"w-4 h-4"}),"Save"]}),i.jsx(Ie,{size:"sm",variant:"secondary",onClick:A,children:"Cancel"})]})]},W.id):i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[i.jsx(J,{className:`w-5 h-5 ${I.color} flex-shrink-0`}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:W.name}),i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:W.description})]}),i.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(W.settings).length})}),i.jsx("button",{onClick:()=>D(W.id),className:`p-1 transition-colors ${W.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:W.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:W.showInModal?i.jsx(Ac,{className:"w-4 h-4"}):i.jsx(fw,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>e(W),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),i.jsx("button",{onClick:()=>k(W),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:i.jsx(Ki,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>N(W.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:i.jsx(en,{className:"w-4 h-4"})})]},W.id)})})})]})})]})}function Boe({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:a,t:s}){const[o,l]=w.useState("changes"),[c,u]=w.useState(""),d=w.useMemo(()=>{const y=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const b of y){if(b==="inherits"||b==="version")continue;const g=e[b],_=n[b],N=b in e,T=b in n;let C;!N&&T?C="added":N&&!T?C="removed":JSON.stringify(g)!==JSON.stringify(_)?C="changed":C="same",v.push({key:b,left:g,right:_,status:C})}return v.sort((b,g)=>{const _={changed:0,added:1,removed:2,same:3};return _[b.status]!==_[g.status]?_[b.status]-_[g.status]:b.key.localeCompare(g.key)})},[e,n]),m=w.useMemo(()=>{let y=[...d];if(o==="changes"&&(y=y.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();y=y.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return y},[d,o,c]),p=w.useMemo(()=>({added:d.filter(y=>y.status==="added").length,removed:d.filter(y=>y.status==="removed").length,changed:d.filter(y=>y.status==="changed").length,same:d.filter(y=>y.status==="same").length}),[d]),f=y=>{if(y===void 0)return"—";if(y===null)return"null";if(Array.isArray(y))return y.length===0?"[]":y.length===1?String(y[0]):y.join(", ");if(typeof y=="object")return JSON.stringify(y);const v=String(y);if(v.includes("\\n")||v.length>100){const b=v.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const y=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsx(Pt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:i.jsxs(Et,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Bb,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),i.jsx("p",{className:"text-white font-medium truncate",children:r})]}),i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),i.jsx("p",{className:"text-white font-medium truncate",children:a})]})]}),i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[i.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[i.jsx(ar,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(RN,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[i.jsx(g3,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[i.jsx($M,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:c,onChange:y=>u(y.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),p.same>0&&i.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),i.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx($M,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:i.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[i.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),i.jsx("th",{className:"text-left p-3 w-1/3",children:r}),i.jsx("th",{className:"text-left p-3 w-1/3",children:a})]})}),i.jsx("tbody",{children:m.map(y=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[y.status],b={added:i.jsx(ar,{className:"w-3.5 h-3.5 text-green-400"}),removed:i.jsx(RN,{className:"w-3.5 h-3.5 text-red-400"}),changed:i.jsx(g3,{className:"w-3.5 h-3.5 text-amber-400"}),same:i.jsx($M,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[y.status];return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[i.jsx("td",{className:"p-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[b,i.jsx("span",{className:"text-sm text-white font-mono",children:y.key})]})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${y.status==="removed"?"text-red-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.left)})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${y.status==="added"?"text-green-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.right)})})]},y.key)})})]})})]})})})}function Zet({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:a}=fn(),s=sn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[u,d]=w.useState(e?.type||"filament"),[m,p]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,y]=w.useState(e?.base_id||""),[v,b]=w.useState(""),[g,_]=w.useState(e?.setting||{inherits:""}),[N,T]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[C,P]=w.useState(null),[k,R]=w.useState(""),[A,D]=w.useState(!1),[B,z]=w.useState(""),[W,I]=w.useState(!1),[J,ie]=w.useState(zoe),[Q,ue]=w.useState(!1),[me,pe]=w.useState(""),[Y,se]=w.useState(""),[oe,be]=w.useState(!0),[Me,q]=w.useState(null),[Z,j]=w.useState(!1),E=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),U=w.useMemo(()=>E.filter(Pe=>uw(Pe.setting_id)),[E]),{data:K}=tt({queryKey:["cloudFields",u],queryFn:()=>fe.getCloudFields(u==="print"?"process":u),staleTime:1e3*60*60}),{data:$}=tt({queryKey:["allPresetDetails",u,U.map(Pe=>Pe.setting_id).join(",")],queryFn:async()=>{const Pe={};for(let je=0;je{try{const Ee=await fe.getCloudSettingDetail(Ge.setting_id);return{id:Ge.setting_id,detail:Ee}}catch{return null}}))).forEach(Ge=>{Ge&&(Pe[Ge.id]=Ge.detail)})}return Pe},enabled:U.length>0,staleTime:1e3*60*10}),{data:ne,isLoading:O}=tt({queryKey:["cloudSettingDetail",f],queryFn:()=>fe.getCloudSettingDetail(f),enabled:!!f});w.useEffect(()=>{l!=="json"&&T(JSON.stringify(g,null,2))},[g,l]);const V=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(Ue=>!uw(Ue.setting_id)).sort((Ue,je)=>Ue.name.localeCompare(je.name)),[n,u]);w.useEffect(()=>{if(!f)return;const Pe=V.find(Ue=>Ue.setting_id===f);Pe&&(b(Pe.name),o||(_({inherits:Pe.name}),T(JSON.stringify({inherits:Pe.name},null,2))))},[f,V,o]);const ee=w.useMemo(()=>{const Pe=K?.fields||[],Ue=new Set(Pe.map(Ge=>Ge.key)),je=new Set,Xe=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);$&&Object.values($).forEach(Ge=>{Ge?.setting&&Object.keys(Ge.setting).forEach(Ee=>{!Ue.has(Ee)&&!Xe.has(Ee)&&je.add(Ee)})}),Object.keys(g).forEach(Ge=>{!Ue.has(Ge)&&!Xe.has(Ge)&&je.add(Ge)});const ye=Array.from(je).sort().map(Ge=>({key:Ge,label:Ge.replace(/_/g," ").replace(/\b\w/g,Ee=>Ee.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Pe,...ye]},[K,$,g,r]),G=ee.filter(Pe=>Pe.label.toLowerCase().includes(k.toLowerCase())||Pe.key.toLowerCase().includes(k.toLowerCase())),re=()=>{if(B.trim()){const Pe=B.trim().toLowerCase().replace(/\s+/g,"_");ce(Pe,""),z(""),I(!1),a(r("profiles.presets.toast.fieldAdded",{key:Pe}))}},ce=(Pe,Ue)=>{_(je=>{const Xe={...je};return Ue===""||Ue===void 0?delete Xe[Pe]:Xe[Pe]=Ue,Xe})},ge=Pe=>{_(Ue=>({...Ue,...Pe.settings})),q(Pe.name),a(r("profiles.templates.toast.applied"))},xe=()=>{if(!me.trim())return;const Pe={...g};if(delete Pe.inherits,Object.keys(Pe).length===0){a(r("profiles.presets.noOverridesToSave"),"error");return}const Ue={id:Date.now().toString(),name:me.trim(),description:Y.trim()||r("profiles.presets.customTemplate"),type:u,settings:Pe,showInModal:oe},je=[...J,Ue];ie(je),Uoe(je),ue(!1),pe(""),se(""),be(!0),a(r("profiles.templates.toast.created"))},ae=w.useMemo(()=>J.filter(Pe=>Pe.type===u&&Pe.showInModal),[u,J]),L=Pe=>{T(Pe);try{const Ue=JSON.parse(Pe);_(Ue),P(null)}catch(Ue){P(Ue.message)}},F=Pe=>{Pe.preventDefault(),D(!1);const Ue=Pe.dataTransfer.files[0];if(Ue&&Ue.name.endsWith(".json")){const je=new FileReader;je.onload=Xe=>{try{const ye=Xe.target?.result,Ge=JSON.parse(ye),Ee=Ge.setting||Ge;_(Ke=>({...Ke,...Ee})),T(JSON.stringify({...g,...Ee},null,2)),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJsonFile"),"error")}},je.readAsText(Ue)}},te=ft({mutationFn:()=>{const Pe={...g},Ue=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";Pe[Ue]=`"${m}"`;const je={type:u,name:m,base_id:f,setting:Pe};return fe.createCloudSetting(je)},onSuccess:async()=>{a(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Pe=>a(Pe.message,"error")}),ve=ft({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return fe.updateCloudSetting(e.setting_id,{name:m,setting:g})},onSuccess:async()=>{a(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Pe=>a(Pe.message,"error")}),he=o?ve:te,de=ne?.setting?.inherits,ke=de?V.find(Pe=>Pe.name===de):void 0,{data:_e}=tt({queryKey:["cloudSettingDetail",ke?.setting_id],queryFn:()=>fe.getCloudSettingDetail(ke.setting_id),enabled:!!ke?.setting_id}),Le=w.useMemo(()=>{const Pe=_e?.setting||{},Ue=ne?.setting||{},je=f&&$?.[f]?.setting?$[f].setting:{};return{...Pe,...Ue,...je}},[f,ne,_e,$]),$e=Pe=>{if(Pe==null)return"";if(Array.isArray(Pe)){const Ue=[...new Set(Pe.map(je=>String(je)))];return Ue.length===1?Ue[0]:Pe.join(", ")}return String(Pe)},Re=Pe=>{const Ue=g[Pe.key],je=Le[Pe.key],Xe=$e(je),ye=O?r("common.loading"):Xe||"",Ge="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(Pe.type==="boolean"){const Ee=Ue==="1"||Ue===void 0&&je==="1";return i.jsx("button",{type:"button",onClick:()=>ce(Pe.key,Ue==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Ee?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Ee?"translate-x-3.5":"translate-x-0.5"}`})})}return Pe.type==="select"?i.jsxs("select",{value:Ue||"",onChange:Ee=>ce(Pe.key,Ee.target.value),className:Ge,children:[i.jsx("option",{value:"",children:ye}),Pe.options?.map(Ee=>i.jsx("option",{value:Ee.value,children:Ee.label},Ee.value))]}):i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:Pe.type==="number"?"number":"text",value:Ue!==void 0?String(Ue):"",onChange:Ee=>ce(Pe.key,Ee.target.value),step:Pe.step,min:Pe.min,max:Pe.max,placeholder:ye,className:Ge}),Pe.unit&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Pe.unit})]})},Ae=w.useMemo(()=>ne?.setting?ne.setting:{},[ne]);return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Pe=>{Pe.preventDefault(),D(!0)},onDragLeave:()=>D(!1),onDrop:F,children:[Z&&f&&i.jsx(Boe,{onClose:()=>j(!1),leftPreset:Ae,rightPreset:g,leftLabel:r("profiles.presets.baseLabel",{name:v||f}),rightLabel:r("profiles.presets.currentLabel",{name:m||r("profiles.presets.newPreset")}),t:r}),i.jsx(Pt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:i.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[f&&i.jsxs("button",{onClick:()=>j(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:r("profiles.presets.compareWithBase"),children:[i.jsx(Bb,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),i.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]})]}),A&&i.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(vi,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),i.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),i.jsxs("select",{value:u,onChange:Pe=>{d(Pe.target.value),y("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),i.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),i.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),i.jsxs("select",{value:f,onChange:Pe=>y(Pe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),V.map(Pe=>i.jsx("option",{value:Pe.setting_id,children:Pe.name},Pe.setting_id))]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),i.jsx("input",{type:"text",value:m,onChange:Pe=>p(Pe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("profiles.presets.myCustomPreset")})]})]}),v&&i.jsx("div",{className:"text-xs text-bambu-gray",children:i.jsxs("p",{className:"flex items-center gap-1",children:[i.jsx(Qr,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",i.jsx("span",{className:"text-white",children:v}),O&&i.jsx(pt,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[i.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(G8,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),i.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(eT,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),i.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(HX,{className:"w-4 h-4"}),"JSON",C&&i.jsx(Li,{className:"w-3 h-3 text-red-400"})]}),i.jsx("div",{className:"flex-1 max-[640px]:hidden"}),i.jsxs("button",{onClick:()=>{const Pe={name:m,type:u,base_id:f,setting:g},Ue=new Blob([JSON.stringify(Pe,null,2)],{type:"application/json"}),je=URL.createObjectURL(Ue),Xe=document.createElement("a");Xe.href=je,Xe.download=`${m||"preset"}.json`,document.body.appendChild(Xe),Xe.click(),document.body.removeChild(Xe),URL.revokeObjectURL(je),a(r("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.exportToJson"),children:[i.jsx(bi,{className:"w-4 h-4"}),r("common.download")]}),i.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.importFromJson"),children:[i.jsx(vi,{className:"w-4 h-4"}),r("common.upload")]}),i.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Pe=>{const Ue=Pe.target.files?.[0];if(Ue){const je=new FileReader;je.onload=Xe=>{try{const ye=JSON.parse(Xe.target?.result),Ge=ye.setting||ye;_(Ee=>({...Ee,...Ge})),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJson"),"error")}},je.readAsText(Ue)}}})]}),i.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(ox,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(g).filter(Pe=>Pe!=="inherits").length>0&&i.jsxs("button",{onClick:()=>ue(!Q),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[i.jsx(ss,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),Q&&i.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[i.jsx("input",{type:"text",value:me,onChange:Pe=>pe(Pe.target.value),placeholder:r("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx("input",{type:"text",value:Y,onChange:Pe=>se(Pe.target.value),placeholder:r("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ie,{size:"sm",onClick:xe,disabled:!me.trim(),children:[i.jsx(ss,{className:"w-3 h-3"}),r("common.save")]}),i.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>ue(!1),children:r("common.cancel")})]}),i.jsxs("button",{onClick:()=>be(!oe),className:`flex items-center gap-1.5 text-xs transition-colors ${oe?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[oe?i.jsx(Ac,{className:"w-3.5 h-3.5"}):i.jsx(fw,{className:"w-3.5 h-3.5"}),r(oe?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Me&&i.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[i.jsx(Qr,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",i.jsx("span",{className:"font-medium",children:Me})]}),i.jsx("button",{onClick:()=>q(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[ae.map(Pe=>i.jsxs("button",{onClick:()=>ge(Pe),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:Pe.name}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Pe.description})]},Pe.id)),ae.length===0&&i.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),i.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),i.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:ee.slice(0,10).map(Pe=>i.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[i.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Pe.label}),i.jsx("div",{className:"w-48 max-[640px]:w-full",children:Re(Pe)})]},Pe.key))})]}),Object.keys(g).length>1&&i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(g).filter(([Pe])=>Pe!=="inherits").map(([Pe,Ue])=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Pe,": ",String(Ue).slice(0,20),i.jsx("button",{onClick:()=>ce(Pe,void 0),className:"hover:text-white",children:i.jsx(Ht,{className:"w-3 h-3"})})]},Pe))})]})]}),l==="fields"&&i.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:$?r("profiles.templates.fieldsCount",{count:ee.length}):r("common.loading")})]}),i.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:k,onChange:Pe=>R(Pe.target.value),placeholder:r("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[G.filter(Pe=>!(Pe.key in g)).map(Pe=>{const Ue=Le[Pe.key],je=$e(Ue);return i.jsxs("div",{onClick:()=>{_(Xe=>({...Xe,[Pe.key]:je||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white truncate",children:Pe.label}),i.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Pe.key})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[je&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:je,children:[je.slice(0,20),je.length>20?"...":""]}),i.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:i.jsx(ar,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Pe.key)}),G.filter(Pe=>!(Pe.key in g)).length===0&&i.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(k?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:W?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:B,onChange:Pe=>z(Pe.target.value),onKeyDown:Pe=>Pe.key==="Enter"&&re(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx(Ie,{size:"sm",onClick:re,disabled:!B.trim(),children:i.jsx(ar,{className:"w-4 h-4"})}),i.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>{I(!1),z("")},children:i.jsx(Ht,{className:"w-4 h-4"})})]}):i.jsxs("button",{onClick:()=>I(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[i.jsx(ar,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(g).filter(Pe=>Pe!=="inherits").length})})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(g).filter(([Pe])=>Pe!=="inherits").map(([Pe,Ue])=>{const je=ee.find(Xe=>Xe.key===Pe);return i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium text-white",children:je?.label||Pe}),i.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Pe})]}),i.jsx("button",{onClick:()=>ce(Pe,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:i.jsx(Ht,{className:"w-4 h-4"})})]}),je?Re(je):i.jsx("input",{type:"text",value:String(Ue),onChange:Xe=>ce(Pe,Xe.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},Pe)}),Object.keys(g).filter(Pe=>Pe!=="inherits").length===0&&i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(G8,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),i.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),i.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(g).filter(Pe=>Pe!=="inherits").length>0&&i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:i.jsxs("button",{onClick:()=>{ue(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[i.jsx(ss,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&i.jsxs("div",{className:"space-y-2",children:[C&&i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(Li,{className:"w-4 h-4"}),C]}),i.jsx("textarea",{value:N,onChange:Pe=>L(Pe.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${C?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[i.jsx(Ie,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsxs(Ie,{onClick:()=>he.mutate(),disabled:he.isPending||!m.trim()||!o&&!f||!!C,className:"flex-1",children:[he.isPending?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):o?i.jsx(ss,{className:"w-4 h-4"}):i.jsx(ar,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function Jet({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:a,hasPermission:s,t:o}){const[l,c]=w.useState(""),[u,d]=w.useState("all"),[m,p]=w.useState("all"),[f,y]=w.useState("all"),[v,b]=w.useState("all"),[g,_]=w.useState("all"),[N,T]=w.useState("all"),[C,P]=w.useState(null),[k,R]=w.useState(!1),[A,D]=w.useState(!1),[B,z]=w.useState(null),[W,I]=w.useState(null),[J,ie]=w.useState(null),[Q,ue]=w.useState(!1),[me,pe]=w.useState([null,null]),[Y,se]=w.useState(!1),[oe,be]=w.useState(null),Me=sn(),q=w.useMemo(()=>[...t.filament.map(re=>({...re,type:"filament"})),...t.printer.map(re=>({...re,type:"printer"})),...t.process.map(re=>({...re,type:"process"}))].map(re=>({...re,meta:C5(re.name)})),[t]),Z=w.useMemo(()=>{const G=new Set,re=new Set,ce=new Set;return q.forEach(ge=>{ge.meta.nozzle&&G.add(ge.meta.nozzle),ge.meta.filamentType&&re.add(ge.meta.filamentType),ge.meta.layerHeight&&ce.add(ge.meta.layerHeight)}),{printers:a.map(ge=>({id:ge.id.toString(),name:ge.name})),nozzles:Array.from(G).sort((ge,xe)=>parseFloat(ge)-parseFloat(xe)),filaments:Array.from(re).sort(),layerHeights:Array.from(ce).sort((ge,xe)=>parseFloat(ge)-parseFloat(xe))}},[q,a]),j=w.useMemo(()=>f==="all"?null:a.find(re=>re.id.toString()===f)?.model||null,[f,a]),E=w.useMemo(()=>q.filter(G=>u==="all"||G.type===u).filter(G=>{if(m==="all")return!0;const re=uw(G.setting_id);return m==="custom"?re:!re}).filter(G=>{if(f==="all"||!j)return!0;const re=G.meta.printer?.toLowerCase()||"",ce=j.toLowerCase();return re.includes(ce)||ce.includes(re)}).filter(G=>v==="all"||G.meta.nozzle===v).filter(G=>g==="all"||G.meta.filamentType===g).filter(G=>N==="all"||G.meta.layerHeight===N).filter(G=>l===""||G.name.toLowerCase().includes(l.toLowerCase())).sort((G,re)=>G.name.localeCompare(re.name)),[q,u,m,f,j,v,g,N,l]),U=G=>{if(Q){const re=me[0]?.setting_id===G.setting_id,ce=me[1]?.setting_id===G.setting_id;if(re)pe([me[1],null]);else if(ce)pe([me[0],null]);else if(!me[0])pe([G,null]);else if(me[1]){if(me[0].type!==G.type)return;pe([me[0],G])}else{if(me[0].type!==G.type)return;pe([me[0],G])}}else P(G)},K=G=>{if(me[0]?.setting_id===G.setting_id)return 0;if(me[1]?.setting_id===G.setting_id)return 1},$=async G=>{try{const re=await fe.getCloudSettingDetail(G.setting_id),ce=G.type==="process"?"print":G.type;z({type:ce,name:G.name,base_id:re.base_id||"GFSA00",setting:re.setting||{}}),P(null)}catch(re){console.error("Failed to fetch preset details for duplication:",re)}},ne=async G=>{try{Me.removeQueries({queryKey:["cloudSettingDetail",G.setting_id]});const re=await fe.getCloudSettingDetail(G.setting_id),ce=G.type==="process"?"print":G.type;I({type:ce,name:G.name,base_id:re.base_id||"GFSA00",setting:re.setting||{},setting_id:G.setting_id}),P(null)}catch(re){console.error("Failed to fetch preset details for editing:",re)}},O=()=>{d("all"),p("all"),y("all"),b("all"),_("all"),T("all"),c("")},V=u!=="all"||m!=="all"||f!=="all"||v!=="all"||g!=="all"||N!=="all"||l!=="",ee=t.filament.length+t.printer.length+t.process.length;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-4 mb-6",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:l,onChange:G=>c(G.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[i.jsxs(Ie,{variant:Q?"primary":"secondary",onClick:()=>{Q?(ue(!1),pe([null,null])):ue(!0)},children:[i.jsx(Bb,{className:"w-4 h-4"}),o(Q?"common.cancel":"profiles.presets.compare")]}),i.jsxs(Ie,{variant:"secondary",onClick:()=>D(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[i.jsx(ox,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),i.jsxs(Ie,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[i.jsx(Sr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),i.jsxs(Ie,{onClick:()=>R(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[i.jsx(ar,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(JC,{className:"w-4 h-4 text-bambu-gray"}),i.jsx(_b,{label:o("profiles.cloudView.filters.type"),value:u,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:ee},{value:"filament",label:o("profiles.cloudView.filters.filament"),count:t.filament.length},{value:"printer",label:o("profiles.cloudView.filters.printer"),count:t.printer.length},{value:"process",label:o("profiles.cloudView.filters.process"),count:t.process.length}],onChange:G=>d(G)}),i.jsx(_b,{label:o("profiles.cloudView.filters.owner"),value:m,options:[{value:"all",label:o("profiles.cloudView.filters.all")},{value:"custom",label:o("profiles.cloudView.filters.myPresets")},{value:"builtin",label:o("profiles.cloudView.filters.builtIn")}],onChange:G=>p(G)}),Z.printers.length>0&&i.jsx(_b,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Z.printers.map(G=>({value:G.id,label:G.name}))],onChange:y}),Z.nozzles.length>0&&i.jsx(_b,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Z.nozzles.map(G=>({value:G,label:G}))],onChange:b}),Z.filaments.length>0&&(u==="all"||u==="filament")&&i.jsx(_b,{label:o("profiles.cloudView.filters.filament"),value:g,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Z.filaments.map(G=>({value:G,label:G}))],onChange:_}),Z.layerHeights.length>0&&(u==="all"||u==="process")&&i.jsx(_b,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Z.layerHeights.map(G=>({value:G,label:G}))],onChange:T}),V&&i.jsx("button",{onClick:O,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),Q&&i.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(Bb,{className:"w-5 h-5 text-blue-400"}),i.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),i.jsx("span",{className:"text-bambu-gray",children:me[0]?o("profiles.cloudView.selectAnotherPreset",{type:me[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${me[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:me[0]?me[0].name:o("profiles.cloudView.selectFirst")}),i.jsx(g3,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${me[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:me[1]?me[1].name:o("profiles.cloudView.selectSecond")})]}),me[0]&&me[1]&&i.jsxs(Ie,{size:"sm",onClick:async()=>{try{const[G,re]=await Promise.all([fe.getCloudSettingDetail(me[0].setting_id),fe.getCloudSettingDetail(me[1].setting_id)]);be([G.setting||{},re.setting||{}]),se(!0)}catch{}},children:[i.jsx(Bb,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),i.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(Jn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",w0(e.toISOString(),"system",o)]}),i.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:E.length,total:ee})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),i.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),E.length===0?i.jsxs("div",{className:"text-center py-16",children:[i.jsx(Vi,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),i.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),V&&i.jsx("button",{onClick:O,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(QC,{className:"w-4 h-4 text-amber-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(G=>G.type==="filament").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(G=>G.type==="filament").map(G=>i.jsx(qD,{setting:G,onClick:()=>U(G),onDuplicate:()=>$(G),compareMode:Q,isCompareSelected:K(G)!==void 0,compareIndex:K(G),compareDisabled:Q&&!!me[0]&&me[0].type!==G.type,t:o},G.setting_id)),E.filter(G=>G.type==="filament").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(Od,{className:"w-4 h-4 text-blue-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(G=>G.type==="process").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(G=>G.type==="process").map(G=>i.jsx(qD,{setting:G,onClick:()=>U(G),onDuplicate:()=>$(G),compareMode:Q,isCompareSelected:K(G)!==void 0,compareIndex:K(G),compareDisabled:Q&&!!me[0]&&me[0].type!==G.type,t:o},G.setting_id)),E.filter(G=>G.type==="process").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(_r,{className:"w-4 h-4 text-purple-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(G=>G.type==="printer").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(G=>G.type==="printer").map(G=>i.jsx(qD,{setting:G,onClick:()=>U(G),onDuplicate:()=>$(G),compareMode:Q,isCompareSelected:K(G)!==void 0,compareIndex:K(G),compareDisabled:Q&&!!me[0]&&me[0].type!==G.type,t:o},G.setting_id)),E.filter(G=>G.type==="printer").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),C&&i.jsx(Xet,{setting:C,onClose:()=>P(null),onDeleted:()=>P(null),onDuplicate:()=>$(C),onEdit:()=>ne(C),hasPermission:s,t:o}),(k||B||W||J)&&i.jsx(Zet,{onClose:()=>{R(!1),z(null),I(null),ie(null)},initialData:W||B||(J?{type:J.type,name:"",base_id:"",setting:J.setting}:void 0),allPresets:t,t:o}),A&&i.jsx(Qet,{onClose:()=>D(!1),onApply:G=>{ie({type:G.type,setting:G.settings}),D(!1)},t:o}),Y&&oe&&me[0]&&me[1]&&i.jsx(Boe,{onClose:()=>{se(!1),be(null)},leftPreset:oe[0],rightPreset:oe[1],leftLabel:me[0].name,rightLabel:me[1].name,t:o})]})}function ett(){const{t}=Rt(),e=sn(),{showToast:n}=fn(),{hasPermission:r}=Nr(),[a,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:u}=tt({queryKey:["cloudStatus"],queryFn:fe.getCloudStatus}),{data:d=[]}=tt({queryKey:["printers"],queryFn:fe.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:y}=tt({queryKey:["cloudSettings"],queryFn:()=>fe.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{y&&l(new Date(y))},[y]);const v=ft({mutationFn:fe.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return u?i.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:i.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"p-6 lg:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),i.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[i.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(Ox,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),i.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(Ix,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),i.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(gw,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),a==="cloud"&&i.jsxs(i.Fragment,{children:[c?.is_authenticated&&i.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",i.jsx("span",{className:"text-white",children:c.email})]})]}),i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[i.jsx(v3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?i.jsx(Jet,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:d,hasPermission:r,t}):i.jsxs("div",{className:"text-center py-16",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),i.jsx(Ie,{onClick:()=>f(),children:t("profiles.retry")})]}):i.jsx(Ket,{onSuccess:b,t})]}),a==="local"&&i.jsx(Wet,{}),a==="kprofiles"&&i.jsx($et,{}),i.jsx(Yet,{})]})}const Bv={Droplet:QC,Flame:Ip,Ruler:Tge,Sparkles:ox,Square:ql,Cable:BL,Wrench:kf,Calendar:Yr,Timer:yd,Cog:gpe,Fan:$X,Zap:Mc,Wind:nQ,Thermometer:sT,Layers:Vi,Box:na,Target:JX,RefreshCw:Sr,Settings:aT,Filter:JC,CircleDot:Qhe};function m0(t){return t&&Bv[t]||kf}function Nb(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const a=Math.round(t);return n?n("maintenance.days",{count:a}):`${a} days`}if(t<180){const a=Math.round(t/7);return a===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:a}):`${a} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const a=r/7;return a<12?`${a<2?a.toFixed(1):Math.round(a)}w`:`${Math.round(a/4)}mo`}}function VD(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function ttt(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),a=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),u=n.includes("H2S"),d=l||c||u,m=n.includes("P2S");switch(t){case"Lubricate Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||a?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":d?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":m?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return r?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":a?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":u?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":m?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||a?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return r||a?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":u?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return d?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}function ntt({item:t,onPerform:e,onToggle:n,hasPermission:r,t:a}){const s=m0(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const f=t.days_since_maintenance??0;return Math.max(0,Math.min(100,f/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),u=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",d=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",m=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",p=()=>{if(!t.enabled)return a("common.disabled");if(o==="days"){const f=t.days_until_due??0;return t.is_due?a("maintenance.overdueBy",{duration:Nb(Math.abs(f),"days",a)}):t.is_warning?a("maintenance.dueIn",{duration:Nb(f,"days",a)}):a("maintenance.timeLeft",{duration:Nb(f,"days",a)})}else return t.is_due?a("maintenance.overdueBy",{duration:Nb(Math.abs(t.hours_until_due),"hours",a)}):t.is_warning?a("maintenance.dueIn",{duration:Nb(t.hours_until_due,"hours",a)}):a("maintenance.timeLeft",{duration:Nb(t.hours_until_due,"hours",a)})};return i.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:i.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[i.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[i.jsx(s,{className:`w-5 h-5 ${u()}`}),t.enabled&&(t.is_due||t.is_warning)&&i.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&i.jsx("span",{title:a("maintenance.timeBasedInterval"),children:i.jsx(Yr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||ttt(t.maintenance_type_name,t.printer_model);return f?i.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:a("maintenance.viewDocumentation"),onClick:y=>y.stopPropagation(),children:i.jsx(ti,{className:"w-3.5 h-3.5"})}):null})()]}),i.jsx("div",{className:"mt-2 mb-1.5",children:i.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${d()}`,style:{width:`${c}%`}})})}),i.jsxs("div",{className:`text-xs flex items-center gap-1 ${u()}`,children:[t.is_due&&i.jsx(Mn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&i.jsx(Jn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&i.jsx(Qr,{className:"w-3 h-3"}),p()]})]}),i.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[i.jsx("span",{title:r("maintenance:update")?void 0:a("maintenance.noPermissionUpdate"),children:i.jsx(Bn,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!r("maintenance:update")})}),i.jsxs(Ie,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:a("maintenance.noPermissionPerform"),className:"!px-3",children:[i.jsx(So,{className:"w-3.5 h-3.5"}),a("common.reset")]})]})]})})}function rtt({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:a,t:s}){const[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,m]=w.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((v,b)=>v.is_due&&!b.is_due?-1:!v.is_due&&b.is_due?1:v.is_warning&&!b.is_warning?-1:!v.is_warning&&b.is_warning?1:v.maintenance_type_id-b.maintenance_type_id),f=p.find(v=>v.enabled&&(v.is_due||v.is_warning)),y=()=>{const v=parseFloat(d);!isNaN(v)&&v>=0&&(r(t.printer_id,v),u(!1))};return i.jsxs(Pt,{className:"overflow-hidden",children:[i.jsxs("div",{className:"p-5",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&i.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(Mn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&i.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(Jn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&i.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(Qr,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),i.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?i.jsx($l,{className:"w-4 h-4"}):i.jsx(On,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),i.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:i.jsx(yd,{className:"w-4 h-4 text-bambu-gray"})}),c?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",value:d,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&y(),v.key==="Escape"&&u(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),i.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),i.jsx(Ie,{size:"sm",onClick:y,children:s("common.save")}),i.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>u(!1),children:s("common.cancel")})]}):i.jsxs("button",{onClick:()=>{a("maintenance:update")&&(m(Math.round(t.total_print_hours).toString()),u(!0))},className:`group ${a("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:a("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[i.jsxs("div",{className:`text-sm font-medium text-white ${a("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),i.jsx(_f,{className:`w-3 h-3 text-bambu-gray ${a("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),i.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),i.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=m0(f.maintenance_type_icon);return i.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),i.jsxs("div",{children:[i.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),i.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&i.jsx(Et,{className:"pt-0 border-t border-bambu-dark-tertiary",children:i.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>i.jsx(ntt,{item:v,onPerform:e,onToggle:n,hasPermission:a,t:s},v.id))})})]})}function itt({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:a,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:u,hasPermission:d,t:m}){const[p,f]=w.useState(null),[y,v]=w.useState(""),[b,g]=w.useState("hours"),[_,N]=w.useState(!1),[T,C]=w.useState(""),[P,k]=w.useState("100"),[R,A]=w.useState("hours"),[D,B]=w.useState("Wrench"),[z,W]=w.useState(""),[I,J]=w.useState(new Set),[ie,Q]=w.useState(null),[ue,me]=w.useState(null),pe=w.useMemo(()=>t?t.map(L=>({id:L.printer_id,name:L.printer_name})):[],[t]),Y=L=>t?t.filter(F=>F.maintenance_items.some(te=>te.maintenance_type_id===L)).map(F=>({printerId:F.printer_id,printerName:F.printer_name,itemId:F.maintenance_items.find(te=>te.maintenance_type_id===L)?.id})):[],se=L=>{if(!t)return[];const F=new Set(Y(L).map(te=>te.printerId));return pe.filter(te=>!F.has(te.id))},[oe,be]=w.useState(null),[Me,q]=w.useState(""),[Z,j]=w.useState(""),[E,U]=w.useState("hours"),[K,$]=w.useState("Wrench"),[ne,O]=w.useState(""),V=L=>{be(L),q(L.name),j(L.default_interval_hours.toString()),U(L.interval_type||"hours"),$(L.icon||"Wrench"),O(L.wiki_url||"")},ee=()=>{oe&&Me.trim()&&parseFloat(Z)>0&&(a(oe.id,{name:Me.trim(),default_interval_hours:parseFloat(Z),interval_type:E,icon:K,wiki_url:ne.trim()||null}),be(null))},G=(L,F,te)=>{const ve=parseFloat(y);if(!isNaN(ve)&&ve>0){const he=Math.abs(ve-F)<.01?null:ve;n(L,{custom_interval_hours:he,custom_interval_type:b!==te?b:null})}f(null)},re=L=>{L.preventDefault(),T.trim()&&parseFloat(P)>0&&I.size>0&&(r({name:T.trim(),default_interval_hours:parseFloat(P),interval_type:R,icon:D,wiki_url:z.trim()||null},Array.from(I)),C(""),k("100"),A("hours"),W(""),J(new Set),N(!1))},ce=L=>{J(F=>{const te=new Set(F);return te.has(L)?te.delete(L):te.add(L),te})},ge=t?.map(L=>({printerId:L.printer_id,printerName:L.printer_name,items:L.maintenance_items.sort((F,te)=>F.maintenance_type_id-te.maintenance_type_id)})).sort((L,F)=>L.printerName.localeCompare(F.printerName))||[],xe=e.filter(L=>L.is_system),ae=e.filter(L=>!L.is_system);return i.jsxs("div",{className:"space-y-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ie,{variant:"secondary",onClick:o,disabled:!d("maintenance:delete")||l,title:d("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),i.jsxs(Ie,{onClick:()=>N(!_),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[i.jsx(ar,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),_&&i.jsx(Pt,{className:"mb-6",children:i.jsx(Et,{className:"py-4",children:i.jsxs("form",{onSubmit:re,children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"lg:col-span-2",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),i.jsx("input",{type:"text",value:T,onChange:L=>C(L.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.exampleName"),autoFocus:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),i.jsxs("select",{value:R,onChange:L=>{A(L.target.value),L.target.value==="days"?k("30"):k("100")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"hours",children:m("maintenance.printHours")}),i.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:R==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),i.jsx("input",{type:"number",value:P,onChange:L=>k(L.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),i.jsx("div",{className:"mt-4 flex items-end justify-between",children:i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),i.jsx("div",{className:"flex gap-1",children:Object.keys(Bv).map(L=>{const F=Bv[L];return i.jsx("button",{type:"button",onClick:()=>B(L),className:`p-2 rounded-lg transition-colors ${D===L?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:i.jsx(F,{className:"w-4 h-4"})},L)})})]})}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),i.jsx("input",{type:"url",value:z,onChange:L=>W(L.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:pe.map(L=>i.jsx("button",{type:"button",onClick:()=>ce(L.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${I.has(L.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:L.name},L.id))}),I.size===0&&i.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),i.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",onClick:()=>{N(!1),J(new Set)},children:m("common.cancel")}),i.jsx(Ie,{type:"submit",disabled:!T.trim()||I.size===0,children:m("maintenance.addType")})]})]})})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[xe.map(L=>{const F=m0(L.icon),te=L.interval_type||"hours";return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:i.jsx(F,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[te==="days"?i.jsx(Yr,{className:"w-3 h-3"}):i.jsx(yd,{className:"w-3 h-3"}),VD(L.default_interval_hours,te,m)]})]}),i.jsx("button",{onClick:()=>{d("maintenance:delete")&&me(L)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(en,{className:"w-4 h-4"})})]})},L.id)}),ae.map(L=>{const F=m0(L.icon),te=L.interval_type||"hours";if(oe?.id===L.id)return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx("input",{type:"text",value:Me,onChange:_e=>q(_e.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("common.name"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("select",{value:E,onChange:_e=>U(_e.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"hours",children:m("maintenance.printHours")}),i.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:Z,onChange:_e=>j(_e.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),i.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(Bv).map(_e=>{const Le=Bv[_e];return i.jsx("button",{type:"button",onClick:()=>$(_e),className:`p-1.5 rounded transition-colors ${K===_e?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:i.jsx(Le,{className:"w-3.5 h-3.5"})},_e)})}),i.jsx("input",{type:"url",value:ne,onChange:_e=>O(_e.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.documentationLink")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ie,{size:"sm",onClick:ee,disabled:!Me.trim(),children:m("common.save")}),i.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>be(null),children:m("common.cancel")})]})]})},L.id);const he=Y(L.id),de=se(L.id),ke=ie===L.id;return i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:i.jsx(F,{className:"w-5 h-5 text-bambu-green"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:m("maintenance.custom")})]}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[te==="days"?i.jsx(Yr,{className:"w-3 h-3"}):i.jsx(yd,{className:"w-3 h-3"}),VD(L.default_interval_hours,te,m)]})]}),i.jsxs("button",{onClick:()=>Q(ke?null:L.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${he.length>0?"border-bambu-green/50 bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20":"border-orange-400/50 bg-orange-400/10 text-orange-400 hover:bg-orange-400/20"}`,title:m("maintenance.printersAssignedClick",{count:he.length}),children:[i.jsx(_r,{className:"w-3 h-3"}),i.jsx("span",{className:"text-xs font-medium",children:he.length}),i.jsx(On,{className:`w-3 h-3 transition-transform ${ke?"rotate-180":""}`})]}),i.jsx("button",{onClick:()=>V(L),disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:m("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${d("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(_f,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:L.name}))&&s(L.id)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(en,{className:"w-4 h-4"})})]}),ke&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),he.length===0?i.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):i.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:he.map(_e=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[_e.printerName,i.jsx("button",{onClick:()=>_e.itemId&&u(_e.itemId),disabled:!d("maintenance:delete"),title:d("maintenance:delete")?m("maintenance.removeFromPrinter"):m("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${d("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},_e.printerId))}),de.length>0&&i.jsxs("div",{className:"flex flex-wrap gap-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),de.map(_e=>i.jsxs("button",{onClick:()=>c(_e.id,L.id),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:m("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${d("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",_e.name]},_e.id))]})]})]},L.id)})]})]}),ge.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"mb-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),i.jsx("div",{className:"space-y-4",children:ge.map(L=>i.jsx(Pt,{children:i.jsxs(Et,{className:"py-4",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:L.printerName}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:L.items.map(F=>{const te=m0(F.maintenance_type_icon),ve=e.find(Le=>Le.id===F.maintenance_type_id),he=ve?.default_interval_hours||F.interval_hours,de=ve?.interval_type||"hours",ke=F.interval_type||"hours",_e=p===F.id;return i.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[i.jsx(te,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:F.maintenance_type_name}),_e?i.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?i.jsx(Yr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):i.jsx(yd,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),i.jsxs("select",{value:b,onChange:Le=>g(Le.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[i.jsx("option",{value:"hours",children:m("maintenance.printHours")}),i.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:y,onChange:Le=>v(Le.target.value),onKeyDown:Le=>{Le.key==="Enter"&&G(F.id,he,de),Le.key==="Escape"&&f(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),i.jsx(Ie,{size:"sm",onClick:()=>G(F.id,he,de),children:"OK"})]}):i.jsxs("button",{onClick:()=>{d("maintenance:update")&&(f(F.id),v(F.interval_hours.toString()),g(ke))},disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:m("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${d("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[ke==="days"?i.jsx(Yr,{className:"w-3 h-3"}):i.jsx(yd,{className:"w-3 h-3"}),VD(F.interval_hours,ke,m),i.jsx(_f,{className:"w-3 h-3 text-bambu-gray"})]})]},F.id)})})]})},L.printerId))})]}),ge.length===0&&i.jsx(Pt,{children:i.jsxs(Et,{className:"text-center py-12",children:[i.jsx(Jn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),ue&&i.jsx(_n,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:ue.name}),confirmText:m("common.delete"),cancelText:m("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(ue.id),me(null)},onCancel:()=>me(null)})]})}function att(){const{t}=Rt(),e=sn(),{showToast:n}=fn(),{hasPermission:r}=Nr(),[a,s]=w.useState("status"),{data:o,isLoading:l}=tt({queryKey:["maintenanceOverview"],queryFn:fe.getMaintenanceOverview}),{data:c}=tt({queryKey:["maintenanceTypes"],queryFn:fe.getMaintenanceTypes}),u=ft({mutationFn:({id:P,notes:k})=>fe.performMaintenance(P,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:P=>{n(P.message,"error")}}),d=ft({mutationFn:({id:P,data:k})=>fe.updateMaintenanceItem(P,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:P=>{n(P.message,"error")}}),m=ft({mutationFn:({id:P,data:k})=>fe.updateMaintenanceType(P,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:P=>{n(P.message,"error")}}),p=ft({mutationFn:fe.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:P=>{n(P.message,"error")}}),f=ft({mutationFn:fe.restoreDefaultMaintenanceTypes,onSuccess:P=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:P.restored}))},onError:P=>{n(P.message,"error")}}),y=ft({mutationFn:({printerId:P,hours:k})=>fe.setPrinterHours(P,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:P=>{n(P.message,"error")}}),v=ft({mutationFn:({printerId:P,typeId:k})=>fe.assignMaintenanceType(P,k),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:P=>{n(P.message,"error")}}),b=ft({mutationFn:fe.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:P=>{n(P.message,"error")}}),g=P=>{u.mutate({id:P})},_=(P,k)=>{d.mutate({id:P,data:{enabled:k}})},N=(P,k)=>{y.mutate({printerId:P,hours:k})};if(l)return i.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:i.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})});const T=o?.reduce((P,k)=>P+k.due_count,0)||0,C=o?.reduce((P,k)=>P+k.warning_count,0)||0;return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),i.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:a==="status"?i.jsxs(i.Fragment,{children:[T>0&&i.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:T})}),T>0&&C>0&&" · ",C>0&&i.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:C})}),T===0&&C===0&&i.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),i.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),i.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),a==="status"?i.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((P,k)=>{const R=P.due_count*10+P.warning_count,A=k.due_count*10+k.warning_count;return R!==A?A-R:P.printer_name.localeCompare(k.printer_name)}).map(P=>i.jsx(rtt,{overview:P,onPerform:g,onToggle:_,onSetHours:N,hasPermission:r,t},P.printer_id)):i.jsx(Pt,{children:i.jsxs(Et,{className:"text-center py-16",children:[i.jsx(kf,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),i.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):i.jsx(itt,{overview:o,types:c||[],onUpdateInterval:(P,k)=>d.mutate({id:P,data:k}),onAddType:async(P,k)=>{const R=await fe.createMaintenanceType(P);for(const A of k)await fe.assignMaintenanceType(A,R.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(P,k)=>m.mutate({id:P,data:k}),onDeleteType:P=>p.mutate(P),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(P,k)=>v.mutate({printerId:P,typeId:k}),onRemoveItem:P=>b.mutate(P),hasPermission:r,t})]})}const PY=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Hoe({project:t,onClose:e,onSave:n,isLoading:r,currencySymbol:a,t:s}){const[o,l]=w.useState(t?.name||""),[c,u]=w.useState(t?.description||""),[d,m]=w.useState(t?.color||PY[0]),[p,f]=w.useState(t?.target_count?.toString()||""),[y,v]=w.useState(t?.target_parts_count?.toString()||""),[b,g]=w.useState(t?.status||"active"),[_,N]=w.useState(t?.tags||""),[T,C]=w.useState(t?.due_date?.split("T")[0]||""),[P,k]=w.useState(t?.priority||"normal"),[R,A]=w.useState(t?.budget?.toString()||""),D=B=>{B.preventDefault(),n({name:o.trim(),description:c.trim()||void 0,color:d,target_count:p?parseInt(p,10):void 0,target_parts_count:y?parseInt(y,10):void 0,tags:_.trim()||void 0,due_date:T||void 0,priority:P,budget:R.trim()?parseFloat(R):null,...t&&{status:b}})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),i.jsxs("form",{onSubmit:D,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),i.jsx("input",{type:"text",value:o,onChange:B=>l(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.namePlaceholder"),required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),i.jsx("textarea",{value:c,onChange:B=>u(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:s("projects.descriptionPlaceholder"),rows:2})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),i.jsx("div",{className:"flex gap-2 flex-wrap",children:PY.map(B=>i.jsx("button",{type:"button",onClick:()=>m(B),className:`w-8 h-8 rounded-full transition-transform ${d===B?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:B}},B))})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),i.jsx("input",{type:"number",value:p,onChange:B=>f(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPlatesPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),i.jsx("input",{type:"number",value:y,onChange:B=>v(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPartsPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),i.jsx("input",{type:"text",value:_,onChange:B=>N(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.tagsPlaceholder")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),i.jsx("input",{type:"date",value:T,onChange:B=>C(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),i.jsxs("select",{value:P,onChange:B=>k(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"low",children:s("projects.priorityLow")}),i.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),i.jsx("option",{value:"high",children:s("projects.priorityHigh")}),i.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),i.jsxs("div",{className:"relative",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:a}),i.jsx("input",{type:"number",step:"0.01",min:"0",value:R,onChange:B=>A(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded pl-8 pr-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"0.00"})]})]}),t&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),i.jsxs("select",{value:b,onChange:B=>g(B.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"active",children:s("projects.statusActive")}),i.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),i.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(Ie,{type:"submit",disabled:!o.trim()||r,children:r?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function stt({project:t,onClick:e,onEdit:n,onDelete:r,hasPermission:a,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",u=t.status==="archived",[d,m]=w.useState(!1),f=c?{icon:su,color:"text-bambu-green",bg:"bg-bambu-green/10"}:u?{icon:$s,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Jn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:Ss,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return i.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[i.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),i.jsxs("div",{className:"p-5 pl-6",children:[i.jsxs("div",{className:"flex items-start justify-between mb-4",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:i.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?i.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?i.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?i.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&i.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),u&&i.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const y=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(Boolean),v=[...new Set(y)],b=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),g=[...new Set(b)];return v.length===0&&g.length===0?null:i.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>i.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),g.length>0&&i.jsxs("div",{className:"flex items-center gap-0.5",children:[g.slice(0,5).map(_=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),g.length>5&&i.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",g.length-5]})]})]})})()]})]}),i.jsxs("div",{className:"relative",onClick:y=>y.stopPropagation(),children:[i.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>m(!d),children:i.jsx(yh,{className:"w-4 h-4"})}),d&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),i.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:update")&&(n(),m(!1))},disabled:!a("projects:update"),title:a("projects:update")?void 0:s("projects.noEditPermission"),children:[i.jsx(_f,{className:"w-4 h-4"}),s("common.edit")]}),i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:delete")&&(r(),m(!1))},disabled:!a("projects:delete"),title:a("projects:delete")?void 0:s("projects.noDeletePermission"),children:[i.jsx(en,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),i.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?i.jsxs("div",{className:"space-y-3",children:[t.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),i.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),i.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&i.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?i.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx($s,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[i.jsx(Mn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[i.jsx(Jn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):i.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&i.jsxs("div",{className:"mb-4",children:[i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(y=>i.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:y.print_name||"Unknown",children:[y.thumbnail_path?i.jsx("img",{src:fe.getArchiveThumbnail(y.id),alt:y.print_name||"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:i.jsx(Gi,{className:"w-6 h-6"})}),y.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:i.jsx(Mn,{className:"w-4 h-4 text-white"})})]},y.id))}),t.archive_count>4&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),i.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[i.jsx(Vi,{className:"w-3.5 h-3.5 text-blue-400"}),i.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[i.jsx(Gi,{className:"w-3.5 h-3.5 text-bambu-green"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[i.jsx(Mn,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[i.jsx(y3,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.queue_count})]})]}),i.jsx(fa,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function ott(){const{t}=Rt(),e=al(),n=sn(),{showToast:r}=fn(),{hasPermission:a}=Nr(),[s,o]=w.useState(!1),[l,c]=w.useState(),[u,d]=w.useState("active"),[m,p]=w.useState(null),{data:f}=tt({queryKey:["settings"],queryFn:fe.getSettings}),y=Go(f?.currency||"USD"),{data:v,isLoading:b}=tt({queryKey:["projects",u==="all"?void 0:u],queryFn:()=>fe.getProjects(u==="all"?void 0:u)}),g=ft({mutationFn:J=>fe.createProject(J),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:J=>{r(J.message,"error")}}),_=ft({mutationFn:({id:J,data:ie})=>fe.updateProject(J,ie),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:J=>{r(J.message,"error")}}),N=ft({mutationFn:J=>fe.deleteProject(J),onSuccess:()=>{p(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:J=>{p(null),r(J.message,"error")}}),T=ft({mutationFn:J=>fe.importProject(J),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:J=>{r(J.message,"error")}}),C=w.useRef(null),P=async()=>{try{const J=await fe.getProjects(),ie=await Promise.all(J.map(async pe=>await fe.exportProjectJson(pe.id))),Q=new Blob([JSON.stringify(ie,null,2)],{type:"application/json"}),ue=URL.createObjectURL(Q),me=document.createElement("a");me.href=ue,me.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,me.click(),URL.revokeObjectURL(ue),r(t("projects.toast.exported"),"success")}catch(J){r(J.message,"error")}},k=()=>{C.current?.click()},R=async J=>{const ie=J.target.files?.[0];if(ie){try{if(ie.name.toLowerCase().endsWith(".zip"))await fe.importProjectFile(ie),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const ue=await ie.text(),me=JSON.parse(ue),pe=Array.isArray(me)?me:[me];for(const Y of pe)await T.mutateAsync(Y);pe.length>1&&r(t("projects.toast.multipleImported",{count:pe.length}),"success")}}catch(Q){r(`${t("projects.toast.importFailed")}: ${Q.message}`,"error")}J.target.value=""}},A=J=>{l?_.mutate({id:l.id,data:J}):g.mutate(J)},D=J=>{c(J),o(!0)},B=J=>{e(`/projects/${J.id}`)},z=J=>{p(J)},W=()=>{m!==null&&N.mutate(m)},I=v?.reduce((J,ie)=>(J[ie.status]=(J[ie.status]||0)+1,J.all=(J.all||0)+1,J),{})||{};return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsx("input",{ref:C,type:"file",accept:".json,.zip",onChange:R,className:"hidden"}),i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(Ss,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ie,{variant:"secondary",onClick:k,disabled:!a("projects:create"),title:a("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[i.jsx(vi,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),i.jsxs(Ie,{variant:"secondary",onClick:P,disabled:!a("projects:read"),title:a("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[i.jsx(bi,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),i.jsxs(Ie,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(ar,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),i.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Jn},{key:"completed",label:t("projects.statusCompleted"),icon:su},{key:"archived",label:t("projects.statusArchived"),icon:$s},{key:"all",label:t("common.all"),icon:Ss}].map(({key:J,label:ie,icon:Q})=>i.jsxs("button",{onClick:()=>d(J),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===J?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Q,{className:"w-4 h-4"}),i.jsx("span",{children:ie}),I[J]>0&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===J?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:I[J]})]},J))}),b?i.jsx("div",{className:"flex items-center justify-center py-20",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(Ss,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:u==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:u})}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:u==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:u})}),u==="all"&&i.jsxs(Ie,{onClick:()=>o(!0),disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(ar,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(J=>i.jsx(stt,{project:J,onClick:()=>B(J),onEdit:()=>D(J),onDelete:()=>z(J.id),hasPermission:a,t},J.id))}),m!==null&&i.jsx(_n,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:W,onCancel:()=>p(null)}),s&&i.jsx(Hoe,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:A,isLoading:g.isPending||_.isPending,currencySymbol:y,t})]})}function ltt(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function ctt({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,a={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return i.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:a[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function MY({icon:t,label:e,value:n,subValue:r,hint:a,color:s="text-bambu-gray"}){return i.jsx(Pt,{children:i.jsx(Et,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",title:a,children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function utt({archives:t,t:e}){return t.length===0?i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(Gi,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),i.jsx("p",{children:e("projectDetail.noPrints")})]}):i.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(n=>i.jsxs(co,{to:`/archives?search=${encodeURIComponent(n.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[n.thumbnail_path?i.jsx("img",{src:fe.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:i.jsx(Gi,{className:"w-8 h-8"})}),n.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:i.jsx(qi,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&i.jsx("div",{className:"absolute top-1 right-1",children:i.jsx(fr,{className:"w-4 h-4 text-bambu-green"})}),i.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function dtt({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:r,label:a}=n[t]||n.normal;return i.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&i.jsx(Mn,{className:"w-3 h-3"}),a]})}function GD(t,e){if(!t)return null;const n=Zn(t);if(!n)return null;const r=new Date,a=Math.ceil((n.getTime()-r.getTime())/(1e3*60*60*24));return a<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:a===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:a<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:a})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:a})}}function mtt(){const{id:t}=hw(),e=al(),{t:n}=Rt(),r=sn(),{showToast:a}=fn(),{hasPermission:s}=Nr(),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,m]=w.useState(""),p=parseInt(t||"0",10),{data:f,isLoading:y,error:v}=tt({queryKey:["project",p],queryFn:()=>fe.getProject(p),enabled:p>0}),{data:b,isLoading:g}=tt({queryKey:["project-archives",p],queryFn:()=>fe.getProjectArchives(p),enabled:p>0}),{data:_,isLoading:N}=tt({queryKey:["project-bom",p],queryFn:()=>fe.getProjectBOM(p),enabled:p>0}),{data:T,isLoading:C}=tt({queryKey:["project-timeline",p],queryFn:()=>fe.getProjectTimeline(p,20),enabled:p>0}),{data:P}=tt({queryKey:["settings"],queryFn:fe.getSettings}),{data:k}=tt({queryKey:["project-folders",p],queryFn:()=>fe.getLibraryFoldersByProject(p),enabled:p>0}),R=Go(P?.currency||"USD"),A=P?.time_format||"system",D=ft({mutationFn:je=>fe.updateProject(p,je),onSuccess:()=>{r.invalidateQueries({queryKey:["project",p]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),a(n("projectDetail.toast.projectUpdated"),"success")},onError:je=>{a(je.message,"error")}}),B=()=>{m(f?.notes||""),u(!0)},z=()=>{D.mutate({notes:d})},W=()=>{u(!1),m("")},[I,J]=w.useState(""),[ie,Q]=w.useState(1),[ue,me]=w.useState(""),[pe,Y]=w.useState(""),[se,oe]=w.useState(""),[be,Me]=w.useState(!1),[q,Z]=w.useState(!1),[j,E]=w.useState(null),[U,K]=w.useState(""),[$,ne]=w.useState(1),[O,V]=w.useState(""),[ee,G]=w.useState(""),[re,ce]=w.useState(""),[ge,xe]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),ae=ft({mutationFn:je=>fe.createBOMItem(p,je),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),J(""),Q(1),me(""),Y(""),oe(""),Me(!1),a(n("projectDetail.toast.partAdded"),"success")},onError:je=>a(je.message,"error")}),L=ft({mutationFn:({itemId:je,data:Xe})=>fe.updateBOMItem(p,je,Xe),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),E(null)},onError:je=>a(je.message,"error")}),F=ft({mutationFn:je=>fe.deleteBOMItem(p,je),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),a(n("projectDetail.toast.partRemoved"),"success")},onError:je=>a(je.message,"error")}),te=je=>{je.preventDefault(),I.trim()&&ae.mutate({name:I.trim(),quantity_needed:ie,unit_price:ue?parseFloat(ue):void 0,sourcing_url:pe.trim()||void 0,remarks:se.trim()||void 0})},ve=je=>{const Xe=je.is_complete?0:je.quantity_needed;L.mutate({itemId:je.id,data:{quantity_acquired:Xe}})},he=(je,Xe)=>{xe({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Xe}),onConfirm:()=>{xe(ye=>({...ye,isOpen:!1})),F.mutate(je)}})},de=je=>{E(je),K(je.name),ne(je.quantity_needed),V(je.unit_price?.toString()||""),G(je.sourcing_url||""),ce(je.remarks||"")},ke=je=>{je.preventDefault(),!(!j||!U.trim())&&L.mutate({itemId:j.id,data:{name:U.trim(),quantity_needed:$,unit_price:O?parseFloat(O):void 0,sourcing_url:ee.trim()||void 0,remarks:re.trim()||void 0}})},_e=()=>{E(null)},Le=async()=>{try{const{blob:je,filename:Xe}=await fe.exportProjectZip(Number(p)),ye=URL.createObjectURL(je),Ge=document.createElement("a");Ge.href=ye,Ge.download=Xe||`${f?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,Ge.click(),URL.revokeObjectURL(ye),a(n("projectDetail.toast.projectExported"),"success")}catch(je){a(je.message,"error")}},$e=ft({mutationFn:()=>fe.createTemplateFromProject(p),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),a(n("projectDetail.toast.templateCreated"),"success")},onError:je=>a(je.message,"error")}),Re=je=>Tf(je,A,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(y)return i.jsx("div",{className:"flex items-center justify-center py-24",children:i.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!f)return i.jsxs("div",{className:"text-center py-24",children:[i.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),i.jsx(Ie,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const Ae=f.stats,Pe=Ae?.progress_percent??0,Ue=Ae?.parts_progress_percent??0;return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(co,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),i.jsx(fa,{className:"w-4 h-4"}),i.jsx("span",{className:"text-white",children:f.name})]}),i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:i.jsx(IX,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:f.color||"#6b7280"}}),i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:f.name}),f.description&&i.jsx("p",{className:"text-bambu-gray mt-1",children:f.description})]})]}),i.jsx(ctt,{status:f.status,t:n})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ie,{variant:"secondary",onClick:Le,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[i.jsx(bi,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),i.jsxs(Ie,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[i.jsx(_f,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(f.target_count||f.target_parts_count)&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4 space-y-4",children:[f.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[Ae?.total_archives||0," / ",f.target_count," ",n("projectDetail.progress.printJobs")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Pe,100)}%`,backgroundColor:Pe>=100?"#22c55e":f.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Pe.toFixed(0)})}),Ae?.remaining_prints!=null&&Ae.remaining_prints>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Ae.remaining_prints})})]})]}),f.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[Ae?.completed_prints||0," / ",f.target_parts_count," ",n("projectDetail.progress.parts")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ue,100)}%`,backgroundColor:Ue>=100?"#22c55e":f.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Ue.toFixed(0)})}),Ae?.remaining_parts!=null&&Ae.remaining_parts>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Ae.remaining_parts})})]})]})]})}),Ae&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(Pt,{children:i.jsx(Et,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:i.jsx(Gi,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),i.jsxs("p",{className:"text-xl font-semibold text-white",children:[Ae.total_archives," ",i.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),Ae.failed_prints>0&&i.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:Ae.failed_prints})}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:Ae.completed_prints})})]})]})})}),i.jsx(MY,{icon:Jn,label:n("projectDetail.stats.printTime"),value:rxe(Ae.total_print_time_hours),color:"text-yellow-400"}),i.jsx(MY,{icon:_r,label:n("projectDetail.stats.filamentUsed"),value:ltt(Ae.total_filament_grams),color:"text-purple-400"})]}),Ae&&(()=>{const je=Ae.estimated_cost+Ae.total_energy_cost+Ae.bom_cost;return Ae.estimated_cost>0||je>0||f.budget!==null})()&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[R,Ae.estimated_cost.toFixed(2)]})]}),Ae.total_energy_kwh>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[Ae.total_energy_kwh.toFixed(3)," kWh",Ae.total_energy_cost>0&&i.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",R,Ae.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const je=Ae.estimated_cost+Ae.total_energy_cost+Ae.bom_cost;return je<=0?null:i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),i.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[R,je.toFixed(2)]}),Ae.bom_cost>0&&i.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),f.budget!==null&&(()=>{const je=Ae.estimated_cost+Ae.total_energy_cost+Ae.bom_cost,Xe=f.budget-je;return i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",i.jsxs("span",{className:"text-white font-semibold",children:[R,f.budget.toFixed(2)]})]}),i.jsxs("p",{className:`text-sm ${Xe>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",i.jsxs("span",{className:"font-semibold",children:[R,Xe.toFixed(2)]})]})]})})()]})]})}),f.children&&f.children.length>0&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[i.jsx(Zpe,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:f.children.length})]}),i.jsx("div",{className:"space-y-2",children:f.children.map(je=>i.jsxs(co,{to:`/projects/${je.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:je.color||"#6b7280"}}),i.jsx("span",{className:"text-white",children:je.name}),i.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${je.status==="completed"?"bg-status-ok/20 text-status-ok":je.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:je.status})]}),je.progress_percent!==null&&i.jsxs("span",{className:"text-sm text-bambu-gray",children:[je.progress_percent.toFixed(0),"%"]})]},je.id))})]})}),f.parent_id&&f.parent_name&&i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Vi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),i.jsx(co,{to:`/projects/${f.parent_id}`,className:"text-bambu-green hover:underline",children:f.parent_name})]}),(f.tags||f.due_date||f.priority!=="normal")&&i.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[f.priority&&f.priority!=="normal"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),i.jsx(dtt,{priority:f.priority,t:n})]}),f.due_date&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Yr,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-sm text-white",children:Cf(f.due_date,{year:"numeric",month:"short",day:"numeric"})}),GD(f.due_date,n)&&i.jsxs("span",{className:`text-xs ${GD(f.due_date,n).color}`,children:["(",GD(f.due_date,n).label,")"]})]}),f.tags&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Id,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:f.tags.split(",").map((je,Xe)=>i.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:je.trim()},Xe))})]})]}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(zs,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:W,disabled:D.isPending,children:[i.jsx(Ht,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),i.jsxs(Ie,{size:"sm",onClick:z,disabled:D.isPending,children:[D.isPending?i.jsx(pt,{className:"w-4 h-4 animate-spin mr-1"}):i.jsx(ss,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:B,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[i.jsx(_f,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?i.jsx(hL,{content:d,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):f.notes?i.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:pie.sanitize(f.notes)}}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Pc,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),i.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[i.jsx(co,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),k&&k.length>0?i.jsx("div",{className:"space-y-2",children:k.map(je=>i.jsxs(co,{to:`/files?folder=${je.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx(Pc,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:je.name}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:je.file_count})})]})]}),i.jsx(fa,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},je.id))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(XX,{className:"w-5 h-5"}),n("projectDetail.bom.title"),Ae&&Ae.bom_total_items>0&&i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:Ae.bom_completed_items,total:Ae.bom_total_items}),")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[_&&_.some(je=>je.is_complete)&&i.jsx("button",{onClick:()=>Z(!q),className:`text-xs px-2 py-1 rounded transition-colors ${q?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(q?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!be&&i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>Me(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[i.jsx(ar,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),be&&i.jsxs("form",{onSubmit:te,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:I,onChange:je=>J(je.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:ie,onChange:je=>Q(parseInt(je.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),i.jsx("input",{type:"number",step:"0.01",value:ue,onChange:je=>me(je.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:R})})]})]}),i.jsx("input",{type:"url",value:pe,onChange:je=>Y(je.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),i.jsx("input",{type:"text",value:se,onChange:je=>oe(je.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",size:"sm",onClick:()=>Me(!1),children:n("common.cancel")}),i.jsx(Ie,{type:"submit",size:"sm",disabled:!I.trim()||ae.isPending,children:ae.isPending?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),N?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):_&&_.length>0?i.jsxs("div",{className:"space-y-2",children:[_.filter(je=>!q||!je.is_complete).map(je=>i.jsx("div",{className:`p-3 rounded-lg transition-colors ${je.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:j?.id===je.id?i.jsxs("form",{onSubmit:ke,className:"space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:U,onChange:Xe=>K(Xe.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partName"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:$,onChange:Xe=>ne(parseInt(Xe.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),i.jsx("input",{type:"number",step:"0.01",value:O,onChange:Xe=>V(Xe.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:R})})]})]}),i.jsx("input",{type:"url",value:ee,onChange:Xe=>G(Xe.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),i.jsx("input",{type:"text",value:re,onChange:Xe=>ce(Xe.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",size:"sm",onClick:_e,children:n("common.cancel")}),i.jsx(Ie,{type:"submit",size:"sm",disabled:!U.trim()||L.isPending,children:L.isPending?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("button",{onClick:()=>s("projects:update")&&ve(je),disabled:L.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors flex-shrink-0 ${je.is_complete?"bg-status-ok border-status-ok text-white":s("projects:update")?"border-bambu-gray hover:border-bambu-green":"border-bambu-gray/50 cursor-not-allowed"}`,children:je.is_complete&&i.jsx(fr,{className:"w-3 h-3"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsxs("p",{className:`text-sm font-medium ${je.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[je.name,i.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",je.quantity_needed]})]}),je.unit_price!==null&&i.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[R,(je.unit_price*je.quantity_needed).toFixed(2)]})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>s("projects:update")&&de(je),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:i.jsx(Ki,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("projects:update")&&he(je.id,je.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:i.jsx(en,{className:"w-4 h-4"})})]})]}),je.sourcing_url&&i.jsxs("a",{href:je.sourcing_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 mt-1 text-xs text-blue-400 hover:text-blue-300 transition-colors",onClick:Xe=>Xe.stopPropagation(),children:[i.jsx(ti,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"truncate",children:(()=>{try{return new URL(je.sourcing_url).hostname.replace("www.","")}catch{return je.sourcing_url}})()})]}),je.remarks&&i.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:je.remarks})]})]})},je.id)),Ae&&Ae.bom_cost>0&&i.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),i.jsxs("span",{className:"text-white font-medium",children:[R,Ae.bom_cost.toFixed(2)]})]})]}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(x0,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),C?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):T&&T.length>0?i.jsx("div",{className:"space-y-3",children:T.slice(0,10).map((je,Xe)=>i.jsxs("div",{className:"flex gap-3",children:[i.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${je.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":je.event_type==="print_failed"?"bg-status-error/20 text-status-error":je.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[je.event_type==="print_completed"&&i.jsx(fr,{className:"w-4 h-4"}),je.event_type==="print_failed"&&i.jsx(qi,{className:"w-4 h-4"}),je.event_type==="print_started"&&i.jsx(_r,{className:"w-4 h-4"}),je.event_type==="queued"&&i.jsx(y3,{className:"w-4 h-4"}),je.event_type==="project_created"&&i.jsx(ar,{className:"w-4 h-4"})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white",children:je.title}),je.description&&i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:je.description}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:Re(je.timestamp)})]})]},Xe))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!f.is_template&&i.jsx("div",{className:"flex justify-end",children:i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>$e.mutate(),disabled:$e.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[$e.isPending?i.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(vo,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),Ae&&(Ae.queued_prints>0||Ae.in_progress_prints>0)&&i.jsx(Pt,{children:i.jsxs(Et,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(y3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),i.jsx(co,{to:`/queue?project=${p}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[Ae.in_progress_prints>0&&i.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:Ae.in_progress_prints})}),Ae.queued_prints>0&&i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:Ae.queued_prints})})]})]})}),i.jsxs("div",{children:[i.jsx("div",{className:"flex items-center justify-between mb-4",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Gi,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:b?.length||0})]})}),g?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):i.jsx(utt,{archives:b||[],t:n})]}),o&&i.jsx(Hoe,{t:n,currencySymbol:R,project:{...f,archive_count:Ae?.total_archives||0,total_items:Ae?.total_items||0,completed_count:Ae?.completed_prints||0,failed_count:Ae?.failed_prints||0,queue_count:Ae?.queued_prints||0,progress_percent:Ae?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:je=>D.mutate(je),isLoading:D.isPending}),ge.isOpen&&i.jsx(_n,{title:ge.title,message:ge.message,confirmText:n("common.delete"),variant:"danger",onConfirm:ge.onConfirm,onCancel:()=>xe(je=>({...je,isOpen:!1}))})]})}function htt({parentId:t,onClose:e,onSave:n,isLoading:r,t:a}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("fileManager.newFolder")})}),i.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.folderName")}),i.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ie,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):a("common.create")})]})]})]})})}function ptt({type:t,currentName:e,onClose:n,onSave:r,isLoading:a,t:s}){const[o,l]=w.useState(e),c=u=>{u.preventDefault(),o.trim()&&o.trim()!==e&&r(o.trim())};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),i.jsxs("form",{onSubmit:c,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),i.jsx("input",{type:"text",value:o,onChange:u=>l(u.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),i.jsx(Ie,{type:"submit",disabled:!o.trim()||o.trim()===e||a,children:a?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function ftt({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:a,isLoading:s,t:o}){const[l,c]=w.useState(null),u=(m,p=0)=>{const f=[];for(const y of m)f.push({id:y.id,name:y.name,depth:p}),y.children.length>0&&f.push(...u(y.children,p+1));return f},d=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...u(t)];return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:d.map(m=>i.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[i.jsx(Pc,{className:"w-4 h-4"}),m.name,m.id===n&&i.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ie,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),i.jsx(Ie,{onClick:()=>a(l),disabled:s,children:s?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function gtt({folder:t,onClose:e,onLink:n,isLoading:r,t:a}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:u}=tt({queryKey:["projects"],queryFn:()=>fe.getProjects()}),{data:d}=tt({queryKey:["archives-for-link"],queryFn:()=>fe.getArchives(void 0,void 0,100)}),m=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(_h,{className:"w-5 h-5 text-bambu-green"}),a("fileManager.linkFolder")]}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("fileManager.linkFolderDescription",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[i.jsx(zX,{className:"w-4 h-4"}),a("fileManager.project")]}),i.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[i.jsx($s,{className:"w-4 h-4"}),a("fileManager.archive")]})]}),i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?u&&u.length>0?u.map(y=>i.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:y.color||"#00ae42"}}),i.jsx("span",{className:"truncate",children:y.name})]},y.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noProjectsFound")}):d&&d.length>0?d.map(y=>i.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx(sf,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"truncate",children:y.print_name||y.filename})]},y.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noArchivesFound")})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&i.jsxs(Ie,{variant:"danger",onClick:p,disabled:r,children:[i.jsx(y0,{className:"w-4 h-4 mr-2"}),a("fileManager.unlink")]}),i.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[i.jsx(Ie,{variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ie,{onClick:m,disabled:!l||r,children:r?i.jsx(pt,{className:"w-4 h-4 animate-spin"}):a("fileManager.link")})]})]})]})})}function $oe({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:u}){const[d,m]=w.useState(!0),[p,f]=w.useState(!1),y=t.children.length>0,v=t.project_id||t.archive_id;return i.jsxs("div",{children:[i.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>n(t.id),children:[y?i.jsx("button",{onClick:b=>{b.stopPropagation(),m(!d)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(fa,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-90":""}`})}):i.jsx("div",{className:"w-4.5"}),i.jsx(Pc,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),i.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&i.jsxs("button",{onClick:b=>{b.stopPropagation(),a(t)},className:"flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors",title:`${t.project_name?`Project: ${t.project_name}`:`Archive: ${t.archive_name}`} (click to change)`,children:[i.jsx(_h,{className:"w-3 h-3"}),t.project_name?i.jsx(zX,{className:"w-3 h-3"}):i.jsx($s,{className:"w-3 h-3"})]}),t.file_count>0&&i.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&i.jsx("button",{onClick:b=>{b.stopPropagation(),a(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:i.jsx(_h,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),i.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:b=>b.stopPropagation(),children:i.jsxs("div",{className:"relative",children:[i.jsx("button",{onClick:()=>f(!p),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:i.jsx(yh,{className:"w-3.5 h-3.5 text-bambu-gray"})}),p&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>f(!1)}),i.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(s(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[i.jsx(Ki,{className:"w-3.5 h-3.5"}),u("common.rename")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(a(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[i.jsx(_h,{className:"w-3.5 h-3.5"}),u(v?"fileManager.changeLink":"fileManager.linkTo")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:delete_all")&&(r(t.id),f(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[i.jsx(en,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),y&&d&&i.jsx("div",{children:t.children.map(b=>i.jsx($oe,{folder:b,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},b.id))})]})}function wL(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function btt({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:a,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:u,onGenerateThumbnail:d,thumbnailVersion:m,hasPermission:p,canModify:f,authEnabled:y,t:v}){const[b,g]=w.useState(!1);return i.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>r(t.id),children:[i.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?i.jsx("img",{src:`${fe.getLibraryFileThumbnailUrl(t.id)}${m?`?v=${m}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):i.jsx(sf,{className:"w-12 h-12 text-bambu-gray/30"}),i.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),i.jsxs("div",{className:"p-3",children:[i.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),i.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[i.jsx("span",{children:ho(t.file_size)}),t.print_time_seconds&&i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Jn,{className:"w-3 h-3"}),Is(t.print_time_seconds)]})]}),t.sliced_for_model&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(_r,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&i.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),y&&t.created_by_username&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(zd,{className:"w-3 h-3"}),t.created_by_username]})]}),i.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[i.jsx("button",{onClick:()=>g(!b),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:i.jsx(yh,{className:"w-4 h-4 text-bambu-gray"})}),b&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),i.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&wL(t.filename)&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("printers:control")&&(l(t),g(!1))},disabled:!p("printers:control"),title:p("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[i.jsx(_r,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&wL(t.filename)&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("queue:create")&&(o(t.id),g(!1))},disabled:!p("queue:create"),title:p("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[i.jsx(Jn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(c(t),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:"You do not have permission to preview files",children:[i.jsx(na,{className:"w-3.5 h-3.5"}),"3D Preview"]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(s(t.id),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[i.jsx(bi,{className:"w-3.5 h-3.5"}),v("common.download")]}),u&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(u(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[i.jsx(Ki,{className:"w-3.5 h-3.5"}),v("common.rename")]}),d&&t.file_type==="stl"&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(d(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[i.jsx(Ld,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","delete",t.created_by_id)&&(a(t.id),g(!1))},disabled:!f("library","delete",t.created_by_id),title:f("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[i.jsx(en,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),i.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function xtt(){const{t}=Rt(),e=sn(),{showToast:n}=fn(),{hasPermission:r,hasAnyPermission:a,canModify:s,authEnabled:o}=Nr(),[l]=jL(),c=l.get("folder"),u=c?parseInt(c,10):null,[d,m]=w.useState(u),[p,f]=w.useState([]),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,N]=w.useState(!1),[T,C]=w.useState(null),[P,k]=w.useState(null),[R,A]=w.useState(null),[D,B]=w.useState(null),[z,W]=w.useState(null),[I,J]=w.useState(null),[ie,Q]=w.useState({}),[ue,me]=w.useState(null),[pe,Y]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[se,oe]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[be,Me]=w.useState(()=>{const qe=localStorage.getItem("library-sidebar-width");return qe?parseInt(qe,10):256}),[q,Z]=w.useState(!1),j=w.useRef(null);w.useEffect(()=>{if(!q)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const qe=Nt=>{if(!j.current)return;const mt=j.current.parentElement?.getBoundingClientRect();if(!mt)return;const jt=Nt.clientX-mt.left,qt=Math.min(500,Math.max(200,jt));Me(qt)},_t=()=>{Z(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(be))};return document.addEventListener("mousemove",qe),document.addEventListener("mouseup",_t),()=>{document.removeEventListener("mousemove",qe),document.removeEventListener("mouseup",_t),document.body.style.userSelect="",document.body.style.cursor=""}},[q,be]);const[E,U]=w.useState(""),[K,$]=w.useState("all"),[ne,O]=w.useState(""),[V,ee]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[G,re]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),ce=aie();w.useEffect(()=>{const qe=l.get("folder");if(qe){const _t=parseInt(qe,10);m(_t)}},[l]);const{data:ge}=tt({queryKey:["settings"],queryFn:()=>fe.getSettings()}),{data:xe,isLoading:ae}=tt({queryKey:["library-folders"],queryFn:()=>fe.getLibraryFolders()}),{data:L,isLoading:F}=tt({queryKey:["library-files",d],queryFn:()=>fe.getLibraryFiles(d,d===null)}),{data:te}=tt({queryKey:["library-stats"],queryFn:()=>fe.getLibraryStats()}),{data:ve}=tt({queryKey:["users"],queryFn:()=>fe.getUsers()}),he=w.useMemo(()=>{if(!L)return[];const qe=new Set(L.map(_t=>_t.file_type));return Array.from(qe).sort()},[L]),de=w.useMemo(()=>{if(!L)return[];let qe=[...L];if(E.trim()){const _t=E.toLowerCase();qe=qe.filter(Nt=>Nt.filename.toLowerCase().includes(_t)||Nt.print_name&&Nt.print_name.toLowerCase().includes(_t))}if(K!=="all"&&(qe=qe.filter(_t=>_t.file_type===K)),ne.trim()){const _t=ne.toLowerCase();qe=qe.filter(Nt=>Nt.created_by_username&&Nt.created_by_username.toLowerCase().includes(_t))}return qe.sort((_t,Nt)=>{let mt=0;switch(V){case"name":mt=(_t.print_name||_t.filename).localeCompare(Nt.print_name||Nt.filename);break;case"date":mt=(Zn(_t.created_at)?.getTime()??0)-(Zn(Nt.created_at)?.getTime()??0);break;case"size":mt=_t.file_size-Nt.file_size;break;case"type":mt=_t.file_type.localeCompare(Nt.file_type);break;case"prints":mt=_t.print_count-Nt.print_count;break}return G==="asc"?mt:-mt}),qe},[L,E,K,ne,V,G]),ke=w.useMemo(()=>{if(!te||!ge)return!1;const qe=(ge.library_disk_warning_gb||5)*1024*1024*1024;return te.disk_free_bytesfe.createLibraryFolder(qe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:qe=>n(qe.message,"error")}),Le=ft({mutationFn:qe=>fe.deleteLibraryFolder(qe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===P?.id&&m(null),k(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:qe=>{k(null),n(qe.message,"error")}}),$e=ft({mutationFn:qe=>fe.deleteLibraryFile(qe),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),f(qe=>qe.filter(_t=>_t!==P?.id)),k(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:qe=>{k(null),n(qe.message,"error")}}),Re=ft({mutationFn:qe=>fe.bulkDeleteLibrary(qe,[]),onSuccess:(qe,_t)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:_t.length}),"success"),f([]),k(null)},onError:qe=>{k(null),n(qe.message,"error")}}),Ae=ft({mutationFn:({fileIds:qe,folderId:_t})=>fe.moveLibraryFiles(qe,_t),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),f([]),g(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:qe=>n(qe.message,"error")}),Pe=ft({mutationFn:({id:qe,data:_t})=>fe.updateLibraryFolder(qe,_t),onSuccess:(qe,_t)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),C(null);const Nt=_t.data.project_id===0&&_t.data.archive_id===0;n(t(Nt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:qe=>n(qe.message,"error")}),Ue=ft({mutationFn:({id:qe,filename:_t})=>fe.updateLibraryFile(qe,{filename:_t}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),J(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:qe=>{J(null),n(qe.message,"error")}}),je=ft({mutationFn:({id:qe,name:_t})=>fe.updateLibraryFolder(qe,{name:_t}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),J(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:qe=>{J(null),n(qe.message,"error")}}),Xe=ft({mutationFn:()=>fe.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:qe=>{if(e.invalidateQueries({queryKey:["library-files"]}),qe.succeeded>0){const _t=Date.now(),Nt={};qe.results.forEach(mt=>{mt.success&&(Nt[mt.file_id]=_t)}),Q(mt=>({...mt,...Nt}))}qe.succeeded>0&&qe.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:qe.succeeded}),"success"):qe.succeeded>0&&qe.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:qe.succeeded,failed:qe.failed}),"success"):qe.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:qe.results[0]?.error||"Unknown error"}),"error")},onError:qe=>n(qe.message,"error")}),ye=ft({mutationFn:qe=>fe.batchGenerateStlThumbnails({file_ids:[qe]}),onSuccess:qe=>{if(e.invalidateQueries({queryKey:["library-files"]}),qe.succeeded>0){const _t=qe.results[0]?.file_id;_t&&Q(Nt=>({...Nt,[_t]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:qe.results[0]?.error||"Unknown error"}),"error")},onError:qe=>n(qe.message,"error")}),Ge=w.useCallback(qe=>{const _t=qe.toLowerCase();return _t.endsWith(".gcode")||_t.includes(".gcode.")},[]),Ee=w.useMemo(()=>L?L.filter(qe=>p.includes(qe.id)&&Ge(qe.filename)):[],[L,p,Ge]),Ke=w.useCallback(qe=>{f(_t=>_t.includes(qe)?_t.filter(Nt=>Nt!==qe):[..._t,qe])},[]),Ve=w.useCallback(()=>{de.length>0&&f(de.map(qe=>qe.id))},[de]),Ne=w.useCallback(()=>{f([])},[]),Ce=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},He=qe=>{fe.downloadLibraryFile(qe).catch(_t=>{console.error("Library file download failed:",_t)})},et=()=>{P&&(P.type==="file"?$e.mutate(P.id):P.type==="folder"?Le.mutate(P.id):P.type==="bulk"&&Re.mutate(p))},it=Le.isPending||$e.isPending||Re.isPending,xt=qe=>{Y(qe),localStorage.setItem("library-view-mode",qe)},vt=ae||F;return i.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(Pc,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[i.jsx("button",{onClick:()=>xt("grid"),className:`p-1.5 rounded transition-colors ${pe==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:i.jsx(xw,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>xt("list"),className:`p-1.5 rounded transition-colors ${pe==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:i.jsx(eT,{className:"w-4 h-4"})})]}),i.jsxs(Ie,{variant:"secondary",onClick:()=>Xe.mutate(),disabled:Xe.isPending||!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[Xe.isPending?i.jsx(pt,{className:"w-4 h-4 mr-2 animate-spin"}):i.jsx(Ld,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),i.jsxs(Ie,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[i.jsx(Xpe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),i.jsxs(Ie,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(vi,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),ke&&te&&ge&&i.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[i.jsx(Mn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),i.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:ho(te.disk_free_bytes),total:ho(te.disk_total_bytes),threshold:ge.library_disk_warning_gb})})]})]}),te&&i.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(ZC,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),i.jsx("span",{className:"text-white font-medium",children:te.total_files})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Pc,{className:"w-4 h-4 text-blue-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),i.jsx("span",{className:"text-white font-medium",children:te.total_folders})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Ix,{className:"w-4 h-4 text-amber-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),i.jsx("span",{className:"text-white font-medium",children:ho(te.total_size_bytes)})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),i.jsx("span",{className:`font-medium ${ke?"text-amber-500":"text-white"}`,children:ho(te.disk_free_bytes)})]})]}),i.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[i.jsx("div",{className:"lg:hidden",children:i.jsxs("select",{value:d??"",onChange:qe=>m(qe.target.value?parseInt(qe.target.value,10):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[i.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),xe&&(()=>{const qe=(_t,Nt=0)=>{const mt=[];for(const jt of _t)mt.push({id:jt.id,name:jt.name,fileCount:jt.file_count,depth:Nt}),jt.children.length>0&&mt.push(...qe(jt.children,Nt+1));return mt};return qe(xe).map(_t=>i.jsxs("option",{value:_t.id,children:["│ ".repeat(_t.depth),"📂 ",_t.name," ",_t.fileCount>0?`(${_t.fileCount})`:""]},_t.id))})()]})}),i.jsxs("div",{ref:j,className:"hidden lg:flex flex-shrink-0 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden flex-col relative",style:{width:`${be}px`},children:[i.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${q?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:qe=>{qe.preventDefault(),Z(!0)},onDoubleClick:()=>{Me(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:i.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${q?"opacity-100":""}`,children:[i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),i.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),i.jsx("button",{onClick:()=>{const qe=!se;oe(qe),localStorage.setItem("library-wrap-folders",String(qe))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${se?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(se?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[i.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${d===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>m(null),children:[i.jsx(sf,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),xe?.map(qe=>i.jsx($oe,{folder:qe,selectedFolderId:d,onSelect:m,onDelete:_t=>k({type:"folder",id:_t}),onLink:C,onRename:_t=>J({type:"folder",id:_t.id,name:_t.name}),wrapNames:se,hasPermission:r,t},qe.id))]})]}),i.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[L&&L.length>0&&i.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[i.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:E,onChange:qe=>U(qe.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(JC,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),i.jsxs("select",{value:K,onChange:qe=>$(qe.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"all",children:t("fileManager.allTypes")}),he.map(qe=>i.jsx("option",{value:qe,children:qe.toUpperCase()},qe))]})]}),o&&i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:ne,onChange:qe=>O(qe.target.value),list:"usernames-list",className:`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${ne?"pr-7":""}`,style:ne?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),ne&&i.jsx("button",{onClick:()=>O(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:i.jsx(Ht,{className:"w-3 h-3"})}),i.jsx("datalist",{id:"usernames-list",children:ve?.map(qe=>i.jsx("option",{value:qe.username},qe.id))})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("select",{value:V,onChange:qe=>{const _t=qe.target.value;ee(_t),localStorage.setItem("library-sort-field",_t)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"name",children:t("common.name")}),i.jsx("option",{value:"date",children:t("common.date")}),i.jsx("option",{value:"size",children:t("fileManager.size")}),i.jsx("option",{value:"type",children:t("common.type")}),i.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),i.jsx("button",{onClick:()=>re(qe=>{const _t=qe==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",_t),_t}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(G==="asc"?"fileManager.ascending":"fileManager.descending"),children:G==="asc"?i.jsx(ghe,{className:"w-4 h-4 text-white"}):i.jsx(che,{className:"w-4 h-4 text-white"})})]}),(E||K!=="all"||ne)&&i.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:de.length,total:L.length})})]}),de.length>0&&i.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[p.length===de.length&&p.length>0?i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:Ne,children:[i.jsx(ql,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:Ve,children:[i.jsx(_o,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),p.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:p.length})}),i.jsx("div",{className:"hidden sm:block flex-1"}),i.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Ee.length===1&&i.jsxs(Ie,{variant:"primary",size:"sm",onClick:()=>B(Ee[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[i.jsx(wo,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Ee.length===1&&i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>W(Ee[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[i.jsx(Jn,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>g(!0),disabled:!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[i.jsx(sge,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),i.jsxs(Ie,{variant:"danger",size:"sm",onClick:()=>{p.length===1?k({type:"file",id:p[0]}):k({type:"bulk",id:0,count:p.length})},disabled:!a("library:delete_own","library:delete_all"),title:a("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[i.jsx(en,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),i.jsxs(Ie,{variant:"secondary",size:"sm",onClick:Ne,children:[i.jsx(Ht,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),vt?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):L?.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(sf,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(d!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(d!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),i.jsxs(Ie,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(ar,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):de.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(Rr,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),i.jsx(Ie,{variant:"secondary",onClick:()=>{U(""),$("all")},children:t("fileManager.clearFilters")})]}):pe==="grid"?i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:de.map(qe=>i.jsx(btt,{file:qe,isSelected:p.includes(qe.id),isMobile:ce,t,onSelect:Ke,onDelete:_t=>k({type:"file",id:_t}),onDownload:He,onAddToQueue:_t=>{const Nt=L?.find(mt=>mt.id===_t);Nt&&W(Nt)},onPrint:A,onPreview3d:me,onRename:_t=>J({type:"file",id:_t.id,name:_t.filename}),onGenerateThumbnail:_t=>ye.mutate(_t.id),thumbnailVersion:ie[qe.id],hasPermission:r,canModify:s,authEnabled:o},qe.id))})}):i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[i.jsx("div",{className:"w-6"}),i.jsx("div",{children:t("common.name")}),o&&i.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),i.jsx("div",{children:t("common.type")}),i.jsx("div",{children:t("fileManager.size")}),i.jsx("div",{children:t("fileManager.prints")}),i.jsx("div",{})]}),de.map(qe=>i.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${p.includes(qe.id)?"bg-bambu-green/10":""}`,onClick:()=>Ke(qe.id),children:[i.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${p.includes(qe.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:p.includes(qe.id)&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsxs("div",{className:"relative group/thumb",children:[i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:qe.thumbnail_path?i.jsx("img",{src:`${fe.getLibraryFileThumbnailUrl(qe.id)}${ie[qe.id]?`?v=${ie[qe.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(sf,{className:"w-5 h-5 text-bambu-gray/50"})})}),qe.thumbnail_path&&i.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:i.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:i.jsx("img",{src:`${fe.getLibraryFileThumbnailUrl(qe.id)}${ie[qe.id]?`?v=${ie[qe.id]}`:""}`,alt:qe.filename,className:"w-full h-full object-contain"})})})]}),i.jsx("div",{className:"min-w-0",children:i.jsx("div",{className:"text-sm text-white truncate",children:qe.print_name||qe.filename})})]}),o&&i.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:qe.created_by_username?i.jsxs(i.Fragment,{children:[i.jsx(zd,{className:"w-3 h-3"}),i.jsx("span",{className:"truncate",children:qe.created_by_username})]}):"-"}),i.jsx("div",{children:i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${qe.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":qe.file_type==="gcode"?"bg-blue-500/20 text-blue-400":qe.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:qe.file_type.toUpperCase()})}),i.jsx("div",{className:"text-sm text-bambu-gray",children:ho(qe.file_size)}),i.jsx("div",{className:"text-sm text-bambu-gray",children:qe.print_count>0?`${qe.print_count}x`:"-"}),i.jsxs("div",{className:"flex items-center gap-1",onClick:_t=>_t.stopPropagation(),children:[wL(qe.filename)&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>r("printers:control")&&A(qe),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:i.jsx(_r,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{r("queue:create")&&W(qe)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:i.jsx(Jn,{className:"w-4 h-4"})})]}),(qe.file_type==="3mf"||qe.file_type==="gcode"||qe.file_type==="stl")&&i.jsx("button",{onClick:()=>r("library:read")&&me(qe),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:i.jsx(na,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>r("library:read")&&He(qe.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:i.jsx(bi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","update",qe.created_by_id)&&J({type:"file",id:qe.id,name:qe.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",qe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",qe.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",qe.created_by_id),children:i.jsx(Ki,{className:"w-4 h-4"})}),qe.file_type==="stl"&&i.jsx("button",{onClick:()=>s("library","update",qe.created_by_id)&&ye.mutate(qe.id),className:`p-1.5 rounded transition-colors ${s("library","update",qe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",qe.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:ye.isPending||!s("library","update",qe.created_by_id),children:i.jsx(Ld,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","delete",qe.created_by_id)&&k({type:"file",id:qe.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",qe.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","delete",qe.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",qe.created_by_id),children:i.jsx(en,{className:"w-4 h-4"})})]})]},qe.id))]})})]})]}),y&&i.jsx(htt,{parentId:d,onClose:()=>v(!1),onSave:qe=>_e.mutate(qe),isLoading:_e.isPending,t}),b&&xe&&i.jsx(ftt,{folders:xe,selectedFiles:p,currentFolderId:d,onClose:()=>g(!1),onMove:qe=>Ae.mutate({fileIds:p,folderId:qe}),isLoading:Ae.isPending,t}),_&&i.jsx(Qre,{folderId:d,onClose:()=>N(!1),onUploadComplete:Ce}),T&&i.jsx(gtt,{folder:T,onClose:()=>C(null),onLink:qe=>Pe.mutate({id:T.id,data:qe}),isLoading:Pe.isPending,t}),P&&i.jsx(_n,{title:P.type==="folder"?t("fileManager.deleteFolder"):P.type==="bulk"?t("fileManager.deleteFilesCount",{count:P.count}):t("fileManager.deleteFile"),message:P.type==="folder"?t("fileManager.deleteFolderConfirm"):P.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:P.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:it,loadingText:t("fileManager.deleting"),onConfirm:et,onCancel:()=>k(null)}),R&&i.jsx(bu,{mode:"reprint",libraryFileId:R.id,archiveName:R.print_name||R.filename,onClose:()=>A(null),onSuccess:()=>{A(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),D&&i.jsx(bu,{mode:"reprint",libraryFileId:D.id,archiveName:D.print_name||D.filename,onClose:()=>B(null),onSuccess:()=>{B(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),z&&i.jsx(bu,{mode:"add-to-queue",libraryFileId:z.id,archiveName:z.print_name||z.filename,onClose:()=>W(null),onSuccess:()=>{W(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),ue&&i.jsx(jI,{libraryFileId:ue.id,title:ue.print_name||ue.filename,fileType:ue.file_type,onClose:()=>me(null)}),I&&i.jsx(ptt,{type:I.type,currentName:I.name,onClose:()=>J(null),onSave:qe=>{I.type==="file"?Ue.mutate({id:I.id,filename:qe}):je.mutate({id:I.id,name:qe})},isLoading:Ue.isPending||je.isPending,t})]})}const WD=5,ytt=2e3,vtt=3e4,wtt=5e3;function Stt(){const{t}=Rt(),e=sn(),{showToast:n}=fn(),{hasPermission:r}=Nr(),{printerId:a}=hw(),s=parseInt(a||"0",10),[o,l]=w.useState("stream"),[c,u]=w.useState(!1),[d,m]=w.useState(!1),[p,f]=w.useState(!0),[y,v]=w.useState(Date.now()),[b,g]=w.useState(!1),[_,N]=w.useState(!1),[T,C]=w.useState(0),[P,k]=w.useState(!1),[R,A]=w.useState(0),[D,B]=w.useState(1),[z,W]=w.useState({x:0,y:0}),[I,J]=w.useState(!1),[ie,Q]=w.useState({x:0,y:0}),[ue,me]=w.useState(null),[pe,Y]=w.useState(null),se=w.useRef(null),oe=w.useRef(null),be=w.useRef(null),Me=w.useRef(null),q=w.useRef(null),{data:Z}=tt({queryKey:["printer",s],queryFn:()=>fe.getPrinter(s),enabled:s>0}),{data:j}=tt({queryKey:["printerStatus",s],queryFn:()=>fe.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),E=ft({mutationFn:Ae=>fe.setChamberLight(s,Ae),onMutate:async Ae=>{await e.cancelQueries({queryKey:["printerStatus",s]});const Pe=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],Ue=>({...Ue,chamber_light:Ae})),{previousStatus:Pe}},onSuccess:(Ae,Pe)=>{n(`Chamber light ${Pe?"on":"off"}`)},onError:(Ae,Pe,Ue)=>{Ue?.previousStatus&&e.setQueryData(["printerStatus",s],Ue.previousStatus),n(Ae.message||t("printers.toast.failedToControlChamberLight"),"error")}}),U=(j?.state==="RUNNING"||j?.state==="PAUSE")&&(j?.printable_objects_count??0)>=2;w.useEffect(()=>(Z&&(document.title=`${Z.name} - Camera`),()=>{document.title="Bambuddy"}),[Z]);const K=w.useRef(!1);w.useEffect(()=>{const Ae=`/api/v1/printers/${s}/camera/stop`;K.current=!1;const Pe=()=>{if(s>0&&!K.current){K.current=!0;const Xe={},ye=Ud();ye&&(Xe.Authorization=`Bearer ${ye}`),fetch(Ae,{method:"POST",keepalive:!0,headers:Xe}).catch(()=>{})}},Ue=()=>{Pe()};window.addEventListener("beforeunload",Ue);const je=se.current;return()=>{window.removeEventListener("beforeunload",Ue),je&&(je.src=""),Pe()}},[s]),w.useEffect(()=>{if(p&&!b){const Pe=setTimeout(()=>{f(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(Pe)}},[o,p,y,b]),w.useEffect(()=>{const Ae=()=>{const Pe=!!document.fullscreenElement;N(Pe),B(1),W({x:0,y:0}),o==="stream"&&!b&&(se.current&&(se.current.src=""),setTimeout(()=>{f(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",Ae),()=>document.removeEventListener("fullscreenchange",Ae)},[o,b]),w.useEffect(()=>{let Ae;const Pe=()=>{clearTimeout(Ae),Ae=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Pe),()=>{clearTimeout(Ae),window.removeEventListener("resize",Pe)}},[]),w.useEffect(()=>()=>{be.current&&clearTimeout(be.current),Me.current&&clearInterval(Me.current),q.current&&clearInterval(q.current)},[]);const $=w.useCallback(()=>{if(T>=WD){k(!1),m(!0);return}const Ae=Math.min(ytt*Math.pow(2,T),vtt);k(!0),A(Math.ceil(Ae/1e3)),Me.current=setInterval(()=>{A(Pe=>Pe<=1?(Me.current&&clearInterval(Me.current),0):Pe-1)},1e3),be.current=setTimeout(()=>{C(Pe=>Pe+1),k(!1),f(!0),m(!1),se.current&&(se.current.src=""),v(Date.now())},Ae)},[T]);w.useEffect(()=>{if(o!=="stream"||p||P||b){q.current&&(clearInterval(q.current),q.current=null);return}return q.current=setInterval(async()=>{try{const Ae=await fe.getCameraStatus(s);(Ae.stalled||!Ae.active&&!d)&&(console.log(`Stream issue detected: stalled=${Ae.stalled}, active=${Ae.active}, reconnecting...`),q.current&&(clearInterval(q.current),q.current=null),f(!1),$())}catch{}},wtt),()=>{q.current&&(clearInterval(q.current),q.current=null)}},[o,p,d,P,b,s,$]);const ne=()=>{f(!1),o==="stream"&&T{if(f(!1),m(!1),C(0),k(!1),be.current&&clearTimeout(be.current),Me.current&&clearInterval(Me.current),se.current&&!localStorage.getItem("cameraWindowState")){const Ae=se.current,Pe=Ae.naturalWidth,Ue=Ae.naturalHeight;if(Pe>0&&Ue>0){const ye=window.outerWidth-window.innerWidth,Ge=window.outerHeight-window.innerHeight,Ee=Pe+16+ye,Ke=Ue+45+16+Ge;try{window.resizeTo(Ee,Ke)}catch{}}}},V=()=>{if(s>0){const Ae={},Pe=Ud();Pe&&(Ae.Authorization=`Bearer ${Pe}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:Ae}).catch(()=>{})}},ee=Ae=>{o===Ae||b||(g(!0),f(!0),m(!1),C(0),k(!1),B(1),W({x:0,y:0}),be.current&&clearTimeout(be.current),Me.current&&clearInterval(Me.current),se.current&&(se.current.src=""),o==="stream"&&V(),setTimeout(()=>{l(Ae),v(Date.now()),g(!1)},100))},G=()=>{b||(g(!0),f(!0),m(!1),C(0),k(!1),be.current&&clearTimeout(be.current),Me.current&&clearInterval(Me.current),se.current&&(se.current.src=""),o==="stream"&&V(),setTimeout(()=>{v(Date.now()),g(!1)},100))},re=()=>{oe.current&&(document.fullscreenElement?document.exitFullscreen():oe.current.requestFullscreen())},ce=()=>{B(Ae=>Math.min(Ae+.5,4))},ge=()=>{B(Ae=>{const Pe=Math.max(Ae-.5,1);return Pe===1&&W({x:0,y:0}),Pe})},xe=Ae=>{Ae.preventDefault(),Ae.deltaY<0?ce():ge()},ae=Ae=>{D>1&&(Ae.preventDefault(),J(!0),Q({x:Ae.clientX-z.x,y:Ae.clientY-z.y}))},L=w.useCallback(()=>{if(!oe.current)return{x:300,y:200};const Ae=oe.current.getBoundingClientRect(),Pe=Ae.width*(D-1)/2,Ue=Ae.height*(D-1)/2;return{x:Math.max(50,Pe),y:Math.max(50,Ue)}},[D]),F=Ae=>{if(I&&D>1){const Pe=Ae.clientX-ie.x,Ue=Ae.clientY-ie.y,je=L();W({x:Math.max(-je.x,Math.min(je.x,Pe)),y:Math.max(-je.y,Math.min(je.y,Ue))})}},te=()=>{J(!1)},ve=Ae=>{if(Ae.length<2)return 0;const Pe=Ae[0].clientX-Ae[1].clientX,Ue=Ae[0].clientY-Ae[1].clientY;return Math.sqrt(Pe*Pe+Ue*Ue)},he=Ae=>Ae.length<2?{x:Ae[0].clientX,y:Ae[0].clientY}:{x:(Ae[0].clientX+Ae[1].clientX)/2,y:(Ae[0].clientY+Ae[1].clientY)/2},de=Ae=>{Ae.touches.length===2?(Ae.preventDefault(),me(ve(Ae.touches)),Y(he(Ae.touches))):Ae.touches.length===1&&D>1&&(Ae.preventDefault(),J(!0),Q({x:Ae.touches[0].clientX-z.x,y:Ae.touches[0].clientY-z.y}))},ke=Ae=>{if(Ae.touches.length===2&&ue!==null){Ae.preventDefault();const Pe=ve(Ae.touches),Ue=Pe/ue;B(Xe=>{const ye=Math.max(1,Math.min(4,Xe*Ue));return ye===1&&W({x:0,y:0}),ye}),me(Pe);const je=he(Ae.touches);if(pe){const Xe=L();W(ye=>({x:Math.max(-Xe.x,Math.min(Xe.x,ye.x+(je.x-pe.x))),y:Math.max(-Xe.y,Math.min(Xe.y,ye.y+(je.y-pe.y)))}))}Y(je)}else if(Ae.touches.length===1&&I&&D>1){Ae.preventDefault();const Pe=Ae.touches[0].clientX-ie.x,Ue=Ae.touches[0].clientY-ie.y,je=L();W({x:Math.max(-je.x,Math.min(je.x,Pe)),y:Math.max(-je.y,Math.min(je.y,Ue))})}},_e=Ae=>{Ae.touches.length<2&&(me(null),Y(null)),Ae.touches.length===0&&J(!1)},Le=()=>{B(1),W({x:0,y:0})},$e=b?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${y}`:`/api/v1/printers/${s}/camera/snapshot?t=${y}`,Re=p||b||P;return s?i.jsxs("div",{ref:oe,className:"min-h-screen bg-black flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[i.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(ax,{className:"w-4 h-4"}),Z?.name||`Printer ${s}`]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[i.jsx("button",{onClick:()=>ee("stream"),disabled:Re,className:`px-3 py-1 text-xs rounded transition-colors ${o==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),i.jsx("button",{onClick:()=>ee("snapshot"),disabled:Re,className:`px-3 py-1 text-xs rounded transition-colors ${o==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),i.jsx("button",{onClick:()=>E.mutate(!j?.chamber_light),disabled:!j?.connected||E.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${j?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:i.jsx(kO,{on:j?.chamber_light??!1,className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>u(!0),disabled:!U||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${U&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(U?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:i.jsx(xT,{className:"w-4 h-4 text-bambu-gray"})}),i.jsx("button",{onClick:G,disabled:Re,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:i.jsx(Sr,{className:`w-4 h-4 text-bambu-gray ${Re?"animate-spin":""}`})}),i.jsx("button",{onClick:re,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?i.jsx(KX,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(Kfe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),i.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:xe,onMouseMove:F,onMouseUp:te,onMouseLeave:te,onTouchStart:de,onTouchMove:ke,onTouchEnd:_e,style:{touchAction:"none"},children:i.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(p||b)&&!P&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(Sr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),P&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(Rh,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:R,attempt:T+1,max:WD})}),i.jsx("button",{onClick:G,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),d&&!P&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(Mn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),i.jsx("button",{onClick:G,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),i.jsx("img",{ref:se,src:$e,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${D}) translate(${z.x/D}px, ${z.y/D}px) rotate(${Z?.camera_rotation||0}deg)`,...Z?.camera_rotation===90||Z?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:D>1?I?"grabbing":"grab":"default"},onError:$e?ne:void 0,onLoad:$e?O:void 0,onMouseDown:ae,draggable:!1},y),i.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[i.jsx("button",{onClick:ge,disabled:D<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:i.jsx(YL,{className:"w-4 h-4 text-white"})}),i.jsxs("button",{onClick:Le,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(D*100),"%"]}),i.jsx("button",{onClick:ce,disabled:D>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:i.jsx(KL,{className:"w-4 h-4 text-white"})})]})]})}),i.jsx(CO,{printerId:s,isOpen:c,onClose:()=>u(!1)})]}):i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function _tt(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),a=t.get("camera"),s=a!=="false"&&a!=="0";return{size:t.get("size")||"medium",fps:r,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function Ntt(t,e){if(t.stg_cur_name)return t.stg_cur_name;switch(t.state){case"RUNNING":return e("streamOverlay.status.printing");case"PAUSE":return e("streamOverlay.status.paused");case"FINISH":return e("streamOverlay.status.finished");case"FAILED":return e("streamOverlay.status.failed");case"IDLE":return e("streamOverlay.status.idle");default:return t.state||e("streamOverlay.status.unknown")}}function ktt(t){switch(t){case"small":return{container:"p-3",text:"text-sm",textLarge:"text-lg",progressHeight:"h-2",icon:"w-3 h-3",gap:"gap-2",logoHeight:"h-12"};case"large":return{container:"p-6",text:"text-xl",textLarge:"text-3xl",progressHeight:"h-4",icon:"w-6 h-6",gap:"gap-4",logoHeight:"h-24"};default:return{container:"p-4",text:"text-base",textLarge:"text-xl",progressHeight:"h-3",icon:"w-4 h-4",gap:"gap-3",logoHeight:"h-16"}}}function Ctt(){const{printerId:t}=hw(),[e]=jL(),{t:n}=Rt(),r=sn(),a=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>_tt(e),[e]),c=ktt(l.size),{data:u}=tt({queryKey:["printer",a],queryFn:()=>fe.getPrinter(a),enabled:a>0}),{data:d}=tt({queryKey:["printerStatus",a],queryFn:()=>fe.getPrinterStatus(a),enabled:a>0,refetchInterval:2e3}),{data:m}=tt({queryKey:["settings"],queryFn:fe.getSettings}),p=m?.time_format||"system";w.useEffect(()=>{if(!a)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,N=new WebSocket(_);return N.onmessage=T=>{try{const C=JSON.parse(T.data);C.type==="printer_status"&&C.printer_id===a&&r.setQueryData(["printerStatus",a],C.status)}catch{}},N.onerror=()=>{},()=>{N.close()}},[a,r]),w.useEffect(()=>(document.title=u?`${u.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[u,n]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!a)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!d)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const y=d.state==="RUNNING"||d.state==="PAUSE",v=d.progress||0,b=`/api/v1/printers/${a}/camera/stream?fps=${l.fps}&t=${s}`;return i.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&i.jsx("img",{src:b,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",style:u?.camera_rotation?{transform:`rotate(${u.camera_rotation}deg)`}:void 0,onError:f},s),i.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:i.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),i.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:i.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&u&&i.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[i.jsx(_r,{className:`${c.icon} text-white/70`}),i.jsx("span",{className:`${c.text} text-white font-medium`,children:u.name})]}),l.showFilename&&d.current_print&&i.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:d.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,"")}),l.showStatus&&i.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:Ntt(d,n)}),l.showProgress&&y&&i.jsxs("div",{className:"mb-3",children:[i.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[i.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),i.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),i.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:i.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),y&&(l.showLayers||l.showEta)&&i.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&d.layer_num!=null&&d.total_layers!=null&&d.total_layers>0&&i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Vi,{className:c.icon}),i.jsxs("span",{className:c.text,children:[i.jsx("span",{className:"text-white",children:d.layer_num}),i.jsx("span",{className:"mx-1",children:"/"}),i.jsx("span",{children:d.total_layers})]})]}),l.showEta&&d.remaining_time!=null&&d.remaining_time>0&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(yd,{className:c.icon}),i.jsx("span",{className:`${c.text} text-white`,children:Is(d.remaining_time*60)})]}),i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Jn,{className:c.icon}),i.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",XL(d.remaining_time,p,n)]})]})]})]}),!y&&i.jsx("div",{className:`${c.text} text-white/70 py-2`,children:d.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function Ttt(){const{t}=Rt(),{id:e}=hw(),{mode:n}=Xf(),{data:r,isLoading:a,error:s}=tt({queryKey:["external-link",e],queryFn:()=>fe.getExternalLink(Number(e)),enabled:!!e});return a?i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[i.jsx(Mn,{className:"w-12 h-12"}),i.jsx("p",{children:t("common.linkNotFound")})]}):i.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function EY(){const{id:t}=hw(),e=al(),n=sn(),{t:r}=Rt(),{showToast:a}=fn(),s=!!t,[o,l]=w.useState(""),[c,u]=w.useState(""),[d,m]=w.useState([]),[p,f]=w.useState(""),[y,v]=w.useState(!1),{data:b,isLoading:g}=tt({queryKey:["group",t],queryFn:()=>fe.getGroup(Number(t)),enabled:s}),{data:_,isLoading:N}=tt({queryKey:["permissions"],queryFn:()=>fe.getPermissions()});s&&b&&!y&&(l(b.name),u(b.description||""),m(b.permissions),v(!0));const T=ft({mutationFn:Q=>fe.createGroup(Q),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.created")),e("/settings?tab=users")},onError:Q=>{a(Q.message,"error")}}),C=ft({mutationFn:Q=>fe.updateGroup(Number(t),Q),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.updated")),e("/settings?tab=users")},onError:Q=>{a(Q.message,"error")}}),P=T.isPending||C.isPending,k=()=>{if(!o.trim()){a(r("groups.toast.enterGroupName"),"error");return}s?C.mutate({name:o!==b?.name?o:void 0,description:c,permissions:d}):T.mutate({name:o,description:c||void 0,permissions:d})},R=Q=>{m(ue=>ue.includes(Q)?ue.filter(me=>me!==Q):[...ue,Q])},A=(Q,ue)=>{const me=Q.permissions.map(pe=>pe.value);m(pe=>{const Y=pe.filter(se=>!me.includes(se));return ue?[...Y,...me]:Y})},D=Q=>Q.permissions.every(ue=>d.includes(ue.value)),B=Q=>{const ue=Q.permissions.filter(me=>d.includes(me.value)).length;return ue>0&&ue{_&&m(_.all_permissions)},W=()=>{m([])},I=p.toLowerCase(),J=w.useMemo(()=>_?I?_.categories.map(Q=>({...Q,permissions:Q.permissions.filter(ue=>ue.label.toLowerCase().includes(I))})).filter(Q=>Q.permissions.length>0):_.categories:[],[_,I]),ie=_?.all_permissions.length??0;return g||N?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:i.jsx(IX,{className:"w-5 h-5"})}),i.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&i.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[i.jsx(Mn,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),i.jsx("input",{type:"text",value:o,onChange:Q=>l(Q.target.value),disabled:s&&b?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:r("groups.form.groupNamePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),i.jsx("input",{type:"text",value:c,onChange:Q=>u(Q.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:r("groups.form.descriptionPlaceholder")})]})]}),i.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:d.length})," / ",ie]}),i.jsx(Ie,{size:"sm",variant:"ghost",onClick:z,children:r("groups.editor.selectAll")}),i.jsx(Ie,{size:"sm",variant:"ghost",onClick:W,children:r("groups.editor.clearAll")})]}),i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),i.jsx("input",{type:"text",value:p,onChange:Q=>f(Q.target.value),placeholder:r("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"})]})]}),J.length===0?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:J.map(Q=>{const ue=_.categories.find(oe=>oe.name===Q.name),me=ue.permissions.filter(oe=>d.includes(oe.value)).length,pe=ue.permissions.length,Y=D(ue),se=B(ue);return i.jsxs(Pt,{children:[i.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>A(ue,!Y),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${Y?"bg-bambu-green border-bambu-green":se?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[Y&&i.jsx(Qr,{className:"w-3 h-3 text-white"}),se&&!Y&&i.jsx(RN,{className:"w-3 h-3 text-white"})]}),i.jsx(S3,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-white font-medium text-sm",children:Q.name})]}),i.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[me,"/",pe]})]}),i.jsx("div",{className:"p-3 space-y-1",children:Q.permissions.map(oe=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d.includes(oe.value),onChange:()=>R(oe.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:oe.label})]},oe.value))})]},Q.name)})}),i.jsx("div",{className:"h-16"}),i.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[i.jsx(Ie,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),i.jsx(Ie,{onClick:k,disabled:P||!o.trim(),children:P?i.jsxs(i.Fragment,{children:[i.jsx(pt,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(ss,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const jY={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function Att(t,e=!1){const n={};return e?(t.material||(n.material="Material is required"),{isValid:Object.keys(n).length===0,errors:n}):(t.slicer_filament||(n.slicer_filament="Slicer preset is required"),t.material||(n.material="Material is required"),t.brand||(n.brand="Brand is required"),t.subtype||(n.subtype="Subtype is required"),{isValid:Object.keys(n).length===0,errors:n})}const Ptt=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Mtt=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],h0=["Basic","Matte","Silk","Tough","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],qoe=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"}],Ett=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],DY=[...qoe,...Ett],Voe="bambuddy-recent-colors",jtt=8,Dtt=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function Dx(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let r="",a=-1;for(const c of n){const u=e.toUpperCase().indexOf(c.toUpperCase());if(u!==-1){r=c,a=u;break}}let s="";a>0&&(s=e.substring(0,a).trim(),s=s.replace(/[-_\s]+$/,""));let o="";a!==-1&&r&&(o=e.substring(a+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of h0)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of h0){const u=new RegExp(`\\s+${c}$`,"i");if(u.test(s)){l=c,s=s.replace(u,"").trim();break}}return{brand:s,material:r,variant:l}}function Rtt(t,e){const n=new Set(Mtt);for(const r of t){const{brand:a}=Dx(r.name);a&&a.length>1&&n.add(a)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:a}=Dx(r.name);a&&a.length>1&&n.add(a)}return Array.from(n).sort((r,a)=>r.localeCompare(a))}function Ftt(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const a=r.name.replace(/@.*$/,"").trim(),s=n.get(a);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(a,{code:o,name:a,displayName:a,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,a)=>r.displayName.localeCompare(a.displayName))}function Ltt(t,e,n){if(t.length>0){const r=[],a=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=a.get(o);l?l.allCodes.push(s.setting_id):a.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(a.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=Ftt(n);if(r.length>0)return r}return Dtt}function Ott(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(a=>a.code.toLowerCase()===r||a.allCodes.some(s=>s.toLowerCase()===r))}return n}function Itt(){try{const t=localStorage.getItem(Voe);if(t)return JSON.parse(t)}catch{}return[]}function ztt(t,e){const n=e.filter(a=>a.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,jtt);try{localStorage.setItem(Voe,JSON.stringify(r))}catch{}return r}function KD(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),a=Dx(r);return!(!(a.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(a.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(a.brand.toLowerCase()))||e.subtype&&!(a.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(a.variant.toLowerCase())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function Utt({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:a,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:u,quickAdd:d,quantity:m,onQuantityChange:p,errors:f}){const{t:y}=Rt(),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[N,T]=w.useState(!1),[C,P]=w.useState(!1),[k,R]=w.useState(""),[A,D]=w.useState(""),[B,z]=w.useState(""),[W,I]=w.useState(String(t.label_weight)),[J,ie]=w.useState(!1),Q=w.useRef(null),ue=w.useRef(null),me=w.useRef(null),pe=w.useRef(null);w.useEffect(()=>{const q=Z=>{Q.current&&!Q.current.contains(Z.target)&&b(!1),pe.current&&!pe.current.contains(Z.target)&&P(!1),ue.current&&!ue.current.contains(Z.target)&&_(!1),me.current&&!me.current.contains(Z.target)&&T(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[]);const Y=w.useMemo(()=>{if(!a)return l;const q=a.toLowerCase();return l.filter(Z=>Z.displayName.toLowerCase().includes(q)||Z.code.toLowerCase().includes(q))},[l,a]),se=w.useMemo(()=>{if(!k)return c;const q=k.toLowerCase();return c.filter(j=>j.toLowerCase().includes(q)).sort((j,E)=>{const U=j.toLowerCase()===q,K=E.toLowerCase()===q;return U&&!K?-1:!U&&K?1:j.localeCompare(E)})},[c,k]),oe=w.useMemo(()=>{if(!A)return h0;const q=A.toLowerCase();return h0.filter(Z=>Z.toLowerCase().includes(q))},[A]),be=w.useMemo(()=>{if(!B)return u;const q=B.toLowerCase();return u.filter(j=>j.toLowerCase().includes(q)).sort((j,E)=>{const U=j.toLowerCase()===q,K=E.toLowerCase()===q;return U&&!K?-1:!U&&K?1:j.localeCompare(E)})},[B,u]);w.useEffect(()=>{J||I(String(t.label_weight))},[t.label_weight,J]);const Me=q=>{e("slicer_filament",q.code),s(q.displayName),b(!1);const Z=Dx(q.name);Z.material&&e("material",Z.material),Z.brand&&e("brand",Z.brand),Z.variant&&e("subtype",Z.variant)};return i.jsxs("div",{className:"space-y-4",children:[!d&&i.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?i.jsxs(i.Fragment,{children:[i.jsx(pt,{className:"w-3 h-3 animate-spin"})," ",y("inventory.loadingPresets")]}):n?i.jsxs(i.Fragment,{children:[i.jsx(Ox,{className:"w-3 h-3 text-bambu-green"})," ",y("inventory.cloudConnected")]}):i.jsxs(i.Fragment,{children:[i.jsx(spe,{className:"w-3 h-3"})," ",y("inventory.cloudNotConnected")]})}),!d&&i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.slicerPreset")," *"]}),i.jsxs("div",{className:"relative",ref:Q,children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.searchPresets"),value:a,onChange:q=>{s(q.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),v&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:Y.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noPresetsFound")}):Y.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===q.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Me(q),children:q.displayName},q.code))})]}),o&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[y("inventory.selectedPreset"),": ",i.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.material")," *"]}),i.jsxs("div",{className:"relative",ref:pe,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.selectMaterial"),value:C?B:t.material,onChange:q=>{z(q.target.value),P(!0)},onFocus:()=>{P(!0),z("")}}),i.jsx(On,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),C&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[be.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):be.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",q),P(!1),z("")},children:q},q)),B&&!be.includes(B)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",B),P(!1),z("")},children:y("inventory.useCustomMaterial",{material:B})})]})]}),f?.material&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.brand"),!d&&" *"]}),i.jsxs("div",{className:"relative",ref:ue,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:y("inventory.searchBrand"),value:g?k:t.brand,onChange:q=>{R(q.target.value),_(!0)},onFocus:()=>{_(!0),R("")}}),i.jsx(On,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),g&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[se.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):se.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",q),_(!1),R("")},children:q},q)),k&&!se.includes(k)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",k),_(!1),R("")},children:y("inventory.useCustomBrand",{brand:k})})]})]}),f?.brand&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.subtype"),!d&&" *"]}),i.jsxs("div",{className:"relative",ref:me,children:[i.jsx("input",{type:"text",value:N?A:t.subtype,onChange:q=>{D(q.target.value),T(!0)},onFocus:()=>{T(!0),D("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),i.jsx(On,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[oe.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):oe.map(q=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",q),T(!1),D("")},children:q},q)),A&&!h0.some(q=>q.toLowerCase()===A.toLowerCase().trim())&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",A),T(!1),D("")},children:y("inventory.useCustomBrand",{brand:A})})]})]}),f?.subtype&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.labelWeight")}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:W,min:0,onFocus:()=>ie(!0),onChange:q=>I(q.target.value),onBlur:()=>{ie(!1);const q=W.trim(),Z=Number(q);if(!q||!Number.isFinite(Z)||Z<0){I(String(t.label_weight));return}const j=Math.round(Z);e("label_weight",j),I(String(j))}}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),d&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.quantity")}),i.jsx("input",{type:"number",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:m,min:1,max:100,onChange:q=>{const Z=Math.max(1,Math.min(100,parseInt(q.target.value)||1));p(Z)}})]})]})}function Btt({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:a}){const{t:s}=Rt(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=t.rgba.replace("#","").substring(0,6),m=g=>d.toUpperCase()===g.toUpperCase(),p=(g,_)=>{e("rgba",g.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:g})},f=w.useMemo(()=>{if(a.length===0)return[];const g=t.brand?.trim(),_=t.material?.toLowerCase().trim(),N=t.subtype?.toLowerCase().trim();if(!g&&!_)return[];const T=g?g.toLowerCase().split(/[\s\-_]+/).filter(k=>k.length>=2):[],C=k=>{if(T.length===0)return!0;const R=k.toLowerCase();return T.some(A=>R.includes(A))};if(g&&!_){const k=a.filter(R=>C(R.manufacturer));if(k.length>0)return k.map(R=>({name:R.color_name,hex:R.hex_color.replace("#","").substring(0,6),manufacturer:R.manufacturer,material:typeof R.material=="string"?R.material:void 0}))}const P=_&&N?`${_} ${N}`:"";if(P){const k=a.filter(A=>C(A.manufacturer)&&A.material?.toLowerCase()===P);if(k.length>0)return k.map(A=>({name:A.color_name,hex:A.hex_color.replace("#","").substring(0,6),manufacturer:A.manufacturer,material:typeof A.material=="string"?A.material:void 0}));const R=P.replace(/\+$/,"");if(R!==P){const A=a.filter(D=>C(D.manufacturer)&&D.material?.toLowerCase()===R);if(A.length>0)return A.map(D=>({name:D.color_name,hex:D.hex_color.replace("#","").substring(0,6),manufacturer:D.manufacturer,material:typeof D.material=="string"?D.material:void 0}))}}if(_){const k=a.filter(R=>C(R.manufacturer)&&(!R.material||R.material.toLowerCase().startsWith(_)));if(k.length>0)return k.map(R=>({name:R.color_name,hex:R.hex_color.replace("#","").substring(0,6),manufacturer:R.manufacturer,material:typeof R.material=="string"?R.material:void 0}))}return[]},[a,t.brand,t.material,t.subtype]),y=w.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const g=c.toLowerCase();return f.filter(N=>N.name.toLowerCase().includes(g)||(N.manufacturer?.toLowerCase().includes(g)??!1)||(N.material?.toLowerCase().includes(g)??!1))},[c,f]),v=f.length>0,b=w.useMemo(()=>c?DY.filter(g=>g.name.toLowerCase().includes(c.toLowerCase())):o?DY:qoe,[c,o]);return i.jsxs("div",{className:"space-y-3",children:[i.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${d}`}}),n.length>0&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[i.jsx(Jn,{className:"w-3 h-3"}),i.jsx("span",{children:s("inventory.recentColors")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(g=>i.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name},g.hex))})]}),i.jsxs("div",{className:"relative",children:[i.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:g=>u(g.target.value)})]}),v?i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.map(g=>i.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name})},`${g.hex}-${g.name}-${g.manufacturer??""}`)),y.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[i.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&i.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?i.jsxs(i.Fragment,{children:[s("inventory.showLess")," ",i.jsx($l,{className:"w-3 h-3"})]}):i.jsxs(i.Fragment,{children:[s("inventory.showAll")," ",i.jsx(On,{className:"w-3 h-3"})]})})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(g=>i.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:g.name})},g.hex)),b.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:g=>e("color_name",g.target.value)})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),i.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:d.toUpperCase(),onChange:g=>{const _=g.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),i.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${d}`,onChange:g=>{const _=g.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function Htt({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:a}){const{t:s}=Rt(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{const v=b=>{d.current&&!d.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(b=>b.weight===e);if(r){const b=t.find(g=>g.id===r);if(b&&b.weight===e)return}v.length===1?a(v[0].id):v.length===0&&r!==null&&a(null)},[e,t,r,a]);const p=w.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(v)||b.weight.toString().includes(v))},[t,c]),f=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),y=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(b=>b.id===r);if(v)return v.name}return f.length>0?f[0].name:""},[o,c,r,t,f]);return i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(Mge,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsxs("div",{className:"flex-1 min-w-0 relative",ref:d,children:[i.jsx("input",{ref:m,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:y,onFocus:()=>{l(!0),u("")},onChange:v=>{u(v.target.value),l(!0)}}),o&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:p.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>i.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{a(v.id),n(v.weight),l(!1),u("")},children:[i.jsx("span",{className:"truncate",children:v.name}),i.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),i.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[i.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:v=>{const b=parseInt(v.target.value);!isNaN(b)&&b>=0&&n(b)}}),i.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function $tt({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:a}=Rt(),{showToast:s}=fn(),[o,l]=w.useState(""),[c,u]=w.useState(!1),[d,m]=w.useState(""),[p,f]=w.useState(!1),y=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+y;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{p||m(String(y))},[p,y]),i.jsxs("div",{className:"space-y-4",children:[i.jsx(Htt,{catalog:n,value:t.core_weight,onChange:b=>e("core_weight",b),catalogId:t.core_weight_catalog_id,onCatalogIdChange:b=>e("core_weight_catalog_id",b)}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.currentWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:d,min:0,max:t.label_weight,onFocus:()=>f(!0),onChange:b=>{m(b.target.value)},onBlur:()=>{f(!1);const b=d.trim(),g=Number(b);if(!b||!Number.isFinite(g)||g<0||g>t.label_weight){m(String(y));return}const _=Math.round(g);e("weight_used",Math.max(0,t.label_weight-_)),m(String(_))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.measuredWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:o,min:0,onFocus:()=>u(!0),onChange:b=>{l(b.target.value)},onBlur:()=>{u(!1);const b=o.trim(),g=Number(b),_=t.core_weight,N=t.core_weight+t.label_weight;if(!b||!Number.isFinite(g)||g<_||g>N){s(a("inventory.measuredWeightError",{min:_,max:N}),"error"),l(String(v));return}const T=Math.round(g),C=Math.max(0,Math.min(t.label_weight,T-t.core_weight));e("weight_used",Math.max(0,t.label_weight-C)),l(String(T))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.costPerKg","Cost per kg")}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),i.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:b=>{const g=b.target.value===""?null:parseFloat(b.target.value);e("cost_per_kg",g)},style:{paddingLeft:`${Math.max(2,r.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.note")}),i.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:a("inventory.notePlaceholder"),value:t.note,onChange:b=>e("note",b.target.value)})]})]})}function qtt({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:a,setExpandedPrinters:s}){const{t:o}=Rt(),l=p=>{s(f=>{const y=new Set(f);return y.has(p)?y.delete(p):y.add(p),y})},c=(p,f,y)=>{const v=`${p}:${f}:${y??"null"}`,b=`${p}:${y??"null"}`;r(g=>{const _=new Set(g);if(_.has(v))_.delete(v);else{for(const N of Array.from(_)){const T=N.split(":");`${T[0]}:${T[2]}`===b&&_.delete(N)}_.add(v)}return _})},u=()=>{const p=new Set;for(const{printer:f,calibrations:y}of e){if(!f.connected)continue;const v=y.filter(g=>KD(g,t)),b=new Map;for(const g of v){const _=`${g.extruder_id??"null"}`;b.has(_)||b.set(_,[]),b.get(_).push(g)}for(const[g,_]of b)if(_.length>0){const T=[..._].sort((C,P)=>P.k_value-C.k_value)[0];p.add(`${f.id}:${T.cali_idx}:${g}`)}}r(p)};if(!t.material)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const d=e.reduce((p,{printer:f,calibrations:y})=>f.connected?p+y.filter(v=>KD(v,t)).length:p,0),m=(p,f)=>{const y=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=n.has(y);return i.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[i.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),i.jsx("div",{className:"flex items-center gap-2 shrink-0",children:i.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),d>0&&i.jsxs("button",{type:"button",onClick:u,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[i.jsx(ox,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",d,")"]})]}),i.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const y=a.has(String(p.id)),v=f.filter(T=>KD(T,t)),b=v.length,g=v.some(T=>T.extruder_id!==void 0&&T.extruder_id!==null&&T.extruder_id>0),_=v.filter(T=>T.extruder_id===1),N=v.filter(T=>T.extruder_id===0||T.extruder_id===void 0||T.extruder_id===null);return i.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{type:"button",onClick:()=>l(String(p.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[y?i.jsx(On,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(fa,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?i.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[b," ",o(b!==1?"inventory.matches":"inventory.match")]}):i.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),i.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),y&&i.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):g?i.jsxs(i.Fragment,{children:[_.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),i.jsx("div",{className:"space-y-2",children:_.map(T=>m(p,T))})]}),N.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),i.jsx("div",{className:"space-y-2",children:N.map(T=>m(p,T))})]})]}):i.jsx("div",{className:"space-y-2",children:v.map(T=>m(p,T))}):i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function Vtt(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const Gtt={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function Wtt({spoolId:t}){const{t:e}=Rt(),n=sn(),{showToast:r}=fn(),{data:a,isLoading:s}=tt({queryKey:["spool-usage",t],queryFn:()=>fe.getSpoolUsageHistory(t)}),o=ft({mutationFn:()=>fe.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?i.jsx("div",{className:"flex justify-center py-4",children:i.jsx(pt,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!a||a.length===0?i.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[i.jsx(Jn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),i.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[i.jsx(en,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:a.map(l=>i.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("span",{className:"text-bambu-gray",children:Vtt(l.created_at)}),l.print_name&&i.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[i.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),i.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),i.jsx("span",{className:Gtt[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function Ktt({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:a}){const{t:s}=Rt(),o=sn(),{showToast:l}=fn(),c=!!n,[u,d]=w.useState(jY),[m,p]=w.useState({}),[f,y]=w.useState("filament"),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[N,T]=w.useState(1),[C,P]=w.useState(!1),[k,R]=w.useState(!1),[A,D]=w.useState([]),[B,z]=w.useState(""),[W,I]=w.useState([]),[J,ie]=w.useState([]),[Q,ue]=w.useState([]),[me,pe]=w.useState([]),[Y,se]=w.useState([]),[oe,be]=w.useState(new Set),[Me,q]=w.useState(new Set),Z=r.length>0?r:Y,j=w.useMemo(()=>oe.size,[oe]);w.useEffect(()=>{pe(Itt())},[]),w.useEffect(()=>{t&&((async()=>{R(!0);try{const de=await fe.getCloudStatus();if(P(de.is_authenticated),de.is_authenticated){const ke=await fe.getFilamentPresets();D(ke)}}catch(de){console.error("Failed to fetch cloud presets:",de),P(!1)}finally{R(!1)}})(),fe.getSpoolCatalog().then(I).catch(console.error),fe.getColorCatalog().then(ue).catch(console.error),fe.getLocalPresets().then(de=>ie(de.filament)).catch(console.error),r.length===0&&(async()=>{try{const de=await fe.getPrinters(),ke=await Promise.all(de.map(Le=>fe.getPrinterStatus(Le.id).catch(()=>null))),_e=[];for(let Le=0;Le({cali_idx:je.slot_id,filament_id:je.filament_id,setting_id:je.setting_id||"",name:je.name,k_value:parseFloat(je.k_value)||0,n_coef:parseFloat(je.n_coef)||0,extruder_id:je.extruder_id,nozzle_diameter:je.nozzle_diameter}))}catch{}_e.push({printer:{...$e,connected:Ae},calibrations:Pe})}se(_e)}catch(de){console.error("Failed to fetch printer calibrations:",de)}})())},[t,r.length]);const E=w.useMemo(()=>Ltt(A,new Set,J),[A,J]),U=w.useMemo(()=>{const he=Rtt(A,J),de=Q.map(_e=>_e.manufacturer?.trim()).filter(_e=>!!_e),ke=new Set([...he,...de]);return Array.from(ke).sort((_e,Le)=>_e.localeCompare(Le))},[A,J,Q]),K=w.useMemo(()=>{const he=Q.map(ke=>ke.material?.trim()).filter(ke=>!!ke),de=new Set([...Ptt,...he]);return Array.from(de).sort((ke,_e)=>ke.localeCompare(_e))},[Q]),$=w.useMemo(()=>{const he=[];for(const de of Q){const ke=de.manufacturer?.trim(),_e=de.material?.trim();ke&&_e&&he.push({brand:ke,material:_e})}for(const de of A){const ke=Dx(de.name);ke.brand&&ke.material&&he.push({brand:ke.brand,material:ke.material})}for(const de of J){const ke=Dx(de.name),_e=de.filament_vendor?.trim()||ke.brand,Le=ke.material;_e&&Le&&he.push({brand:_e,material:Le})}return he},[A,Q,J]),ne=w.useMemo(()=>{const he=new Map;for(const de of $){const ke=de.brand.toLowerCase(),_e=de.material.toLowerCase();he.has(ke)||he.set(ke,new Set),he.get(ke).add(_e)}return he},[$]),O=w.useMemo(()=>{const he=new Map;for(const de of $){const ke=de.brand.toLowerCase(),_e=de.material.toLowerCase();he.has(_e)||he.set(_e,new Set),he.get(_e).add(ke)}return he},[$]),V=w.useMemo(()=>{if(!u.material)return U;const he=u.material.toLowerCase(),de=O.get(he);return!de||de.size===0?U:U.filter(ke=>de.has(ke.toLowerCase()))},[U,u.material,O]),ee=w.useMemo(()=>{if(!u.brand)return K;const he=u.brand.toLowerCase(),de=ne.get(he);return!de||de.size===0?K:K.filter(ke=>de.has(ke.toLowerCase()))},[K,u.brand,ne]),G=w.useMemo(()=>Ott(u.slicer_filament,E),[u.slicer_filament,E]);w.useEffect(()=>{if(t){if(n)if(d({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),z(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const he=new Set;for(const de of n.k_profiles)de.cali_idx!==null&&de.cali_idx!==void 0&&he.add(`${de.printer_id}:${de.cali_idx}:${de.extruder??"null"}`);be(he)}else be(new Set);else d(jY),z(""),be(new Set),_(!1),T(1);p({}),y("filament"),b(!1)}},[t,n]),w.useEffect(()=>{t&&Z.length>0&&q(new Set(Z.map(he=>String(he.printer.id))))},[t,Z]);const re=(he,de)=>{d(ke=>({...ke,[he]:de})),he==="weight_used"&&b(!0),m[he]&&p(ke=>({...ke,[he]:void 0}))},ce=he=>{pe(de=>ztt(he,de))},ge=ft({mutationFn:he=>fe.createSpool(he),onSuccess:async he=>{oe.size>0&&he?.id&&await F(he.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolCreated"),"success"),e()},onError:he=>{l(he.message,"error")}}),xe=ft({mutationFn:({data:he,qty:de})=>fe.bulkCreateSpools(he,de),onSuccess:async he=>{if(oe.size>0)for(const de of he)await F(de.id);await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolsCreated",{count:he.length}),"success"),e()},onError:he=>{l(he.message,"error")}}),ae=ft({mutationFn:he=>fe.updateSpool(n.id,he),onSuccess:async()=>{n?.id&&await F(n.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolUpdated"),"success"),e()},onError:he=>{l(he.message,"error")}}),L=ft({mutationFn:()=>fe.updateSpool(n.id,{tag_uid:null}),onSuccess:async()=>{await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.tagDeleted","Tag removed"),"success"),e()},onError:he=>{l(he.message,"error")}}),F=async he=>{if(oe.size===0){try{await fe.saveSpoolKProfiles(he,[])}catch{}return}const de=[];for(const ke of oe){const[_e,Le,$e]=ke.split(":"),Re=parseInt(_e),Ae=parseInt(Le),Pe=$e==="null"?0:parseInt($e),Ue=Z.find(je=>je.printer.id===Re);if(Ue){const je=Ue.calibrations.find(Xe=>Xe.cali_idx===Ae);je&&de.push({printer_id:Re,extruder:Pe,nozzle_diameter:je.nozzle_diameter||"0.4",k_value:je.k_value,name:je.name||null,cali_idx:je.cali_idx,setting_id:je.setting_id||null})}}if(de.length>0)try{await fe.saveSpoolKProfiles(he,de)}catch(ke){console.error("Failed to save K-profiles:",ke)}};if(w.useEffect(()=>{if(!t)return;const he=de=>{de.key==="Escape"&&e()};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[t,e]),!t)return null;const te=()=>{const he=Att(u,g);if(!he.isValid){p(he.errors),(he.errors.slicer_filament||he.errors.material||he.errors.brand||he.errors.subtype)&&y("filament");return}const de=G?.displayName||B||null,ke={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:de,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!c||v)&&(ke.weight_used=u.weight_used),c?ae.mutate(ke):N>1?xe.mutate({data:ke,qty:N}):ge.mutate(ke)},ve=ge.isPending||xe.isPending||ae.isPending||L.isPending;return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(c?"inventory.editSpool":"inventory.addSpool")}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ht,{className:"w-5 h-5"})})]}),!c&&i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Mc,{className:"w-4 h-4 text-amber-400"}),i.jsx("span",{className:"text-sm text-white",children:s("inventory.quickAdd")})]}),i.jsx("button",{type:"button",onClick:()=>{_(!g),g||y("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${g?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${g?"translate-x-4":"translate-x-0.5"}`})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("button",{onClick:()=>y("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${f==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(yw,{className:"w-4 h-4"}),s("inventory.filamentInfoTab")]}),!g&&i.jsxs("button",{onClick:()=>y("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${f==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(yhe,{className:"w-4 h-4"}),s("inventory.paProfileTab"),j>0&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:j})]})]}),i.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:f==="filament"?i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.filamentInfo")}),i.jsx(Utt,{formData:u,updateField:re,cloudAuthenticated:C,loadingCloudPresets:k,presetInputValue:B,setPresetInputValue:z,selectedPresetOption:G,filamentOptions:E,availableBrands:V,availableMaterials:ee,quickAdd:g,quantity:N,onQuantityChange:T,errors:m})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.color")}),i.jsx(Btt,{formData:u,updateField:re,recentColors:me,onColorUsed:ce,catalogColors:Q})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.additional")}),i.jsx($tt,{formData:u,updateField:re,spoolCatalog:W,currencySymbol:a})]}),c&&n&&i.jsx("div",{children:i.jsx(Wtt,{spoolId:n.id})})]}):i.jsx(qtt,{formData:u,updateField:re,printersWithCalibrations:Z,selectedProfiles:oe,setSelectedProfiles:be,expandedPrinters:Me,setExpandedPrinters:q})}),i.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[c&&i.jsxs(Ie,{variant:"secondary",onClick:()=>L.mutate(),disabled:ve||!n?.tag_uid,className:"mr-auto",children:[i.jsx(Id,{className:"w-4 h-4"}),s("inventory.deleteTag","Delete Tag")]}),i.jsxs("div",{className:"flex gap-2 ml-auto",children:[i.jsx(Ie,{variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(Ie,{onClick:te,disabled:ve,children:ve?i.jsxs(i.Fragment,{children:[i.jsx(pt,{className:"w-4 h-4 animate-spin"}),s("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(ss,{className:"w-4 h-4"}),s(c?"common.save":"inventory.addSpool")]})})]})]})]})]})}function Ytt({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:a}){const{t:s}=Rt(),[o,l]=w.useState(n),[c,u]=w.useState(null),d=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(T=>({...T})))},[t,n]),w.useEffect(()=>{if(!t)return;const T=C=>{C.key==="Escape"&&e()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[t,e]),!t)return null;const m=T=>{l(C=>C.map((P,k)=>k===T?{...P,visible:!P.visible}:P))},p=(T,C)=>{C<0||C>=o.length||l(P=>{const k=[...P],[R]=k.splice(T,1);return k.splice(C,0,R),k})},f=(T,C)=>{d.current=C,u(C),T.dataTransfer.effectAllowed="move"},y=(T,C)=>{T.preventDefault(),T.dataTransfer.dropEffect="move";const P=d.current;P!==null&&P!==C&&(p(P,C),d.current=C,u(C))},v=T=>{T.preventDefault()},b=()=>{d.current=null,u(null)},g=()=>{l(r.map(T=>({...T})))},_=()=>{a(o),e()},N=o.filter(T=>T.visible).length;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsx(Pt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:T=>T.stopPropagation(),children:i.jsxs(Et,{className:"p-6 flex flex-col min-h-0",children:[i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),i.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),i.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),i.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((T,C)=>i.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===C?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${T.visible?"":"opacity-50"}`,draggable:!0,onDragStart:P=>f(P,C),onDragOver:P=>y(P,C),onDrop:v,onDragEnd:b,children:[i.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:i.jsx(Sh,{className:"w-4 h-4"})}),i.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:T.label}),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{onClick:()=>p(C,C-1),disabled:C===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:i.jsx($l,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>p(C,C+1),disabled:C===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:i.jsx(On,{className:"w-4 h-4"})})]}),i.jsx("button",{onClick:()=>m(C),className:`p-1.5 rounded transition-colors ${T.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:T.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:T.visible?i.jsx(Ac,{className:"w-4 h-4"}):i.jsx(fw,{className:"w-4 h-4"})})]},T.id))}),i.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs(Ie,{variant:"secondary",onClick:g,className:"mr-auto",children:[i.jsx(So,{className:"w-4 h-4"}),s("inventory.reset")]}),i.jsx(Ie,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),i.jsx(Ie,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}function RY(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.label_weight}`}const Goe="bambuddy-inventory-columns",SN=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function Xtt(){try{const t=localStorage.getItem(Goe);if(t){const e=JSON.parse(t),n=new Set(SN.map(o=>o.id)),r=new Set(e.map(o=>o.id)),a=e.filter(o=>n.has(o.id)),s=SN.filter(o=>!r.has(o.id));return[...a,...s]}}catch{}return SN.map(t=>({...t}))}function Qtt(t){try{localStorage.setItem(Goe,JSON.stringify(t))}catch{}}function du(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const Ztt={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function YD(t,e="system"){if(!t)return"-";const n=Zn(t);return n?N3(n,e):"-"}const Jtt={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},SL={id:({spool:t})=>i.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:YD(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:YD(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?YD(t.last_used,e):"Never"}),rgba:({spool:t})=>i.jsx("div",{className:"flex items-center justify-center",children:i.jsx("span",{className:"w-5 h-5 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:PI(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,a=n.ams_id===254||n.ams_id===255,s=!a&&n.ams_id>=128,o=EI(n.ams_id,n.tray_id,s,a);return i.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[r," ",o,n.ams_label?` (${n.ams_label})`:""]})},label_weight:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:du(t.label_weight)}),net:({remaining:t})=>i.jsx("span",{className:"text-sm text-white",children:du(t)}),gross:({spool:t,remaining:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:du(e+t.core_weight)}),added_full:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?du(t.weight_used):"-"}),printed_total:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?i.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return i.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const n=t.last_scale_weight;if(n==null)return i.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const r=t.core_weight||0,a=Math.max(0,t.label_weight-t.weight_used)+r;let s,o;n0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g Calculated: ${Math.round(a)}g Difference: ${l}g (within tolerance)`:`Scale: ${Math.round(n)}g Calculated: ${Math.round(a)}g diff --git a/static/index.html b/static/index.html index 7c7c8d5ed..0ab90e6af 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +